From 0ee0fa7f2147d4cb3e813783dc79fdb6c4567a82 Mon Sep 17 00:00:00 2001 From: brkalow Date: Tue, 1 Dec 2026 13:07:21 -0600 Subject: [PATCH 1/8] feat(backend): Support CIMD clients in the OAuth applications API Backend SDK users cannot pre-register or list clients identified by a Client ID Metadata Document (CIMD), an OAuth client whose client_id is the HTTPS URL of a JSON document describing it, such as an MCP client. The Backend API gained this in clerk/clerk_go#24786, but `clerkClient.oauthApplications` has no way to send the URL, filter the list, or read the CIMD fields, so customers scripting pre-registration across many apps must call the API by hand. `oauthApplications.create()` now accepts `clientIdMetadataDocumentUrl` (with `name` optional and only `name` and `scopes` allowed beside it), `oauthApplications.list()` accepts `clientIdMetadataDocument: true` to return only CIMD clients, and `OAuthApplication` exposes `clientIdMetadataDocument` and `clientIdMetadataDocumentDetails`. Co-Authored-By: Claude Opus 5.5 --- .changeset/backend-cimd-oauth-applications.md | 5 + .../__tests__/OAuthApplicationsApi.test.ts | 139 +++++++++++++++++- .../src/api/endpoints/OAuthApplicationsApi.ts | 49 +++++- packages/backend/src/api/resources/JSON.ts | 10 ++ .../src/api/resources/OAuthApplication.ts | 39 ++++- packages/backend/src/index.ts | 2 + 6 files changed, 236 insertions(+), 8 deletions(-) create mode 100644 .changeset/backend-cimd-oauth-applications.md diff --git a/.changeset/backend-cimd-oauth-applications.md b/.changeset/backend-cimd-oauth-applications.md new file mode 100644 index 00000000000..c7cccc96c29 --- /dev/null +++ b/.changeset/backend-cimd-oauth-applications.md @@ -0,0 +1,5 @@ +--- +'@clerk/backend': minor +--- + +Add Client ID Metadata Document (CIMD) client support to `clerkClient.oauthApplications`. Pass `clientIdMetadataDocumentUrl` to `create()` to pre-register a client from its metadata document URL; `name` is optional in that case, and only `name` and `scopes` can be set. Pass `clientIdMetadataDocument: true` to `list()` to list only CIMD clients. `OAuthApplication` now exposes `clientIdMetadataDocument` and `clientIdMetadataDocumentDetails`, which holds the client's admission status and the state of its last metadata fetch. diff --git a/packages/backend/src/api/__tests__/OAuthApplicationsApi.test.ts b/packages/backend/src/api/__tests__/OAuthApplicationsApi.test.ts index fea5080abad..99008ed352e 100644 --- a/packages/backend/src/api/__tests__/OAuthApplicationsApi.test.ts +++ b/packages/backend/src/api/__tests__/OAuthApplicationsApi.test.ts @@ -5,11 +5,42 @@ import { describe, expect, it } from 'vitest'; import { OAuthTokenExchangeError } from '../../errors'; import { server, validateHeaders } from '../../mock-server'; -import type { ExchangeOAuthApplicationTokenParams } from '../endpoints'; +import type { CreateOAuthApplicationParams, ExchangeOAuthApplicationTokenParams } from '../endpoints'; import { createBackendApiClient } from '../factory'; describe('OAuthApplications', () => { const oauthApplicationId = 'oauthapp_xxxxx'; + const cimdUrl = 'https://mcp-client.example.com/oauth/client-metadata.json'; + const cimdClientJSON = { + object: 'oauth_application', + id: oauthApplicationId, + instance_id: 'ins_xxxxx', + name: 'MCP Client', + client_id: cimdUrl, + client_uri: null, + client_image_url: null, + dynamically_registered: false, + client_id_metadata_document: true, + client_id_metadata_document_details: { + pre_registered: true, + status: 'explicitly_allowed', + metadata_status: 'error', + metadata_fetched_at: null, + metadata_error: 'metadata document returned HTTP 404', + }, + consent_screen_enabled: true, + pkce_required: true, + public: true, + scopes: 'profile email offline_access', + redirect_uris: [], + authorize_url: 'https://clerk.example.test/oauth/authorize', + token_fetch_url: 'https://clerk.example.test/oauth/token', + user_info_url: 'https://clerk.example.test/oauth/userinfo', + discovery_url: 'https://clerk.example.test/.well-known/openid-configuration', + token_introspection_url: 'https://clerk.example.test/oauth/token_info', + created_at: 1764600000000, + updated_at: 1764600000000, + }; describe('list', () => { it('forwards the name filter alongside pagination', async () => { @@ -36,6 +67,112 @@ describe('OAuthApplications', () => { expect(response).toEqual({ data: [], totalCount: 100 }); }); + + it('lists only CIMD clients when clientIdMetadataDocument is true', async () => { + const apiClient = createBackendApiClient({ + apiUrl: 'https://api.clerk.test', + secretKey: 'sk_xxxxx', + }); + + server.use( + http.get( + 'https://api.clerk.test/v1/oauth_applications', + validateHeaders(({ request }) => { + expect(Object.fromEntries(new URL(request.url).searchParams)).toEqual({ + client_id_metadata_document: 'true', + }); + return HttpResponse.json({ data: [cimdClientJSON], total_count: 1 }); + }), + ), + ); + + const response = await apiClient.oauthApplications.list({ clientIdMetadataDocument: true }); + + expect(response.totalCount).toBe(1); + expect(response.data[0].clientId).toBe(cimdUrl); + expect(response.data[0].clientIdMetadataDocument).toBe(true); + }); + }); + + describe('create', () => { + it('pre-registers a CIMD client from its metadata document URL', async () => { + const apiClient = createBackendApiClient({ + apiUrl: 'https://api.clerk.test', + secretKey: 'sk_xxxxx', + }); + + server.use( + http.post( + 'https://api.clerk.test/v1/oauth_applications', + validateHeaders(async ({ request }) => { + expect(await request.json()).toEqual({ + client_id_metadata_document_url: cimdUrl, + scopes: 'profile email', + }); + return HttpResponse.json(cimdClientJSON); + }), + ), + ); + + const response = await apiClient.oauthApplications.create({ + clientIdMetadataDocumentUrl: cimdUrl, + scopes: 'profile email', + }); + + expect(response.clientId).toBe(cimdUrl); + expect(response.clientSecret).toBeUndefined(); + expect(response.clientIdMetadataDocument).toBe(true); + expect(response.clientIdMetadataDocumentDetails).toEqual({ + preRegistered: true, + status: 'explicitly_allowed', + metadataStatus: 'error', + metadataFetchedAt: null, + metadataError: 'metadata document returned HTTP 404', + }); + }); + + it('deserializes a regular OAuth application with no CIMD details', async () => { + const apiClient = createBackendApiClient({ + apiUrl: 'https://api.clerk.test', + secretKey: 'sk_xxxxx', + }); + + server.use( + http.post( + 'https://api.clerk.test/v1/oauth_applications', + validateHeaders(() => + HttpResponse.json({ + ...cimdClientJSON, + client_id: 'generated_client_id', + client_secret: 'secret', + client_id_metadata_document: false, + client_id_metadata_document_details: null, + }), + ), + ), + ); + + const response = await apiClient.oauthApplications.create({ + name: 'My App', + redirectUris: ['https://example.com/callback'], + }); + + expect(response.clientIdMetadataDocument).toBe(false); + expect(response.clientIdMetadataDocumentDetails).toBeNull(); + }); + + it('requires a name unless clientIdMetadataDocumentUrl is set, and rejects redirect URIs alongside it', () => { + const cimd: CreateOAuthApplicationParams = { clientIdMetadataDocumentUrl: cimdUrl }; + // @ts-expect-error name is required without clientIdMetadataDocumentUrl + const missingName: CreateOAuthApplicationParams = { scopes: 'profile' }; + // @ts-expect-error the metadata document defines a CIMD client's redirect URIs + const withRedirectUris: CreateOAuthApplicationParams = { + clientIdMetadataDocumentUrl: cimdUrl, + redirectUris: ['https://example.com/callback'], + }; + + expect([cimd, missingName, withRedirectUris]).toHaveLength(3); + }); }); describe('revokeToken', () => { diff --git a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts index c35e66ef390..da3c07e9c0a 100644 --- a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts +++ b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts @@ -12,8 +12,8 @@ import type { WithSign } from './util-types'; const basePath = '/oauth_applications'; -/** @generateWithEmptyComment */ -export type CreateOAuthApplicationParams = { +/** @inline */ +export type OAuthApplicationParams = { /** * A descriptive name for the OAuth application (e.g., "My Web App", "My Mobile App"). Maximum length: 256 characters. */ @@ -27,7 +27,29 @@ export type CreateOAuthApplicationParams = { }; /** @generateWithEmptyComment */ -export type UpdateOAuthApplicationParams = CreateOAuthApplicationParams & { +export type CreateOAuthApplicationParams = + | (OAuthApplicationParams & { + clientIdMetadataDocumentUrl?: never; + }) + | { + /** + * The HTTPS URL of a [Client ID Metadata Document (CIMD)](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/), at most 512 bytes, with a path and without credentials or a fragment. Pre-registers the client the document describes, using the URL as its `clientId`. The metadata document defines the redirect URIs, and Clerk makes the client public with the consent screen and PKCE required. If the instance already has an implicitly allowed client for the URL, that client becomes pre-registered. Requires the new OAuth provider. + */ + clientIdMetadataDocumentUrl: string; + /** + * A descriptive name for the client. Maximum length: 256 characters. Defaults to the metadata document's `client_name`, or to the URL's host. + */ + name?: string; + /** Scopes for the client, separated by spaces. `offline_access` is always included. When omitted, a new client gets the default scopes, and a client that was implicitly allowed keeps its scopes. */ + scopes?: string | null | undefined; + redirectUris?: never; + public?: never; + }; + +/** + * For a client identified by a Client ID Metadata Document (`clientIdMetadataDocument` is `true`), only `name` and `scopes` can be updated. + */ +export type UpdateOAuthApplicationParams = OAuthApplicationParams & { /** The ID of the OAuth application to update. */ oauthApplicationId: string; }; @@ -91,13 +113,17 @@ export type ExchangeOAuthApplicationTokenResult = { /** @generateWithEmptyComment */ export type GetOAuthApplicationListParams = ClerkPaginationRequest<{ /** - * Filters by a case-insensitive substring of the application name or an exact client ID. + * Filters by a case-insensitive substring of the application name or an exact client ID. To look up a client by its Client ID Metadata Document URL, also set `clientIdMetadataDocument` to `true`. */ nameQuery?: string; /** * Returns OAuth applications in a particular order. Prefix a value with `+` to sort in ascending order, or `-` to sort in descending order. Defaults to `-created_at`. */ orderBy?: WithSign<'name' | 'created_at'>; + /** + * When `true`, returns only clients identified by a Client ID Metadata Document (CIMD), both pre-registered and implicitly allowed. When omitted or `false`, returns only regular OAuth applications. + */ + clientIdMetadataDocument?: boolean; }>; type TokenExchangeResponseJSON = { @@ -280,6 +306,17 @@ export class OAuthApplicationsApi extends AbstractAPI { /** * Creates a new OAuth application. + * + * To pre-register a client identified by a Client ID Metadata Document (CIMD), set `clientIdMetadataDocumentUrl`. Only `name` and `scopes` can be set alongside it. The response has no client secret. Requires the new OAuth provider: otherwise the request fails with `feature_requires_oidc_provider`. If the client is already pre-registered, the request fails with `cimd_client_already_exists`. + * + * @example + * ```ts + * const client = await clerkClient.oauthApplications.create({ + * clientIdMetadataDocumentUrl: 'https://mcp-client.example.com/oauth/client-metadata.json', + * scopes: 'profile email', + * }); + * ``` + * * @param params - The parameters to create the OAuth application with. * @returns The created [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object. */ @@ -292,7 +329,7 @@ export class OAuthApplicationsApi extends AbstractAPI { } /** - * Updates the given OAuth application. + * Updates the given OAuth application. For a client identified by a Client ID Metadata Document, only `name` and `scopes` can be updated. * @returns The updated [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object. */ public async update(params: UpdateOAuthApplicationParams) { @@ -322,7 +359,7 @@ export class OAuthApplicationsApi extends AbstractAPI { } /** - * Rotates the secret of the given OAuth application. When the client secret is rotated, ensure that you update it in your authorized OAuth clients. + * Rotates the secret of the given OAuth application. When the client secret is rotated, ensure that you update it in your authorized OAuth clients. Clients identified by a Client ID Metadata Document have no secret, and the request fails with `cimd_client_operation_not_supported`. * @param oauthApplicationId - The ID of the OAuth application to rotate the secret of. * @returns The [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object. */ diff --git a/packages/backend/src/api/resources/JSON.ts b/packages/backend/src/api/resources/JSON.ts index ce2f2e00a0d..ebdcaad5388 100644 --- a/packages/backend/src/api/resources/JSON.ts +++ b/packages/backend/src/api/resources/JSON.ts @@ -359,6 +359,14 @@ export interface OauthAccessTokenJSON { id_token?: string; } +export interface OAuthApplicationClientIdMetadataDocumentDetailsJSON { + pre_registered: boolean; + status: 'explicitly_allowed' | 'implicitly_allowed' | 'blocked'; + metadata_status: 'ok' | 'error' | 'metadata_unavailable'; + metadata_fetched_at: number | null; + metadata_error: string | null; +} + export interface OAuthApplicationJSON extends ClerkResourceJSON { object: typeof ObjectType.OAuthApplication; id: string; @@ -368,6 +376,8 @@ export interface OAuthApplicationJSON extends ClerkResourceJSON { client_uri: string | null; client_image_url: string | null; dynamically_registered: boolean; + client_id_metadata_document: boolean; + client_id_metadata_document_details: OAuthApplicationClientIdMetadataDocumentDetailsJSON | null; consent_screen_enabled: boolean; pkce_required: boolean; public: boolean; diff --git a/packages/backend/src/api/resources/OAuthApplication.ts b/packages/backend/src/api/resources/OAuthApplication.ts index bb871cdf559..de9fd42cc59 100644 --- a/packages/backend/src/api/resources/OAuthApplication.ts +++ b/packages/backend/src/api/resources/OAuthApplication.ts @@ -1,4 +1,35 @@ -import type { OAuthApplicationJSON } from './JSON'; +import type { OAuthApplicationClientIdMetadataDocumentDetailsJSON, OAuthApplicationJSON } from './JSON'; + +/** + * The admission and metadata state of a client identified by a Client ID Metadata Document (CIMD). + */ +export type OAuthApplicationClientIdMetadataDocumentDetails = { + /** Whether the client was pre-registered through the Dashboard or the Backend API. `false` when Clerk provisioned it on the client's first OAuth flow. */ + preRegistered: boolean; + /** Whether the instance currently admits the client. Pre-registered clients are `'explicitly_allowed'`. Other clients are `'blocked'` when the instance blocks implicitly allowed clients, and `'implicitly_allowed'` otherwise. */ + status: 'explicitly_allowed' | 'implicitly_allowed' | 'blocked'; + /** The outcome of the last metadata document fetch, or `'metadata_unavailable'` when no fetched document backs the client. */ + metadataStatus: 'ok' | 'error' | 'metadata_unavailable'; + /** The Unix timestamp, in milliseconds, of the last successful metadata document fetch. */ + metadataFetchedAt: number | null; + /** Why the last metadata document fetch failed, when `metadataStatus` is `'error'`. */ + metadataError: string | null; +}; + +function clientIdMetadataDocumentDetailsFromJSON( + data: OAuthApplicationClientIdMetadataDocumentDetailsJSON | null, +): OAuthApplicationClientIdMetadataDocumentDetails | null { + if (!data) { + return null; + } + return { + preRegistered: data.pre_registered, + status: data.status, + metadataStatus: data.metadata_status, + metadataFetchedAt: data.metadata_fetched_at, + metadataError: data.metadata_error, + }; +} /** * The Backend `OAuthApplication` object holds information about an OAuth application. @@ -19,6 +50,10 @@ export class OAuthApplication { readonly clientImageUrl: string | null, /** Whether the OAuth application is dynamically registered. */ readonly dynamicallyRegistered: boolean, + /** Whether the `clientId` is the HTTPS URL of the client's Client ID Metadata Document (CIMD) rather than an identifier Clerk generated. CIMD clients are always public, with PKCE and the consent screen required. */ + readonly clientIdMetadataDocument: boolean, + /** The admission and metadata state of the client. `null` unless `clientIdMetadataDocument` is `true`. */ + readonly clientIdMetadataDocumentDetails: OAuthApplicationClientIdMetadataDocumentDetails | null, /** Whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications. */ readonly consentScreenEnabled: boolean, /** Whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow. */ @@ -56,6 +91,8 @@ export class OAuthApplication { data.client_uri, data.client_image_url, data.dynamically_registered, + data.client_id_metadata_document, + clientIdMetadataDocumentDetailsFromJSON(data.client_id_metadata_document_details), data.consent_screen_enabled, data.pkce_required, data.public, diff --git a/packages/backend/src/index.ts b/packages/backend/src/index.ts index 8ba5394c209..c1430816ead 100644 --- a/packages/backend/src/index.ts +++ b/packages/backend/src/index.ts @@ -79,6 +79,7 @@ export type { InvitationJSON, JwtTemplateJSON, OauthAccessTokenJSON, + OAuthApplicationClientIdMetadataDocumentDetailsJSON, OAuthApplicationJSON, OrganizationJSON, OrganizationDomainJSON, @@ -150,6 +151,7 @@ export type { M2MToken, OauthAccessToken, OAuthApplication, + OAuthApplicationClientIdMetadataDocumentDetails, Organization, OrganizationDomain, OrganizationDomainVerification, From a165f8cd2fbc1866c6e072f2fc9d702b4af5b7ef Mon Sep 17 00:00:00 2001 From: brkalow Date: Tue, 1 Dec 2026 13:12:34 -0600 Subject: [PATCH 2/8] docs(backend): Describe implicitly provisioned CIMD clients accurately Co-Authored-By: Claude Opus 5.5 --- packages/backend/src/api/endpoints/OAuthApplicationsApi.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts index da3c07e9c0a..fb78ad638db 100644 --- a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts +++ b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts @@ -33,14 +33,14 @@ export type CreateOAuthApplicationParams = }) | { /** - * The HTTPS URL of a [Client ID Metadata Document (CIMD)](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/), at most 512 bytes, with a path and without credentials or a fragment. Pre-registers the client the document describes, using the URL as its `clientId`. The metadata document defines the redirect URIs, and Clerk makes the client public with the consent screen and PKCE required. If the instance already has an implicitly allowed client for the URL, that client becomes pre-registered. Requires the new OAuth provider. + * The HTTPS URL of a [Client ID Metadata Document (CIMD)](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/), at most 512 bytes, with a path and without credentials or a fragment. Pre-registers the client the document describes, using the URL as its `clientId`. The metadata document defines the redirect URIs, and Clerk makes the client public with the consent screen and PKCE required. If the instance already has an implicitly provisioned client for the URL, including a blocked one, that client becomes pre-registered. Requires the new OAuth provider. */ clientIdMetadataDocumentUrl: string; /** * A descriptive name for the client. Maximum length: 256 characters. Defaults to the metadata document's `client_name`, or to the URL's host. */ name?: string; - /** Scopes for the client, separated by spaces. `offline_access` is always included. When omitted, a new client gets the default scopes, and a client that was implicitly allowed keeps its scopes. */ + /** Scopes for the client, separated by spaces. `offline_access` is always included. When omitted, a new client gets the default scopes, and an implicitly provisioned client that becomes pre-registered keeps its scopes. */ scopes?: string | null | undefined; redirectUris?: never; public?: never; @@ -121,7 +121,7 @@ export type GetOAuthApplicationListParams = ClerkPaginationRequest<{ */ orderBy?: WithSign<'name' | 'created_at'>; /** - * When `true`, returns only clients identified by a Client ID Metadata Document (CIMD), both pre-registered and implicitly allowed. When omitted or `false`, returns only regular OAuth applications. + * When `true`, returns only clients identified by a Client ID Metadata Document (CIMD), both pre-registered and implicitly provisioned, including blocked ones. When omitted or `false`, returns only regular OAuth applications. */ clientIdMetadataDocument?: boolean; }>; From 50bedab7226fbc949cfcf9228e32079b0bf6aebe Mon Sep 17 00:00:00 2001 From: brkalow Date: Tue, 1 Dec 2026 13:25:55 -0600 Subject: [PATCH 3/8] fix(repo): Mark union-only params optional in generated method docs The generated reference for `oauthApplications.create()` showed `clientIdMetadataDocumentUrl` as required and described `name` only for CIMD clients, so readers could not tell that a regular app needs a name and a CIMD client does not. The Typedoc method-page generator merges the arms of a union param type into one table but kept the required flag of whichever arm it picked, which also showed `organizationId` and `slug` as both required on `getOrganization()`, and the password-hashing fields as required on `createUser()` and `updateUser()`. Mark a merged property optional unless every union arm requires it, on a copy so pages that render the same reflection elsewhere keep their flag. Write the CIMD `name` and `scopes` docs to cover both kinds of app, and document on `update()` that `scopes` replaces the whole set and must keep required built-in scopes such as `offline_access`. Co-Authored-By: Claude Opus 5.5 --- .typedoc/__tests__/extract-methods.test.ts | 17 +++++++++ .typedoc/extract-methods.mjs | 38 ++++++++++++++++--- .../src/api/endpoints/OAuthApplicationsApi.ts | 8 ++-- 3 files changed, 54 insertions(+), 9 deletions(-) diff --git a/.typedoc/__tests__/extract-methods.test.ts b/.typedoc/__tests__/extract-methods.test.ts index 932395404b0..fc6ae87fe60 100644 --- a/.typedoc/__tests__/extract-methods.test.ts +++ b/.typedoc/__tests__/extract-methods.test.ts @@ -38,6 +38,23 @@ describe('extract-methods snapshots', () => { expect(content).not.toContain('revoke-session-params.mdx'); }); + it('marks union-merged params optional unless every arm requires them', async () => { + const createOAuthApplication = await readGenerated('backend/o-auth-applications-api/methods/create.mdx'); + expect(createOAuthApplication).toContain('| `clientIdMetadataDocumentUrl?` |'); + expect(createOAuthApplication).toContain('| `name?` |'); + expect(createOAuthApplication).not.toContain('`never`'); + + const getOrganization = await readGenerated('backend/organization-api/methods/get-organization.mdx'); + expect(getOrganization).toContain('| `organizationId?` |'); + expect(getOrganization).toContain('| `slug?` |'); + + const createUser = await readGenerated('backend/user-api/methods/create-user.mdx'); + expect(createUser).toContain('| `passwordDigest?` |'); + + const updateOAuthApplication = await readGenerated('backend/o-auth-applications-api/methods/update.mdx'); + expect(updateOAuthApplication).toContain('| `name` |'); + }); + it('simple callable: clerk.signOut()', async () => { const content = await readGenerated('shared/clerk/methods/sign-out.mdx'); await expect(content).toMatchFileSnapshot('./__snapshots__/clerk-methods-sign-out.mdx'); diff --git a/.typedoc/extract-methods.mjs b/.typedoc/extract-methods.mjs index d85f1e435ed..4a0766472e1 100644 --- a/.typedoc/extract-methods.mjs +++ b/.typedoc/extract-methods.mjs @@ -21,6 +21,8 @@ import { IntersectionType, OptionalType, ReferenceType, + ReflectionFlag, + ReflectionFlags, ReflectionKind, ReflectionType, UnionType, @@ -826,6 +828,22 @@ function collectLiteralStringKeys(t) { return undefined; } +/** + * Shallow copy of `prop` with the optional flag set, so marking a union-merged row optional does not change other pages that render the same reflection. + * + * @param {import('typedoc').DeclarationReflection} prop + * @returns {import('typedoc').DeclarationReflection} + */ +function withOptionalFlag(prop) { + if (prop.flags.isOptional) { + return prop; + } + const flags = new ReflectionFlags(); + flags.flags = prop.flags.flags; + flags.setFlag(ReflectionFlag.Optional, true); + return Object.assign(Object.create(Object.getPrototypeOf(prop)), prop, { flags }); +} + /** * Filter each arm to `Property` reflections and dedupe by name, returning a single sorted list * (or `undefined` if every arm was empty). Used for intersection / union / generic-instantiation @@ -833,16 +851,20 @@ function collectLiteralStringKeys(t) { * * Default behavior is "later arm wins" overwrite (right for intersections + generic instantiations * where every arm's properties are part of the final shape). For unions, set - * `{ skipNever: true, pickBetter: true }`: union arms often use `prop?: never` as a discriminator, - * so we drop those and keep the documentable branch when names collide. + * `{ skipNever: true, pickBetter: true, optionalUnlessRequiredInEveryArm: true }`: union arms often + * use `prop?: never` as a discriminator, so we drop those and keep the documentable branch when + * names collide. A property that some arm omits or makes optional, including an arm with no + * properties such as `object`, is not required by the union, so its merged row is marked optional. * * @param {Array} arms - * @param {{ skipNever?: boolean, pickBetter?: boolean }} [options] + * @param {{ skipNever?: boolean, pickBetter?: boolean, optionalUnlessRequiredInEveryArm?: boolean }} [options] * @returns {import('typedoc').DeclarationReflection[] | undefined} */ function mergePropertyArms(arms, options) { /** @type {Map} */ const byName = new Map(); + /** @type {Map} */ + const requiredArmCount = new Map(); for (const arm of arms) { if (!arm?.length) { continue; @@ -854,6 +876,9 @@ function mergePropertyArms(arms, options) { if (options?.skipNever && propertyReflectionTypeIsNever(c)) { continue; } + if (!c.flags.isOptional) { + requiredArmCount.set(c.name, (requiredArmCount.get(c.name) ?? 0) + 1); + } const existing = byName.get(c.name); if (!existing) { byName.set(c.name, c); @@ -865,7 +890,10 @@ function mergePropertyArms(arms, options) { if (byName.size === 0) { return undefined; } - const merged = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); + let merged = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); + if (options?.optionalUnlessRequiredInEveryArm) { + merged = merged.map(prop => ((requiredArmCount.get(prop.name) ?? 0) < arms.length ? withOptionalFlag(prop) : prop)); + } return substituteTypeParameterDefaultsInChildren(merged); } @@ -957,7 +985,7 @@ function resolveDeclarationWithObjectMembers(t, project) { const u = /** @type {import('typedoc').UnionType} */ (t); return mergePropertyArms( u.types.map(inner => resolveDeclarationWithObjectMembers(inner, project)), - { skipNever: true, pickBetter: true }, + { skipNever: true, pickBetter: true, optionalUnlessRequiredInEveryArm: true }, ); } return undefined; diff --git a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts index fb78ad638db..d9270b2aad1 100644 --- a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts +++ b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts @@ -37,17 +37,17 @@ export type CreateOAuthApplicationParams = */ clientIdMetadataDocumentUrl: string; /** - * A descriptive name for the client. Maximum length: 256 characters. Defaults to the metadata document's `client_name`, or to the URL's host. + * A descriptive name for the OAuth application (e.g., "My Web App", "My Mobile App"). Maximum length: 256 characters. Required unless `clientIdMetadataDocumentUrl` is set, in which case it defaults to the metadata document's `client_name`, or to the URL's host. */ name?: string; - /** Scopes for the client, separated by spaces. `offline_access` is always included. When omitted, a new client gets the default scopes, and an implicitly provisioned client that becomes pre-registered keeps its scopes. */ + /** Scopes for the OAuth application that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces. When `clientIdMetadataDocumentUrl` is set, `offline_access` is always included, and if `scopes` is omitted, a new client gets the default scopes and an implicitly provisioned client that becomes pre-registered keeps its scopes. */ scopes?: string | null | undefined; redirectUris?: never; public?: never; }; /** - * For a client identified by a Client ID Metadata Document (`clientIdMetadataDocument` is `true`), only `name` and `scopes` can be updated. + * The parameters for updating an OAuth application. For a client identified by a Client ID Metadata Document (`clientIdMetadataDocument` is `true`), only `name` and `scopes` can be updated. `scopes` replaces the complete scope set, so it must include required built-in scopes such as `offline_access`, otherwise the request is rejected. */ export type UpdateOAuthApplicationParams = OAuthApplicationParams & { /** The ID of the OAuth application to update. */ @@ -329,7 +329,7 @@ export class OAuthApplicationsApi extends AbstractAPI { } /** - * Updates the given OAuth application. For a client identified by a Client ID Metadata Document, only `name` and `scopes` can be updated. + * Updates the given OAuth application. For a client identified by a Client ID Metadata Document, only `name` and `scopes` can be updated. `scopes` replaces the complete scope set, so it must include required built-in scopes such as `offline_access`, otherwise the request is rejected. * @returns The updated [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object. */ public async update(params: UpdateOAuthApplicationParams) { From a5bc9b52c98845457d2e475eafa1348ad23c2153 Mon Sep 17 00:00:00 2001 From: brkalow Date: Tue, 1 Dec 2026 13:35:20 -0600 Subject: [PATCH 4/8] fix(repo): Correct union params on standalone type pages and scopes docs Staging testing showed the `update()` JSDoc was wrong: Clerk does not reject a `scopes` value that omits `offline_access`, it adds it back. The `scopes` descriptions also listed only four built-in scopes, though the API accepts custom scope keys. The standalone `CreateOAuthApplicationParams` page, linked from the main `OAuthApplicationsApi` page, still showed the CIMD URL as required and `redirectUris` and `public` typed `never`, because the theme merged union arms with last-arm-wins. Share one union merge rule between the method pages and the theme: ignore literal and primitive arms such as `null` or `false`, drop `never` discriminators, and mark a property optional unless every object-like arm requires it. This also fixes `never` rows on the sign-in-future params pages and either/or fields on `ClerkOptions` and plan-details props. `CreateOAuthApplicationParams` becomes `(regular | CIMD) & { scopes }` so each field has one description, and the `update()` JSDoc now says `offline_access` is always kept. Co-Authored-By: Claude Opus 5.5 --- .typedoc/__tests__/extract-methods.test.ts | 10 ++++ .typedoc/custom-theme.mjs | 21 +++++-- .typedoc/extract-methods.mjs | 58 +++++-------------- .typedoc/type-utils.mjs | 51 ++++++++++++++++ .../src/api/endpoints/OAuthApplicationsApi.ts | 28 ++++++--- 5 files changed, 109 insertions(+), 59 deletions(-) diff --git a/.typedoc/__tests__/extract-methods.test.ts b/.typedoc/__tests__/extract-methods.test.ts index fc6ae87fe60..b04fb9313f5 100644 --- a/.typedoc/__tests__/extract-methods.test.ts +++ b/.typedoc/__tests__/extract-methods.test.ts @@ -55,6 +55,16 @@ describe('extract-methods snapshots', () => { expect(updateOAuthApplication).toContain('| `name` |'); }); + it('marks union-merged properties optional on standalone type pages', async () => { + const createOAuthApplicationParams = await readGenerated('backend/create-o-auth-application-params.mdx'); + expect(createOAuthApplicationParams).toMatch(/\| `clientIdMetadataDocumentUrl\?` +\| `string`/); + expect(createOAuthApplicationParams).toMatch(/\| `redirectUris\?` +\| string\[\] \\\| null<\/code>/); + expect(createOAuthApplicationParams).not.toContain('`never`'); + + const getOrganizationParams = await readGenerated('backend/get-organization-params.mdx'); + expect(getOrganizationParams).toMatch(/\| `organizationId\?` +\|/); + }); + it('simple callable: clerk.signOut()', async () => { const content = await readGenerated('shared/clerk/methods/sign-out.mdx'); await expect(content).toMatchFileSnapshot('./__snapshots__/clerk-methods-sign-out.mdx'); diff --git a/.typedoc/custom-theme.mjs b/.typedoc/custom-theme.mjs index 1a7244848f2..63b863439d7 100644 --- a/.typedoc/custom-theme.mjs +++ b/.typedoc/custom-theme.mjs @@ -6,7 +6,12 @@ import { applyTodoStrippingToComment } from './comment-utils.mjs'; import { backTicks, heading, htmlTable, removeLineBreaks, table } from './markdown-helpers.mjs'; import { REFERENCE_OBJECTS_LIST } from './reference-objects.mjs'; import { isInlineModifierWithoutStandalonePage } from './standalone-page-tag.mjs'; -import { unwrapOptional } from './type-utils.mjs'; +import { + isObjectLikeUnionArm, + markOptionalUnlessRequiredInEveryArm, + propertyReflectionTypeIsNever, + unwrapOptional, +} from './type-utils.mjs'; export { REFERENCE_OBJECTS_LIST }; @@ -391,14 +396,20 @@ function collectPropertyReflectionsFromUnionObjectArms(t, visitedReflectionIds, return []; } const union = /** @type {import('typedoc').UnionType} */ (unwrapped); + const arms = union.types + .filter(isObjectLikeUnionArm) + .map(arm => collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project)); /** @type {Map} */ const byName = new Map(); - for (const arm of union.types) { - for (const p of collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project)) { - byName.set(p.name, p); + for (const arm of arms) { + for (const p of arm) { + if (!propertyReflectionTypeIsNever(p)) { + byName.set(p.name, p); + } } } - return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); + const merged = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); + return markOptionalUnlessRequiredInEveryArm(merged, arms); } /** diff --git a/.typedoc/extract-methods.mjs b/.typedoc/extract-methods.mjs index 4a0766472e1..d6c91bee07d 100644 --- a/.typedoc/extract-methods.mjs +++ b/.typedoc/extract-methods.mjs @@ -21,8 +21,6 @@ import { IntersectionType, OptionalType, ReferenceType, - ReflectionFlag, - ReflectionFlags, ReflectionKind, ReflectionType, UnionType, @@ -53,7 +51,12 @@ function methodFormatForPageUrl(pageUrl) { } import { toFileSlug } from './slug.mjs'; import { isInlineModifierWithoutStandalonePage } from './standalone-page-tag.mjs'; -import { unwrapOptional } from './type-utils.mjs'; +import { + isObjectLikeUnionArm, + markOptionalUnlessRequiredInEveryArm, + propertyReflectionTypeIsNever, + unwrapOptional, +} from './type-utils.mjs'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -771,14 +774,6 @@ function appendSignatureOnlyReturns(declComment, sigComment) { return formatReturnsLineFromTag(tag); } -/** - * @param {import('typedoc').DeclarationReflection} prop - */ -function propertyReflectionTypeIsNever(prop) { - const ty = unwrapOptional(prop.type, { deep: true }); - return ty?.type === 'intrinsic' && ty.name === 'never'; -} - /** * Union discriminators often use `otherProp?: never`. Prefer the branch with a documentable type. * @@ -828,22 +823,6 @@ function collectLiteralStringKeys(t) { return undefined; } -/** - * Shallow copy of `prop` with the optional flag set, so marking a union-merged row optional does not change other pages that render the same reflection. - * - * @param {import('typedoc').DeclarationReflection} prop - * @returns {import('typedoc').DeclarationReflection} - */ -function withOptionalFlag(prop) { - if (prop.flags.isOptional) { - return prop; - } - const flags = new ReflectionFlags(); - flags.flags = prop.flags.flags; - flags.setFlag(ReflectionFlag.Optional, true); - return Object.assign(Object.create(Object.getPrototypeOf(prop)), prop, { flags }); -} - /** * Filter each arm to `Property` reflections and dedupe by name, returning a single sorted list * (or `undefined` if every arm was empty). Used for intersection / union / generic-instantiation @@ -851,20 +830,16 @@ function withOptionalFlag(prop) { * * Default behavior is "later arm wins" overwrite (right for intersections + generic instantiations * where every arm's properties are part of the final shape). For unions, set - * `{ skipNever: true, pickBetter: true, optionalUnlessRequiredInEveryArm: true }`: union arms often - * use `prop?: never` as a discriminator, so we drop those and keep the documentable branch when - * names collide. A property that some arm omits or makes optional, including an arm with no - * properties such as `object`, is not required by the union, so its merged row is marked optional. + * `{ skipNever: true, pickBetter: true }`: union arms often use `prop?: never` as a discriminator, + * so we drop those and keep the documentable branch when names collide. * * @param {Array} arms - * @param {{ skipNever?: boolean, pickBetter?: boolean, optionalUnlessRequiredInEveryArm?: boolean }} [options] + * @param {{ skipNever?: boolean, pickBetter?: boolean }} [options] * @returns {import('typedoc').DeclarationReflection[] | undefined} */ function mergePropertyArms(arms, options) { /** @type {Map} */ const byName = new Map(); - /** @type {Map} */ - const requiredArmCount = new Map(); for (const arm of arms) { if (!arm?.length) { continue; @@ -876,9 +851,6 @@ function mergePropertyArms(arms, options) { if (options?.skipNever && propertyReflectionTypeIsNever(c)) { continue; } - if (!c.flags.isOptional) { - requiredArmCount.set(c.name, (requiredArmCount.get(c.name) ?? 0) + 1); - } const existing = byName.get(c.name); if (!existing) { byName.set(c.name, c); @@ -890,10 +862,7 @@ function mergePropertyArms(arms, options) { if (byName.size === 0) { return undefined; } - let merged = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); - if (options?.optionalUnlessRequiredInEveryArm) { - merged = merged.map(prop => ((requiredArmCount.get(prop.name) ?? 0) < arms.length ? withOptionalFlag(prop) : prop)); - } + const merged = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); return substituteTypeParameterDefaultsInChildren(merged); } @@ -983,10 +952,9 @@ function resolveDeclarationWithObjectMembers(t, project) { } if (t.type === 'union') { const u = /** @type {import('typedoc').UnionType} */ (t); - return mergePropertyArms( - u.types.map(inner => resolveDeclarationWithObjectMembers(inner, project)), - { skipNever: true, pickBetter: true, optionalUnlessRequiredInEveryArm: true }, - ); + const arms = u.types.filter(isObjectLikeUnionArm).map(inner => resolveDeclarationWithObjectMembers(inner, project)); + const merged = mergePropertyArms(arms, { skipNever: true, pickBetter: true }); + return merged && markOptionalUnlessRequiredInEveryArm(merged, arms); } return undefined; } diff --git a/.typedoc/type-utils.mjs b/.typedoc/type-utils.mjs index 38ba45c4e5f..09cbf6a25a6 100644 --- a/.typedoc/type-utils.mjs +++ b/.typedoc/type-utils.mjs @@ -1,5 +1,7 @@ // @ts-check — JSDoc-typed plugin helpers shared between custom-theme.mjs and extract-methods.mjs. +import { ReflectionFlag, ReflectionFlags } from 'typedoc'; + /** * Strip one (or, with `{ deep: true }`, all) `OptionalType` layers and return the inner type. Returns `t` unchanged when it isn't an `OptionalType`, or when `t` is nullish. * @@ -25,3 +27,52 @@ export function unwrapOptional(t, options) { } return cur; } + +/** + * @param {import('typedoc').DeclarationReflection} prop + */ +export function propertyReflectionTypeIsNever(prop) { + const ty = unwrapOptional(prop.type, { deep: true }); + return ty?.type === 'intrinsic' && ty.name === 'never'; +} + +/** + * Whether a union arm can contribute properties. Literal and primitive arms such as `null`, `undefined` or `false` make the whole value an alternative, not its properties optional. `object` counts, because it accepts a value without any of the other arms' properties. + * + * @param {import('typedoc').Type | import('typedoc').SomeType | undefined} t + */ +export function isObjectLikeUnionArm(t) { + const u = unwrapOptional(t); + if (!u) { + return false; + } + if (u.type === 'literal') { + return false; + } + if (u.type === 'intrinsic') { + return /** @type {import('typedoc').IntrinsicType} */ (u).name === 'object'; + } + return true; +} + +/** + * Mark each merged union property optional unless every object-like arm requires it. Optional rows are shallow copies, so other pages that render the same reflection keep its flag. + * + * @param {import('typedoc').DeclarationReflection[]} merged + * @param {Array} armProperties One entry per object-like union arm. + * @returns {import('typedoc').DeclarationReflection[]} + */ +export function markOptionalUnlessRequiredInEveryArm(merged, armProperties) { + return merged.map(prop => { + const requiredInEveryArm = armProperties.every(arm => + arm?.some(p => p.name === prop.name && !p.flags.isOptional && !propertyReflectionTypeIsNever(p)), + ); + if (requiredInEveryArm || prop.flags.isOptional) { + return prop; + } + const flags = new ReflectionFlags(); + flags.flags = prop.flags.flags; + flags.setFlag(ReflectionFlag.Optional, true); + return Object.assign(Object.create(Object.getPrototypeOf(prop)), prop, { flags }); + }); +} diff --git a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts index d9270b2aad1..83c26a8408a 100644 --- a/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts +++ b/packages/backend/src/api/endpoints/OAuthApplicationsApi.ts @@ -20,17 +20,25 @@ export type OAuthApplicationParams = { name: string; /** An array of redirect URIs for the OAuth application. */ redirectUris?: Array | null | undefined; - /** Scopes for the OAuth application that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces. */ + /** The scopes of the OAuth application, as a space-separated string of built-in scopes, such as `profile`, `email`, `public_metadata` and `private_metadata`, and custom scope keys from the instance's OAuth scope catalog. `offline_access` is always included. */ scopes?: string | null | undefined; /** Whether the OAuth application is public. If `true`, the Proof Key of Code Exchange (PKCE) flow can be used. */ public?: boolean | null | undefined; }; /** @generateWithEmptyComment */ -export type CreateOAuthApplicationParams = - | (OAuthApplicationParams & { +export type CreateOAuthApplicationParams = ( + | { + /** + * A descriptive name for the OAuth application (e.g., "My Web App", "My Mobile App"). Maximum length: 256 characters. Required unless `clientIdMetadataDocumentUrl` is set, in which case it defaults to the metadata document's `client_name`, or to the URL's host. + */ + name: string; + /** An array of redirect URIs for the OAuth application. Not allowed with `clientIdMetadataDocumentUrl`, because the metadata document defines the redirect URIs. */ + redirectUris?: Array | null | undefined; + /** Whether the OAuth application is public. If `true`, the Proof Key of Code Exchange (PKCE) flow can be used. Not allowed with `clientIdMetadataDocumentUrl`, because Clerk always makes those clients public. */ + public?: boolean | null | undefined; clientIdMetadataDocumentUrl?: never; - }) + } | { /** * The HTTPS URL of a [Client ID Metadata Document (CIMD)](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/), at most 512 bytes, with a path and without credentials or a fragment. Pre-registers the client the document describes, using the URL as its `clientId`. The metadata document defines the redirect URIs, and Clerk makes the client public with the consent screen and PKCE required. If the instance already has an implicitly provisioned client for the URL, including a blocked one, that client becomes pre-registered. Requires the new OAuth provider. @@ -40,14 +48,16 @@ export type CreateOAuthApplicationParams = * A descriptive name for the OAuth application (e.g., "My Web App", "My Mobile App"). Maximum length: 256 characters. Required unless `clientIdMetadataDocumentUrl` is set, in which case it defaults to the metadata document's `client_name`, or to the URL's host. */ name?: string; - /** Scopes for the OAuth application that dictate the user payload of the OAuth user info endpoint. Available scopes are `profile`, `email`, `public_metadata`, `private_metadata`. Provide the requested scopes as a string, separated by spaces. When `clientIdMetadataDocumentUrl` is set, `offline_access` is always included, and if `scopes` is omitted, a new client gets the default scopes and an implicitly provisioned client that becomes pre-registered keeps its scopes. */ - scopes?: string | null | undefined; redirectUris?: never; public?: never; - }; + } +) & { + /** The scopes of the OAuth application, as a space-separated string of built-in scopes, such as `profile`, `email`, `public_metadata` and `private_metadata`, and custom scope keys from the instance's OAuth scope catalog. `offline_access` is always included. When `clientIdMetadataDocumentUrl` is set and `scopes` is omitted, a new client gets the default scopes, and an implicitly provisioned client that becomes pre-registered keeps its scopes. */ + scopes?: string | null | undefined; +}; /** - * The parameters for updating an OAuth application. For a client identified by a Client ID Metadata Document (`clientIdMetadataDocument` is `true`), only `name` and `scopes` can be updated. `scopes` replaces the complete scope set, so it must include required built-in scopes such as `offline_access`, otherwise the request is rejected. + * The parameters for updating an OAuth application. For a client identified by a Client ID Metadata Document (`clientIdMetadataDocument` is `true`), only `name` and `scopes` can be updated. */ export type UpdateOAuthApplicationParams = OAuthApplicationParams & { /** The ID of the OAuth application to update. */ @@ -329,7 +339,7 @@ export class OAuthApplicationsApi extends AbstractAPI { } /** - * Updates the given OAuth application. For a client identified by a Client ID Metadata Document, only `name` and `scopes` can be updated. `scopes` replaces the complete scope set, so it must include required built-in scopes such as `offline_access`, otherwise the request is rejected. + * Updates the given OAuth application. For a client identified by a Client ID Metadata Document, only `name` and `scopes` can be updated. `scopes` replaces the complete scope set, and `offline_access` is always kept. For a CIMD client, an empty `scopes` resets it to the default scopes. * @returns The updated [`OAuthApplication`](https://clerk.com/docs/reference/backend/types/backend-oauth-application) object. */ public async update(params: UpdateOAuthApplicationParams) { From f2572dd71557ca81977b3b1e61459fe2f71576bb Mon Sep 17 00:00:00 2001 From: brkalow Date: Thu, 3 Dec 2026 11:36:35 -0500 Subject: [PATCH 5/8] fix(backend): Append CIMD fields to the OAuthApplication constructor Adding the CIMD fields in the middle of the `OAuthApplication` constructor shifted every later positional parameter, which Break Check reports as a breaking change in a minor release. Append them with defaults instead, as `User` does for `deprovisioned`. Also fix two cases in the generated docs' union merge. An arm whose properties TypeDoc leaves unresolved, such as an `Omit` reference, could make properties that every other arm requires look optional. And the copy made to mark a property optional dropped its non-enumerable `parent` and `project`. No generated page changes today. Co-Authored-By: Claude Opus 5.5 --- .typedoc/__tests__/type-utils.test.ts | 66 +++++++++++++++++++ .typedoc/custom-theme.mjs | 12 ++-- .typedoc/extract-methods.mjs | 8 ++- .typedoc/type-utils.mjs | 45 ++++++++++++- .../src/api/resources/OAuthApplication.ts | 12 ++-- 5 files changed, 125 insertions(+), 18 deletions(-) create mode 100644 .typedoc/__tests__/type-utils.test.ts diff --git a/.typedoc/__tests__/type-utils.test.ts b/.typedoc/__tests__/type-utils.test.ts new file mode 100644 index 00000000000..4e33bdf748b --- /dev/null +++ b/.typedoc/__tests__/type-utils.test.ts @@ -0,0 +1,66 @@ +import { DeclarationReflection, FileRegistry, ProjectReflection, ReflectionKind } from 'typedoc'; +import { describe, expect, it } from 'vitest'; + +import { collectUnionArms, markOptionalUnlessRequiredInEveryArm } from '../type-utils.mjs'; + +const project = new ProjectReflection('project', new FileRegistry()); +const parent = new DeclarationReflection('Params', ReflectionKind.TypeAlias, project); +const property = (name: string) => new DeclarationReflection(name, ReflectionKind.Property, parent); + +describe('union property merging', () => { + it('ignores an arm whose properties could not be collected', () => { + const strategy = property('strategy'); + const collected = { type: 'reference', name: 'EmailCodeConfig' }; + const unresolved = { type: 'reference', name: 'Omit' }; + const union = { type: 'union', types: [collected, unresolved] } as any; + + const { arms, requirednessArms } = collectUnionArms(union, t => (t === collected ? [strategy] : [])); + + expect(arms).toHaveLength(2); + expect(markOptionalUnlessRequiredInEveryArm([strategy], requirednessArms)[0].flags.isOptional).toBe(false); + }); + + it('ignores an intersection arm with an uncollected member', () => { + const strategy = property('strategy'); + const collected = { type: 'reference', name: 'EmailCodeConfig' }; + const unresolved = { type: 'reference', name: 'Omit' }; + const partial = { type: 'intersection', types: [{ type: 'reference', name: 'Other' }, unresolved] }; + const union = { type: 'union', types: [collected, partial] } as any; + + const { requirednessArms } = collectUnionArms(union, t => { + if (t === collected) { + return [strategy]; + } + return t === unresolved ? [] : [property('other')]; + }); + + expect(markOptionalUnlessRequiredInEveryArm([strategy], requirednessArms)[0].flags.isOptional).toBe(false); + }); + + it('treats `object` as an arm that requires nothing, and ignores null', () => { + const digest = property('passwordDigest'); + const hashing = { type: 'reference', name: 'UserPasswordHashingParams' }; + const collect = (t: unknown) => (t === hashing ? [digest] : []); + const withObject = { type: 'union', types: [hashing, { type: 'intrinsic', name: 'object' }] } as any; + const withNull = { type: 'union', types: [hashing, { type: 'literal', value: null }] } as any; + const isOptional = (union: any) => + markOptionalUnlessRequiredInEveryArm([digest], collectUnionArms(union, collect).requirednessArms)[0].flags + .isOptional; + + expect(isOptional(withObject)).toBe(true); + expect(isOptional(withNull)).toBe(false); + }); + + it('changes only the optional flag on the copy and leaves the original alone', () => { + const original = property('organizationId'); + + const [copy] = markOptionalUnlessRequiredInEveryArm([original], [[original], []]); + + expect(copy).not.toBe(original); + expect(copy.flags.isOptional).toBe(true); + expect(original.flags.isOptional).toBe(false); + expect(copy.parent).toBe(parent); + expect(copy.project).toBe(project); + expect(copy.getFullName()).toBe(original.getFullName()); + }); +}); diff --git a/.typedoc/custom-theme.mjs b/.typedoc/custom-theme.mjs index 63b863439d7..9b8d5d68fc0 100644 --- a/.typedoc/custom-theme.mjs +++ b/.typedoc/custom-theme.mjs @@ -7,7 +7,7 @@ import { backTicks, heading, htmlTable, removeLineBreaks, table } from './markdo import { REFERENCE_OBJECTS_LIST } from './reference-objects.mjs'; import { isInlineModifierWithoutStandalonePage } from './standalone-page-tag.mjs'; import { - isObjectLikeUnionArm, + collectUnionArms, markOptionalUnlessRequiredInEveryArm, propertyReflectionTypeIsNever, unwrapOptional, @@ -396,20 +396,20 @@ function collectPropertyReflectionsFromUnionObjectArms(t, visitedReflectionIds, return []; } const union = /** @type {import('typedoc').UnionType} */ (unwrapped); - const arms = union.types - .filter(isObjectLikeUnionArm) - .map(arm => collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project)); + const { arms, requirednessArms } = collectUnionArms(union, arm => + collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project), + ); /** @type {Map} */ const byName = new Map(); for (const arm of arms) { - for (const p of arm) { + for (const p of arm ?? []) { if (!propertyReflectionTypeIsNever(p)) { byName.set(p.name, p); } } } const merged = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); - return markOptionalUnlessRequiredInEveryArm(merged, arms); + return markOptionalUnlessRequiredInEveryArm(merged, requirednessArms); } /** diff --git a/.typedoc/extract-methods.mjs b/.typedoc/extract-methods.mjs index d6c91bee07d..6b47ac2db19 100644 --- a/.typedoc/extract-methods.mjs +++ b/.typedoc/extract-methods.mjs @@ -52,7 +52,7 @@ function methodFormatForPageUrl(pageUrl) { import { toFileSlug } from './slug.mjs'; import { isInlineModifierWithoutStandalonePage } from './standalone-page-tag.mjs'; import { - isObjectLikeUnionArm, + collectUnionArms, markOptionalUnlessRequiredInEveryArm, propertyReflectionTypeIsNever, unwrapOptional, @@ -952,9 +952,11 @@ function resolveDeclarationWithObjectMembers(t, project) { } if (t.type === 'union') { const u = /** @type {import('typedoc').UnionType} */ (t); - const arms = u.types.filter(isObjectLikeUnionArm).map(inner => resolveDeclarationWithObjectMembers(inner, project)); + const { arms, requirednessArms } = collectUnionArms(u, inner => + resolveDeclarationWithObjectMembers(inner, project), + ); const merged = mergePropertyArms(arms, { skipNever: true, pickBetter: true }); - return merged && markOptionalUnlessRequiredInEveryArm(merged, arms); + return merged && markOptionalUnlessRequiredInEveryArm(merged, requirednessArms); } return undefined; } diff --git a/.typedoc/type-utils.mjs b/.typedoc/type-utils.mjs index 09cbf6a25a6..90a8a3e96b1 100644 --- a/.typedoc/type-utils.mjs +++ b/.typedoc/type-utils.mjs @@ -41,7 +41,7 @@ export function propertyReflectionTypeIsNever(prop) { * * @param {import('typedoc').Type | import('typedoc').SomeType | undefined} t */ -export function isObjectLikeUnionArm(t) { +function isObjectLikeUnionArm(t) { const u = unwrapOptional(t); if (!u) { return false; @@ -55,11 +55,48 @@ export function isObjectLikeUnionArm(t) { return true; } +/** + * Whether `collect` sees every property of a union arm. It can miss some, for example an `Omit` reference TypeDoc leaves unresolved, and an arm with missing properties says nothing about which properties are required. + * + * @param {import('typedoc').Type | import('typedoc').SomeType} t + * @param {(t: any) => import('typedoc').DeclarationReflection[] | undefined} collect + * @returns {boolean} + */ +function isUnionArmCollected(t, collect) { + const u = unwrapOptional(t); + if (u.type === 'intersection') { + return /** @type {import('typedoc').IntersectionType} */ (u).types.every(inner => + isUnionArmCollected(inner, collect), + ); + } + if (u.type === 'reflection' || u.type === 'intrinsic') { + return true; + } + return Boolean(collect(u)?.length); +} + +/** + * Collect the properties of each object-like union arm. `arms` is every arm, for merging. `requirednessArms` leaves out arms whose properties could not all be collected, for {@link markOptionalUnlessRequiredInEveryArm}. + * + * @param {import('typedoc').UnionType} union + * @param {(t: any) => import('typedoc').DeclarationReflection[] | undefined} collect + */ +export function collectUnionArms(union, collect) { + const collected = union.types.filter(isObjectLikeUnionArm).map(t => ({ + properties: collect(t), + isCollected: isUnionArmCollected(t, collect), + })); + return { + arms: collected.map(arm => arm.properties), + requirednessArms: collected.filter(arm => arm.isCollected).map(arm => arm.properties), + }; +} + /** * Mark each merged union property optional unless every object-like arm requires it. Optional rows are shallow copies, so other pages that render the same reflection keep its flag. * * @param {import('typedoc').DeclarationReflection[]} merged - * @param {Array} armProperties One entry per object-like union arm. + * @param {Array} armProperties One entry per fully collected object-like union arm. * @returns {import('typedoc').DeclarationReflection[]} */ export function markOptionalUnlessRequiredInEveryArm(merged, armProperties) { @@ -73,6 +110,8 @@ export function markOptionalUnlessRequiredInEveryArm(merged, armProperties) { const flags = new ReflectionFlags(); flags.flags = prop.flags.flags; flags.setFlag(ReflectionFlag.Optional, true); - return Object.assign(Object.create(Object.getPrototypeOf(prop)), prop, { flags }); + const copy = Object.create(Object.getPrototypeOf(prop), Object.getOwnPropertyDescriptors(prop)); + copy.flags = flags; + return copy; }); } diff --git a/packages/backend/src/api/resources/OAuthApplication.ts b/packages/backend/src/api/resources/OAuthApplication.ts index de9fd42cc59..7f1402a2f3a 100644 --- a/packages/backend/src/api/resources/OAuthApplication.ts +++ b/packages/backend/src/api/resources/OAuthApplication.ts @@ -50,10 +50,6 @@ export class OAuthApplication { readonly clientImageUrl: string | null, /** Whether the OAuth application is dynamically registered. */ readonly dynamicallyRegistered: boolean, - /** Whether the `clientId` is the HTTPS URL of the client's Client ID Metadata Document (CIMD) rather than an identifier Clerk generated. CIMD clients are always public, with PKCE and the consent screen required. */ - readonly clientIdMetadataDocument: boolean, - /** The admission and metadata state of the client. `null` unless `clientIdMetadataDocument` is `true`. */ - readonly clientIdMetadataDocumentDetails: OAuthApplicationClientIdMetadataDocumentDetails | null, /** Whether the consent screen should be displayed in the authentication flow. Cannot be disabled for dynamically registered OAuth applications. */ readonly consentScreenEnabled: boolean, /** Whether the Proof Key of Code Exchange (PKCE) flow should be required in the authentication flow. */ @@ -80,6 +76,10 @@ export class OAuthApplication { readonly updatedAt: number, /** The client secret associated with the OAuth application. Empty if public client. */ readonly clientSecret?: string, + /** Whether the `clientId` is the HTTPS URL of the client's Client ID Metadata Document (CIMD) rather than an identifier Clerk generated. CIMD clients are always public, with PKCE and the consent screen required. */ + readonly clientIdMetadataDocument: boolean = false, + /** The admission and metadata state of the client. `null` unless `clientIdMetadataDocument` is `true`. */ + readonly clientIdMetadataDocumentDetails: OAuthApplicationClientIdMetadataDocumentDetails | null = null, ) {} static fromJSON(data: OAuthApplicationJSON) { @@ -91,8 +91,6 @@ export class OAuthApplication { data.client_uri, data.client_image_url, data.dynamically_registered, - data.client_id_metadata_document, - clientIdMetadataDocumentDetailsFromJSON(data.client_id_metadata_document_details), data.consent_screen_enabled, data.pkce_required, data.public, @@ -106,6 +104,8 @@ export class OAuthApplication { data.created_at, data.updated_at, data.client_secret, + data.client_id_metadata_document, + clientIdMetadataDocumentDetailsFromJSON(data.client_id_metadata_document_details), ); } } From 82c65d08359f47e1c142cbd242eb97a71094cc60 Mon Sep 17 00:00:00 2001 From: brkalow Date: Thu, 3 Dec 2026 11:49:58 -0500 Subject: [PATCH 6/8] fix(repo): Collect each union arm once and count resolved empty arms The generated docs' union merge treated an arm that resolved to no properties, such as `Omit` where `x` is the only property, as unresolved, so the other arm's properties could look required when they are not. It also collected every reference arm twice, which doubles the work at each level of nested unions. Collect each arm and intersection member once, and leave an arm out only when a member could not be resolved. No generated page changes today. Co-Authored-By: Claude Opus 5.5 --- .typedoc/__tests__/type-utils.test.ts | 31 ++++++++++++++++++--- .typedoc/custom-theme.mjs | 9 +++--- .typedoc/type-utils.mjs | 40 ++++++++++++++------------- 3 files changed, 53 insertions(+), 27 deletions(-) diff --git a/.typedoc/__tests__/type-utils.test.ts b/.typedoc/__tests__/type-utils.test.ts index 4e33bdf748b..9a04a89a705 100644 --- a/.typedoc/__tests__/type-utils.test.ts +++ b/.typedoc/__tests__/type-utils.test.ts @@ -1,5 +1,5 @@ import { DeclarationReflection, FileRegistry, ProjectReflection, ReflectionKind } from 'typedoc'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { collectUnionArms, markOptionalUnlessRequiredInEveryArm } from '../type-utils.mjs'; @@ -14,7 +14,7 @@ describe('union property merging', () => { const unresolved = { type: 'reference', name: 'Omit' }; const union = { type: 'union', types: [collected, unresolved] } as any; - const { arms, requirednessArms } = collectUnionArms(union, t => (t === collected ? [strategy] : [])); + const { arms, requirednessArms } = collectUnionArms(union, t => (t === collected ? [strategy] : undefined)); expect(arms).toHaveLength(2); expect(markOptionalUnlessRequiredInEveryArm([strategy], requirednessArms)[0].flags.isOptional).toBe(false); @@ -31,16 +31,39 @@ describe('union property merging', () => { if (t === collected) { return [strategy]; } - return t === unresolved ? [] : [property('other')]; + return t === unresolved ? undefined : [property('other')]; }); expect(markOptionalUnlessRequiredInEveryArm([strategy], requirednessArms)[0].flags.isOptional).toBe(false); }); + it('counts an arm that resolved to no properties', () => { + const x = property('x'); + const base = { type: 'reference', name: 'X' }; + const omitted = { type: 'reference', name: 'Omit' }; + const union = { type: 'union', types: [base, omitted] } as any; + + const { requirednessArms } = collectUnionArms(union, t => (t === base ? [x] : [])); + + expect(markOptionalUnlessRequiredInEveryArm([x], requirednessArms)[0].flags.isOptional).toBe(true); + }); + + it('collects each arm and intersection member once', () => { + const a = { type: 'reference', name: 'A' }; + const b = { type: 'reference', name: 'B' }; + const c = { type: 'reference', name: 'C' }; + const union = { type: 'union', types: [a, { type: 'intersection', types: [b, c] }] } as any; + const collect = vi.fn(() => [property('x')]); + + collectUnionArms(union, collect); + + expect(collect.mock.calls).toEqual([[a], [b], [c]]); + }); + it('treats `object` as an arm that requires nothing, and ignores null', () => { const digest = property('passwordDigest'); const hashing = { type: 'reference', name: 'UserPasswordHashingParams' }; - const collect = (t: unknown) => (t === hashing ? [digest] : []); + const collect = (t: unknown) => (t === hashing ? [digest] : undefined); const withObject = { type: 'union', types: [hashing, { type: 'intrinsic', name: 'object' }] } as any; const withNull = { type: 'union', types: [hashing, { type: 'literal', value: null }] } as any; const isOptional = (union: any) => diff --git a/.typedoc/custom-theme.mjs b/.typedoc/custom-theme.mjs index 9b8d5d68fc0..b223bdf53cb 100644 --- a/.typedoc/custom-theme.mjs +++ b/.typedoc/custom-theme.mjs @@ -396,13 +396,14 @@ function collectPropertyReflectionsFromUnionObjectArms(t, visitedReflectionIds, return []; } const union = /** @type {import('typedoc').UnionType} */ (unwrapped); - const { arms, requirednessArms } = collectUnionArms(union, arm => - collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project), - ); + const { arms, requirednessArms } = collectUnionArms(union, arm => { + const properties = collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project); + return properties.length ? properties : undefined; + }); /** @type {Map} */ const byName = new Map(); for (const arm of arms) { - for (const p of arm ?? []) { + for (const p of arm) { if (!propertyReflectionTypeIsNever(p)) { byName.set(p.name, p); } diff --git a/.typedoc/type-utils.mjs b/.typedoc/type-utils.mjs index 90a8a3e96b1..52b9c6727b6 100644 --- a/.typedoc/type-utils.mjs +++ b/.typedoc/type-utils.mjs @@ -56,39 +56,41 @@ function isObjectLikeUnionArm(t) { } /** - * Whether `collect` sees every property of a union arm. It can miss some, for example an `Omit` reference TypeDoc leaves unresolved, and an arm with missing properties says nothing about which properties are required. + * Collect one union arm, visiting each intersection member once. An arm is complete when every member resolved. * * @param {import('typedoc').Type | import('typedoc').SomeType} t * @param {(t: any) => import('typedoc').DeclarationReflection[] | undefined} collect - * @returns {boolean} + * @returns {{ properties: import('typedoc').DeclarationReflection[], isComplete: boolean }} */ -function isUnionArmCollected(t, collect) { +function collectUnionArm(t, collect) { const u = unwrapOptional(t); if (u.type === 'intersection') { - return /** @type {import('typedoc').IntersectionType} */ (u).types.every(inner => - isUnionArmCollected(inner, collect), + const members = /** @type {import('typedoc').IntersectionType} */ (u).types.map(inner => + collectUnionArm(inner, collect), ); + return { + properties: members.flatMap(member => member.properties), + isComplete: members.every(member => member.isComplete), + }; } - if (u.type === 'reflection' || u.type === 'intrinsic') { - return true; - } - return Boolean(collect(u)?.length); + const properties = collect(u); + return { + properties: properties ?? [], + isComplete: properties !== undefined || u.type === 'reflection' || u.type === 'intrinsic', + }; } /** - * Collect the properties of each object-like union arm. `arms` is every arm, for merging. `requirednessArms` leaves out arms whose properties could not all be collected, for {@link markOptionalUnlessRequiredInEveryArm}. + * Collect the properties of each object-like union arm. `arms` is every arm, for merging. `requirednessArms` leaves out arms with a member that could not be resolved, for {@link markOptionalUnlessRequiredInEveryArm}: an `Omit` reference TypeDoc leaves unresolved says nothing about which properties are required. * * @param {import('typedoc').UnionType} union - * @param {(t: any) => import('typedoc').DeclarationReflection[] | undefined} collect + * @param {(t: any) => import('typedoc').DeclarationReflection[] | undefined} collect Returns `undefined` for a type it cannot resolve, and an empty list for one it resolved to no properties. */ export function collectUnionArms(union, collect) { - const collected = union.types.filter(isObjectLikeUnionArm).map(t => ({ - properties: collect(t), - isCollected: isUnionArmCollected(t, collect), - })); + const collected = union.types.filter(isObjectLikeUnionArm).map(t => collectUnionArm(t, collect)); return { - arms: collected.map(arm => arm.properties), - requirednessArms: collected.filter(arm => arm.isCollected).map(arm => arm.properties), + arms: collected.map(arm => [...new Map(arm.properties.map(p => [p.name, p])).values()]), + requirednessArms: collected.filter(arm => arm.isComplete).map(arm => arm.properties), }; } @@ -96,13 +98,13 @@ export function collectUnionArms(union, collect) { * Mark each merged union property optional unless every object-like arm requires it. Optional rows are shallow copies, so other pages that render the same reflection keep its flag. * * @param {import('typedoc').DeclarationReflection[]} merged - * @param {Array} armProperties One entry per fully collected object-like union arm. + * @param {import('typedoc').DeclarationReflection[][]} armProperties One entry per fully collected object-like union arm. * @returns {import('typedoc').DeclarationReflection[]} */ export function markOptionalUnlessRequiredInEveryArm(merged, armProperties) { return merged.map(prop => { const requiredInEveryArm = armProperties.every(arm => - arm?.some(p => p.name === prop.name && !p.flags.isOptional && !propertyReflectionTypeIsNever(p)), + arm.some(p => p.name === prop.name && !p.flags.isOptional && !propertyReflectionTypeIsNever(p)), ); if (requiredInEveryArm || prop.flags.isOptional) { return prop; From a192e9e25cf0dbb4ba9b329354dd9f60393fb22f Mon Sep 17 00:00:00 2001 From: brkalow Date: Thu, 3 Dec 2026 11:59:40 -0500 Subject: [PATCH 7/8] fix(repo): Count empty declarations as resolved union arms In the generated docs, a union such as `{ a: string } | EmptyInterface` showed `a` as required, because both property collectors report an empty declaration the same way as a reference they cannot resolve. Check whether TypeDoc resolved the arm's declaration, so an empty one counts toward what is optional. No generated page changes today. Co-Authored-By: Claude Opus 5.5 --- .typedoc/__tests__/type-utils.test.ts | 30 +++++++++++++++++++++- .typedoc/type-utils.mjs | 37 +++++++++++++++++++++++++-- 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/.typedoc/__tests__/type-utils.test.ts b/.typedoc/__tests__/type-utils.test.ts index 9a04a89a705..948030864e4 100644 --- a/.typedoc/__tests__/type-utils.test.ts +++ b/.typedoc/__tests__/type-utils.test.ts @@ -1,4 +1,11 @@ -import { DeclarationReflection, FileRegistry, ProjectReflection, ReflectionKind } from 'typedoc'; +import { + DeclarationReflection, + FileRegistry, + ProjectReflection, + ReferenceType, + ReflectionKind, + ReflectionType, +} from 'typedoc'; import { describe, expect, it, vi } from 'vitest'; import { collectUnionArms, markOptionalUnlessRequiredInEveryArm } from '../type-utils.mjs'; @@ -48,6 +55,27 @@ describe('union property merging', () => { expect(markOptionalUnlessRequiredInEveryArm([x], requirednessArms)[0].flags.isOptional).toBe(true); }); + it.each([ + ['an empty interface', ReflectionKind.Interface], + ['an alias of an empty object type', ReflectionKind.TypeAlias], + ])('counts %s that the collector reports as undefined', (_, kind) => { + const a = property('a'); + const empty = new DeclarationReflection('Empty', kind, project); + project.registerReflection(empty, undefined, undefined); + if (kind === ReflectionKind.TypeAlias) { + empty.type = new ReflectionType(new DeclarationReflection('__type', ReflectionKind.TypeLiteral, empty)); + } + const base = { type: 'reference', name: 'A' }; + const union = { + type: 'union', + types: [base, ReferenceType.createResolvedReference('Empty', empty, project)], + } as any; + + const { requirednessArms } = collectUnionArms(union, t => (t === base ? [a] : undefined)); + + expect(markOptionalUnlessRequiredInEveryArm([a], requirednessArms)[0].flags.isOptional).toBe(true); + }); + it('collects each arm and intersection member once', () => { const a = { type: 'reference', name: 'A' }; const b = { type: 'reference', name: 'B' }; diff --git a/.typedoc/type-utils.mjs b/.typedoc/type-utils.mjs index 52b9c6727b6..35a82088448 100644 --- a/.typedoc/type-utils.mjs +++ b/.typedoc/type-utils.mjs @@ -1,6 +1,6 @@ // @ts-check — JSDoc-typed plugin helpers shared between custom-theme.mjs and extract-methods.mjs. -import { ReflectionFlag, ReflectionFlags } from 'typedoc'; +import { ReflectionFlag, ReflectionFlags, ReflectionKind } from 'typedoc'; /** * Strip one (or, with `{ deep: true }`, all) `OptionalType` layers and return the inner type. Returns `t` unchanged when it isn't an `OptionalType`, or when `t` is nullish. @@ -55,6 +55,39 @@ function isObjectLikeUnionArm(t) { return true; } +/** + * Whether `t` is an object type TypeDoc resolved, even if it declares no properties. Collectors report an empty interface the same way as a reference they cannot resolve, so this tells the two apart. + * + * @param {import('typedoc').Type | import('typedoc').SomeType | undefined} t + * @param {Set} [visitedIds] + * @returns {boolean} + */ +function isResolvedObjectType(t, visitedIds = new Set()) { + const u = unwrapOptional(t); + if (!u) { + return false; + } + if (u.type === 'reflection') { + return true; + } + if (u.type === 'intrinsic') { + return /** @type {import('typedoc').IntrinsicType} */ (u).name === 'object'; + } + if (u.type !== 'reference') { + return false; + } + const decl = /** @type {import('typedoc').DeclarationReflection | undefined} */ ( + /** @type {import('typedoc').ReferenceType} */ (u).reflection + ); + if (!decl || visitedIds.has(decl.id)) { + return false; + } + if (decl.kind === ReflectionKind.Interface || decl.kind === ReflectionKind.Class) { + return true; + } + return isResolvedObjectType(decl.type, new Set([...visitedIds, decl.id])); +} + /** * Collect one union arm, visiting each intersection member once. An arm is complete when every member resolved. * @@ -76,7 +109,7 @@ function collectUnionArm(t, collect) { const properties = collect(u); return { properties: properties ?? [], - isComplete: properties !== undefined || u.type === 'reflection' || u.type === 'intrinsic', + isComplete: properties !== undefined || isResolvedObjectType(u), }; } From d9d6c9b947b35fb89fe203e5cc594c3e03b72177 Mon Sep 17 00:00:00 2001 From: brkalow Date: Thu, 3 Dec 2026 12:05:13 -0500 Subject: [PATCH 8/8] fix(repo): Avoid marking optional params required in generated docs The generated SDK reference can tell developers that a parameter is required when it is optional. This happens when a parameter's type is a union and one alternative is an empty interface, as in `{ a: string } | EmptyInterface`: callers may omit `a`, because the empty interface does not need it. If TypeDoc does not link to that interface directly, the page generators find it by name, but the code deciding which properties are optional did not, so it ignored the interface. That code now finds types the same way the page generators do. No published page has this problem today: the generated docs are unchanged, and this keeps a future type from triggering it. Co-Authored-By: Claude Opus 5.5 --- .typedoc/__tests__/type-utils.test.ts | 51 ++++++++++++++++++++------- .typedoc/custom-theme.mjs | 12 ++++--- .typedoc/extract-methods.mjs | 6 ++-- .typedoc/type-utils.mjs | 20 ++++++----- 4 files changed, 63 insertions(+), 26 deletions(-) diff --git a/.typedoc/__tests__/type-utils.test.ts b/.typedoc/__tests__/type-utils.test.ts index 948030864e4..358bf5a00f8 100644 --- a/.typedoc/__tests__/type-utils.test.ts +++ b/.typedoc/__tests__/type-utils.test.ts @@ -12,6 +12,7 @@ import { collectUnionArms, markOptionalUnlessRequiredInEveryArm } from '../type- const project = new ProjectReflection('project', new FileRegistry()); const parent = new DeclarationReflection('Params', ReflectionKind.TypeAlias, project); +const findNothing = () => undefined; const property = (name: string) => new DeclarationReflection(name, ReflectionKind.Property, parent); describe('union property merging', () => { @@ -21,7 +22,11 @@ describe('union property merging', () => { const unresolved = { type: 'reference', name: 'Omit' }; const union = { type: 'union', types: [collected, unresolved] } as any; - const { arms, requirednessArms } = collectUnionArms(union, t => (t === collected ? [strategy] : undefined)); + const { arms, requirednessArms } = collectUnionArms( + union, + t => (t === collected ? [strategy] : undefined), + findNothing, + ); expect(arms).toHaveLength(2); expect(markOptionalUnlessRequiredInEveryArm([strategy], requirednessArms)[0].flags.isOptional).toBe(false); @@ -34,12 +39,16 @@ describe('union property merging', () => { const partial = { type: 'intersection', types: [{ type: 'reference', name: 'Other' }, unresolved] }; const union = { type: 'union', types: [collected, partial] } as any; - const { requirednessArms } = collectUnionArms(union, t => { - if (t === collected) { - return [strategy]; - } - return t === unresolved ? undefined : [property('other')]; - }); + const { requirednessArms } = collectUnionArms( + union, + t => { + if (t === collected) { + return [strategy]; + } + return t === unresolved ? undefined : [property('other')]; + }, + findNothing, + ); expect(markOptionalUnlessRequiredInEveryArm([strategy], requirednessArms)[0].flags.isOptional).toBe(false); }); @@ -50,7 +59,7 @@ describe('union property merging', () => { const omitted = { type: 'reference', name: 'Omit' }; const union = { type: 'union', types: [base, omitted] } as any; - const { requirednessArms } = collectUnionArms(union, t => (t === base ? [x] : [])); + const { requirednessArms } = collectUnionArms(union, t => (t === base ? [x] : []), findNothing); expect(markOptionalUnlessRequiredInEveryArm([x], requirednessArms)[0].flags.isOptional).toBe(true); }); @@ -71,11 +80,29 @@ describe('union property merging', () => { types: [base, ReferenceType.createResolvedReference('Empty', empty, project)], } as any; - const { requirednessArms } = collectUnionArms(union, t => (t === base ? [a] : undefined)); + const { requirednessArms } = collectUnionArms(union, t => (t === base ? [a] : undefined), findNothing); expect(markOptionalUnlessRequiredInEveryArm([a], requirednessArms)[0].flags.isOptional).toBe(true); }); + it.each([ + ['counts an empty declaration found by name', true], + ['ignores a reference not found by name', false], + ])('%s', (_, isFound) => { + const a = property('a'); + const empty = new DeclarationReflection('EmptyByName', ReflectionKind.Interface, project); + const base = { type: 'reference', name: 'A' }; + const union = { type: 'union', types: [base, { type: 'reference', name: 'EmptyByName' }] } as any; + + const { requirednessArms } = collectUnionArms( + union, + t => (t === base ? [a] : undefined), + name => (isFound && name === 'EmptyByName' ? empty : undefined), + ); + + expect(markOptionalUnlessRequiredInEveryArm([a], requirednessArms)[0].flags.isOptional).toBe(isFound); + }); + it('collects each arm and intersection member once', () => { const a = { type: 'reference', name: 'A' }; const b = { type: 'reference', name: 'B' }; @@ -83,7 +110,7 @@ describe('union property merging', () => { const union = { type: 'union', types: [a, { type: 'intersection', types: [b, c] }] } as any; const collect = vi.fn(() => [property('x')]); - collectUnionArms(union, collect); + collectUnionArms(union, collect, findNothing); expect(collect.mock.calls).toEqual([[a], [b], [c]]); }); @@ -95,8 +122,8 @@ describe('union property merging', () => { const withObject = { type: 'union', types: [hashing, { type: 'intrinsic', name: 'object' }] } as any; const withNull = { type: 'union', types: [hashing, { type: 'literal', value: null }] } as any; const isOptional = (union: any) => - markOptionalUnlessRequiredInEveryArm([digest], collectUnionArms(union, collect).requirednessArms)[0].flags - .isOptional; + markOptionalUnlessRequiredInEveryArm([digest], collectUnionArms(union, collect, findNothing).requirednessArms)[0] + .flags.isOptional; expect(isOptional(withObject)).toBe(true); expect(isOptional(withNull)).toBe(false); diff --git a/.typedoc/custom-theme.mjs b/.typedoc/custom-theme.mjs index b223bdf53cb..1e2635a462c 100644 --- a/.typedoc/custom-theme.mjs +++ b/.typedoc/custom-theme.mjs @@ -396,10 +396,14 @@ function collectPropertyReflectionsFromUnionObjectArms(t, visitedReflectionIds, return []; } const union = /** @type {import('typedoc').UnionType} */ (unwrapped); - const { arms, requirednessArms } = collectUnionArms(union, arm => { - const properties = collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project); - return properties.length ? properties : undefined; - }); + const { arms, requirednessArms } = collectUnionArms( + union, + arm => { + const properties = collectPropertyReflectionsFromIntersectionArm(arm, visitedReflectionIds, project); + return properties.length ? properties : undefined; + }, + name => (project ? findNamedTypeDeclaration(project, name) : undefined), + ); /** @type {Map} */ const byName = new Map(); for (const arm of arms) { diff --git a/.typedoc/extract-methods.mjs b/.typedoc/extract-methods.mjs index 6b47ac2db19..1062c790b31 100644 --- a/.typedoc/extract-methods.mjs +++ b/.typedoc/extract-methods.mjs @@ -952,8 +952,10 @@ function resolveDeclarationWithObjectMembers(t, project) { } if (t.type === 'union') { const u = /** @type {import('typedoc').UnionType} */ (t); - const { arms, requirednessArms } = collectUnionArms(u, inner => - resolveDeclarationWithObjectMembers(inner, project), + const { arms, requirednessArms } = collectUnionArms( + u, + inner => resolveDeclarationWithObjectMembers(inner, project), + name => (project ? lookupInterfaceOrTypeAliasByName(project, name) : undefined), ); const merged = mergePropertyArms(arms, { skipNever: true, pickBetter: true }); return merged && markOptionalUnlessRequiredInEveryArm(merged, requirednessArms); diff --git a/.typedoc/type-utils.mjs b/.typedoc/type-utils.mjs index 35a82088448..45d4d1d1ebb 100644 --- a/.typedoc/type-utils.mjs +++ b/.typedoc/type-utils.mjs @@ -59,10 +59,11 @@ function isObjectLikeUnionArm(t) { * Whether `t` is an object type TypeDoc resolved, even if it declares no properties. Collectors report an empty interface the same way as a reference they cannot resolve, so this tells the two apart. * * @param {import('typedoc').Type | import('typedoc').SomeType | undefined} t + * @param {(name: string) => import('typedoc').DeclarationReflection | undefined} findDeclaration * @param {Set} [visitedIds] * @returns {boolean} */ -function isResolvedObjectType(t, visitedIds = new Set()) { +function isResolvedObjectType(t, findDeclaration, visitedIds = new Set()) { const u = unwrapOptional(t); if (!u) { return false; @@ -76,8 +77,9 @@ function isResolvedObjectType(t, visitedIds = new Set()) { if (u.type !== 'reference') { return false; } + const ref = /** @type {import('typedoc').ReferenceType} */ (u); const decl = /** @type {import('typedoc').DeclarationReflection | undefined} */ ( - /** @type {import('typedoc').ReferenceType} */ (u).reflection + ref.reflection ?? findDeclaration(ref.name) ); if (!decl || visitedIds.has(decl.id)) { return false; @@ -85,7 +87,7 @@ function isResolvedObjectType(t, visitedIds = new Set()) { if (decl.kind === ReflectionKind.Interface || decl.kind === ReflectionKind.Class) { return true; } - return isResolvedObjectType(decl.type, new Set([...visitedIds, decl.id])); + return isResolvedObjectType(decl.type, findDeclaration, new Set([...visitedIds, decl.id])); } /** @@ -93,13 +95,14 @@ function isResolvedObjectType(t, visitedIds = new Set()) { * * @param {import('typedoc').Type | import('typedoc').SomeType} t * @param {(t: any) => import('typedoc').DeclarationReflection[] | undefined} collect + * @param {(name: string) => import('typedoc').DeclarationReflection | undefined} findDeclaration * @returns {{ properties: import('typedoc').DeclarationReflection[], isComplete: boolean }} */ -function collectUnionArm(t, collect) { +function collectUnionArm(t, collect, findDeclaration) { const u = unwrapOptional(t); if (u.type === 'intersection') { const members = /** @type {import('typedoc').IntersectionType} */ (u).types.map(inner => - collectUnionArm(inner, collect), + collectUnionArm(inner, collect, findDeclaration), ); return { properties: members.flatMap(member => member.properties), @@ -109,7 +112,7 @@ function collectUnionArm(t, collect) { const properties = collect(u); return { properties: properties ?? [], - isComplete: properties !== undefined || isResolvedObjectType(u), + isComplete: properties !== undefined || isResolvedObjectType(u, findDeclaration), }; } @@ -118,9 +121,10 @@ function collectUnionArm(t, collect) { * * @param {import('typedoc').UnionType} union * @param {(t: any) => import('typedoc').DeclarationReflection[] | undefined} collect Returns `undefined` for a type it cannot resolve, and an empty list for one it resolved to no properties. + * @param {(name: string) => import('typedoc').DeclarationReflection | undefined} findDeclaration The lookup `collect` uses when a reference has no `reflection`. */ -export function collectUnionArms(union, collect) { - const collected = union.types.filter(isObjectLikeUnionArm).map(t => collectUnionArm(t, collect)); +export function collectUnionArms(union, collect, findDeclaration) { + const collected = union.types.filter(isObjectLikeUnionArm).map(t => collectUnionArm(t, collect, findDeclaration)); return { arms: collected.map(arm => [...new Map(arm.properties.map(p => [p.name, p])).values()]), requirednessArms: collected.filter(arm => arm.isComplete).map(arm => arm.properties),