{"version":3,"file":"plugin-DIyUV1MX.mjs","names":["buildHiddenParams","articleFor","yamlLoad","buildExportedClassNameSet","resolveServiceTarget","className","fileName","fieldName","servicePropertyName","resolveClassName","buildExportedClassNameSet","buildExportedClassNameSetShared","resolveServiceTarget","resolveServiceTargetShared","resolveServiceDir","resolveMethodName","mapTypeRef","irMapTypeRef","mapPrimitive","parenthesizeUnion","joinUnionVariants","operationOverrideFor","path","fs","walk","docComment","mapTypeRef","resolveServiceDir","fileName","resolveMethodName","fieldName","generateEnums","resolveServiceDir","fileName","docComment","assignModelsToServices","fileName","deserializeExpression","tsMapTypeRef","fieldName","fieldName","generateWrapperMethods","collectWrapperResponseModels","emitWrapperMethod","fieldName","mapTypeRef","tsLiteral","clientFieldExpression","buildPathStr","fileName","resolveResourceClassName","resolveServiceTarget","buildExportedClassNameSet","resolveServiceDir","baselineMethodFor","optionsObjectParam","methodOptionsName","operationOverrideFor","autoPaginatableItemType","singularize","resolveMethodName","docComment","fieldName","generateResources","unwrapListModel","collectWrapperResponseModels","renderMethod","generateWrapperMethods","resolveOptionsObjectField","mapTypeRef","clientFieldExpression","renderUrlBuilderMethod","ID_PREFIXES","generateFixtures","assignModelsToServices","resolveServiceDir","fileName","generateModelFixture","resolveResourceClassName","unwrapListModel","generateFieldValue","generatePrimitiveValue","fileName","generateModels","collectFieldDependencies","fieldName","docComment","mapTypeRef","resolveResourceClassName","resolveMethodName","unwrapListModel","collectWrapperResponseModels","generateClient","generateWorkOSClient","resolveResourceClassName","fileName","docComment","servicePropertyName","resolveResourceClassName","generateTests","generateFixtures","servicePropertyName","fileName","generateServiceTest","resolveMethodName","unwrapListModel","fieldName","buildExpectedPath","ID_PREFIXES","assignModelsToServices","resolveServiceDir","singularize","collectImports","fileName","fs","path","resolveResourceClassName","fileName","assignModelsToServices","generateEnumFiles","generateResources","generateClient","generateTestFiles","className","fileName","fieldName","domainFieldName","safeParamName","moduleName","servicePropertyName","resolveMethodName","buildExportedClassNameSet","buildExportedClassNameSetShared","resolveServiceTarget","resolveServiceTargetShared","resolveClassName","buildMountDirMap","mapTypeRef","irMapTypeRef","mapPrimitive","className","joinUnionVariants","toPythonLiteral","fileName","buildRecursiveHashMap","generateEnums","buildMountDirMap","fileName","className","generateModels","buildMountDirMap","className","fileName","domainFieldName","isDateTimeType","mapTypeRef","fieldName","emitWrapperMethod","fieldName","className","clientFieldExpression","fieldName","resolveResourceClassName","resolveClassName","buildHiddenParamsShared","groupVariantClassName","className","isRedirectEndpoint","buildPathString","clientFieldExpression","generateResources","buildMountDirMap","buildExportedClassNameSet","moduleName","resolveServiceTarget","fileName","generateClient","deduplicateByMount","buildServiceAccessPaths","servicePropertyName","resolveResourceClassName","buildMountDirMap","buildExportedClassNameSet","className","resolveServiceTarget","ID_PREFIXES","generateFixtures","fileName","generateModelFixture","unwrapListModel","domainFieldName","generateFieldValue","generatePrimitiveValue","className","generateModelFixture","isRedirectEndpoint","generateTests","generateFixtures","buildServiceAccessPaths","resolveResourceClassName","generateServiceTest","buildMountDirMap","moduleName","buildHiddenParams","resolveMethodName","fileName","buildTestArgs","buildExpectedPath","generateTestValue","emitWrapperTests","fieldName","domainFieldName","buildOperationsMap","buildServiceAccessPaths","resolveMethodName","ensureTrailingNewlines","generateModels","generateEnums","generateResources","generateClient","generateTests","buildOperationsMap","className","resolveEnumName","buildExportedClassNameSet","buildExportedClassNameSetShared","resolveServiceTarget","resolveServiceTargetShared","resolveMethodName","fieldName","domainFieldName","servicePropertyName","mapTypeRef","irMapTypeRef","mapPrimitive","className","joinUnionVariants","generateModels","className","domainFieldName","mapTypeRef","generateEnums","resolveEnumName","className","fieldName","generateWrapperMethods","emitWrapperMethod","fieldName","className","mapTypeRef","phpLiteral","isEnumType","clientFieldExpression","generateResources","className","buildExportedClassNameSet","resolveServiceTarget","collectImports","resolveMethodName","generateWrapperMethods","groupVariantClassName","deriveVariantFieldName","fieldName","mapTypeRef","generateMethod","clientFieldExpression","generateClient","deduplicateByMount","buildServiceAccessPaths","servicePropertyName","buildExportedClassNameSet","className","resolveServiceTarget","ID_PREFIXES","generateFixtures","generateModelFixture","unwrapListModel","generateFieldValue","generatePrimitiveValue","generateTests","className","generateFixtures","servicePropertyName","resolveMethodName","buildHiddenParams","buildExpectedPath","deriveVariantFieldName","domainFieldName","buildOperationsMap","buildServiceAccessPaths","resolveMethodName","ensureTrailingNewlines","generateModels","generateEnums","generateResources","generateClient","generateTests","buildOperationsMap","fs","path","className","fileName","methodName","fieldName","domainFieldName","resolveMethodName","trimMountedResourceFromMethod","resolveClassName","splitPascalWords","singularize","wordsMatch","mapTypeRef","irMapTypeRef","mapPrimitive","className","joinUnionVariants","collectRequestBodyOnlyModelNames","generateModels","structuralHash","className","lowerFirst","humanize","articleFor","domainFieldName","makeOptional","mapTypeRef","HUMANIZE_ACRONYMS","HUMANIZE_RESTORE","generateEnums","collectEnumAliasOf","className","humanize","escapeGoString","generateWrapperMethods","goMethodName","goFieldName","emitWrapperMethod","goClassName","sortPathParamsByTemplateOrder","goLiteral","clientFieldExpression","GO_RESERVED","sortPathParamsByTemplateOrder","resolveResourceClassName","resolveClassName","generateResources","generateServiceFile","serviceTypeName","resolveGoMethodName","generateMethod","generateWrapperMethods","methodName","resolveMethodName","className","fieldName","buildHiddenParams","domainFieldName","makeOptional","mapTypeRef","buildPathExpr","clientFieldExpression","singularizePascal","generateClient","deduplicateByMount","buildServiceAccessPaths","resolveResourceClassName","className","ID_PREFIXES","generateFixtures","fileName","generateModelFixture","unwrapListModel","domainFieldName","generateFieldValue","generatePrimitiveValue","generateTests","generateFixtures","buildServiceAccessPaths","resolveResourceClassName","generateServiceTest","buildHiddenParams","buildExpectedPath","sortPathParamsByTemplateOrder","fileName","buildMethodCallArgs","buildFixtureAssertions","goMethodName","resolveMethodName","goFieldName","ID_PREFIXES","buildOperationsMap","buildServiceAccessPaths","resolveMethodName","ensureTrailingNewlines","generateModels","generateEnums","generateResources","generateClient","generateTests","buildOperationsMap","className","methodName","fieldName","domainFieldName","trimMountedResourceFromMethod","resolveClassName","resolveMethodName","splitPascalWords","singularize","wordsMatch","clientFieldExpression","escapeXml","humanize","mapTypeRef","irMapTypeRef","mapPrimitive","className","joinUnionVariants","discriminatedUnions","generateModels","domainFieldName","mapTypeRef","fieldName","humanize","structuralHash","normalizeTypeForHash","generateEnums","collectEnumAliasOf","className","humanize","generateWrapperMethods","emitWrapperMethod","csMethodName","sortPathParamsByTemplateOrder","escapeXml","humanize","csFieldName","clientFieldExpression","mapTypeRef","sortPathParamsByTemplateOrder","resolveClassName","generateResources","className","groupVariantClassName","fieldName","mapTypeRef","humanize","resolveCsMethodStem","resolveCsMethodName","generateWrapperMethods","methodName","buildHiddenParams","escapeXml","clientFieldExpression","resolveMethodName","generateClient","deduplicateByMount","className","humanize","TEST_PREFIX","generateFixtures","generateModelFixture","domainFieldName","generateTests","generateFixtures","csMethodName","sortPathParamsByTemplateOrder","resolveMethodName","buildHiddenParams","csFieldName","generateModelFixture","csDomainFieldName","buildOperationsMap","resolveMethodName","ensureTrailingNewlines","TEST_PREFIX","generateModels","discriminatedUnions","generateEnums","generateResources","generateClient","generateTests","buildOperationsMap","fs","path","className","methodName","resolveServiceTarget","buildExportedClassNameSet","buildExportedClassNameSetShared","resolveServiceTargetShared","servicePropertyName","resolveMethodName","resolveClassName","clientFieldExpression","KOTLIN_SRC_PREFIX","generateEnums","className","escapeKdoc","className","mapTypeRef","irMapTypeRef","mapPrimitive","KOTLIN_SRC_PREFIX","modelFilePath","className","ISO_8601_DESCRIPTION_RE","looksLikeIso8601String","promoteIso8601TypeRef","promoteFieldType","generateModels","mapTypeRef","escapeKdoc","generateWrapperMethods","emitWrapperMethod","className","escapeKdoc","mapTypeRef","clientFieldExpression","KOTLIN_SRC_PREFIX","ISO_8601_DESCRIPTION_RE","looksLikeIso8601String","promoteIso8601TypeRef","generateResources","buildExportedClassNameSet","className","generateWrapperMethods","resolveMethodName","findService","renderMethod","buildHiddenParams","resolveBodyModel","mapTypeRef","assignGroupParameterNames","sealedGroupName","clientFieldExpression","reserveUniqueGroupParameterName","generateClient","buildExportedClassNameSet","servicePropertyName","className","generateTests","buildExportedClassNameSet","generateModelRoundTripTest","resolveMethodName","buildHiddenParams","resolveBodyModel","mapTypeRef","buildOperationsMap","servicePropertyName","resolveClassName","resolveMethodName","ensureTrailingNewlines","generateModels","generateEnums","generateResources","generateClient","generateTests","buildOperationsMap","fieldName","domainFieldName","moduleName","buildExportedClassNameSetShared","resolveServiceTargetShared","generateModels","domainFieldName","generateEnums","irMapTypeRef","fieldName","rubyStringLit","interpolateRubyPath","mapSorbetType","fieldName","generateResources","buildHiddenParams","fieldName","generateClient","generateTests","buildHiddenParams","fieldName","domainFieldName","buildOperationsMap","irMapTypeRef","domainFieldName","buildHiddenParams","fieldName","ensureTrailingNewlines","generateModels","generateEnums","generateResources","generateClient","generateTests","buildOperationsMap","mapTypeRef","docComment","formatDefault","mapTypeRef","mapTypeRef","path"],"sources":["../src/shared/resolved-ops.ts","../src/shared/naming-utils.ts","../node_modules/js-yaml/dist/js-yaml.mjs","../src/shared/model-utils.ts","../src/shared/service-name-collision.ts","../src/node/naming.ts","../src/node/type-map.ts","../src/node/options.ts","../src/node/live-surface.ts","../src/node/utils.ts","../src/node/enums.ts","../src/node/field-plan.ts","../src/node/sdk-errors.ts","../src/shared/wrapper-utils.ts","../src/shared/path-template.ts","../src/node/path-expression.ts","../src/node/wrappers.ts","../src/node/resources.ts","../src/node/fixtures.ts","../src/node/models.ts","../src/node/client.ts","../src/node/tests.ts","../src/shared/union-flatten.ts","../src/node/discriminated-models.ts","../src/node/node-overrides.ts","../src/shared/file-header.ts","../src/node/index.ts","../src/python/naming.ts","../src/python/type-map.ts","../src/python/shared-schemas.ts","../src/python/enums.ts","../src/python/models.ts","../src/python/path-expression.ts","../src/python/wrappers.ts","../src/python/resources.ts","../src/shared/non-spec-services.ts","../src/python/client.ts","../src/python/fixtures.ts","../src/python/tests.ts","../src/python/manifest.ts","../src/python/index.ts","../src/php/naming.ts","../src/php/type-map.ts","../src/php/utils.ts","../src/php/models.ts","../src/php/enums.ts","../src/php/path-expression.ts","../src/php/wrappers.ts","../src/php/resources.ts","../src/php/client.ts","../src/php/fixtures.ts","../src/php/tests.ts","../src/php/manifest.ts","../src/php/index.ts","../src/go/naming.ts","../src/go/type-map.ts","../src/go/flat-merge.ts","../src/go/models.ts","../src/go/enums.ts","../src/go/wrappers.ts","../src/go/resources.ts","../src/go/client.ts","../src/go/fixtures.ts","../src/go/tests.ts","../src/go/manifest.ts","../src/go/index.ts","../src/dotnet/naming.ts","../src/dotnet/type-map.ts","../src/dotnet/models.ts","../src/dotnet/enums.ts","../src/dotnet/wrappers.ts","../src/dotnet/resources.ts","../src/dotnet/client.ts","../src/dotnet/fixtures.ts","../src/dotnet/tests.ts","../src/dotnet/manifest.ts","../src/dotnet/index.ts","../src/kotlin/naming.ts","../src/kotlin/enums.ts","../src/kotlin/type-map.ts","../src/kotlin/models.ts","../src/kotlin/path-expression.ts","../src/kotlin/suspend.ts","../src/kotlin/wrappers.ts","../src/kotlin/overrides.ts","../src/kotlin/resources.ts","../src/kotlin/client.ts","../src/kotlin/tests.ts","../src/kotlin/manifest.ts","../src/kotlin/index.ts","../src/ruby/naming.ts","../src/ruby/models.ts","../src/ruby/enums.ts","../src/ruby/type-map.ts","../src/ruby/wrappers.ts","../src/ruby/parameter-groups.ts","../src/ruby/resources.ts","../src/ruby/client.ts","../src/ruby/tests.ts","../src/ruby/manifest.ts","../src/ruby/rbi.ts","../src/ruby/index.ts","../src/rust/naming.ts","../src/rust/type-map.ts","../src/rust/secret.ts","../src/rust/models.ts","../src/rust/enums.ts","../src/rust/resources.ts","../src/rust/client.ts","../src/rust/fixtures.ts","../src/rust/tests.ts","../src/rust/manifest.ts","../src/rust/index.ts","../src/plugin.ts"],"sourcesContent":["import type { Operation, EmitterContext, Service, ResolvedOperation, Model, TypeRef } from '@workos/oagen';\nimport { toPascalCase } from '@workos/oagen';\n\n/**\n * Fail fast when two distinct paths in the same mount resolve to the same SDK\n * method name. Emitters can sometimes paper over this with per-language\n * deduplication, but manifests and cross-language parity become inconsistent.\n */\nexport function assertUniqueResolvedMethods(ctx: EmitterContext): void {\n  const seen = new Map<string, { path: string; httpMethod: string }>();\n\n  for (const resolved of ctx.resolvedOperations ?? []) {\n    const key = `${resolved.mountOn}.${resolved.methodName}`;\n    const current = {\n      path: resolved.operation.path,\n      httpMethod: resolved.operation.httpMethod.toUpperCase(),\n    };\n    const existing = seen.get(key);\n\n    if (existing && existing.path !== current.path) {\n      throw new Error(\n        `Resolved operation name collision for ${key}: ` +\n          `${existing.httpMethod} ${existing.path} conflicts with ${current.httpMethod} ${current.path}`,\n      );\n    }\n\n    if (!existing) {\n      seen.set(key, current);\n    }\n  }\n}\n\n/**\n * Build a lookup map from \"METHOD /path\" to ResolvedOperation.\n * Used by emitters to find the resolved method name for any IR operation.\n */\nexport function buildResolvedLookup(ctx: EmitterContext): Map<string, ResolvedOperation> {\n  assertUniqueResolvedMethods(ctx);\n\n  const map = new Map<string, ResolvedOperation>();\n  for (const r of ctx.resolvedOperations ?? []) {\n    const key = `${r.operation.httpMethod.toUpperCase()} ${r.operation.path}`;\n    map.set(key, r);\n  }\n  return map;\n}\n\n/**\n * Look up the resolved method name for an operation.\n * Returns the snake_case resolved name, or undefined if not found.\n */\nexport function lookupMethodName(op: Operation, lookup: Map<string, ResolvedOperation>): string | undefined {\n  const key = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  return lookup.get(key)?.methodName;\n}\n\n/**\n * Look up the full ResolvedOperation for an IR operation.\n */\nexport function lookupResolved(op: Operation, lookup: Map<string, ResolvedOperation>): ResolvedOperation | undefined {\n  const key = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  return lookup.get(key);\n}\n\n/**\n * A mount group: a set of resolved operations that all mount on the same target.\n * Serves the same role as a Service in the old architecture, but operations may\n * come from multiple IR services.\n */\nexport interface MountGroup {\n  /** PascalCase mount target name (e.g., \"SSO\", \"UserManagement\"). */\n  name: string;\n  /** All resolved operations in this group. */\n  resolvedOps: ResolvedOperation[];\n  /** The raw IR operations (convenience — same as resolvedOps[*].operation). */\n  operations: Operation[];\n}\n\n/**\n * Group resolved operations by their mountOn target.\n * Returns a map from PascalCase mount target to MountGroup.\n */\nexport function groupByMount(ctx: EmitterContext): Map<string, MountGroup> {\n  const groups = new Map<string, MountGroup>();\n  for (const r of ctx.resolvedOperations ?? []) {\n    let group = groups.get(r.mountOn);\n    if (!group) {\n      group = { name: r.mountOn, resolvedOps: [], operations: [] };\n      groups.set(r.mountOn, group);\n    }\n    group.resolvedOps.push(r);\n    group.operations.push(r.operation);\n  }\n  return groups;\n}\n\n/**\n * Like {@link groupByMount}, but for a scoped (`--services`) run returns ONLY the\n * mount groups the run selected (`ctx.scopedServices`, POST-MOUNT names). When\n * scoping is inactive the full set is returned unchanged.\n *\n * Use this for PER-SERVICE resource/test emission. Do NOT use it for\n * aggregate/barrel files (Rust `mod.rs`, Ruby `client.rbi`, the root client) —\n * those must continue to list every service, so they keep calling\n * {@link groupByMount} over the full set; otherwise a scoped run would drop\n * sibling modules and break the build/type-check.\n */\nexport function scopedMountGroups(ctx: EmitterContext): Map<string, MountGroup> {\n  const groups = groupByMount(ctx);\n  const scope = ctx.scopedServices;\n  if (!scope || scope.size === 0) return groups;\n  return new Map([...groups].filter(([mountName]) => scope.has(mountName)));\n}\n\n/**\n * True when a POST-MOUNT service name should be emitted in the current run.\n * Inactive scoping (no `ctx.scopedServices`) ⇒ everything is in scope. Use this\n * for inline per-service gates (e.g. manifest loops keyed by `getMountTarget`).\n */\nexport function isMountInScope(mountName: string, ctx: EmitterContext): boolean {\n  const scope = ctx.scopedServices;\n  return !scope || scope.size === 0 || scope.has(mountName);\n}\n\n/**\n * True when a MODEL's per-model FILE should be written in the current run (FR-1.4).\n * A scoped run sets `ctx.scopedModelNames` to the models reachable from the\n * selected services; out-of-scope models are left untouched on disk. Inactive\n * scoping ⇒ everything is in scope. NOTE: gate only the per-model FILE write —\n * the model must still appear in barrels/indexes (built from the full set) so the\n * untouched on-disk file stays importable.\n */\nexport function isModelInScope(modelName: string, ctx: EmitterContext): boolean {\n  const scope = ctx.scopedModelNames;\n  return !scope || scope.has(modelName);\n}\n\n/** Like {@link isModelInScope} but for an ENUM's per-enum file (`ctx.scopedEnumNames`). */\nexport function isEnumInScope(enumName: string, ctx: EmitterContext): boolean {\n  const scope = ctx.scopedEnumNames;\n  return !scope || scope.has(enumName);\n}\n\n/** True when a scoped (`--services`) run is active. */\nexport function isScopedRun(ctx: EmitterContext): boolean {\n  return !!ctx.scopedServices && ctx.scopedServices.size > 0;\n}\n\n/**\n * Barrel/index inclusion gate for one item (model, enum, fixture) under a\n * scoped run. A barrel/index may only reference an item whose per-item FILE\n * EXISTS ON DISK after the run — otherwise the reference dangles and the SDK\n * fails to compile (the bug this guards: a brand-new model belonging to an\n * out-of-scope service gets declared in `mod.rs`/`__init__.py` but its source\n * file is never emitted). That on-disk set is:\n *   in-scope items (freshly emitted this run) ∪ items already on disk\n *   (recorded in the prior manifest, left untouched because scoped runs never\n *   prune).\n * Inactive scoping ⇒ always true (a full run emits and declares everything).\n *\n * `relPath` is the per-item file path the emitter writes (e.g.\n * `src/models/foo.rs`); `inScope` is the per-item scope predicate result\n * (`isModelInScope` / `isEnumInScope`).\n */\nexport function fileExistsAfterRun(relPath: string, inScope: boolean, ctx: EmitterContext): boolean {\n  if (!isScopedRun(ctx)) return true;\n  return inScope || (ctx.priorTargetManifestPaths?.has(relPath) ?? false);\n}\n\n/**\n * Per-item basenames recorded in the prior manifest directly under `dir` (e.g.\n * `src/models`) with extension `ext` (e.g. `.rs`), EXCLUDING `reserved` names\n * (barrels such as `mod`, `_unions`, `__init__`). A scoped run uses this to\n * RETAIN barrel declarations for items that were renamed/removed from the spec\n * but whose files still sit on disk — and may still be referenced by\n * out-of-scope code the scoped run did not regenerate (e.g. a stale resource\n * file). Returns `[]` for a full run or when no prior manifest is available;\n * the caller is responsible for de-duping against items it already emitted.\n */\nexport function priorManifestBasenames(\n  ctx: EmitterContext,\n  dir: string,\n  ext: string,\n  reserved: Set<string> = new Set(),\n): string[] {\n  if (!isScopedRun(ctx)) return [];\n  const paths = ctx.priorTargetManifestPaths;\n  if (!paths) return [];\n  const prefix = dir.endsWith('/') ? dir : `${dir}/`;\n  const out: string[] = [];\n  for (const p of paths) {\n    if (!p.startsWith(prefix) || !p.endsWith(ext)) continue;\n    const base = p.slice(prefix.length, p.length - ext.length);\n    if (base.includes('/')) continue; // direct children only\n    if (reserved.has(base)) continue;\n    out.push(base);\n  }\n  return out;\n}\n\n/**\n * Get the mount target for an IR service.\n * Checks the first resolved operation that belongs to this service.\n * Falls back to PascalCase of the service name if no resolved ops exist.\n */\nexport function getMountTarget(service: Service, ctx: EmitterContext): string {\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (r.service.name === service.name) return r.mountOn;\n  }\n  return toPascalCase(service.name);\n}\n\n// ---------------------------------------------------------------------------\n// Defaults / inferFromClient helpers\n//\n// For non-split operations with operationHints that specify `defaults` or\n// `inferFromClient`, oagen attaches these properties at runtime but they\n// are not part of the ResolvedOperation TypeScript interface (they live on\n// ResolvedWrapper for split operations). These helpers provide type-safe\n// access so individual emitters don't need `as any` casts.\n// ---------------------------------------------------------------------------\n\n/** Extract constant defaults from a resolved operation (if any). */\nexport function getOpDefaults(resolvedOp?: ResolvedOperation): Record<string, string | number | boolean> {\n  return ((resolvedOp as any)?.defaults as Record<string, string | number | boolean> | undefined) ?? {};\n}\n\n/** Extract inferFromClient fields from a resolved operation (if any). */\nexport function getOpInferFromClient(resolvedOp?: ResolvedOperation): string[] {\n  return ((resolvedOp as any)?.inferFromClient as string[] | undefined) ?? [];\n}\n\n/** Build the set of param names hidden from the public API (injected as defaults or inferred from client config). */\nexport function buildHiddenParams(resolvedOp?: ResolvedOperation): Set<string> {\n  const hidden = new Set<string>();\n  for (const key of Object.keys(getOpDefaults(resolvedOp))) hidden.add(key);\n  for (const key of getOpInferFromClient(resolvedOp)) hidden.add(key);\n  return hidden;\n}\n\n/** Check whether a resolved operation has any hidden params. */\nexport function hasHiddenParams(resolvedOp?: ResolvedOperation): boolean {\n  return Object.keys(getOpDefaults(resolvedOp)).length > 0 || getOpInferFromClient(resolvedOp).length > 0;\n}\n\n// ---------------------------------------------------------------------------\n// Parameter group helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Collect all parameter names that belong to any mutually-exclusive parameter group.\n * These params are serialized via group-level dispatch (e.g. applyToQuery, isinstance,\n * sealed-class when, etc.) instead of individual struct/class fields.\n */\nexport function collectGroupedParamNames(op: Operation): Set<string> {\n  const names = new Set<string>();\n  for (const group of op.parameterGroups ?? []) {\n    for (const variant of group.variants) {\n      for (const param of variant.parameters) {\n        names.add(param.name);\n      }\n    }\n  }\n  return names;\n}\n\n/**\n * Build a fallback map from request-body wire field name to TypeRef.\n *\n * Some parameter-group variants lose array/object fidelity in the IR and fall\n * back to primitive strings. Cross-referencing the request body model restores\n * the actual field type when the grouped params belong to the body.\n */\nexport function collectBodyFieldTypes(op: Operation, models: Model[]): Map<string, TypeRef> {\n  const fieldTypes = new Map<string, TypeRef>();\n  const reqBody = op.requestBody;\n  if (reqBody?.kind !== 'model') return fieldTypes;\n\n  const bodyModel = models.find((model) => model.name === reqBody.name);\n  if (!bodyModel) return fieldTypes;\n\n  for (const field of bodyModel.fields) {\n    fieldTypes.set(field.name, field.type);\n  }\n\n  return fieldTypes;\n}\n","// ---------------------------------------------------------------------------\n// Shared acronym fixes\n// ---------------------------------------------------------------------------\n\n/**\n * Base set of acronym corrections applied after PascalCase conversion.\n * These are domain-specific terms that `toPascalCase` produces as e.g.\n * \"Sso\" but should be rendered as \"SSO\" in every SDK language.\n *\n * Language emitters can extend this with additional entries (e.g. Go adds\n * API, URL, HTTP, JSON, etc. per Go naming conventions).\n */\nexport const BASE_ACRONYM_FIXES: readonly [RegExp, string][] = [\n  [/Workos/g, 'WorkOS'],\n  [/Sso/g, 'SSO'],\n  [/Mfa/g, 'MFA'],\n  [/Jwt/g, 'JWT'],\n  [/Cors/g, 'CORS'],\n  [/Saml/g, 'SAML'],\n  [/Scim/g, 'SCIM'],\n  [/Rbac/g, 'RBAC'],\n  [/Oauth/g, 'OAuth'],\n  [/Oidc/g, 'OIDC'],\n];\n\n/**\n * Apply acronym corrections to a PascalCase string.\n * Uses the base set by default; pass extra entries for language-specific\n * conventions (e.g. Go's `[/Api(?=[A-Z]|$)/g, 'API']`).\n */\nexport function applyAcronymFixes(s: string, extra?: readonly [RegExp, string][]): string {\n  let result = s;\n  for (const [pattern, replacement] of BASE_ACRONYM_FIXES) {\n    result = result.replace(pattern, replacement);\n  }\n  if (extra) {\n    for (const [pattern, replacement] of extra) {\n      result = result.replace(pattern, replacement);\n    }\n  }\n  return result;\n}\n\n// ---------------------------------------------------------------------------\n// URN stripping\n// ---------------------------------------------------------------------------\n\n/** Strip URN OAuth grant-type prefixes from discriminator-derived schema names. */\nexport function stripUrnPrefix(name: string): string {\n  // Handles both OAuth and Oauth casing from different PascalCase implementations\n  return name.replace(/^Urn(?:IetfParams|Workos)O[Aa]uthGrantType/, '');\n}\n\n/**\n * Build the GoDoc prefix for a field comment.\n * If the description already starts with a verb (e.g., \"Distinguishes...\", \"Indicates...\"),\n * returns just the lowered description. Otherwise prepends \"is \".\n *\n *   fieldDocComment(\"ID\", \"the unique identifier\")   → \"ID is the unique identifier\"\n *   fieldDocComment(\"Object\", \"Distinguishes the X\")  → \"Object distinguishes the X\"\n */\nexport function fieldDocComment(fieldName: string, description: string): string {\n  const lowered = lowerFirstForDoc(description);\n  if (startsWithVerb(lowered)) {\n    return `${fieldName} ${lowered}`;\n  }\n  return `${fieldName} is ${lowered}`;\n}\n\n/** Known English 3rd-person-singular verbs that appear as OpenAPI description starters. */\nconst VERB_STARTERS = new Set([\n  'distinguishes',\n  'indicates',\n  'represents',\n  'contains',\n  'specifies',\n  'determines',\n  'controls',\n  'defines',\n  'identifies',\n  'describes',\n  'returns',\n  'creates',\n  'deletes',\n  'updates',\n  'lists',\n  'provides',\n  'enables',\n  'disables',\n  'allows',\n  'prevents',\n  'triggers',\n  'marks',\n  'tracks',\n  'stores',\n  'holds',\n  'maps',\n  'links',\n  'connects',\n  'wraps',\n  'denotes',\n  'shows',\n  'tells',\n  'gives',\n  'takes',\n  'sets',\n  'gets',\n  'configures',\n  'manages',\n  'validates',\n  'authenticates',\n  'authorizes',\n  'verifies',\n  'limits',\n  'restricts',\n  'overrides',\n  'applies',\n]);\n\nfunction startsWithVerb(desc: string): boolean {\n  const firstWord = desc\n    .split(/\\s/)[0]\n    .toLowerCase()\n    .replace(/[^a-z]/g, '');\n  return VERB_STARTERS.has(firstWord);\n}\n\n/**\n * Words beginning with a vowel letter but a consonant /j/ or /w/ sound —\n * take \"a\", not \"an\".\n */\nconst CONSONANT_SOUND_INITIAL_VOWEL = new Set([\n  'user',\n  'unit',\n  'unique',\n  'united',\n  'universal',\n  'university',\n  'european',\n  'one',\n  'once',\n  'useful',\n  'used',\n  'usable',\n  'ubiquitous',\n]);\n\n/**\n * Words beginning with a consonant letter but a vowel sound (silent h) —\n * take \"an\", not \"a\".\n */\nconst VOWEL_SOUND_INITIAL_CONSONANT = new Set(['hour', 'honest', 'honor', 'honorable', 'heir']);\n\n/**\n * Select the correct indefinite article (\"a\" or \"an\") for a word.\n *\n * Matches English phonetics, not orthography: \"a user\" (consonant /j/ sound\n * despite leading 'u'), \"an hour\" (vowel sound despite leading 'h'). Falls\n * back to a vowel-letter regex for words not in either exception set.\n */\nexport function articleFor(word: string): string {\n  const firstWord = word\n    .split(/\\s+/)[0]\n    .toLowerCase()\n    .replace(/[^a-z]/g, '');\n  if (CONSONANT_SOUND_INITIAL_VOWEL.has(firstWord)) return 'a';\n  if (VOWEL_SOUND_INITIAL_CONSONANT.has(firstWord)) return 'an';\n  return /^[aeiou]/i.test(word) ? 'an' : 'a';\n}\n\n/**\n * Lowercase the first character of a string for doc comments/descriptions.\n * Handles acronyms: \"SSO-specific\" becomes \"sso-specific\" not \"sSO-specific\".\n * \"JSONSchema\" becomes \"jsonSchema\", \"IP Address\" becomes \"ip Address\".\n */\nexport function lowerFirstForDoc(s: string): string {\n  if (!s) return s;\n  const acronymMatch = s.match(/^[A-Z]{2,}/);\n  if (acronymMatch) {\n    const acronym = acronymMatch[0];\n    const nextChar = s[acronym.length];\n    // If followed by a lowercase letter (e.g. \"SSOAuth\"), keep the last\n    // uppercase char as the start of the next camelCase word.\n    if (nextChar && /[a-z]/.test(nextChar)) {\n      return acronym.slice(0, -1).toLowerCase() + acronym.slice(-1) + s.slice(acronym.length);\n    }\n    return acronym.toLowerCase() + s.slice(acronym.length);\n  }\n  return s.charAt(0).toLowerCase() + s.slice(1);\n}\n","/*! js-yaml 4.2.0 https://github.com/nodeca/js-yaml @license MIT */\n//#region \\0rolldown/runtime.js\nvar __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);\nvar __copyProps = (to, from, except, desc) => {\n\tif (from && typeof from === \"object\" || typeof from === \"function\") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {\n\t\tkey = keys[i];\n\t\tif (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {\n\t\t\tget: ((k) => from[k]).bind(null, key),\n\t\t\tenumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable\n\t\t});\n\t}\n\treturn to;\n};\nvar __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, \"default\", {\n\tvalue: mod,\n\tenumerable: true\n}) : target, mod));\n//#endregion\n//#region lib/common.js\nvar require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tfunction isNothing(subject) {\n\t\treturn typeof subject === \"undefined\" || subject === null;\n\t}\n\tfunction isObject(subject) {\n\t\treturn typeof subject === \"object\" && subject !== null;\n\t}\n\tfunction toArray(sequence) {\n\t\tif (Array.isArray(sequence)) return sequence;\n\t\telse if (isNothing(sequence)) return [];\n\t\treturn [sequence];\n\t}\n\tfunction extend(target, source) {\n\t\tif (source) {\n\t\t\tconst sourceKeys = Object.keys(source);\n\t\t\tfor (let index = 0, length = sourceKeys.length; index < length; index += 1) {\n\t\t\t\tconst key = sourceKeys[index];\n\t\t\t\ttarget[key] = source[key];\n\t\t\t}\n\t\t}\n\t\treturn target;\n\t}\n\tfunction repeat(string, count) {\n\t\tlet result = \"\";\n\t\tfor (let cycle = 0; cycle < count; cycle += 1) result += string;\n\t\treturn result;\n\t}\n\tfunction isNegativeZero(number) {\n\t\treturn number === 0 && Number.NEGATIVE_INFINITY === 1 / number;\n\t}\n\tmodule.exports.isNothing = isNothing;\n\tmodule.exports.isObject = isObject;\n\tmodule.exports.toArray = toArray;\n\tmodule.exports.repeat = repeat;\n\tmodule.exports.isNegativeZero = isNegativeZero;\n\tmodule.exports.extend = extend;\n}));\n//#endregion\n//#region lib/exception.js\nvar require_exception = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tfunction formatError(exception, compact) {\n\t\tlet where = \"\";\n\t\tconst message = exception.reason || \"(unknown reason)\";\n\t\tif (!exception.mark) return message;\n\t\tif (exception.mark.name) where += \"in \\\"\" + exception.mark.name + \"\\\" \";\n\t\twhere += \"(\" + (exception.mark.line + 1) + \":\" + (exception.mark.column + 1) + \")\";\n\t\tif (!compact && exception.mark.snippet) where += \"\\n\\n\" + exception.mark.snippet;\n\t\treturn message + \" \" + where;\n\t}\n\tfunction YAMLException(reason, mark) {\n\t\tError.call(this);\n\t\tthis.name = \"YAMLException\";\n\t\tthis.reason = reason;\n\t\tthis.mark = mark;\n\t\tthis.message = formatError(this, false);\n\t\tif (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);\n\t\telse this.stack = (/* @__PURE__ */ new Error()).stack || \"\";\n\t}\n\tYAMLException.prototype = Object.create(Error.prototype);\n\tYAMLException.prototype.constructor = YAMLException;\n\tYAMLException.prototype.toString = function toString(compact) {\n\t\treturn this.name + \": \" + formatError(this, compact);\n\t};\n\tmodule.exports = YAMLException;\n}));\n//#endregion\n//#region lib/snippet.js\nvar require_snippet = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar common = require_common();\n\tfunction getLine(buffer, lineStart, lineEnd, position, maxLineLength) {\n\t\tlet head = \"\";\n\t\tlet tail = \"\";\n\t\tconst maxHalfLength = Math.floor(maxLineLength / 2) - 1;\n\t\tif (position - lineStart > maxHalfLength) {\n\t\t\thead = \" ... \";\n\t\t\tlineStart = position - maxHalfLength + head.length;\n\t\t}\n\t\tif (lineEnd - position > maxHalfLength) {\n\t\t\ttail = \" ...\";\n\t\t\tlineEnd = position + maxHalfLength - tail.length;\n\t\t}\n\t\treturn {\n\t\t\tstr: head + buffer.slice(lineStart, lineEnd).replace(/\\t/g, \"→\") + tail,\n\t\t\tpos: position - lineStart + head.length\n\t\t};\n\t}\n\tfunction padStart(string, max) {\n\t\treturn common.repeat(\" \", max - string.length) + string;\n\t}\n\tfunction makeSnippet(mark, options) {\n\t\toptions = Object.create(options || null);\n\t\tif (!mark.buffer) return null;\n\t\tif (!options.maxLength) options.maxLength = 79;\n\t\tif (typeof options.indent !== \"number\") options.indent = 1;\n\t\tif (typeof options.linesBefore !== \"number\") options.linesBefore = 3;\n\t\tif (typeof options.linesAfter !== \"number\") options.linesAfter = 2;\n\t\tconst re = /\\r?\\n|\\r|\\0/g;\n\t\tconst lineStarts = [0];\n\t\tconst lineEnds = [];\n\t\tlet match;\n\t\tlet foundLineNo = -1;\n\t\twhile (match = re.exec(mark.buffer)) {\n\t\t\tlineEnds.push(match.index);\n\t\t\tlineStarts.push(match.index + match[0].length);\n\t\t\tif (mark.position <= match.index && foundLineNo < 0) foundLineNo = lineStarts.length - 2;\n\t\t}\n\t\tif (foundLineNo < 0) foundLineNo = lineStarts.length - 1;\n\t\tlet result = \"\";\n\t\tconst lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;\n\t\tconst maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);\n\t\tfor (let i = 1; i <= options.linesBefore; i++) {\n\t\t\tif (foundLineNo - i < 0) break;\n\t\t\tconst line = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength);\n\t\t\tresult = common.repeat(\" \", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + \" | \" + line.str + \"\\n\" + result;\n\t\t}\n\t\tconst line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);\n\t\tresult += common.repeat(\" \", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + \" | \" + line.str + \"\\n\";\n\t\tresult += common.repeat(\"-\", options.indent + lineNoLength + 3 + line.pos) + \"^\\n\";\n\t\tfor (let i = 1; i <= options.linesAfter; i++) {\n\t\t\tif (foundLineNo + i >= lineEnds.length) break;\n\t\t\tconst line = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength);\n\t\t\tresult += common.repeat(\" \", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + \" | \" + line.str + \"\\n\";\n\t\t}\n\t\treturn result.replace(/\\n$/, \"\");\n\t}\n\tmodule.exports = makeSnippet;\n}));\n//#endregion\n//#region lib/type.js\nvar require_type = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar YAMLException = require_exception();\n\tvar TYPE_CONSTRUCTOR_OPTIONS = [\n\t\t\"kind\",\n\t\t\"multi\",\n\t\t\"resolve\",\n\t\t\"construct\",\n\t\t\"instanceOf\",\n\t\t\"predicate\",\n\t\t\"represent\",\n\t\t\"representName\",\n\t\t\"defaultStyle\",\n\t\t\"styleAliases\"\n\t];\n\tvar YAML_NODE_KINDS = [\n\t\t\"scalar\",\n\t\t\"sequence\",\n\t\t\"mapping\"\n\t];\n\tfunction compileStyleAliases(map) {\n\t\tconst result = {};\n\t\tif (map !== null) Object.keys(map).forEach(function(style) {\n\t\t\tmap[style].forEach(function(alias) {\n\t\t\t\tresult[String(alias)] = style;\n\t\t\t});\n\t\t});\n\t\treturn result;\n\t}\n\tfunction Type(tag, options) {\n\t\toptions = options || {};\n\t\tObject.keys(options).forEach(function(name) {\n\t\t\tif (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) throw new YAMLException(\"Unknown option \\\"\" + name + \"\\\" is met in definition of \\\"\" + tag + \"\\\" YAML type.\");\n\t\t});\n\t\tthis.options = options;\n\t\tthis.tag = tag;\n\t\tthis.kind = options[\"kind\"] || null;\n\t\tthis.resolve = options[\"resolve\"] || function() {\n\t\t\treturn true;\n\t\t};\n\t\tthis.construct = options[\"construct\"] || function(data) {\n\t\t\treturn data;\n\t\t};\n\t\tthis.instanceOf = options[\"instanceOf\"] || null;\n\t\tthis.predicate = options[\"predicate\"] || null;\n\t\tthis.represent = options[\"represent\"] || null;\n\t\tthis.representName = options[\"representName\"] || null;\n\t\tthis.defaultStyle = options[\"defaultStyle\"] || null;\n\t\tthis.multi = options[\"multi\"] || false;\n\t\tthis.styleAliases = compileStyleAliases(options[\"styleAliases\"] || null);\n\t\tif (YAML_NODE_KINDS.indexOf(this.kind) === -1) throw new YAMLException(\"Unknown kind \\\"\" + this.kind + \"\\\" is specified for \\\"\" + tag + \"\\\" YAML type.\");\n\t}\n\tmodule.exports = Type;\n}));\n//#endregion\n//#region lib/schema.js\nvar require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar YAMLException = require_exception();\n\tvar Type = require_type();\n\tfunction compileList(schema, name) {\n\t\tconst result = [];\n\t\tschema[name].forEach(function(currentType) {\n\t\t\tlet newIndex = result.length;\n\t\t\tresult.forEach(function(previousType, previousIndex) {\n\t\t\t\tif (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) newIndex = previousIndex;\n\t\t\t});\n\t\t\tresult[newIndex] = currentType;\n\t\t});\n\t\treturn result;\n\t}\n\tfunction compileMap() {\n\t\tconst result = {\n\t\t\tscalar: {},\n\t\t\tsequence: {},\n\t\t\tmapping: {},\n\t\t\tfallback: {},\n\t\t\tmulti: {\n\t\t\t\tscalar: [],\n\t\t\t\tsequence: [],\n\t\t\t\tmapping: [],\n\t\t\t\tfallback: []\n\t\t\t}\n\t\t};\n\t\tfunction collectType(type) {\n\t\t\tif (type.multi) {\n\t\t\t\tresult.multi[type.kind].push(type);\n\t\t\t\tresult.multi[\"fallback\"].push(type);\n\t\t\t} else result[type.kind][type.tag] = result[\"fallback\"][type.tag] = type;\n\t\t}\n\t\tfor (let index = 0, length = arguments.length; index < length; index += 1) arguments[index].forEach(collectType);\n\t\treturn result;\n\t}\n\tfunction Schema(definition) {\n\t\treturn this.extend(definition);\n\t}\n\tSchema.prototype.extend = function extend(definition) {\n\t\tlet implicit = [];\n\t\tlet explicit = [];\n\t\tif (definition instanceof Type) explicit.push(definition);\n\t\telse if (Array.isArray(definition)) explicit = explicit.concat(definition);\n\t\telse if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {\n\t\t\tif (definition.implicit) implicit = implicit.concat(definition.implicit);\n\t\t\tif (definition.explicit) explicit = explicit.concat(definition.explicit);\n\t\t} else throw new YAMLException(\"Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })\");\n\t\timplicit.forEach(function(type) {\n\t\t\tif (!(type instanceof Type)) throw new YAMLException(\"Specified list of YAML types (or a single Type object) contains a non-Type object.\");\n\t\t\tif (type.loadKind && type.loadKind !== \"scalar\") throw new YAMLException(\"There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.\");\n\t\t\tif (type.multi) throw new YAMLException(\"There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.\");\n\t\t});\n\t\texplicit.forEach(function(type) {\n\t\t\tif (!(type instanceof Type)) throw new YAMLException(\"Specified list of YAML types (or a single Type object) contains a non-Type object.\");\n\t\t});\n\t\tconst result = Object.create(Schema.prototype);\n\t\tresult.implicit = (this.implicit || []).concat(implicit);\n\t\tresult.explicit = (this.explicit || []).concat(explicit);\n\t\tresult.compiledImplicit = compileList(result, \"implicit\");\n\t\tresult.compiledExplicit = compileList(result, \"explicit\");\n\t\tresult.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);\n\t\treturn result;\n\t};\n\tmodule.exports = Schema;\n}));\n//#endregion\n//#region lib/type/str.js\nvar require_str = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tmodule.exports = new (require_type())(\"tag:yaml.org,2002:str\", {\n\t\tkind: \"scalar\",\n\t\tconstruct: function(data) {\n\t\t\treturn data !== null ? data : \"\";\n\t\t}\n\t});\n}));\n//#endregion\n//#region lib/type/seq.js\nvar require_seq = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tmodule.exports = new (require_type())(\"tag:yaml.org,2002:seq\", {\n\t\tkind: \"sequence\",\n\t\tconstruct: function(data) {\n\t\t\treturn data !== null ? data : [];\n\t\t}\n\t});\n}));\n//#endregion\n//#region lib/type/map.js\nvar require_map = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tmodule.exports = new (require_type())(\"tag:yaml.org,2002:map\", {\n\t\tkind: \"mapping\",\n\t\tconstruct: function(data) {\n\t\t\treturn data !== null ? data : {};\n\t\t}\n\t});\n}));\n//#endregion\n//#region lib/schema/failsafe.js\nvar require_failsafe = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tmodule.exports = new (require_schema())({ explicit: [\n\t\trequire_str(),\n\t\trequire_seq(),\n\t\trequire_map()\n\t] });\n}));\n//#endregion\n//#region lib/type/null.js\nvar require_null = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar Type = require_type();\n\tfunction resolveYamlNull(data) {\n\t\tif (data === null) return true;\n\t\tconst max = data.length;\n\t\treturn max === 1 && data === \"~\" || max === 4 && (data === \"null\" || data === \"Null\" || data === \"NULL\");\n\t}\n\tfunction constructYamlNull() {\n\t\treturn null;\n\t}\n\tfunction isNull(object) {\n\t\treturn object === null;\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:null\", {\n\t\tkind: \"scalar\",\n\t\tresolve: resolveYamlNull,\n\t\tconstruct: constructYamlNull,\n\t\tpredicate: isNull,\n\t\trepresent: {\n\t\t\tcanonical: function() {\n\t\t\t\treturn \"~\";\n\t\t\t},\n\t\t\tlowercase: function() {\n\t\t\t\treturn \"null\";\n\t\t\t},\n\t\t\tuppercase: function() {\n\t\t\t\treturn \"NULL\";\n\t\t\t},\n\t\t\tcamelcase: function() {\n\t\t\t\treturn \"Null\";\n\t\t\t},\n\t\t\tempty: function() {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t},\n\t\tdefaultStyle: \"lowercase\"\n\t});\n}));\n//#endregion\n//#region lib/type/bool.js\nvar require_bool = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar Type = require_type();\n\tfunction resolveYamlBoolean(data) {\n\t\tif (data === null) return false;\n\t\tconst max = data.length;\n\t\treturn max === 4 && (data === \"true\" || data === \"True\" || data === \"TRUE\") || max === 5 && (data === \"false\" || data === \"False\" || data === \"FALSE\");\n\t}\n\tfunction constructYamlBoolean(data) {\n\t\treturn data === \"true\" || data === \"True\" || data === \"TRUE\";\n\t}\n\tfunction isBoolean(object) {\n\t\treturn Object.prototype.toString.call(object) === \"[object Boolean]\";\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:bool\", {\n\t\tkind: \"scalar\",\n\t\tresolve: resolveYamlBoolean,\n\t\tconstruct: constructYamlBoolean,\n\t\tpredicate: isBoolean,\n\t\trepresent: {\n\t\t\tlowercase: function(object) {\n\t\t\t\treturn object ? \"true\" : \"false\";\n\t\t\t},\n\t\t\tuppercase: function(object) {\n\t\t\t\treturn object ? \"TRUE\" : \"FALSE\";\n\t\t\t},\n\t\t\tcamelcase: function(object) {\n\t\t\t\treturn object ? \"True\" : \"False\";\n\t\t\t}\n\t\t},\n\t\tdefaultStyle: \"lowercase\"\n\t});\n}));\n//#endregion\n//#region lib/type/int.js\nvar require_int = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar common = require_common();\n\tvar Type = require_type();\n\tfunction isHexCode(c) {\n\t\treturn c >= 48 && c <= 57 || c >= 65 && c <= 70 || c >= 97 && c <= 102;\n\t}\n\tfunction isOctCode(c) {\n\t\treturn c >= 48 && c <= 55;\n\t}\n\tfunction isDecCode(c) {\n\t\treturn c >= 48 && c <= 57;\n\t}\n\tfunction resolveYamlInteger(data) {\n\t\tif (data === null) return false;\n\t\tconst max = data.length;\n\t\tlet index = 0;\n\t\tlet hasDigits = false;\n\t\tif (!max) return false;\n\t\tlet ch = data[index];\n\t\tif (ch === \"-\" || ch === \"+\") ch = data[++index];\n\t\tif (ch === \"0\") {\n\t\t\tif (index + 1 === max) return true;\n\t\t\tch = data[++index];\n\t\t\tif (ch === \"b\") {\n\t\t\t\tindex++;\n\t\t\t\tfor (; index < max; index++) {\n\t\t\t\t\tch = data[index];\n\t\t\t\t\tif (ch !== \"0\" && ch !== \"1\") return false;\n\t\t\t\t\thasDigits = true;\n\t\t\t\t}\n\t\t\t\treturn hasDigits && Number.isFinite(parseYamlInteger(data));\n\t\t\t}\n\t\t\tif (ch === \"x\") {\n\t\t\t\tindex++;\n\t\t\t\tfor (; index < max; index++) {\n\t\t\t\t\tif (!isHexCode(data.charCodeAt(index))) return false;\n\t\t\t\t\thasDigits = true;\n\t\t\t\t}\n\t\t\t\treturn hasDigits && Number.isFinite(parseYamlInteger(data));\n\t\t\t}\n\t\t\tif (ch === \"o\") {\n\t\t\t\tindex++;\n\t\t\t\tfor (; index < max; index++) {\n\t\t\t\t\tif (!isOctCode(data.charCodeAt(index))) return false;\n\t\t\t\t\thasDigits = true;\n\t\t\t\t}\n\t\t\t\treturn hasDigits && Number.isFinite(parseYamlInteger(data));\n\t\t\t}\n\t\t}\n\t\tfor (; index < max; index++) {\n\t\t\tif (!isDecCode(data.charCodeAt(index))) return false;\n\t\t\thasDigits = true;\n\t\t}\n\t\tif (!hasDigits) return false;\n\t\treturn Number.isFinite(parseYamlInteger(data));\n\t}\n\tfunction parseYamlInteger(data) {\n\t\tlet value = data;\n\t\tlet sign = 1;\n\t\tlet ch = value[0];\n\t\tif (ch === \"-\" || ch === \"+\") {\n\t\t\tif (ch === \"-\") sign = -1;\n\t\t\tvalue = value.slice(1);\n\t\t\tch = value[0];\n\t\t}\n\t\tif (value === \"0\") return 0;\n\t\tif (ch === \"0\") {\n\t\t\tif (value[1] === \"b\") return sign * parseInt(value.slice(2), 2);\n\t\t\tif (value[1] === \"x\") return sign * parseInt(value.slice(2), 16);\n\t\t\tif (value[1] === \"o\") return sign * parseInt(value.slice(2), 8);\n\t\t}\n\t\treturn sign * parseInt(value, 10);\n\t}\n\tfunction constructYamlInteger(data) {\n\t\treturn parseYamlInteger(data);\n\t}\n\tfunction isInteger(object) {\n\t\treturn Object.prototype.toString.call(object) === \"[object Number]\" && object % 1 === 0 && !common.isNegativeZero(object);\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:int\", {\n\t\tkind: \"scalar\",\n\t\tresolve: resolveYamlInteger,\n\t\tconstruct: constructYamlInteger,\n\t\tpredicate: isInteger,\n\t\trepresent: {\n\t\t\tbinary: function(obj) {\n\t\t\t\treturn obj >= 0 ? \"0b\" + obj.toString(2) : \"-0b\" + obj.toString(2).slice(1);\n\t\t\t},\n\t\t\toctal: function(obj) {\n\t\t\t\treturn obj >= 0 ? \"0o\" + obj.toString(8) : \"-0o\" + obj.toString(8).slice(1);\n\t\t\t},\n\t\t\tdecimal: function(obj) {\n\t\t\t\treturn obj.toString(10);\n\t\t\t},\n\t\t\thexadecimal: function(obj) {\n\t\t\t\treturn obj >= 0 ? \"0x\" + obj.toString(16).toUpperCase() : \"-0x\" + obj.toString(16).toUpperCase().slice(1);\n\t\t\t}\n\t\t},\n\t\tdefaultStyle: \"decimal\",\n\t\tstyleAliases: {\n\t\t\tbinary: [2, \"bin\"],\n\t\t\toctal: [8, \"oct\"],\n\t\t\tdecimal: [10, \"dec\"],\n\t\t\thexadecimal: [16, \"hex\"]\n\t\t}\n\t});\n}));\n//#endregion\n//#region lib/type/float.js\nvar require_float = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar common = require_common();\n\tvar Type = require_type();\n\tvar YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp(\"^(?:[-+]?(?:[0-9]+)(?:\\\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\\\.(?:inf|Inf|INF)|\\\\.(?:nan|NaN|NAN))$\");\n\tvar YAML_FLOAT_SPECIAL_PATTERN = /* @__PURE__ */ new RegExp(\"^(?:[-+]?\\\\.(?:inf|Inf|INF)|\\\\.(?:nan|NaN|NAN))$\");\n\tfunction resolveYamlFloat(data) {\n\t\tif (data === null) return false;\n\t\tif (!YAML_FLOAT_PATTERN.test(data)) return false;\n\t\tif (Number.isFinite(parseFloat(data, 10))) return true;\n\t\treturn YAML_FLOAT_SPECIAL_PATTERN.test(data);\n\t}\n\tfunction constructYamlFloat(data) {\n\t\tlet value = data.toLowerCase();\n\t\tconst sign = value[0] === \"-\" ? -1 : 1;\n\t\tif (\"+-\".indexOf(value[0]) >= 0) value = value.slice(1);\n\t\tif (value === \".inf\") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;\n\t\telse if (value === \".nan\") return NaN;\n\t\treturn sign * parseFloat(value, 10);\n\t}\n\tvar SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;\n\tfunction representYamlFloat(object, style) {\n\t\tif (isNaN(object)) switch (style) {\n\t\t\tcase \"lowercase\": return \".nan\";\n\t\t\tcase \"uppercase\": return \".NAN\";\n\t\t\tcase \"camelcase\": return \".NaN\";\n\t\t}\n\t\telse if (Number.POSITIVE_INFINITY === object) switch (style) {\n\t\t\tcase \"lowercase\": return \".inf\";\n\t\t\tcase \"uppercase\": return \".INF\";\n\t\t\tcase \"camelcase\": return \".Inf\";\n\t\t}\n\t\telse if (Number.NEGATIVE_INFINITY === object) switch (style) {\n\t\t\tcase \"lowercase\": return \"-.inf\";\n\t\t\tcase \"uppercase\": return \"-.INF\";\n\t\t\tcase \"camelcase\": return \"-.Inf\";\n\t\t}\n\t\telse if (common.isNegativeZero(object)) return \"-0.0\";\n\t\tconst res = object.toString(10);\n\t\treturn SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace(\"e\", \".e\") : res;\n\t}\n\tfunction isFloat(object) {\n\t\treturn Object.prototype.toString.call(object) === \"[object Number]\" && (object % 1 !== 0 || common.isNegativeZero(object));\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:float\", {\n\t\tkind: \"scalar\",\n\t\tresolve: resolveYamlFloat,\n\t\tconstruct: constructYamlFloat,\n\t\tpredicate: isFloat,\n\t\trepresent: representYamlFloat,\n\t\tdefaultStyle: \"lowercase\"\n\t});\n}));\n//#endregion\n//#region lib/schema/json.js\nvar require_json = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tmodule.exports = require_failsafe().extend({ implicit: [\n\t\trequire_null(),\n\t\trequire_bool(),\n\t\trequire_int(),\n\t\trequire_float()\n\t] });\n}));\n//#endregion\n//#region lib/schema/core.js\nvar require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tmodule.exports = require_json();\n}));\n//#endregion\n//#region lib/type/timestamp.js\nvar require_timestamp = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar Type = require_type();\n\tvar YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp(\"^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$\");\n\tvar YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp(\"^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\\\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\\\.([0-9]*))?(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$\");\n\tfunction resolveYamlTimestamp(data) {\n\t\tif (data === null) return false;\n\t\tif (YAML_DATE_REGEXP.exec(data) !== null) return true;\n\t\tif (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;\n\t\treturn false;\n\t}\n\tfunction constructYamlTimestamp(data) {\n\t\tlet fraction = 0;\n\t\tlet delta = null;\n\t\tlet match = YAML_DATE_REGEXP.exec(data);\n\t\tif (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);\n\t\tif (match === null) throw new Error(\"Date resolve error\");\n\t\tconst year = +match[1];\n\t\tconst month = +match[2] - 1;\n\t\tconst day = +match[3];\n\t\tif (!match[4]) return new Date(Date.UTC(year, month, day));\n\t\tconst hour = +match[4];\n\t\tconst minute = +match[5];\n\t\tconst second = +match[6];\n\t\tif (match[7]) {\n\t\t\tfraction = match[7].slice(0, 3);\n\t\t\twhile (fraction.length < 3) fraction += \"0\";\n\t\t\tfraction = +fraction;\n\t\t}\n\t\tif (match[9]) {\n\t\t\tconst tzHour = +match[10];\n\t\t\tconst tzMinute = +(match[11] || 0);\n\t\t\tdelta = (tzHour * 60 + tzMinute) * 6e4;\n\t\t\tif (match[9] === \"-\") delta = -delta;\n\t\t}\n\t\tconst date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));\n\t\tif (delta) date.setTime(date.getTime() - delta);\n\t\treturn date;\n\t}\n\tfunction representYamlTimestamp(object) {\n\t\treturn object.toISOString();\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:timestamp\", {\n\t\tkind: \"scalar\",\n\t\tresolve: resolveYamlTimestamp,\n\t\tconstruct: constructYamlTimestamp,\n\t\tinstanceOf: Date,\n\t\trepresent: representYamlTimestamp\n\t});\n}));\n//#endregion\n//#region lib/type/merge.js\nvar require_merge = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar Type = require_type();\n\tfunction resolveYamlMerge(data) {\n\t\treturn data === \"<<\" || data === null;\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:merge\", {\n\t\tkind: \"scalar\",\n\t\tresolve: resolveYamlMerge\n\t});\n}));\n//#endregion\n//#region lib/type/binary.js\nvar require_binary = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar Type = require_type();\n\tvar BASE64_MAP = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r\";\n\tfunction resolveYamlBinary(data) {\n\t\tif (data === null) return false;\n\t\tlet bitlen = 0;\n\t\tconst max = data.length;\n\t\tconst map = BASE64_MAP;\n\t\tfor (let idx = 0; idx < max; idx++) {\n\t\t\tconst code = map.indexOf(data.charAt(idx));\n\t\t\tif (code > 64) continue;\n\t\t\tif (code < 0) return false;\n\t\t\tbitlen += 6;\n\t\t}\n\t\treturn bitlen % 8 === 0;\n\t}\n\tfunction constructYamlBinary(data) {\n\t\tconst input = data.replace(/[\\r\\n=]/g, \"\");\n\t\tconst max = input.length;\n\t\tconst map = BASE64_MAP;\n\t\tlet bits = 0;\n\t\tconst result = [];\n\t\tfor (let idx = 0; idx < max; idx++) {\n\t\t\tif (idx % 4 === 0 && idx) {\n\t\t\t\tresult.push(bits >> 16 & 255);\n\t\t\t\tresult.push(bits >> 8 & 255);\n\t\t\t\tresult.push(bits & 255);\n\t\t\t}\n\t\t\tbits = bits << 6 | map.indexOf(input.charAt(idx));\n\t\t}\n\t\tconst tailbits = max % 4 * 6;\n\t\tif (tailbits === 0) {\n\t\t\tresult.push(bits >> 16 & 255);\n\t\t\tresult.push(bits >> 8 & 255);\n\t\t\tresult.push(bits & 255);\n\t\t} else if (tailbits === 18) {\n\t\t\tresult.push(bits >> 10 & 255);\n\t\t\tresult.push(bits >> 2 & 255);\n\t\t} else if (tailbits === 12) result.push(bits >> 4 & 255);\n\t\treturn new Uint8Array(result);\n\t}\n\tfunction representYamlBinary(object) {\n\t\tlet result = \"\";\n\t\tlet bits = 0;\n\t\tconst max = object.length;\n\t\tconst map = BASE64_MAP;\n\t\tfor (let idx = 0; idx < max; idx++) {\n\t\t\tif (idx % 3 === 0 && idx) {\n\t\t\t\tresult += map[bits >> 18 & 63];\n\t\t\t\tresult += map[bits >> 12 & 63];\n\t\t\t\tresult += map[bits >> 6 & 63];\n\t\t\t\tresult += map[bits & 63];\n\t\t\t}\n\t\t\tbits = (bits << 8) + object[idx];\n\t\t}\n\t\tconst tail = max % 3;\n\t\tif (tail === 0) {\n\t\t\tresult += map[bits >> 18 & 63];\n\t\t\tresult += map[bits >> 12 & 63];\n\t\t\tresult += map[bits >> 6 & 63];\n\t\t\tresult += map[bits & 63];\n\t\t} else if (tail === 2) {\n\t\t\tresult += map[bits >> 10 & 63];\n\t\t\tresult += map[bits >> 4 & 63];\n\t\t\tresult += map[bits << 2 & 63];\n\t\t\tresult += map[64];\n\t\t} else if (tail === 1) {\n\t\t\tresult += map[bits >> 2 & 63];\n\t\t\tresult += map[bits << 4 & 63];\n\t\t\tresult += map[64];\n\t\t\tresult += map[64];\n\t\t}\n\t\treturn result;\n\t}\n\tfunction isBinary(obj) {\n\t\treturn Object.prototype.toString.call(obj) === \"[object Uint8Array]\";\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:binary\", {\n\t\tkind: \"scalar\",\n\t\tresolve: resolveYamlBinary,\n\t\tconstruct: constructYamlBinary,\n\t\tpredicate: isBinary,\n\t\trepresent: representYamlBinary\n\t});\n}));\n//#endregion\n//#region lib/type/omap.js\nvar require_omap = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar Type = require_type();\n\tvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\tvar _toString = Object.prototype.toString;\n\tfunction resolveYamlOmap(data) {\n\t\tif (data === null) return true;\n\t\tconst objectKeys = [];\n\t\tconst object = data;\n\t\tfor (let index = 0, length = object.length; index < length; index += 1) {\n\t\t\tconst pair = object[index];\n\t\t\tlet pairHasKey = false;\n\t\t\tif (_toString.call(pair) !== \"[object Object]\") return false;\n\t\t\tlet pairKey;\n\t\t\tfor (pairKey in pair) if (_hasOwnProperty.call(pair, pairKey)) if (!pairHasKey) pairHasKey = true;\n\t\t\telse return false;\n\t\t\tif (!pairHasKey) return false;\n\t\t\tif (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);\n\t\t\telse return false;\n\t\t}\n\t\treturn true;\n\t}\n\tfunction constructYamlOmap(data) {\n\t\treturn data !== null ? data : [];\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:omap\", {\n\t\tkind: \"sequence\",\n\t\tresolve: resolveYamlOmap,\n\t\tconstruct: constructYamlOmap\n\t});\n}));\n//#endregion\n//#region lib/type/pairs.js\nvar require_pairs = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar Type = require_type();\n\tvar _toString = Object.prototype.toString;\n\tfunction resolveYamlPairs(data) {\n\t\tif (data === null) return true;\n\t\tconst object = data;\n\t\tconst result = new Array(object.length);\n\t\tfor (let index = 0, length = object.length; index < length; index += 1) {\n\t\t\tconst pair = object[index];\n\t\t\tif (_toString.call(pair) !== \"[object Object]\") return false;\n\t\t\tconst keys = Object.keys(pair);\n\t\t\tif (keys.length !== 1) return false;\n\t\t\tresult[index] = [keys[0], pair[keys[0]]];\n\t\t}\n\t\treturn true;\n\t}\n\tfunction constructYamlPairs(data) {\n\t\tif (data === null) return [];\n\t\tconst object = data;\n\t\tconst result = new Array(object.length);\n\t\tfor (let index = 0, length = object.length; index < length; index += 1) {\n\t\t\tconst pair = object[index];\n\t\t\tconst keys = Object.keys(pair);\n\t\t\tresult[index] = [keys[0], pair[keys[0]]];\n\t\t}\n\t\treturn result;\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:pairs\", {\n\t\tkind: \"sequence\",\n\t\tresolve: resolveYamlPairs,\n\t\tconstruct: constructYamlPairs\n\t});\n}));\n//#endregion\n//#region lib/type/set.js\nvar require_set = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar Type = require_type();\n\tvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\tfunction resolveYamlSet(data) {\n\t\tif (data === null) return true;\n\t\tconst object = data;\n\t\tfor (const key in object) if (_hasOwnProperty.call(object, key)) {\n\t\t\tif (object[key] !== null) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tfunction constructYamlSet(data) {\n\t\treturn data !== null ? data : {};\n\t}\n\tmodule.exports = new Type(\"tag:yaml.org,2002:set\", {\n\t\tkind: \"mapping\",\n\t\tresolve: resolveYamlSet,\n\t\tconstruct: constructYamlSet\n\t});\n}));\n//#endregion\n//#region lib/schema/default.js\nvar require_default = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tmodule.exports = require_core().extend({\n\t\timplicit: [require_timestamp(), require_merge()],\n\t\texplicit: [\n\t\t\trequire_binary(),\n\t\t\trequire_omap(),\n\t\t\trequire_pairs(),\n\t\t\trequire_set()\n\t\t]\n\t});\n}));\n//#endregion\n//#region lib/loader.js\nvar require_loader = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar common = require_common();\n\tvar YAMLException = require_exception();\n\tvar makeSnippet = require_snippet();\n\tvar DEFAULT_SCHEMA = require_default();\n\tvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\tvar CONTEXT_FLOW_IN = 1;\n\tvar CONTEXT_FLOW_OUT = 2;\n\tvar CONTEXT_BLOCK_IN = 3;\n\tvar CONTEXT_BLOCK_OUT = 4;\n\tvar CHOMPING_CLIP = 1;\n\tvar CHOMPING_STRIP = 2;\n\tvar CHOMPING_KEEP = 3;\n\tvar PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\n\tvar PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/;\n\tvar PATTERN_FLOW_INDICATORS = /[,\\[\\]{}]/;\n\tvar PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/;\n\tvar PATTERN_TAG_URI = /^(?:!|[^,\\[\\]{}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;/?:@&=+$,_.!~*'()\\[\\]])*$/i;\n\tfunction _class(obj) {\n\t\treturn Object.prototype.toString.call(obj);\n\t}\n\tfunction isEol(c) {\n\t\treturn c === 10 || c === 13;\n\t}\n\tfunction isWhiteSpace(c) {\n\t\treturn c === 9 || c === 32;\n\t}\n\tfunction isWsOrEol(c) {\n\t\treturn c === 9 || c === 32 || c === 10 || c === 13;\n\t}\n\tfunction isFlowIndicator(c) {\n\t\treturn c === 44 || c === 91 || c === 93 || c === 123 || c === 125;\n\t}\n\tfunction fromHexCode(c) {\n\t\tif (c >= 48 && c <= 57) return c - 48;\n\t\tconst lc = c | 32;\n\t\tif (lc >= 97 && lc <= 102) return lc - 97 + 10;\n\t\treturn -1;\n\t}\n\tfunction escapedHexLen(c) {\n\t\tif (c === 120) return 2;\n\t\tif (c === 117) return 4;\n\t\tif (c === 85) return 8;\n\t\treturn 0;\n\t}\n\tfunction fromDecimalCode(c) {\n\t\tif (c >= 48 && c <= 57) return c - 48;\n\t\treturn -1;\n\t}\n\tfunction simpleEscapeSequence(c) {\n\t\tswitch (c) {\n\t\t\tcase 48: return \"\\0\";\n\t\t\tcase 97: return \"\\x07\";\n\t\t\tcase 98: return \"\\b\";\n\t\t\tcase 116: return \"\t\";\n\t\t\tcase 9: return \"\t\";\n\t\t\tcase 110: return \"\\n\";\n\t\t\tcase 118: return \"\\v\";\n\t\t\tcase 102: return \"\\f\";\n\t\t\tcase 114: return \"\\r\";\n\t\t\tcase 101: return \"\\x1B\";\n\t\t\tcase 32: return \" \";\n\t\t\tcase 34: return \"\\\"\";\n\t\t\tcase 47: return \"/\";\n\t\t\tcase 92: return \"\\\\\";\n\t\t\tcase 78: return \"\";\n\t\t\tcase 95: return \"\\xA0\";\n\t\t\tcase 76: return \"\\u2028\";\n\t\t\tcase 80: return \"\\u2029\";\n\t\t\tdefault: return \"\";\n\t\t}\n\t}\n\tfunction charFromCodepoint(c) {\n\t\tif (c <= 65535) return String.fromCharCode(c);\n\t\treturn String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320);\n\t}\n\tfunction setProperty(object, key, value) {\n\t\tif (key === \"__proto__\") Object.defineProperty(object, key, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: true,\n\t\t\twritable: true,\n\t\t\tvalue\n\t\t});\n\t\telse object[key] = value;\n\t}\n\tvar simpleEscapeCheck = new Array(256);\n\tvar simpleEscapeMap = new Array(256);\n\tfor (let i = 0; i < 256; i++) {\n\t\tsimpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;\n\t\tsimpleEscapeMap[i] = simpleEscapeSequence(i);\n\t}\n\tfunction State(input, options) {\n\t\tthis.input = input;\n\t\tthis.filename = options[\"filename\"] || null;\n\t\tthis.schema = options[\"schema\"] || DEFAULT_SCHEMA;\n\t\tthis.onWarning = options[\"onWarning\"] || null;\n\t\tthis.legacy = options[\"legacy\"] || false;\n\t\tthis.json = options[\"json\"] || false;\n\t\tthis.listener = options[\"listener\"] || null;\n\t\tthis.maxDepth = typeof options[\"maxDepth\"] === \"number\" ? options[\"maxDepth\"] : 100;\n\t\tthis.maxMergeSeqLength = typeof options[\"maxMergeSeqLength\"] === \"number\" ? options[\"maxMergeSeqLength\"] : 20;\n\t\tthis.implicitTypes = this.schema.compiledImplicit;\n\t\tthis.typeMap = this.schema.compiledTypeMap;\n\t\tthis.length = input.length;\n\t\tthis.position = 0;\n\t\tthis.line = 0;\n\t\tthis.lineStart = 0;\n\t\tthis.lineIndent = 0;\n\t\tthis.depth = 0;\n\t\tthis.firstTabInLine = -1;\n\t\tthis.documents = [];\n\t\tthis.anchorMapTransactions = [];\n\t}\n\tfunction generateError(state, message) {\n\t\tconst mark = {\n\t\t\tname: state.filename,\n\t\t\tbuffer: state.input.slice(0, -1),\n\t\t\tposition: state.position,\n\t\t\tline: state.line,\n\t\t\tcolumn: state.position - state.lineStart\n\t\t};\n\t\tmark.snippet = makeSnippet(mark);\n\t\treturn new YAMLException(message, mark);\n\t}\n\tfunction throwError(state, message) {\n\t\tthrow generateError(state, message);\n\t}\n\tfunction throwWarning(state, message) {\n\t\tif (state.onWarning) state.onWarning.call(null, generateError(state, message));\n\t}\n\tfunction storeAnchor(state, name, value) {\n\t\tconst transactions = state.anchorMapTransactions;\n\t\tif (transactions.length !== 0) {\n\t\t\tconst transaction = transactions[transactions.length - 1];\n\t\t\tif (!_hasOwnProperty.call(transaction, name)) transaction[name] = {\n\t\t\t\texisted: _hasOwnProperty.call(state.anchorMap, name),\n\t\t\t\tvalue: state.anchorMap[name]\n\t\t\t};\n\t\t}\n\t\tstate.anchorMap[name] = value;\n\t}\n\tfunction beginAnchorTransaction(state) {\n\t\tstate.anchorMapTransactions.push(Object.create(null));\n\t}\n\tfunction commitAnchorTransaction(state) {\n\t\tconst transaction = state.anchorMapTransactions.pop();\n\t\tconst transactions = state.anchorMapTransactions;\n\t\tif (transactions.length === 0) return;\n\t\tconst parent = transactions[transactions.length - 1];\n\t\tconst names = Object.keys(transaction);\n\t\tfor (let index = 0, length = names.length; index < length; index += 1) {\n\t\t\tconst name = names[index];\n\t\t\tif (!_hasOwnProperty.call(parent, name)) parent[name] = transaction[name];\n\t\t}\n\t}\n\tfunction rollbackAnchorTransaction(state) {\n\t\tconst transaction = state.anchorMapTransactions.pop();\n\t\tconst names = Object.keys(transaction);\n\t\tfor (let index = names.length - 1; index >= 0; index -= 1) {\n\t\t\tconst entry = transaction[names[index]];\n\t\t\tif (entry.existed) state.anchorMap[names[index]] = entry.value;\n\t\t\telse delete state.anchorMap[names[index]];\n\t\t}\n\t}\n\tfunction snapshotState(state) {\n\t\treturn {\n\t\t\tposition: state.position,\n\t\t\tline: state.line,\n\t\t\tlineStart: state.lineStart,\n\t\t\tlineIndent: state.lineIndent,\n\t\t\tfirstTabInLine: state.firstTabInLine,\n\t\t\ttag: state.tag,\n\t\t\tanchor: state.anchor,\n\t\t\tkind: state.kind,\n\t\t\tresult: state.result\n\t\t};\n\t}\n\tfunction restoreState(state, snapshot) {\n\t\tstate.position = snapshot.position;\n\t\tstate.line = snapshot.line;\n\t\tstate.lineStart = snapshot.lineStart;\n\t\tstate.lineIndent = snapshot.lineIndent;\n\t\tstate.firstTabInLine = snapshot.firstTabInLine;\n\t\tstate.tag = snapshot.tag;\n\t\tstate.anchor = snapshot.anchor;\n\t\tstate.kind = snapshot.kind;\n\t\tstate.result = snapshot.result;\n\t}\n\tvar directiveHandlers = {\n\t\tYAML: function handleYamlDirective(state, name, args) {\n\t\t\tif (state.version !== null) throwError(state, \"duplication of %YAML directive\");\n\t\t\tif (args.length !== 1) throwError(state, \"YAML directive accepts exactly one argument\");\n\t\t\tconst match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0]);\n\t\t\tif (match === null) throwError(state, \"ill-formed argument of the YAML directive\");\n\t\t\tconst major = parseInt(match[1], 10);\n\t\t\tconst minor = parseInt(match[2], 10);\n\t\t\tif (major !== 1) throwError(state, \"unacceptable YAML version of the document\");\n\t\t\tstate.version = args[0];\n\t\t\tstate.checkLineBreaks = minor < 2;\n\t\t\tif (minor !== 1 && minor !== 2) throwWarning(state, \"unsupported YAML version of the document\");\n\t\t},\n\t\tTAG: function handleTagDirective(state, name, args) {\n\t\t\tlet prefix;\n\t\t\tif (args.length !== 2) throwError(state, \"TAG directive accepts exactly two arguments\");\n\t\t\tconst handle = args[0];\n\t\t\tprefix = args[1];\n\t\t\tif (!PATTERN_TAG_HANDLE.test(handle)) throwError(state, \"ill-formed tag handle (first argument) of the TAG directive\");\n\t\t\tif (_hasOwnProperty.call(state.tagMap, handle)) throwError(state, \"there is a previously declared suffix for \\\"\" + handle + \"\\\" tag handle\");\n\t\t\tif (!PATTERN_TAG_URI.test(prefix)) throwError(state, \"ill-formed tag prefix (second argument) of the TAG directive\");\n\t\t\ttry {\n\t\t\t\tprefix = decodeURIComponent(prefix);\n\t\t\t} catch (err) {\n\t\t\t\tthrowError(state, \"tag prefix is malformed: \" + prefix);\n\t\t\t}\n\t\t\tstate.tagMap[handle] = prefix;\n\t\t}\n\t};\n\tfunction captureSegment(state, start, end, checkJson) {\n\t\tif (start < end) {\n\t\t\tconst _result = state.input.slice(start, end);\n\t\t\tif (checkJson) for (let _position = 0, _length = _result.length; _position < _length; _position += 1) {\n\t\t\t\tconst _character = _result.charCodeAt(_position);\n\t\t\t\tif (!(_character === 9 || _character >= 32 && _character <= 1114111)) throwError(state, \"expected valid JSON character\");\n\t\t\t}\n\t\t\telse if (PATTERN_NON_PRINTABLE.test(_result)) throwError(state, \"the stream contains non-printable characters\");\n\t\t\tstate.result += _result;\n\t\t}\n\t}\n\tfunction mergeMappings(state, destination, source, overridableKeys) {\n\t\tif (!common.isObject(source)) throwError(state, \"cannot merge mappings; the provided source object is unacceptable\");\n\t\tconst sourceKeys = Object.keys(source);\n\t\tfor (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n\t\t\tconst key = sourceKeys[index];\n\t\t\tif (!_hasOwnProperty.call(destination, key)) {\n\t\t\t\tsetProperty(destination, key, source[key]);\n\t\t\t\toverridableKeys[key] = true;\n\t\t\t}\n\t\t}\n\t}\n\tfunction storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {\n\t\tif (Array.isArray(keyNode)) {\n\t\t\tkeyNode = Array.prototype.slice.call(keyNode);\n\t\t\tfor (let index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n\t\t\t\tif (Array.isArray(keyNode[index])) throwError(state, \"nested arrays are not supported inside keys\");\n\t\t\t\tif (typeof keyNode === \"object\" && _class(keyNode[index]) === \"[object Object]\") keyNode[index] = \"[object Object]\";\n\t\t\t}\n\t\t}\n\t\tif (typeof keyNode === \"object\" && _class(keyNode) === \"[object Object]\") keyNode = \"[object Object]\";\n\t\tkeyNode = String(keyNode);\n\t\tif (_result === null) _result = {};\n\t\tif (keyTag === \"tag:yaml.org,2002:merge\") if (Array.isArray(valueNode)) {\n\t\t\tif (valueNode.length > state.maxMergeSeqLength) throwError(state, \"merge sequence length exceeded maxMergeSeqLength (\" + state.maxMergeSeqLength + \")\");\n\t\t\tconst seen = /* @__PURE__ */ new Set();\n\t\t\tfor (let index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n\t\t\t\tconst src = valueNode[index];\n\t\t\t\tif (seen.has(src)) continue;\n\t\t\t\tseen.add(src);\n\t\t\t\tmergeMappings(state, _result, src, overridableKeys);\n\t\t\t}\n\t\t} else mergeMappings(state, _result, valueNode, overridableKeys);\n\t\telse {\n\t\t\tif (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {\n\t\t\t\tstate.line = startLine || state.line;\n\t\t\t\tstate.lineStart = startLineStart || state.lineStart;\n\t\t\t\tstate.position = startPos || state.position;\n\t\t\t\tthrowError(state, \"duplicated mapping key\");\n\t\t\t}\n\t\t\tsetProperty(_result, keyNode, valueNode);\n\t\t\tdelete overridableKeys[keyNode];\n\t\t}\n\t\treturn _result;\n\t}\n\tfunction readLineBreak(state) {\n\t\tconst ch = state.input.charCodeAt(state.position);\n\t\tif (ch === 10) state.position++;\n\t\telse if (ch === 13) {\n\t\t\tstate.position++;\n\t\t\tif (state.input.charCodeAt(state.position) === 10) state.position++;\n\t\t} else throwError(state, \"a line break is expected\");\n\t\tstate.line += 1;\n\t\tstate.lineStart = state.position;\n\t\tstate.firstTabInLine = -1;\n\t}\n\tfunction skipSeparationSpace(state, allowComments, checkIndent) {\n\t\tlet lineBreaks = 0;\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\twhile (ch !== 0) {\n\t\t\twhile (isWhiteSpace(ch)) {\n\t\t\t\tif (ch === 9 && state.firstTabInLine === -1) state.firstTabInLine = state.position;\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t}\n\t\t\tif (allowComments && ch === 35) do\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\twhile (ch !== 10 && ch !== 13 && ch !== 0);\n\t\t\tif (isEol(ch)) {\n\t\t\t\treadLineBreak(state);\n\t\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\t\tlineBreaks++;\n\t\t\t\tstate.lineIndent = 0;\n\t\t\t\twhile (ch === 32) {\n\t\t\t\t\tstate.lineIndent++;\n\t\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t\t}\n\t\t\t} else break;\n\t\t}\n\t\tif (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) throwWarning(state, \"deficient indentation\");\n\t\treturn lineBreaks;\n\t}\n\tfunction testDocumentSeparator(state) {\n\t\tlet _position = state.position;\n\t\tlet ch = state.input.charCodeAt(_position);\n\t\tif ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {\n\t\t\t_position += 3;\n\t\t\tch = state.input.charCodeAt(_position);\n\t\t\tif (ch === 0 || isWsOrEol(ch)) return true;\n\t\t}\n\t\treturn false;\n\t}\n\tfunction writeFoldedLines(state, count) {\n\t\tif (count === 1) state.result += \" \";\n\t\telse if (count > 1) state.result += common.repeat(\"\\n\", count - 1);\n\t}\n\tfunction readPlainScalar(state, nodeIndent, withinFlowCollection) {\n\t\tlet captureStart;\n\t\tlet captureEnd;\n\t\tlet hasPendingContent;\n\t\tlet _line;\n\t\tlet _lineStart;\n\t\tlet _lineIndent;\n\t\tconst _kind = state.kind;\n\t\tconst _result = state.result;\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\tif (isWsOrEol(ch) || isFlowIndicator(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) return false;\n\t\tif (ch === 63 || ch === 45) {\n\t\t\tconst following = state.input.charCodeAt(state.position + 1);\n\t\t\tif (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) return false;\n\t\t}\n\t\tstate.kind = \"scalar\";\n\t\tstate.result = \"\";\n\t\tcaptureStart = captureEnd = state.position;\n\t\thasPendingContent = false;\n\t\twhile (ch !== 0) {\n\t\t\tif (ch === 58) {\n\t\t\t\tconst following = state.input.charCodeAt(state.position + 1);\n\t\t\t\tif (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) break;\n\t\t\t} else if (ch === 35) {\n\t\t\t\tif (isWsOrEol(state.input.charCodeAt(state.position - 1))) break;\n\t\t\t} else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && isFlowIndicator(ch)) break;\n\t\t\telse if (isEol(ch)) {\n\t\t\t\t_line = state.line;\n\t\t\t\t_lineStart = state.lineStart;\n\t\t\t\t_lineIndent = state.lineIndent;\n\t\t\t\tskipSeparationSpace(state, false, -1);\n\t\t\t\tif (state.lineIndent >= nodeIndent) {\n\t\t\t\t\thasPendingContent = true;\n\t\t\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tstate.position = captureEnd;\n\t\t\t\t\tstate.line = _line;\n\t\t\t\t\tstate.lineStart = _lineStart;\n\t\t\t\t\tstate.lineIndent = _lineIndent;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasPendingContent) {\n\t\t\t\tcaptureSegment(state, captureStart, captureEnd, false);\n\t\t\t\twriteFoldedLines(state, state.line - _line);\n\t\t\t\tcaptureStart = captureEnd = state.position;\n\t\t\t\thasPendingContent = false;\n\t\t\t}\n\t\t\tif (!isWhiteSpace(ch)) captureEnd = state.position + 1;\n\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t}\n\t\tcaptureSegment(state, captureStart, captureEnd, false);\n\t\tif (state.result) return true;\n\t\tstate.kind = _kind;\n\t\tstate.result = _result;\n\t\treturn false;\n\t}\n\tfunction readSingleQuotedScalar(state, nodeIndent) {\n\t\tlet captureStart;\n\t\tlet captureEnd;\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\tif (ch !== 39) return false;\n\t\tstate.kind = \"scalar\";\n\t\tstate.result = \"\";\n\t\tstate.position++;\n\t\tcaptureStart = captureEnd = state.position;\n\t\twhile ((ch = state.input.charCodeAt(state.position)) !== 0) if (ch === 39) {\n\t\t\tcaptureSegment(state, captureStart, state.position, true);\n\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\tif (ch === 39) {\n\t\t\t\tcaptureStart = state.position;\n\t\t\t\tstate.position++;\n\t\t\t\tcaptureEnd = state.position;\n\t\t\t} else return true;\n\t\t} else if (isEol(ch)) {\n\t\t\tcaptureSegment(state, captureStart, captureEnd, true);\n\t\t\twriteFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n\t\t\tcaptureStart = captureEnd = state.position;\n\t\t} else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, \"unexpected end of the document within a single quoted scalar\");\n\t\telse {\n\t\t\tstate.position++;\n\t\t\tif (!isWhiteSpace(ch)) captureEnd = state.position;\n\t\t}\n\t\tthrowError(state, \"unexpected end of the stream within a single quoted scalar\");\n\t}\n\tfunction readDoubleQuotedScalar(state, nodeIndent) {\n\t\tlet captureStart;\n\t\tlet captureEnd;\n\t\tlet tmp;\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\tif (ch !== 34) return false;\n\t\tstate.kind = \"scalar\";\n\t\tstate.result = \"\";\n\t\tstate.position++;\n\t\tcaptureStart = captureEnd = state.position;\n\t\twhile ((ch = state.input.charCodeAt(state.position)) !== 0) if (ch === 34) {\n\t\t\tcaptureSegment(state, captureStart, state.position, true);\n\t\t\tstate.position++;\n\t\t\treturn true;\n\t\t} else if (ch === 92) {\n\t\t\tcaptureSegment(state, captureStart, state.position, true);\n\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\tif (isEol(ch)) skipSeparationSpace(state, false, nodeIndent);\n\t\t\telse if (ch < 256 && simpleEscapeCheck[ch]) {\n\t\t\t\tstate.result += simpleEscapeMap[ch];\n\t\t\t\tstate.position++;\n\t\t\t} else if ((tmp = escapedHexLen(ch)) > 0) {\n\t\t\t\tlet hexLength = tmp;\n\t\t\t\tlet hexResult = 0;\n\t\t\t\tfor (; hexLength > 0; hexLength--) {\n\t\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t\t\tif ((tmp = fromHexCode(ch)) >= 0) hexResult = (hexResult << 4) + tmp;\n\t\t\t\t\telse throwError(state, \"expected hexadecimal character\");\n\t\t\t\t}\n\t\t\t\tstate.result += charFromCodepoint(hexResult);\n\t\t\t\tstate.position++;\n\t\t\t} else throwError(state, \"unknown escape sequence\");\n\t\t\tcaptureStart = captureEnd = state.position;\n\t\t} else if (isEol(ch)) {\n\t\t\tcaptureSegment(state, captureStart, captureEnd, true);\n\t\t\twriteFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n\t\t\tcaptureStart = captureEnd = state.position;\n\t\t} else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, \"unexpected end of the document within a double quoted scalar\");\n\t\telse {\n\t\t\tstate.position++;\n\t\t\tif (!isWhiteSpace(ch)) captureEnd = state.position;\n\t\t}\n\t\tthrowError(state, \"unexpected end of the stream within a double quoted scalar\");\n\t}\n\tfunction readFlowCollection(state, nodeIndent) {\n\t\tlet readNext = true;\n\t\tlet _line;\n\t\tlet _lineStart;\n\t\tlet _pos;\n\t\tconst _tag = state.tag;\n\t\tlet _result;\n\t\tconst _anchor = state.anchor;\n\t\tlet terminator;\n\t\tlet isPair;\n\t\tlet isExplicitPair;\n\t\tlet isMapping;\n\t\tconst overridableKeys = Object.create(null);\n\t\tlet keyNode;\n\t\tlet keyTag;\n\t\tlet valueNode;\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\tif (ch === 91) {\n\t\t\tterminator = 93;\n\t\t\tisMapping = false;\n\t\t\t_result = [];\n\t\t} else if (ch === 123) {\n\t\t\tterminator = 125;\n\t\t\tisMapping = true;\n\t\t\t_result = {};\n\t\t} else return false;\n\t\tif (state.anchor !== null) storeAnchor(state, state.anchor, _result);\n\t\tch = state.input.charCodeAt(++state.position);\n\t\twhile (ch !== 0) {\n\t\t\tskipSeparationSpace(state, true, nodeIndent);\n\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\tif (ch === terminator) {\n\t\t\t\tstate.position++;\n\t\t\t\tstate.tag = _tag;\n\t\t\t\tstate.anchor = _anchor;\n\t\t\t\tstate.kind = isMapping ? \"mapping\" : \"sequence\";\n\t\t\t\tstate.result = _result;\n\t\t\t\treturn true;\n\t\t\t} else if (!readNext) throwError(state, \"missed comma between flow collection entries\");\n\t\t\telse if (ch === 44) throwError(state, \"expected the node content, but found ','\");\n\t\t\tkeyTag = keyNode = valueNode = null;\n\t\t\tisPair = isExplicitPair = false;\n\t\t\tif (ch === 63) {\n\t\t\t\tif (isWsOrEol(state.input.charCodeAt(state.position + 1))) {\n\t\t\t\t\tisPair = isExplicitPair = true;\n\t\t\t\t\tstate.position++;\n\t\t\t\t\tskipSeparationSpace(state, true, nodeIndent);\n\t\t\t\t}\n\t\t\t}\n\t\t\t_line = state.line;\n\t\t\t_lineStart = state.lineStart;\n\t\t\t_pos = state.position;\n\t\t\tcomposeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n\t\t\tkeyTag = state.tag;\n\t\t\tkeyNode = state.result;\n\t\t\tskipSeparationSpace(state, true, nodeIndent);\n\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\tif ((isExplicitPair || state.line === _line) && ch === 58) {\n\t\t\t\tisPair = true;\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t\tskipSeparationSpace(state, true, nodeIndent);\n\t\t\t\tcomposeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n\t\t\t\tvalueNode = state.result;\n\t\t\t}\n\t\t\tif (isMapping) storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);\n\t\t\telse if (isPair) _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));\n\t\t\telse _result.push(keyNode);\n\t\t\tskipSeparationSpace(state, true, nodeIndent);\n\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\tif (ch === 44) {\n\t\t\t\treadNext = true;\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t} else readNext = false;\n\t\t}\n\t\tthrowError(state, \"unexpected end of the stream within a flow collection\");\n\t}\n\tfunction readBlockScalar(state, nodeIndent) {\n\t\tlet folding;\n\t\tlet chomping = CHOMPING_CLIP;\n\t\tlet didReadContent = false;\n\t\tlet detectedIndent = false;\n\t\tlet textIndent = nodeIndent;\n\t\tlet emptyLines = 0;\n\t\tlet atMoreIndented = false;\n\t\tlet tmp;\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\tif (ch === 124) folding = false;\n\t\telse if (ch === 62) folding = true;\n\t\telse return false;\n\t\tstate.kind = \"scalar\";\n\t\tstate.result = \"\";\n\t\twhile (ch !== 0) {\n\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\tif (ch === 43 || ch === 45) if (CHOMPING_CLIP === chomping) chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;\n\t\t\telse throwError(state, \"repeat of a chomping mode identifier\");\n\t\t\telse if ((tmp = fromDecimalCode(ch)) >= 0) if (tmp === 0) throwError(state, \"bad explicit indentation width of a block scalar; it cannot be less than one\");\n\t\t\telse if (!detectedIndent) {\n\t\t\t\ttextIndent = nodeIndent + tmp - 1;\n\t\t\t\tdetectedIndent = true;\n\t\t\t} else throwError(state, \"repeat of an indentation width identifier\");\n\t\t\telse break;\n\t\t}\n\t\tif (isWhiteSpace(ch)) {\n\t\t\tdo\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\twhile (isWhiteSpace(ch));\n\t\t\tif (ch === 35) do\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\twhile (!isEol(ch) && ch !== 0);\n\t\t}\n\t\twhile (ch !== 0) {\n\t\t\treadLineBreak(state);\n\t\t\tstate.lineIndent = 0;\n\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\twhile ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {\n\t\t\t\tstate.lineIndent++;\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t}\n\t\t\tif (!detectedIndent && state.lineIndent > textIndent) textIndent = state.lineIndent;\n\t\t\tif (isEol(ch)) {\n\t\t\t\temptyLines++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!detectedIndent && textIndent === 0) throwError(state, \"missing indentation for block scalar\");\n\t\t\tif (state.lineIndent < textIndent) {\n\t\t\t\tif (chomping === CHOMPING_KEEP) state.result += common.repeat(\"\\n\", didReadContent ? 1 + emptyLines : emptyLines);\n\t\t\t\telse if (chomping === CHOMPING_CLIP) {\n\t\t\t\t\tif (didReadContent) state.result += \"\\n\";\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (folding) if (isWhiteSpace(ch)) {\n\t\t\t\tatMoreIndented = true;\n\t\t\t\tstate.result += common.repeat(\"\\n\", didReadContent ? 1 + emptyLines : emptyLines);\n\t\t\t} else if (atMoreIndented) {\n\t\t\t\tatMoreIndented = false;\n\t\t\t\tstate.result += common.repeat(\"\\n\", emptyLines + 1);\n\t\t\t} else if (emptyLines === 0) {\n\t\t\t\tif (didReadContent) state.result += \" \";\n\t\t\t} else state.result += common.repeat(\"\\n\", emptyLines);\n\t\t\telse state.result += common.repeat(\"\\n\", didReadContent ? 1 + emptyLines : emptyLines);\n\t\t\tdidReadContent = true;\n\t\t\tdetectedIndent = true;\n\t\t\temptyLines = 0;\n\t\t\tconst captureStart = state.position;\n\t\t\twhile (!isEol(ch) && ch !== 0) ch = state.input.charCodeAt(++state.position);\n\t\t\tcaptureSegment(state, captureStart, state.position, false);\n\t\t}\n\t\treturn true;\n\t}\n\tfunction readBlockSequence(state, nodeIndent) {\n\t\tconst _tag = state.tag;\n\t\tconst _anchor = state.anchor;\n\t\tconst _result = [];\n\t\tlet detected = false;\n\t\tif (state.firstTabInLine !== -1) return false;\n\t\tif (state.anchor !== null) storeAnchor(state, state.anchor, _result);\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\twhile (ch !== 0) {\n\t\t\tif (state.firstTabInLine !== -1) {\n\t\t\t\tstate.position = state.firstTabInLine;\n\t\t\t\tthrowError(state, \"tab characters must not be used in indentation\");\n\t\t\t}\n\t\t\tif (ch !== 45) break;\n\t\t\tif (!isWsOrEol(state.input.charCodeAt(state.position + 1))) break;\n\t\t\tdetected = true;\n\t\t\tstate.position++;\n\t\t\tif (skipSeparationSpace(state, true, -1)) {\n\t\t\t\tif (state.lineIndent <= nodeIndent) {\n\t\t\t\t\t_result.push(null);\n\t\t\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst _line = state.line;\n\t\t\tcomposeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);\n\t\t\t_result.push(state.result);\n\t\t\tskipSeparationSpace(state, true, -1);\n\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\tif ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, \"bad indentation of a sequence entry\");\n\t\t\telse if (state.lineIndent < nodeIndent) break;\n\t\t}\n\t\tif (detected) {\n\t\t\tstate.tag = _tag;\n\t\t\tstate.anchor = _anchor;\n\t\t\tstate.kind = \"sequence\";\n\t\t\tstate.result = _result;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tfunction readBlockMapping(state, nodeIndent, flowIndent) {\n\t\tlet allowCompact;\n\t\tlet _keyLine;\n\t\tlet _keyLineStart;\n\t\tlet _keyPos;\n\t\tconst _tag = state.tag;\n\t\tconst _anchor = state.anchor;\n\t\tconst _result = {};\n\t\tconst overridableKeys = Object.create(null);\n\t\tlet keyTag = null;\n\t\tlet keyNode = null;\n\t\tlet valueNode = null;\n\t\tlet atExplicitKey = false;\n\t\tlet detected = false;\n\t\tif (state.firstTabInLine !== -1) return false;\n\t\tif (state.anchor !== null) storeAnchor(state, state.anchor, _result);\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\twhile (ch !== 0) {\n\t\t\tif (!atExplicitKey && state.firstTabInLine !== -1) {\n\t\t\t\tstate.position = state.firstTabInLine;\n\t\t\t\tthrowError(state, \"tab characters must not be used in indentation\");\n\t\t\t}\n\t\t\tconst following = state.input.charCodeAt(state.position + 1);\n\t\t\tconst _line = state.line;\n\t\t\tif ((ch === 63 || ch === 58) && isWsOrEol(following)) {\n\t\t\t\tif (ch === 63) {\n\t\t\t\t\tif (atExplicitKey) {\n\t\t\t\t\t\tstoreMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n\t\t\t\t\t\tkeyTag = keyNode = valueNode = null;\n\t\t\t\t\t}\n\t\t\t\t\tdetected = true;\n\t\t\t\t\tatExplicitKey = true;\n\t\t\t\t\tallowCompact = true;\n\t\t\t\t} else if (atExplicitKey) {\n\t\t\t\t\tatExplicitKey = false;\n\t\t\t\t\tallowCompact = true;\n\t\t\t\t} else throwError(state, \"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line\");\n\t\t\t\tstate.position += 1;\n\t\t\t\tch = following;\n\t\t\t} else {\n\t\t\t\t_keyLine = state.line;\n\t\t\t\t_keyLineStart = state.lineStart;\n\t\t\t\t_keyPos = state.position;\n\t\t\t\tif (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) break;\n\t\t\t\tif (state.line === _line) {\n\t\t\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\t\t\twhile (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);\n\t\t\t\t\tif (ch === 58) {\n\t\t\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t\t\t\tif (!isWsOrEol(ch)) throwError(state, \"a whitespace character is expected after the key-value separator within a block mapping\");\n\t\t\t\t\t\tif (atExplicitKey) {\n\t\t\t\t\t\t\tstoreMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n\t\t\t\t\t\t\tkeyTag = keyNode = valueNode = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdetected = true;\n\t\t\t\t\t\tatExplicitKey = false;\n\t\t\t\t\t\tallowCompact = false;\n\t\t\t\t\t\tkeyTag = state.tag;\n\t\t\t\t\t\tkeyNode = state.result;\n\t\t\t\t\t} else if (detected) throwError(state, \"can not read an implicit mapping pair; a colon is missed\");\n\t\t\t\t\telse {\n\t\t\t\t\t\tstate.tag = _tag;\n\t\t\t\t\t\tstate.anchor = _anchor;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t} else if (detected) throwError(state, \"can not read a block mapping entry; a multiline key may not be an implicit key\");\n\t\t\t\telse {\n\t\t\t\t\tstate.tag = _tag;\n\t\t\t\t\tstate.anchor = _anchor;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (state.line === _line || state.lineIndent > nodeIndent) {\n\t\t\t\tif (atExplicitKey) {\n\t\t\t\t\t_keyLine = state.line;\n\t\t\t\t\t_keyLineStart = state.lineStart;\n\t\t\t\t\t_keyPos = state.position;\n\t\t\t\t}\n\t\t\t\tif (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) if (atExplicitKey) keyNode = state.result;\n\t\t\t\telse valueNode = state.result;\n\t\t\t\tif (!atExplicitKey) {\n\t\t\t\t\tstoreMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);\n\t\t\t\t\tkeyTag = keyNode = valueNode = null;\n\t\t\t\t}\n\t\t\t\tskipSeparationSpace(state, true, -1);\n\t\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\t}\n\t\t\tif ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, \"bad indentation of a mapping entry\");\n\t\t\telse if (state.lineIndent < nodeIndent) break;\n\t\t}\n\t\tif (atExplicitKey) storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);\n\t\tif (detected) {\n\t\t\tstate.tag = _tag;\n\t\t\tstate.anchor = _anchor;\n\t\t\tstate.kind = \"mapping\";\n\t\t\tstate.result = _result;\n\t\t}\n\t\treturn detected;\n\t}\n\tfunction readTagProperty(state) {\n\t\tlet isVerbatim = false;\n\t\tlet isNamed = false;\n\t\tlet tagHandle;\n\t\tlet tagName;\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\tif (ch !== 33) return false;\n\t\tif (state.tag !== null) throwError(state, \"duplication of a tag property\");\n\t\tch = state.input.charCodeAt(++state.position);\n\t\tif (ch === 60) {\n\t\t\tisVerbatim = true;\n\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t} else if (ch === 33) {\n\t\t\tisNamed = true;\n\t\t\ttagHandle = \"!!\";\n\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t} else tagHandle = \"!\";\n\t\tlet _position = state.position;\n\t\tif (isVerbatim) {\n\t\t\tdo\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\twhile (ch !== 0 && ch !== 62);\n\t\t\tif (state.position < state.length) {\n\t\t\t\ttagName = state.input.slice(_position, state.position);\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t} else throwError(state, \"unexpected end of the stream within a verbatim tag\");\n\t\t} else {\n\t\t\twhile (ch !== 0 && !isWsOrEol(ch)) {\n\t\t\t\tif (ch === 33) if (!isNamed) {\n\t\t\t\t\ttagHandle = state.input.slice(_position - 1, state.position + 1);\n\t\t\t\t\tif (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, \"named tag handle cannot contain such characters\");\n\t\t\t\t\tisNamed = true;\n\t\t\t\t\t_position = state.position + 1;\n\t\t\t\t} else throwError(state, \"tag suffix cannot contain exclamation marks\");\n\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t}\n\t\t\ttagName = state.input.slice(_position, state.position);\n\t\t\tif (PATTERN_FLOW_INDICATORS.test(tagName)) throwError(state, \"tag suffix cannot contain flow indicator characters\");\n\t\t}\n\t\tif (tagName && !PATTERN_TAG_URI.test(tagName)) throwError(state, \"tag name cannot contain such characters: \" + tagName);\n\t\ttry {\n\t\t\ttagName = decodeURIComponent(tagName);\n\t\t} catch (err) {\n\t\t\tthrowError(state, \"tag name is malformed: \" + tagName);\n\t\t}\n\t\tif (isVerbatim) state.tag = tagName;\n\t\telse if (_hasOwnProperty.call(state.tagMap, tagHandle)) state.tag = state.tagMap[tagHandle] + tagName;\n\t\telse if (tagHandle === \"!\") state.tag = \"!\" + tagName;\n\t\telse if (tagHandle === \"!!\") state.tag = \"tag:yaml.org,2002:\" + tagName;\n\t\telse throwError(state, \"undeclared tag handle \\\"\" + tagHandle + \"\\\"\");\n\t\treturn true;\n\t}\n\tfunction readAnchorProperty(state) {\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\tif (ch !== 38) return false;\n\t\tif (state.anchor !== null) throwError(state, \"duplication of an anchor property\");\n\t\tch = state.input.charCodeAt(++state.position);\n\t\tconst _position = state.position;\n\t\twhile (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) ch = state.input.charCodeAt(++state.position);\n\t\tif (state.position === _position) throwError(state, \"name of an anchor node must contain at least one character\");\n\t\tstate.anchor = state.input.slice(_position, state.position);\n\t\treturn true;\n\t}\n\tfunction readAlias(state) {\n\t\tlet ch = state.input.charCodeAt(state.position);\n\t\tif (ch !== 42) return false;\n\t\tch = state.input.charCodeAt(++state.position);\n\t\tconst _position = state.position;\n\t\twhile (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) ch = state.input.charCodeAt(++state.position);\n\t\tif (state.position === _position) throwError(state, \"name of an alias node must contain at least one character\");\n\t\tconst alias = state.input.slice(_position, state.position);\n\t\tif (!_hasOwnProperty.call(state.anchorMap, alias)) throwError(state, \"unidentified alias \\\"\" + alias + \"\\\"\");\n\t\tstate.result = state.anchorMap[alias];\n\t\tskipSeparationSpace(state, true, -1);\n\t\treturn true;\n\t}\n\tfunction tryReadBlockMappingFromProperty(state, propertyStart, nodeIndent, flowIndent) {\n\t\tconst fallbackState = snapshotState(state);\n\t\tbeginAnchorTransaction(state);\n\t\trestoreState(state, propertyStart);\n\t\tstate.tag = null;\n\t\tstate.anchor = null;\n\t\tstate.kind = null;\n\t\tstate.result = null;\n\t\tif (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === \"mapping\") {\n\t\t\tcommitAnchorTransaction(state);\n\t\t\treturn true;\n\t\t}\n\t\trollbackAnchorTransaction(state);\n\t\trestoreState(state, fallbackState);\n\t\treturn false;\n\t}\n\tfunction composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n\t\tlet allowBlockScalars;\n\t\tlet allowBlockCollections;\n\t\tlet indentStatus = 1;\n\t\tlet atNewLine = false;\n\t\tlet hasContent = false;\n\t\tlet propertyStart = null;\n\t\tlet type;\n\t\tlet flowIndent;\n\t\tlet blockIndent;\n\t\tif (state.depth >= state.maxDepth) throwError(state, \"nesting exceeded maxDepth (\" + state.maxDepth + \")\");\n\t\tstate.depth += 1;\n\t\tif (state.listener !== null) state.listener(\"open\", state);\n\t\tstate.tag = null;\n\t\tstate.anchor = null;\n\t\tstate.kind = null;\n\t\tstate.result = null;\n\t\tconst allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;\n\t\tif (allowToSeek) {\n\t\t\tif (skipSeparationSpace(state, true, -1)) {\n\t\t\t\tatNewLine = true;\n\t\t\t\tif (state.lineIndent > parentIndent) indentStatus = 1;\n\t\t\t\telse if (state.lineIndent === parentIndent) indentStatus = 0;\n\t\t\t\telse if (state.lineIndent < parentIndent) indentStatus = -1;\n\t\t\t}\n\t\t}\n\t\tif (indentStatus === 1) while (true) {\n\t\t\tconst ch = state.input.charCodeAt(state.position);\n\t\t\tconst propertyState = snapshotState(state);\n\t\t\tif (atNewLine && (ch === 33 && state.tag !== null || ch === 38 && state.anchor !== null)) break;\n\t\t\tif (!readTagProperty(state) && !readAnchorProperty(state)) break;\n\t\t\tif (propertyStart === null) propertyStart = propertyState;\n\t\t\tif (skipSeparationSpace(state, true, -1)) {\n\t\t\t\tatNewLine = true;\n\t\t\t\tallowBlockCollections = allowBlockStyles;\n\t\t\t\tif (state.lineIndent > parentIndent) indentStatus = 1;\n\t\t\t\telse if (state.lineIndent === parentIndent) indentStatus = 0;\n\t\t\t\telse if (state.lineIndent < parentIndent) indentStatus = -1;\n\t\t\t} else allowBlockCollections = false;\n\t\t}\n\t\tif (allowBlockCollections) allowBlockCollections = atNewLine || allowCompact;\n\t\tif (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n\t\t\tif (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) flowIndent = parentIndent;\n\t\t\telse flowIndent = parentIndent + 1;\n\t\t\tblockIndent = state.position - state.lineStart;\n\t\t\tif (indentStatus === 1) if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) hasContent = true;\n\t\t\telse {\n\t\t\t\tconst ch = state.input.charCodeAt(state.position);\n\t\t\t\tif (propertyStart !== null && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62 && tryReadBlockMappingFromProperty(state, propertyStart, propertyStart.position - propertyStart.lineStart, flowIndent)) hasContent = true;\n\t\t\t\telse if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) hasContent = true;\n\t\t\t\telse if (readAlias(state)) {\n\t\t\t\t\thasContent = true;\n\t\t\t\t\tif (state.tag !== null || state.anchor !== null) throwError(state, \"alias node should not have any properties\");\n\t\t\t\t} else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n\t\t\t\t\thasContent = true;\n\t\t\t\t\tif (state.tag === null) state.tag = \"?\";\n\t\t\t\t}\n\t\t\t\tif (state.anchor !== null) storeAnchor(state, state.anchor, state.result);\n\t\t\t}\n\t\t\telse if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);\n\t\t}\n\t\tif (state.tag === null) {\n\t\t\tif (state.anchor !== null) storeAnchor(state, state.anchor, state.result);\n\t\t} else if (state.tag === \"?\") {\n\t\t\tif (state.result !== null && state.kind !== \"scalar\") throwError(state, \"unacceptable node kind for !<?> tag; it should be \\\"scalar\\\", not \\\"\" + state.kind + \"\\\"\");\n\t\t\tfor (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n\t\t\t\ttype = state.implicitTypes[typeIndex];\n\t\t\t\tif (type.resolve(state.result)) {\n\t\t\t\t\tstate.result = type.construct(state.result);\n\t\t\t\t\tstate.tag = type.tag;\n\t\t\t\t\tif (state.anchor !== null) storeAnchor(state, state.anchor, state.result);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (state.tag !== \"!\") {\n\t\t\tif (_hasOwnProperty.call(state.typeMap[state.kind || \"fallback\"], state.tag)) type = state.typeMap[state.kind || \"fallback\"][state.tag];\n\t\t\telse {\n\t\t\t\ttype = null;\n\t\t\t\tconst typeList = state.typeMap.multi[state.kind || \"fallback\"];\n\t\t\t\tfor (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {\n\t\t\t\t\ttype = typeList[typeIndex];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!type) throwError(state, \"unknown tag !<\" + state.tag + \">\");\n\t\t\tif (state.result !== null && type.kind !== state.kind) throwError(state, \"unacceptable node kind for !<\" + state.tag + \"> tag; it should be \\\"\" + type.kind + \"\\\", not \\\"\" + state.kind + \"\\\"\");\n\t\t\tif (!type.resolve(state.result, state.tag)) throwError(state, \"cannot resolve a node with !<\" + state.tag + \"> explicit tag\");\n\t\t\telse {\n\t\t\t\tstate.result = type.construct(state.result, state.tag);\n\t\t\t\tif (state.anchor !== null) storeAnchor(state, state.anchor, state.result);\n\t\t\t}\n\t\t}\n\t\tif (state.listener !== null) state.listener(\"close\", state);\n\t\tstate.depth -= 1;\n\t\treturn state.tag !== null || state.anchor !== null || hasContent;\n\t}\n\tfunction readDocument(state) {\n\t\tconst documentStart = state.position;\n\t\tlet hasDirectives = false;\n\t\tlet ch;\n\t\tstate.version = null;\n\t\tstate.checkLineBreaks = state.legacy;\n\t\tstate.tagMap = Object.create(null);\n\t\tstate.anchorMap = Object.create(null);\n\t\twhile ((ch = state.input.charCodeAt(state.position)) !== 0) {\n\t\t\tskipSeparationSpace(state, true, -1);\n\t\t\tch = state.input.charCodeAt(state.position);\n\t\t\tif (state.lineIndent > 0 || ch !== 37) break;\n\t\t\thasDirectives = true;\n\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\tlet _position = state.position;\n\t\t\twhile (ch !== 0 && !isWsOrEol(ch)) ch = state.input.charCodeAt(++state.position);\n\t\t\tconst directiveName = state.input.slice(_position, state.position);\n\t\t\tconst directiveArgs = [];\n\t\t\tif (directiveName.length < 1) throwError(state, \"directive name must not be less than one character in length\");\n\t\t\twhile (ch !== 0) {\n\t\t\t\twhile (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);\n\t\t\t\tif (ch === 35) {\n\t\t\t\t\tdo\n\t\t\t\t\t\tch = state.input.charCodeAt(++state.position);\n\t\t\t\t\twhile (ch !== 0 && !isEol(ch));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (isEol(ch)) break;\n\t\t\t\t_position = state.position;\n\t\t\t\twhile (ch !== 0 && !isWsOrEol(ch)) ch = state.input.charCodeAt(++state.position);\n\t\t\t\tdirectiveArgs.push(state.input.slice(_position, state.position));\n\t\t\t}\n\t\t\tif (ch !== 0) readLineBreak(state);\n\t\t\tif (_hasOwnProperty.call(directiveHandlers, directiveName)) directiveHandlers[directiveName](state, directiveName, directiveArgs);\n\t\t\telse throwWarning(state, \"unknown document directive \\\"\" + directiveName + \"\\\"\");\n\t\t}\n\t\tskipSeparationSpace(state, true, -1);\n\t\tif (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {\n\t\t\tstate.position += 3;\n\t\t\tskipSeparationSpace(state, true, -1);\n\t\t} else if (hasDirectives) throwError(state, \"directives end mark is expected\");\n\t\tcomposeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);\n\t\tskipSeparationSpace(state, true, -1);\n\t\tif (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) throwWarning(state, \"non-ASCII line breaks are interpreted as content\");\n\t\tstate.documents.push(state.result);\n\t\tif (state.position === state.lineStart && testDocumentSeparator(state)) {\n\t\t\tif (state.input.charCodeAt(state.position) === 46) {\n\t\t\t\tstate.position += 3;\n\t\t\t\tskipSeparationSpace(state, true, -1);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (state.position < state.length - 1) throwError(state, \"end of the stream or a document separator is expected\");\n\t}\n\tfunction loadDocuments(input, options) {\n\t\tinput = String(input);\n\t\toptions = options || {};\n\t\tif (input.length !== 0) {\n\t\t\tif (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) input += \"\\n\";\n\t\t\tif (input.charCodeAt(0) === 65279) input = input.slice(1);\n\t\t}\n\t\tconst state = new State(input, options);\n\t\tconst nullpos = input.indexOf(\"\\0\");\n\t\tif (nullpos !== -1) {\n\t\t\tstate.position = nullpos;\n\t\t\tthrowError(state, \"null byte is not allowed in input\");\n\t\t}\n\t\tstate.input += \"\\0\";\n\t\twhile (state.input.charCodeAt(state.position) === 32) {\n\t\t\tstate.lineIndent += 1;\n\t\t\tstate.position += 1;\n\t\t}\n\t\twhile (state.position < state.length - 1) readDocument(state);\n\t\treturn state.documents;\n\t}\n\tfunction loadAll(input, iterator, options) {\n\t\tif (iterator !== null && typeof iterator === \"object\" && typeof options === \"undefined\") {\n\t\t\toptions = iterator;\n\t\t\titerator = null;\n\t\t}\n\t\tconst documents = loadDocuments(input, options);\n\t\tif (typeof iterator !== \"function\") return documents;\n\t\tfor (let index = 0, length = documents.length; index < length; index += 1) iterator(documents[index]);\n\t}\n\tfunction load(input, options) {\n\t\tconst documents = loadDocuments(input, options);\n\t\tif (documents.length === 0) return;\n\t\telse if (documents.length === 1) return documents[0];\n\t\tthrow new YAMLException(\"expected a single document in the stream, but found more\");\n\t}\n\tmodule.exports.loadAll = loadAll;\n\tmodule.exports.load = load;\n}));\n//#endregion\n//#region lib/dumper.js\nvar require_dumper = /* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar common = require_common();\n\tvar YAMLException = require_exception();\n\tvar DEFAULT_SCHEMA = require_default();\n\tvar _toString = Object.prototype.toString;\n\tvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\tvar CHAR_BOM = 65279;\n\tvar CHAR_TAB = 9;\n\tvar CHAR_LINE_FEED = 10;\n\tvar CHAR_CARRIAGE_RETURN = 13;\n\tvar CHAR_SPACE = 32;\n\tvar CHAR_EXCLAMATION = 33;\n\tvar CHAR_DOUBLE_QUOTE = 34;\n\tvar CHAR_SHARP = 35;\n\tvar CHAR_PERCENT = 37;\n\tvar CHAR_AMPERSAND = 38;\n\tvar CHAR_SINGLE_QUOTE = 39;\n\tvar CHAR_ASTERISK = 42;\n\tvar CHAR_COMMA = 44;\n\tvar CHAR_MINUS = 45;\n\tvar CHAR_COLON = 58;\n\tvar CHAR_EQUALS = 61;\n\tvar CHAR_GREATER_THAN = 62;\n\tvar CHAR_QUESTION = 63;\n\tvar CHAR_COMMERCIAL_AT = 64;\n\tvar CHAR_LEFT_SQUARE_BRACKET = 91;\n\tvar CHAR_RIGHT_SQUARE_BRACKET = 93;\n\tvar CHAR_GRAVE_ACCENT = 96;\n\tvar CHAR_LEFT_CURLY_BRACKET = 123;\n\tvar CHAR_VERTICAL_LINE = 124;\n\tvar CHAR_RIGHT_CURLY_BRACKET = 125;\n\tvar ESCAPE_SEQUENCES = {};\n\tESCAPE_SEQUENCES[0] = \"\\\\0\";\n\tESCAPE_SEQUENCES[7] = \"\\\\a\";\n\tESCAPE_SEQUENCES[8] = \"\\\\b\";\n\tESCAPE_SEQUENCES[9] = \"\\\\t\";\n\tESCAPE_SEQUENCES[10] = \"\\\\n\";\n\tESCAPE_SEQUENCES[11] = \"\\\\v\";\n\tESCAPE_SEQUENCES[12] = \"\\\\f\";\n\tESCAPE_SEQUENCES[13] = \"\\\\r\";\n\tESCAPE_SEQUENCES[27] = \"\\\\e\";\n\tESCAPE_SEQUENCES[34] = \"\\\\\\\"\";\n\tESCAPE_SEQUENCES[92] = \"\\\\\\\\\";\n\tESCAPE_SEQUENCES[133] = \"\\\\N\";\n\tESCAPE_SEQUENCES[160] = \"\\\\_\";\n\tESCAPE_SEQUENCES[8232] = \"\\\\L\";\n\tESCAPE_SEQUENCES[8233] = \"\\\\P\";\n\tvar DEPRECATED_BOOLEANS_SYNTAX = [\n\t\t\"y\",\n\t\t\"Y\",\n\t\t\"yes\",\n\t\t\"Yes\",\n\t\t\"YES\",\n\t\t\"on\",\n\t\t\"On\",\n\t\t\"ON\",\n\t\t\"n\",\n\t\t\"N\",\n\t\t\"no\",\n\t\t\"No\",\n\t\t\"NO\",\n\t\t\"off\",\n\t\t\"Off\",\n\t\t\"OFF\"\n\t];\n\tvar DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\\.[0-9_]*)?$/;\n\tfunction compileStyleMap(schema, map) {\n\t\tif (map === null) return {};\n\t\tconst result = {};\n\t\tconst keys = Object.keys(map);\n\t\tfor (let index = 0, length = keys.length; index < length; index += 1) {\n\t\t\tlet tag = keys[index];\n\t\t\tlet style = String(map[tag]);\n\t\t\tif (tag.slice(0, 2) === \"!!\") tag = \"tag:yaml.org,2002:\" + tag.slice(2);\n\t\t\tconst type = schema.compiledTypeMap[\"fallback\"][tag];\n\t\t\tif (type && _hasOwnProperty.call(type.styleAliases, style)) style = type.styleAliases[style];\n\t\t\tresult[tag] = style;\n\t\t}\n\t\treturn result;\n\t}\n\tfunction encodeHex(character) {\n\t\tlet handle;\n\t\tlet length;\n\t\tconst string = character.toString(16).toUpperCase();\n\t\tif (character <= 255) {\n\t\t\thandle = \"x\";\n\t\t\tlength = 2;\n\t\t} else if (character <= 65535) {\n\t\t\thandle = \"u\";\n\t\t\tlength = 4;\n\t\t} else if (character <= 4294967295) {\n\t\t\thandle = \"U\";\n\t\t\tlength = 8;\n\t\t} else throw new YAMLException(\"code point within a string may not be greater than 0xFFFFFFFF\");\n\t\treturn \"\\\\\" + handle + common.repeat(\"0\", length - string.length) + string;\n\t}\n\tvar QUOTING_TYPE_SINGLE = 1;\n\tvar QUOTING_TYPE_DOUBLE = 2;\n\tfunction State(options) {\n\t\tthis.schema = options[\"schema\"] || DEFAULT_SCHEMA;\n\t\tthis.indent = Math.max(1, options[\"indent\"] || 2);\n\t\tthis.noArrayIndent = options[\"noArrayIndent\"] || false;\n\t\tthis.skipInvalid = options[\"skipInvalid\"] || false;\n\t\tthis.flowLevel = common.isNothing(options[\"flowLevel\"]) ? -1 : options[\"flowLevel\"];\n\t\tthis.styleMap = compileStyleMap(this.schema, options[\"styles\"] || null);\n\t\tthis.sortKeys = options[\"sortKeys\"] || false;\n\t\tthis.lineWidth = options[\"lineWidth\"] || 80;\n\t\tthis.noRefs = options[\"noRefs\"] || false;\n\t\tthis.noCompatMode = options[\"noCompatMode\"] || false;\n\t\tthis.condenseFlow = options[\"condenseFlow\"] || false;\n\t\tthis.quotingType = options[\"quotingType\"] === \"\\\"\" ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;\n\t\tthis.forceQuotes = options[\"forceQuotes\"] || false;\n\t\tthis.replacer = typeof options[\"replacer\"] === \"function\" ? options[\"replacer\"] : null;\n\t\tthis.implicitTypes = this.schema.compiledImplicit;\n\t\tthis.explicitTypes = this.schema.compiledExplicit;\n\t\tthis.tag = null;\n\t\tthis.result = \"\";\n\t\tthis.duplicates = [];\n\t\tthis.usedDuplicates = null;\n\t}\n\tfunction indentString(string, spaces) {\n\t\tconst ind = common.repeat(\" \", spaces);\n\t\tlet position = 0;\n\t\tlet result = \"\";\n\t\tconst length = string.length;\n\t\twhile (position < length) {\n\t\t\tlet line;\n\t\t\tconst next = string.indexOf(\"\\n\", position);\n\t\t\tif (next === -1) {\n\t\t\t\tline = string.slice(position);\n\t\t\t\tposition = length;\n\t\t\t} else {\n\t\t\t\tline = string.slice(position, next + 1);\n\t\t\t\tposition = next + 1;\n\t\t\t}\n\t\t\tif (line.length && line !== \"\\n\") result += ind;\n\t\t\tresult += line;\n\t\t}\n\t\treturn result;\n\t}\n\tfunction generateNextLine(state, level) {\n\t\treturn \"\\n\" + common.repeat(\" \", state.indent * level);\n\t}\n\tfunction testImplicitResolving(state, str) {\n\t\tfor (let index = 0, length = state.implicitTypes.length; index < length; index += 1) if (state.implicitTypes[index].resolve(str)) return true;\n\t\treturn false;\n\t}\n\tfunction isWhitespace(c) {\n\t\treturn c === CHAR_SPACE || c === CHAR_TAB;\n\t}\n\tfunction isPrintable(c) {\n\t\treturn c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111;\n\t}\n\tfunction isNsCharOrWhitespace(c) {\n\t\treturn isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;\n\t}\n\tfunction isPlainSafe(c, prev, inblock) {\n\t\tconst cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);\n\t\tconst cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);\n\t\treturn (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar;\n\t}\n\tfunction isPlainSafeFirst(c) {\n\t\treturn isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;\n\t}\n\tfunction isPlainSafeLast(c) {\n\t\treturn !isWhitespace(c) && c !== CHAR_COLON;\n\t}\n\tfunction codePointAt(string, pos) {\n\t\tconst first = string.charCodeAt(pos);\n\t\tlet second;\n\t\tif (first >= 55296 && first <= 56319 && pos + 1 < string.length) {\n\t\t\tsecond = string.charCodeAt(pos + 1);\n\t\t\tif (second >= 56320 && second <= 57343) return (first - 55296) * 1024 + second - 56320 + 65536;\n\t\t}\n\t\treturn first;\n\t}\n\tfunction needIndentIndicator(string) {\n\t\treturn /^\\n* /.test(string);\n\t}\n\tvar STYLE_PLAIN = 1;\n\tvar STYLE_SINGLE = 2;\n\tvar STYLE_LITERAL = 3;\n\tvar STYLE_FOLDED = 4;\n\tvar STYLE_DOUBLE = 5;\n\tfunction chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {\n\t\tlet i;\n\t\tlet char = 0;\n\t\tlet prevChar = null;\n\t\tlet hasLineBreak = false;\n\t\tlet hasFoldableLine = false;\n\t\tconst shouldTrackWidth = lineWidth !== -1;\n\t\tlet previousLineBreak = -1;\n\t\tlet plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));\n\t\tif (singleLineOnly || forceQuotes) for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {\n\t\t\tchar = codePointAt(string, i);\n\t\t\tif (!isPrintable(char)) return STYLE_DOUBLE;\n\t\t\tplain = plain && isPlainSafe(char, prevChar, inblock);\n\t\t\tprevChar = char;\n\t\t}\n\t\telse {\n\t\t\tfor (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {\n\t\t\t\tchar = codePointAt(string, i);\n\t\t\t\tif (char === CHAR_LINE_FEED) {\n\t\t\t\t\thasLineBreak = true;\n\t\t\t\t\tif (shouldTrackWidth) {\n\t\t\t\t\t\thasFoldableLine = hasFoldableLine || i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== \" \";\n\t\t\t\t\t\tpreviousLineBreak = i;\n\t\t\t\t\t}\n\t\t\t\t} else if (!isPrintable(char)) return STYLE_DOUBLE;\n\t\t\t\tplain = plain && isPlainSafe(char, prevChar, inblock);\n\t\t\t\tprevChar = char;\n\t\t\t}\n\t\t\thasFoldableLine = hasFoldableLine || shouldTrackWidth && i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== \" \";\n\t\t}\n\t\tif (!hasLineBreak && !hasFoldableLine) {\n\t\t\tif (plain && !forceQuotes && !testAmbiguousType(string)) return STYLE_PLAIN;\n\t\t\treturn quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n\t\t}\n\t\tif (indentPerLevel > 9 && needIndentIndicator(string)) return STYLE_DOUBLE;\n\t\tif (!forceQuotes) return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;\n\t\treturn quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;\n\t}\n\tfunction writeScalar(state, string, level, iskey, inblock) {\n\t\tstate.dump = function() {\n\t\t\tif (string.length === 0) return state.quotingType === QUOTING_TYPE_DOUBLE ? \"\\\"\\\"\" : \"''\";\n\t\t\tif (!state.noCompatMode) {\n\t\t\t\tif (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) return state.quotingType === QUOTING_TYPE_DOUBLE ? \"\\\"\" + string + \"\\\"\" : \"'\" + string + \"'\";\n\t\t\t}\n\t\t\tconst indent = state.indent * Math.max(1, level);\n\t\t\tconst lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);\n\t\t\tconst singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;\n\t\t\tfunction testAmbiguity(string) {\n\t\t\t\treturn testImplicitResolving(state, string);\n\t\t\t}\n\t\t\tswitch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {\n\t\t\t\tcase STYLE_PLAIN: return string;\n\t\t\t\tcase STYLE_SINGLE: return \"'\" + string.replace(/'/g, \"''\") + \"'\";\n\t\t\t\tcase STYLE_LITERAL: return \"|\" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));\n\t\t\t\tcase STYLE_FOLDED: return \">\" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));\n\t\t\t\tcase STYLE_DOUBLE: return \"\\\"\" + escapeString(string, lineWidth) + \"\\\"\";\n\t\t\t\tdefault: throw new YAMLException(\"impossible error: invalid scalar style\");\n\t\t\t}\n\t\t}();\n\t}\n\tfunction blockHeader(string, indentPerLevel) {\n\t\tconst indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : \"\";\n\t\tconst clip = string[string.length - 1] === \"\\n\";\n\t\treturn indentIndicator + (clip && (string[string.length - 2] === \"\\n\" || string === \"\\n\") ? \"+\" : clip ? \"\" : \"-\") + \"\\n\";\n\t}\n\tfunction dropEndingNewline(string) {\n\t\treturn string[string.length - 1] === \"\\n\" ? string.slice(0, -1) : string;\n\t}\n\tfunction foldString(string, width) {\n\t\tconst lineRe = /(\\n+)([^\\n]*)/g;\n\t\tlet result = function() {\n\t\t\tlet nextLF = string.indexOf(\"\\n\");\n\t\t\tnextLF = nextLF !== -1 ? nextLF : string.length;\n\t\t\tlineRe.lastIndex = nextLF;\n\t\t\treturn foldLine(string.slice(0, nextLF), width);\n\t\t}();\n\t\tlet prevMoreIndented = string[0] === \"\\n\" || string[0] === \" \";\n\t\tlet moreIndented;\n\t\tlet match;\n\t\twhile (match = lineRe.exec(string)) {\n\t\t\tconst prefix = match[1];\n\t\t\tconst line = match[2];\n\t\t\tmoreIndented = line[0] === \" \";\n\t\t\tresult += prefix + (!prevMoreIndented && !moreIndented && line !== \"\" ? \"\\n\" : \"\") + foldLine(line, width);\n\t\t\tprevMoreIndented = moreIndented;\n\t\t}\n\t\treturn result;\n\t}\n\tfunction foldLine(line, width) {\n\t\tif (line === \"\" || line[0] === \" \") return line;\n\t\tconst breakRe = / [^ ]/g;\n\t\tlet match;\n\t\tlet start = 0;\n\t\tlet end;\n\t\tlet curr = 0;\n\t\tlet next = 0;\n\t\tlet result = \"\";\n\t\twhile (match = breakRe.exec(line)) {\n\t\t\tnext = match.index;\n\t\t\tif (next - start > width) {\n\t\t\t\tend = curr > start ? curr : next;\n\t\t\t\tresult += \"\\n\" + line.slice(start, end);\n\t\t\t\tstart = end + 1;\n\t\t\t}\n\t\t\tcurr = next;\n\t\t}\n\t\tresult += \"\\n\";\n\t\tif (line.length - start > width && curr > start) result += line.slice(start, curr) + \"\\n\" + line.slice(curr + 1);\n\t\telse result += line.slice(start);\n\t\treturn result.slice(1);\n\t}\n\tfunction escapeString(string) {\n\t\tlet result = \"\";\n\t\tlet char = 0;\n\t\tfor (let i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {\n\t\t\tchar = codePointAt(string, i);\n\t\t\tconst escapeSeq = ESCAPE_SEQUENCES[char];\n\t\t\tif (!escapeSeq && isPrintable(char)) {\n\t\t\t\tresult += string[i];\n\t\t\t\tif (char >= 65536) result += string[i + 1];\n\t\t\t} else result += escapeSeq || encodeHex(char);\n\t\t}\n\t\treturn result;\n\t}\n\tfunction writeFlowSequence(state, level, object) {\n\t\tlet _result = \"\";\n\t\tconst _tag = state.tag;\n\t\tfor (let index = 0, length = object.length; index < length; index += 1) {\n\t\t\tlet value = object[index];\n\t\t\tif (state.replacer) value = state.replacer.call(object, String(index), value);\n\t\t\tif (writeNode(state, level, value, false, false) || typeof value === \"undefined\" && writeNode(state, level, null, false, false)) {\n\t\t\t\tif (_result !== \"\") _result += \",\" + (!state.condenseFlow ? \" \" : \"\");\n\t\t\t\t_result += state.dump;\n\t\t\t}\n\t\t}\n\t\tstate.tag = _tag;\n\t\tstate.dump = \"[\" + _result + \"]\";\n\t}\n\tfunction writeBlockSequence(state, level, object, compact) {\n\t\tlet _result = \"\";\n\t\tconst _tag = state.tag;\n\t\tfor (let index = 0, length = object.length; index < length; index += 1) {\n\t\t\tlet value = object[index];\n\t\t\tif (state.replacer) value = state.replacer.call(object, String(index), value);\n\t\t\tif (writeNode(state, level + 1, value, true, true, false, true) || typeof value === \"undefined\" && writeNode(state, level + 1, null, true, true, false, true)) {\n\t\t\t\tif (!compact || _result !== \"\") _result += generateNextLine(state, level);\n\t\t\t\tif (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) _result += \"-\";\n\t\t\t\telse _result += \"- \";\n\t\t\t\t_result += state.dump;\n\t\t\t}\n\t\t}\n\t\tstate.tag = _tag;\n\t\tstate.dump = _result || \"[]\";\n\t}\n\tfunction writeFlowMapping(state, level, object) {\n\t\tlet _result = \"\";\n\t\tconst _tag = state.tag;\n\t\tconst objectKeyList = Object.keys(object);\n\t\tfor (let index = 0, length = objectKeyList.length; index < length; index += 1) {\n\t\t\tlet pairBuffer = \"\";\n\t\t\tif (_result !== \"\") pairBuffer += \", \";\n\t\t\tif (state.condenseFlow) pairBuffer += \"\\\"\";\n\t\t\tconst objectKey = objectKeyList[index];\n\t\t\tlet objectValue = object[objectKey];\n\t\t\tif (state.replacer) objectValue = state.replacer.call(object, objectKey, objectValue);\n\t\t\tif (!writeNode(state, level, objectKey, false, false)) continue;\n\t\t\tif (state.dump.length > 1024) pairBuffer += \"? \";\n\t\t\tpairBuffer += state.dump + (state.condenseFlow ? \"\\\"\" : \"\") + \":\" + (state.condenseFlow ? \"\" : \" \");\n\t\t\tif (!writeNode(state, level, objectValue, false, false)) continue;\n\t\t\tpairBuffer += state.dump;\n\t\t\t_result += pairBuffer;\n\t\t}\n\t\tstate.tag = _tag;\n\t\tstate.dump = \"{\" + _result + \"}\";\n\t}\n\tfunction writeBlockMapping(state, level, object, compact) {\n\t\tlet _result = \"\";\n\t\tconst _tag = state.tag;\n\t\tconst objectKeyList = Object.keys(object);\n\t\tif (state.sortKeys === true) objectKeyList.sort();\n\t\telse if (typeof state.sortKeys === \"function\") objectKeyList.sort(state.sortKeys);\n\t\telse if (state.sortKeys) throw new YAMLException(\"sortKeys must be a boolean or a function\");\n\t\tfor (let index = 0, length = objectKeyList.length; index < length; index += 1) {\n\t\t\tlet pairBuffer = \"\";\n\t\t\tif (!compact || _result !== \"\") pairBuffer += generateNextLine(state, level);\n\t\t\tconst objectKey = objectKeyList[index];\n\t\t\tlet objectValue = object[objectKey];\n\t\t\tif (state.replacer) objectValue = state.replacer.call(object, objectKey, objectValue);\n\t\t\tif (!writeNode(state, level + 1, objectKey, true, true, true)) continue;\n\t\t\tconst explicitPair = state.tag !== null && state.tag !== \"?\" || state.dump && state.dump.length > 1024;\n\t\t\tif (explicitPair) if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) pairBuffer += \"?\";\n\t\t\telse pairBuffer += \"? \";\n\t\t\tpairBuffer += state.dump;\n\t\t\tif (explicitPair) pairBuffer += generateNextLine(state, level);\n\t\t\tif (!writeNode(state, level + 1, objectValue, true, explicitPair)) continue;\n\t\t\tif (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) pairBuffer += \":\";\n\t\t\telse pairBuffer += \": \";\n\t\t\tpairBuffer += state.dump;\n\t\t\t_result += pairBuffer;\n\t\t}\n\t\tstate.tag = _tag;\n\t\tstate.dump = _result || \"{}\";\n\t}\n\tfunction detectType(state, object, explicit) {\n\t\tconst typeList = explicit ? state.explicitTypes : state.implicitTypes;\n\t\tfor (let index = 0, length = typeList.length; index < length; index += 1) {\n\t\t\tconst type = typeList[index];\n\t\t\tif ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === \"object\" && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) {\n\t\t\t\tif (explicit) if (type.multi && type.representName) state.tag = type.representName(object);\n\t\t\t\telse state.tag = type.tag;\n\t\t\t\telse state.tag = \"?\";\n\t\t\t\tif (type.represent) {\n\t\t\t\t\tconst style = state.styleMap[type.tag] || type.defaultStyle;\n\t\t\t\t\tlet _result;\n\t\t\t\t\tif (_toString.call(type.represent) === \"[object Function]\") _result = type.represent(object, style);\n\t\t\t\t\telse if (_hasOwnProperty.call(type.represent, style)) _result = type.represent[style](object, style);\n\t\t\t\t\telse throw new YAMLException(\"!<\" + type.tag + \"> tag resolver accepts not \\\"\" + style + \"\\\" style\");\n\t\t\t\t\tstate.dump = _result;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\tfunction writeNode(state, level, object, block, compact, iskey, isblockseq) {\n\t\tstate.tag = null;\n\t\tstate.dump = object;\n\t\tif (!detectType(state, object, false)) detectType(state, object, true);\n\t\tconst type = _toString.call(state.dump);\n\t\tconst inblock = block;\n\t\tif (block) block = state.flowLevel < 0 || state.flowLevel > level;\n\t\tconst objectOrArray = type === \"[object Object]\" || type === \"[object Array]\";\n\t\tlet duplicateIndex;\n\t\tlet duplicate;\n\t\tif (objectOrArray) {\n\t\t\tduplicateIndex = state.duplicates.indexOf(object);\n\t\t\tduplicate = duplicateIndex !== -1;\n\t\t}\n\t\tif (state.tag !== null && state.tag !== \"?\" || duplicate || state.indent !== 2 && level > 0) compact = false;\n\t\tif (duplicate && state.usedDuplicates[duplicateIndex]) state.dump = \"*ref_\" + duplicateIndex;\n\t\telse {\n\t\t\tif (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) state.usedDuplicates[duplicateIndex] = true;\n\t\t\tif (type === \"[object Object]\") if (block && Object.keys(state.dump).length !== 0) {\n\t\t\t\twriteBlockMapping(state, level, state.dump, compact);\n\t\t\t\tif (duplicate) state.dump = \"&ref_\" + duplicateIndex + state.dump;\n\t\t\t} else {\n\t\t\t\twriteFlowMapping(state, level, state.dump);\n\t\t\t\tif (duplicate) state.dump = \"&ref_\" + duplicateIndex + \" \" + state.dump;\n\t\t\t}\n\t\t\telse if (type === \"[object Array]\") if (block && state.dump.length !== 0) {\n\t\t\t\tif (state.noArrayIndent && !isblockseq && level > 0) writeBlockSequence(state, level - 1, state.dump, compact);\n\t\t\t\telse writeBlockSequence(state, level, state.dump, compact);\n\t\t\t\tif (duplicate) state.dump = \"&ref_\" + duplicateIndex + state.dump;\n\t\t\t} else {\n\t\t\t\twriteFlowSequence(state, level, state.dump);\n\t\t\t\tif (duplicate) state.dump = \"&ref_\" + duplicateIndex + \" \" + state.dump;\n\t\t\t}\n\t\t\telse if (type === \"[object String]\") {\n\t\t\t\tif (state.tag !== \"?\") writeScalar(state, state.dump, level, iskey, inblock);\n\t\t\t} else if (type === \"[object Undefined]\") return false;\n\t\t\telse {\n\t\t\t\tif (state.skipInvalid) return false;\n\t\t\t\tthrow new YAMLException(\"unacceptable kind of an object to dump \" + type);\n\t\t\t}\n\t\t\tif (state.tag !== null && state.tag !== \"?\") {\n\t\t\t\tlet tagStr = encodeURI(state.tag[0] === \"!\" ? state.tag.slice(1) : state.tag).replace(/!/g, \"%21\");\n\t\t\t\tif (state.tag[0] === \"!\") tagStr = \"!\" + tagStr;\n\t\t\t\telse if (tagStr.slice(0, 18) === \"tag:yaml.org,2002:\") tagStr = \"!!\" + tagStr.slice(18);\n\t\t\t\telse tagStr = \"!<\" + tagStr + \">\";\n\t\t\t\tstate.dump = tagStr + \" \" + state.dump;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\tfunction getDuplicateReferences(object, state) {\n\t\tconst objects = [];\n\t\tconst duplicatesIndexes = [];\n\t\tinspectNode(object, objects, duplicatesIndexes);\n\t\tconst length = duplicatesIndexes.length;\n\t\tfor (let index = 0; index < length; index += 1) state.duplicates.push(objects[duplicatesIndexes[index]]);\n\t\tstate.usedDuplicates = new Array(length);\n\t}\n\tfunction inspectNode(object, objects, duplicatesIndexes) {\n\t\tif (object !== null && typeof object === \"object\") {\n\t\t\tconst index = objects.indexOf(object);\n\t\t\tif (index !== -1) {\n\t\t\t\tif (duplicatesIndexes.indexOf(index) === -1) duplicatesIndexes.push(index);\n\t\t\t} else {\n\t\t\t\tobjects.push(object);\n\t\t\t\tif (Array.isArray(object)) for (let i = 0, length = object.length; i < length; i += 1) inspectNode(object[i], objects, duplicatesIndexes);\n\t\t\t\telse {\n\t\t\t\t\tconst objectKeyList = Object.keys(object);\n\t\t\t\t\tfor (let i = 0, length = objectKeyList.length; i < length; i += 1) inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfunction dump(input, options) {\n\t\toptions = options || {};\n\t\tconst state = new State(options);\n\t\tif (!state.noRefs) getDuplicateReferences(input, state);\n\t\tlet value = input;\n\t\tif (state.replacer) value = state.replacer.call({ \"\": value }, \"\", value);\n\t\tif (writeNode(state, 0, value, true, true)) return state.dump + \"\\n\";\n\t\treturn \"\";\n\t}\n\tmodule.exports.dump = dump;\n}));\n//#endregion\n//#region lib/index_vite_proxy.tmp.mjs\nvar import_js_yaml = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {\n\tvar loader = require_loader();\n\tvar dumper = require_dumper();\n\tfunction renamed(from, to) {\n\t\treturn function() {\n\t\t\tthrow new Error(\"Function yaml.\" + from + \" is removed in js-yaml 4. Use yaml.\" + to + \" instead, which is now safe by default.\");\n\t\t};\n\t}\n\tmodule.exports.Type = require_type();\n\tmodule.exports.Schema = require_schema();\n\tmodule.exports.FAILSAFE_SCHEMA = require_failsafe();\n\tmodule.exports.JSON_SCHEMA = require_json();\n\tmodule.exports.CORE_SCHEMA = require_core();\n\tmodule.exports.DEFAULT_SCHEMA = require_default();\n\tmodule.exports.load = loader.load;\n\tmodule.exports.loadAll = loader.loadAll;\n\tmodule.exports.dump = dumper.dump;\n\tmodule.exports.YAMLException = require_exception();\n\tmodule.exports.types = {\n\t\tbinary: require_binary(),\n\t\tfloat: require_float(),\n\t\tmap: require_map(),\n\t\tnull: require_null(),\n\t\tpairs: require_pairs(),\n\t\tset: require_set(),\n\t\ttimestamp: require_timestamp(),\n\t\tbool: require_bool(),\n\t\tint: require_int(),\n\t\tmerge: require_merge(),\n\t\tomap: require_omap(),\n\t\tseq: require_seq(),\n\t\tstr: require_str()\n\t};\n\tmodule.exports.safeLoad = renamed(\"safeLoad\", \"load\");\n\tmodule.exports.safeLoadAll = renamed(\"safeLoadAll\", \"loadAll\");\n\tmodule.exports.safeDump = renamed(\"safeDump\", \"dump\");\n})))(), 1);\nvar { Type, Schema, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, DEFAULT_SCHEMA, load, loadAll, dump, YAMLException, types, safeLoad, safeLoadAll, safeDump } = import_js_yaml.default;\nvar index_vite_proxy_tmp_default = import_js_yaml.default;\n//#endregion\nexport { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema, Type, YAMLException, index_vite_proxy_tmp_default as default, dump, load, loadAll, safeDump, safeLoad, safeLoadAll, types };\n\n//# sourceMappingURL=js-yaml.mjs.map","import type { Model, Field, TypeRef, Enum, Service } from '@workos/oagen';\nimport { collectFieldDependencies, toSnakeCase, toUpperSnakeCase, walkTypeRef } from '@workos/oagen';\nimport { readFileSync, existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\n// @ts-ignore -- js-yaml has no type declarations in this project\nimport { load as yamlLoad } from 'js-yaml';\n\n/**\n * Collect model names referenced as the return type of any non-paginated\n * operation. The list-wrapper skip rule below assumes a wrapper is always\n * replaced by the SDK's pagination machinery — but a few endpoints\n * (e.g. `GET /vault/v1/kv/{id}/versions`) have a list-envelope response\n * shape with no pagination params, so the parser leaves them as a plain\n * model reference. We must still emit those wrappers as regular models;\n * otherwise the generated resource code references an undefined name.\n */\nexport function collectNonPaginatedResponseModelNames(services: Service[]): Set<string> {\n  const names = new Set<string>();\n  for (const service of services) {\n    for (const op of service.operations) {\n      if (op.pagination) continue;\n      walkTypeRef(op.response, { model: (r) => names.add(r.name) });\n      for (const sr of op.successResponses ?? []) walkTypeRef(sr.type, { model: (r) => names.add(r.name) });\n    }\n  }\n  return names;\n}\n\n/**\n * Detect whether a model is a list wrapper -- the standard paginated\n * list envelope with `data` (array), `list_metadata`, and optionally `object: 'list'`.\n *\n * These models are redundant because each language SDK already has its own\n * pagination wrapper, and the runtime handles deserialization.\n */\nexport function isListWrapperModel(model: Model): boolean {\n  const fieldsByName = new Map(model.fields.map((f) => [f.name, f]));\n\n  // Must have a `data` field that is an array type\n  const dataField = fieldsByName.get('data');\n  if (!dataField) return false;\n  if (dataField.type.kind !== 'array') return false;\n\n  // Must have a `list_metadata` field (IR may use snake_case or camelCase)\n  const listMetadataField = fieldsByName.get('list_metadata') ?? fieldsByName.get('listMetadata');\n  if (!listMetadataField) return false;\n\n  // Optionally has an `object` field with literal value 'list'\n  const objectField = fieldsByName.get('object');\n  if (objectField) {\n    if (objectField.type.kind !== 'literal' || objectField.type.value !== 'list') {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n/**\n * Detect whether a model is a list metadata model (e.g., ListMetadata).\n * These models typically have exactly `before` and `after` nullable string fields.\n */\nexport function isListMetadataModel(model: Model): boolean {\n  if (model.fields.length !== 2) return false;\n\n  const fieldsByName = new Map(model.fields.map((f) => [f.name, f]));\n  const before = fieldsByName.get('before');\n  const after = fieldsByName.get('after');\n\n  if (!before || !after) return false;\n\n  return isNullableString(before) && isNullableString(after);\n}\n\n/**\n * Compute the `ListMetadata`-shape model names that must still be emitted\n * because some surviving wrapper references them.\n *\n * Each language emitter blanket-skips `isListMetadataModel` models on the\n * assumption that the SDK's shared pagination wrapper subsumes them. That\n * is correct for paginated list envelopes (the iterator unwraps the\n * envelope and `list_metadata` is handled at runtime), but a *non-paginated*\n * wrapper like vault's `VersionListResponse` still has a\n * `list_metadata: ListMetadata` field — and skipping emission of\n * `ListMetadata` leaves the wrapper's interface importing from a file that\n * was never written.\n *\n * Pass the same `nonPaginatedRefs` set the emitter uses for its own\n * wrapper-survival decision so the two answers stay in sync.\n */\nexport function collectReferencedListMetadataModels(models: Model[], nonPaginatedRefs: Set<string>): Set<string> {\n  const listMetadataNames = new Set<string>();\n  for (const m of models) {\n    if (isListMetadataModel(m)) listMetadataNames.add(m.name);\n  }\n  if (listMetadataNames.size === 0) return new Set();\n\n  const referenced = new Set<string>();\n  for (const model of models) {\n    if (isListMetadataModel(model)) continue;\n    if (isListWrapperModel(model) && !nonPaginatedRefs.has(model.name)) continue;\n    const deps = collectFieldDependencies(model);\n    for (const dep of deps.models) {\n      if (listMetadataNames.has(dep)) referenced.add(dep);\n    }\n  }\n  return referenced;\n}\n\n/** Check if a field type is nullable string (nullable<string> or just string). */\nfunction isNullableString(field: Field): boolean {\n  if (field.type.kind === 'primitive' && field.type.type === 'string') return true;\n  if (field.type.kind === 'nullable' && field.type.inner.kind === 'primitive' && field.type.inner.type === 'string')\n    return true;\n  return false;\n}\n\n// ---------------------------------------------------------------------------\n// oneOf / allOf+oneOf flattening\n// ---------------------------------------------------------------------------\n\n/**\n * Discover the OpenAPI spec path from CLI args or environment.\n * Returns null if not found.\n */\nfunction discoverSpecPath(): string | null {\n  // Check --spec CLI arg\n  const args = process.argv;\n  for (let i = 0; i < args.length; i++) {\n    if (args[i] === '--spec' && args[i + 1]) return resolve(args[i + 1]);\n    if (args[i]?.startsWith('--spec=')) return resolve(args[i].slice('--spec='.length));\n  }\n  // Check OPENAPI_SPEC_PATH env\n  if (process.env.OPENAPI_SPEC_PATH) return resolve(process.env.OPENAPI_SPEC_PATH);\n  return null;\n}\n\n/** Cached raw spec to avoid re-reading on multiple calls. */\nlet _rawSpecCache: Record<string, any> | null = null;\nlet _rawSpecLoaded = false;\n\nexport function loadRawSpec(): Record<string, any> | null {\n  if (_rawSpecLoaded) return _rawSpecCache;\n  _rawSpecLoaded = true;\n  const specPath = discoverSpecPath();\n  if (!specPath || !existsSync(specPath)) return null;\n  try {\n    const content = readFileSync(specPath, 'utf-8');\n    _rawSpecCache = yamlLoad(content) as Record<string, any>;\n    return _rawSpecCache;\n  } catch {\n    return null;\n  }\n}\n\n/** Look up a schema by name in the raw spec's components/schemas. */\nfunction lookupRawSchema(name: string): Record<string, any> | null {\n  const spec = loadRawSpec();\n  if (!spec) return null;\n  return spec?.components?.schemas?.[name] ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Synthetic model / enum collection\n// ---------------------------------------------------------------------------\n\n/**\n * Accumulator for synthetic models and enums generated from inline\n * definitions encountered during oneOf flattening.\n */\ninterface SyntheticCollector {\n  models: Model[];\n  enums: Array<{\n    name: string;\n    values: Array<{ value: string; description?: string }>;\n  }>;\n  /** Track names already used to avoid duplicates. */\n  usedNames: Set<string>;\n}\n\nfunction createCollector(): SyntheticCollector {\n  return { models: [], enums: [], usedNames: new Set() };\n}\n\n/**\n * Singularize a snake_case name for use as an array-item model name.\n * `redirect_uris` -> `redirect_uri`, `scopes` -> `scope`.\n */\nfunction singularizeSnake(name: string): string {\n  if (name.endsWith('ies') && name.length > 3) {\n    return `${name.slice(0, -3)}y`;\n  }\n  if (name.endsWith('s') && !name.endsWith('ss')) {\n    return name.slice(0, -1);\n  }\n  return name;\n}\n\n// ---------------------------------------------------------------------------\n// rawSchemaToTypeRef  -- with synthetic model/enum generation\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a raw OpenAPI type+format to an IR TypeRef.\n *\n * When `parentModelName` and `fieldName` are provided, inline objects and\n * enums generate synthetic models/enums instead of degrading to `unknown`\n * or `string`.\n */\nfunction rawSchemaToTypeRef(\n  schema: Record<string, any>,\n  parentModelName?: string,\n  fName?: string,\n  collector?: SyntheticCollector,\n): TypeRef {\n  if (schema.const !== undefined) {\n    return { kind: 'literal', value: schema.const };\n  }\n  if (schema.enum && collector && parentModelName && fName) {\n    // Generate a synthetic enum\n    const syntheticName = `${parentModelName}_${fName}`;\n    if (!collector.usedNames.has(syntheticName) && !collector.usedNames.has(toSnakeCase(syntheticName))) {\n      collector.usedNames.add(syntheticName);\n      collector.enums.push({\n        name: syntheticName,\n        values: (schema.enum as string[]).map((v: string) => ({\n          value: v,\n          description: undefined,\n        })),\n      });\n    }\n    return {\n      kind: 'enum',\n      name: syntheticName,\n      values: schema.enum as string[],\n    } as TypeRef;\n  }\n  if (schema.enum) {\n    // Simple string enum -- represent as primitive string (no collector)\n    return { kind: 'primitive', type: 'string' } as TypeRef;\n  }\n  if (schema.$ref) {\n    const refName = schema.$ref.split('/').pop()!;\n    return { kind: 'model', name: refName } as TypeRef;\n  }\n\n  // Handle nullable type arrays like [string, null]\n  let baseType = schema.type;\n  let isNullable = false;\n  if (Array.isArray(baseType)) {\n    const nonNull = baseType.filter((t: string) => t !== 'null');\n    isNullable = baseType.includes('null');\n    baseType = nonNull[0] ?? 'string';\n  }\n\n  let ref: TypeRef;\n  if (baseType === 'object' && schema.properties && collector && parentModelName && fName) {\n    // Inline object -- generate a synthetic model\n    const syntheticName = `${parentModelName}_${fName}`;\n    if (!collector.usedNames.has(syntheticName) && !collector.usedNames.has(toSnakeCase(syntheticName))) {\n      collector.usedNames.add(syntheticName);\n      const fields: Field[] = [];\n      const requiredSet = new Set<string>(schema.required ?? []);\n      for (const [propName, propSchema] of Object.entries(schema.properties) as [string, Record<string, any>][]) {\n        fields.push({\n          name: propName,\n          type: rawSchemaToTypeRef(propSchema, syntheticName, propName, collector),\n          required: requiredSet.has(propName),\n          description: propSchema.description,\n          deprecated: propSchema.deprecated,\n        });\n      }\n      collector.models.push({\n        name: syntheticName,\n        fields,\n        description: schema.description,\n      } as Model);\n    }\n    ref = { kind: 'model', name: syntheticName } as TypeRef;\n  } else if (baseType === 'object' && schema.properties) {\n    // Inline object -- treat as unknown (no collector)\n    ref = { kind: 'primitive', type: 'unknown' } as TypeRef;\n  } else if (baseType === 'array' && schema.items) {\n    // For array items that are inline objects, use the singular field name\n    const itemFieldName = fName ? singularizeSnake(fName) : undefined;\n    ref = {\n      kind: 'array',\n      items: rawSchemaToTypeRef(schema.items, parentModelName, itemFieldName, collector),\n    } as TypeRef;\n  } else if (baseType === 'boolean') {\n    ref = { kind: 'primitive', type: 'boolean' } as TypeRef;\n  } else if (baseType === 'integer' || baseType === 'number') {\n    ref = { kind: 'primitive', type: baseType } as TypeRef;\n  } else {\n    ref = { kind: 'primitive', type: 'string' } as TypeRef;\n  }\n\n  if (isNullable) {\n    return { kind: 'nullable', inner: ref } as TypeRef;\n  }\n  return ref;\n}\n\n/**\n * Extract fields from a raw OpenAPI object schema.\n * All fields are returned as optional (not required) since they come from\n * oneOf variants where only one variant is active at a time.\n */\nfunction extractFieldsFromRawSchema(\n  schema: Record<string, any>,\n  parentModelName?: string,\n  collector?: SyntheticCollector,\n): Field[] {\n  const fields: Field[] = [];\n  const props = schema.properties ?? {};\n  for (const [name, propSchema] of Object.entries(props) as [string, Record<string, any>][]) {\n    fields.push({\n      name,\n      type: rawSchemaToTypeRef(propSchema, parentModelName, name, collector),\n      required: false, // All oneOf variant fields are optional\n      description: propSchema.description,\n      deprecated: propSchema.deprecated,\n    });\n  }\n  return fields;\n}\n\n/**\n * Recursively collect all fields from a oneOf schema, flattening nested\n * allOf+oneOf compositions. All fields are marked optional.\n */\nfunction collectOneOfFields(\n  schema: Record<string, any>,\n  parentModelName?: string,\n  collector?: SyntheticCollector,\n): Field[] {\n  const allFields: Field[] = [];\n  const seenFieldNames = new Set<string>();\n\n  function walkSchema(s: Record<string, any>): void {\n    // Direct properties\n    if (s.properties) {\n      for (const f of extractFieldsFromRawSchema(s, parentModelName, collector)) {\n        if (!seenFieldNames.has(f.name)) {\n          seenFieldNames.add(f.name);\n          allFields.push(f);\n        }\n      }\n    }\n    // allOf composition\n    if (s.allOf) {\n      for (const sub of s.allOf) {\n        walkSchema(sub);\n      }\n    }\n    // oneOf composition (flatten all variants)\n    if (s.oneOf) {\n      for (const variant of s.oneOf) {\n        walkSchema(variant);\n      }\n    }\n    // anyOf composition\n    if (s.anyOf) {\n      for (const variant of s.anyOf) {\n        walkSchema(variant);\n      }\n    }\n  }\n\n  walkSchema(schema);\n  return allFields;\n}\n\n// ---------------------------------------------------------------------------\n// Array-item type upgrade\n// ---------------------------------------------------------------------------\n\n/**\n * Check if a TypeRef is `unknown` (the degraded type for inline objects).\n */\nfunction isUnknownType(ref: TypeRef): boolean {\n  return ref.kind === 'primitive' && (ref as any).type === 'unknown';\n}\n\n/**\n * If a field is an `array<unknown>` (or `nullable<array<unknown>>`) and the\n * raw spec defines inline object/enum items, replace the item type with a\n * synthetic model/enum. Returns the original field unchanged when no upgrade\n * is needed.\n */\nfunction upgradeArrayItemType(\n  field: Field,\n  rawSchema: Record<string, any>,\n  parentModelName: string,\n  collector: SyntheticCollector,\n): Field {\n  // Unwrap nullable to find the array\n  let arrayRef: TypeRef | null = null;\n  let isNullableWrapper = false;\n  if (field.type.kind === 'array') {\n    arrayRef = field.type;\n  } else if (field.type.kind === 'nullable' && field.type.inner.kind === 'array') {\n    arrayRef = field.type.inner;\n    isNullableWrapper = true;\n  }\n  if (!arrayRef || arrayRef.kind !== 'array') return field;\n  if (!isUnknownType(arrayRef.items)) return field;\n\n  // Look up the raw spec for this field\n  const rawProp = rawSchema.properties?.[field.name];\n  if (!rawProp) return field;\n\n  // Handle the case where the raw property is inside a nullable type array\n  let rawArraySchema = rawProp;\n  if (Array.isArray(rawProp.type)) {\n    const nonNull = rawProp.type.filter((t: string) => t !== 'null');\n    if (nonNull[0] === 'array') {\n      rawArraySchema = rawProp;\n    }\n  }\n  if (rawArraySchema.type !== 'array' && !(Array.isArray(rawArraySchema.type) && rawArraySchema.type.includes('array')))\n    return field;\n  if (!rawArraySchema.items) return field;\n\n  // Generate a proper TypeRef from the raw items schema\n  const itemFieldName = singularizeSnake(field.name);\n  const newItemRef = rawSchemaToTypeRef(rawArraySchema.items, parentModelName, itemFieldName, collector);\n  if (isUnknownType(newItemRef)) return field;\n\n  const newArrayRef: TypeRef = { kind: 'array', items: newItemRef } as TypeRef;\n  const newType: TypeRef = isNullableWrapper ? ({ kind: 'nullable', inner: newArrayRef } as TypeRef) : newArrayRef;\n\n  return { ...field, type: newType };\n}\n\n// ---------------------------------------------------------------------------\n// Module-level store for synthetic enums produced during enrichment.\n// Consumed by `getSyntheticEnums()` after `enrichModelsFromSpec` runs.\n// ---------------------------------------------------------------------------\nlet _lastSyntheticEnums: Enum[] = [];\n\n/**\n * Return the synthetic enums generated during the last call to\n * `enrichModelsFromSpec`. Call this after enrichment to merge them into the\n * enum generation phase.\n */\nexport function getSyntheticEnums(): Enum[] {\n  return _lastSyntheticEnums;\n}\n\n// ---------------------------------------------------------------------------\n// Implicit discriminator detection\n// ---------------------------------------------------------------------------\n\n/**\n * Find a property name that has a `const` value in ALL oneOf variants.\n * Returns null if no shared const property is found.\n */\nfunction findSharedConstProperty(oneOfSchemas: Record<string, any>[]): string | null {\n  if (oneOfSchemas.length === 0) return null;\n\n  const first = oneOfSchemas[0];\n  if (!first.properties) return null;\n\n  // Candidate properties from the first variant that have const values\n  const candidates = Object.keys(first.properties).filter((name) => first.properties[name].const !== undefined);\n\n  // Return the first candidate that has const values in ALL variants\n  for (const candidate of candidates) {\n    const allHaveConst = oneOfSchemas.every((variant) => variant.properties?.[candidate]?.const !== undefined);\n    if (allHaveConst) return candidate;\n  }\n\n  return null;\n}\n\n/**\n * Build a discriminator mapping from const values to IR model names.\n * For each oneOf variant's const value on `discProperty`, find the IR model\n * whose field with the same name is a Literal type with that value.\n */\nfunction buildDiscriminatorMapping(\n  discProperty: string,\n  oneOfSchemas: Record<string, any>[],\n  models: Model[],\n  parentModelName: string,\n): Record<string, string> {\n  const mapping: Record<string, string> = {};\n\n  for (const variant of oneOfSchemas) {\n    const constValue = variant.properties?.[discProperty]?.const;\n    if (constValue === undefined) continue;\n\n    const variantModel = models.find(\n      (m) =>\n        m.name !== parentModelName &&\n        m.fields.some(\n          (f) => f.name === discProperty && f.type.kind === 'literal' && (f.type as any).value === constValue,\n        ),\n    );\n    if (variantModel) {\n      mapping[String(constValue)] = variantModel.name;\n    }\n  }\n\n  return mapping;\n}\n\n/**\n * Detect implicit discriminators on models without full oneOf flattening.\n * Returns a new array with discriminator annotations; models without\n * discriminators are returned as-is. Use this when you need discriminator\n * info but don't want the side-effects of full enrichment (synthetic\n * models/enums, field flattening).\n */\nexport function detectDiscriminators(models: Model[]): Model[] {\n  const spec = loadRawSpec();\n  if (!spec) return models;\n\n  let changed = false;\n  const result = models.map((model) => {\n    if ((model as any).discriminator) return model;\n\n    const rawSchema = lookupRawSchema(model.name);\n    if (!rawSchema) return model;\n\n    const oneOfContainer = rawSchema.allOf?.find((s: any) => s.oneOf);\n    if (!oneOfContainer?.oneOf || oneOfContainer.oneOf.length === 0) return model;\n\n    const discProperty = findSharedConstProperty(oneOfContainer.oneOf);\n    if (!discProperty) return model;\n\n    const mapping = buildDiscriminatorMapping(discProperty, oneOfContainer.oneOf, models, model.name);\n    if (Object.keys(mapping).length === 0) return model;\n\n    changed = true;\n    return {\n      ...model,\n      fields: [],\n      discriminator: { property: discProperty, mapping },\n    };\n  });\n\n  return changed ? result : models;\n}\n\n/**\n * Enrich IR models by flattening oneOf/allOf+oneOf variant fields from the raw spec.\n *\n * For models with 0 fields whose raw spec schema is a pure oneOf:\n *   - Collect all variant fields and add them as optional fields.\n *\n * For models whose raw spec schema has allOf containing a oneOf:\n *   - Collect the missing variant fields and add them as optional.\n *\n * Inline objects and enums in oneOf branches are promoted to synthetic\n * models/enums instead of degrading to `object` / `string`.\n *\n * Returns a new array of enriched models (original models are not mutated).\n * Synthetic enums are stored internally; retrieve them via `getSyntheticEnums()`.\n */\nexport function enrichModelsFromSpec(models: Model[], enums: Enum[] = []): Model[] {\n  const spec = loadRawSpec();\n  if (!spec) {\n    _lastSyntheticEnums = [];\n    return models;\n  }\n\n  const collector = createCollector();\n  // Avoid name collisions with existing models (check both PascalCase and\n  // snake_case to prevent synthetic models from shadowing existing ones when\n  // they share a file name, e.g. FooBar vs Foo_bar -> foo_bar).\n  for (const m of models) {\n    collector.usedNames.add(m.name);\n    collector.usedNames.add(toSnakeCase(m.name));\n  }\n  // Seed existing IR enum names too. The parser already emits inline enums\n  // like `DataIntegrationAccessTokenResponseError` (PascalCase); without this\n  // seed, the synthetic path would emit a sibling enum named\n  // `DataIntegrationAccessTokenResponse_error`, and language emitters that\n  // PascalCase-normalize identifiers (Ruby, Go, PHP, Python) would collapse\n  // both onto the same class/file path — the second overwrites the first\n  // with a `X = X` self-alias.\n  for (const e of enums) {\n    collector.usedNames.add(e.name);\n    collector.usedNames.add(toSnakeCase(e.name));\n  }\n\n  const enriched = models.map((model) => {\n    const rawSchema = lookupRawSchema(model.name);\n    if (!rawSchema) return model;\n\n    const hasOneOf = rawSchema.oneOf || rawSchema.allOf?.some((s: any) => s.oneOf);\n    if (!hasOneOf) return model;\n\n    // Skip schemas with explicit discriminator -- those are intentional unions\n    const hasDiscriminator =\n      rawSchema.discriminator ||\n      rawSchema.oneOf?.some((v: any) => v.discriminator) ||\n      rawSchema.allOf?.some((s: any) => s.discriminator || s.oneOf?.some((v: any) => v.discriminator));\n    if (hasDiscriminator) return model;\n\n    // Detect implicit discriminators: allOf+oneOf where all variants share a\n    // property with const values (e.g., EventSchema with event: const: \"user.created\").\n    // When found, attach a discriminator mapping and clear fields so the emitter\n    // generates a dispatcher class instead of a flat dataclass.\n    const oneOfContainer = rawSchema.allOf?.find((s: any) => s.oneOf);\n    if (oneOfContainer?.oneOf && oneOfContainer.oneOf.length > 0) {\n      const discProperty = findSharedConstProperty(oneOfContainer.oneOf);\n      if (discProperty) {\n        const mapping = buildDiscriminatorMapping(discProperty, oneOfContainer.oneOf, models, model.name);\n        if (Object.keys(mapping).length > 0) {\n          return {\n            ...model,\n            fields: [],\n            discriminator: { property: discProperty, mapping },\n          };\n        }\n      }\n    }\n\n    // Collect all variant fields from the raw schema, generating synthetic\n    // models/enums for inline definitions along the way.\n    const variantFields = collectOneOfFields(rawSchema, model.name, collector);\n    if (variantFields.length === 0) return model;\n\n    // Merge variant fields into the existing model, skipping duplicates\n    const existingNames = new Set(model.fields.map((f) => f.name));\n    const newFields = variantFields.filter((f) => !existingNames.has(f.name));\n\n    if (newFields.length === 0) return model;\n\n    return {\n      ...model,\n      fields: [...model.fields, ...newFields],\n    };\n  });\n\n  // Second pass: fix array fields whose items degraded to `unknown` in the\n  // IR but are actually inline objects or enums in the raw spec.\n  const enriched2 = enriched.map((model) => {\n    const rawSchema = lookupRawSchema(model.name);\n    if (!rawSchema?.properties) return model;\n\n    let modified = false;\n    const newFields = model.fields.map((field) => {\n      const upgraded = upgradeArrayItemType(field, rawSchema, model.name, collector);\n      if (upgraded !== field) modified = true;\n      return upgraded;\n    });\n\n    return modified ? { ...model, fields: newFields } : model;\n  });\n\n  // Convert synthetic enum collector entries to proper Enum objects. PHP's\n  // emitter (and others built on top of `EnumValue.name`) crash when this\n  // field is missing, so derive it from the value via the same upper-snake\n  // transform the parser uses for declared enums.\n  _lastSyntheticEnums = collector.enums.map((e) => ({\n    name: e.name,\n    values: e.values.map((v) => ({\n      name: toUpperSnakeCase(String(v.value)),\n      value: v.value,\n      description: v.description,\n    })),\n  })) as Enum[];\n\n  // Append synthetic models, skipping those whose snake_case name collides\n  // with an existing model (prevents broken TypeAlias self-imports).\n  const existingSnakeNames = new Set(enriched2.map((m) => toSnakeCase(m.name)));\n  const filteredSynthetic = collector.models.filter((m) => !existingSnakeNames.has(toSnakeCase(m.name)));\n  return [...enriched2, ...filteredSynthetic];\n}\n","import type { EmitterContext, Model, Enum } from '@workos/oagen';\nimport { isListWrapperModel, isListMetadataModel } from './model-utils.js';\n\n/**\n * Suffix applied to an operation-client class name when it collides with an\n * exported model/enum class name in the same SDK namespace. Standardized\n * across emitters so colliding services look the same in every language —\n * e.g. `OrganizationMembershipService` regardless of language.\n *\n * Languages whose operation clients already carry a unique suffix (Go's\n * `…Service`, Rust's `…Api`, .NET's `…Service`) skip this helper entirely.\n */\nexport const SERVICE_COLLISION_SUFFIX = 'Service';\n\n/**\n * Build the set of model + enum class names that the SDK exports under its\n * top-level namespace. Each emitter passes its own `classNameFn` so the\n * comparison happens on the language-specific class-name form (e.g. Ruby's\n * `RoleList`, Python's `RoleList`).\n *\n * List-wrapper and list-metadata models are excluded — they aren't exposed\n * as user-facing types.\n */\nexport function buildExportedClassNameSet(ctx: EmitterContext, classNameFn: (name: string) => string): Set<string> {\n  const out = new Set<string>();\n  for (const model of ctx.spec.models as Model[]) {\n    if (isListWrapperModel(model) || isListMetadataModel(model)) continue;\n    out.add(classNameFn(model.name));\n  }\n  for (const enumDef of ctx.spec.enums as Enum[]) {\n    out.add(classNameFn(enumDef.name));\n  }\n  return out;\n}\n\n/**\n * Resolve the PascalCase mount-target identifier for an operation client,\n * appending `Service` when the un-suffixed class name would shadow an\n * exported model or enum.\n *\n * Operates on the PascalCase target (the mount-target string the IR carries),\n * so the returned value feeds cleanly into each language's `className` and\n * `fileName` helpers — e.g. `OrganizationMembership` → `OrganizationMembershipService`,\n * then `fileName` → `organization_membership_service` / `organization-membership-service`.\n *\n * The accessor on the client (`client.organization_membership`) is intentionally\n * NOT suffixed — callers should keep using the raw target for `servicePropertyName`\n * so the accessor reads naturally.\n */\nexport function resolveServiceTarget(\n  target: string,\n  exportedClasses: Set<string>,\n  classNameFn: (name: string) => string,\n): string {\n  return exportedClasses.has(classNameFn(target)) ? `${target}${SERVICE_COLLISION_SUFFIX}` : target;\n}\n","import type { Operation, Service, EmitterContext } from '@workos/oagen';\nimport { toPascalCase, toCamelCase, toKebabCase, toSnakeCase } from '@workos/oagen';\nimport { buildResolvedLookup, lookupMethodName } from '../shared/resolved-ops.js';\nimport { stripUrnPrefix } from '../shared/naming-utils.js';\nimport {\n  buildExportedClassNameSet as buildExportedClassNameSetShared,\n  resolveServiceTarget as resolveServiceTargetShared,\n} from '../shared/service-name-collision.js';\n\n/** Strip spec-noise suffixes (e.g., \"Dto\") from an IR name. */\nexport function stripNoiseSuffixes(name: string): string {\n  return name.replace(/Dto$/i, '');\n}\n\n/** PascalCase class/interface name. */\nexport function className(name: string): string {\n  return toPascalCase(stripUrnPrefix(name));\n}\n\n/** kebab-case file name (without extension). */\nexport function fileName(name: string): string {\n  return toKebabCase(stripUrnPrefix(name));\n}\n\n/** camelCase method name. */\nexport function methodName(name: string): string {\n  return toCamelCase(name);\n}\n\n/** camelCase field name for domain interfaces. */\nexport function fieldName(name: string): string {\n  return toCamelCase(name);\n}\n\n/**\n * camelCase domain field name for a model field, honoring a `domainName`\n * override (set via the `fieldHints` config) so a wire field can surface under\n * a friendlier name. The wire name (see {@link wireFieldName}) still derives\n * from `field.name`.\n */\nexport function domainFieldName(field: { name: string; domainName?: string }): string {\n  return toCamelCase(field.domainName ?? field.name);\n}\n\n/** snake_case field name for wire/response interfaces. */\nexport function wireFieldName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/**\n * Active set of `Serialized${Name}` interfaces in the live SDK, harvested\n * from `ctx.apiSurface` once per generation run. When non-empty, the\n * legacy wire-naming scheme wins so existing hand-written serializer files\n * continue to compile.\n *\n * Set by `index.ts` immediately after `getSurface(ctx)` runs.\n */\nlet baselineSerializedNames: Set<string> = new Set();\nexport function setBaselineSerializedNames(names: Set<string>): void {\n  baselineSerializedNames = names;\n}\n\n/**\n * Set of every interface name present in the baseline live SDK, regardless\n * of naming convention. Used to detect single-form baselines (where one\n * `*Response`-suffixed interface stands for both the domain and wire shape)\n * so we don't synthesize a non-existent `*Wire` variant.\n */\nlet baselineInterfaceNames: Set<string> = new Set();\nexport function setBaselineInterfaceNames(names: Set<string>): void {\n  baselineInterfaceNames = names;\n}\n\n/**\n * Every name DECLARED by the live SDK or baseline api-surface — interfaces\n * AND type aliases. Exact-name declarations preempt structural renames in\n * `resolveInterfaceName`: when the IR model's own name is already declared,\n * the structural matcher must not re-point it at a different declaration.\n *\n * This matters for alias-form files (`export type X = Y;`): the engine's\n * api-surface records X under `typeAliases` with no fields, so its\n * exact-name pass cannot claim X and the Jaccard fallback \"renames\" IR\n * model X to whatever interface looks similar. Propagating that rename\n * emitted duplicate, renamed declarations whose form flip-flopped on every\n * regeneration (workos-node ApiKeyOwner / UserManagement model files).\n *\n * Set by `index.ts` immediately after `getSurface(ctx)` runs.\n */\nlet baselineDeclaredNames: Set<string> = new Set();\nexport function setBaselineDeclaredNames(names: Set<string>): void {\n  baselineDeclaredNames = names;\n}\n\n/**\n * IR models that belong to newly-adopted services should not be renamed by\n * structural baseline matches from unrelated hand-written services.\n */\nlet adoptedModelNames: Set<string> = new Set();\nexport function setAdoptedModelNames(names: Set<string>): void {\n  adoptedModelNames = names;\n}\nexport function isAdoptedModelName(name: string): boolean {\n  return adoptedModelNames.has(name);\n}\n\n/**\n * IR model names handled by the discriminated-models module. These must not\n * be remapped by the structural matcher because that module emits files and\n * helpers under the original IR names.\n */\nlet discriminatedModelNames: Set<string> = new Set();\nexport function setDiscriminatedModelNames(names: Set<string>): void {\n  discriminatedModelNames = names;\n}\n\n/**\n * Domain names that `resolveInterfaceName` reached via a structural rename\n * — the resolved name differs from the IR model's own name. `wireInterfaceName`\n * consults this set to decide whether to fire the \"single-form wire\" case:\n * that case is *only* meant for structurally-renamed models, where the\n * baseline owns a `*Response` interface representing the wire shape with no\n * separate `*Wire` companion. Without this signal, a freshly-emitted model\n * whose IR name already ends in `Response` (e.g. `CreateDataKeyResponse`)\n * would land in the same case as soon as a prior buggy regen wrote the\n * baseline — producing two `export interface CreateDataKeyResponse { ... }`\n * declarations in the same file.\n */\nlet structurallyRenamedDomainNames: Set<string> = new Set();\nexport function setStructurallyRenamedDomainNames(names: Set<string>): void {\n  structurallyRenamedDomainNames = names;\n}\n\n/**\n * The structural half of `resolveInterfaceName`, pre-injectivity: look up the\n * engine's structurally-inferred match (`overlayLookup.modelNameByIR`), apply\n * the adopted/discriminated/declared-name guards, and normalize legacy\n * `Serialized*` / wire-shaped `*Response` matches down to the baseline domain\n * name. Returns the candidate live name, or undefined when no structural\n * match applies. Shared by `resolveInterfaceName` and the claims registry so\n * both see the exact same candidate for every IR model.\n */\nfunction inferStructuralRename(name: string, ctx: EmitterContext): string | undefined {\n  let inferred =\n    adoptedModelNames.has(name) || discriminatedModelNames.has(name)\n      ? undefined\n      : ctx.overlayLookup?.modelNameByIR?.get(name);\n  // Exact-name declarations preempt structural renames: when the live SDK\n  // already declares `name` (interface or type alias), a non-identity\n  // structural match is a misfire — the alias/typeAlias resolution in\n  // `resolveInterfaceName` (or the name itself) is the canonical answer. See\n  // `setBaselineDeclaredNames` for the alias-form feedback loop this breaks.\n  if (inferred && inferred !== name && baselineDeclaredNames.has(name)) {\n    return undefined;\n  }\n  if (!inferred) return undefined;\n  if (inferred.startsWith('Serialized')) {\n    const stripped = inferred.slice('Serialized'.length);\n    if (stripped && ctx.apiSurface?.interfaces?.[stripped]) {\n      inferred = stripped;\n    }\n  }\n  // Structural matchers tend to lock onto the wire-shaped baseline\n  // interface (`AuditLogSchemaResponse`) because the IR carries\n  // snake_case fields. Prefer the corresponding domain name (without\n  // the `Response` suffix) when both exist in baseline — domain refs\n  // belong on the domain side, the wire/serialize path picks up the\n  // `*Response` variant via `wireInterfaceName`.\n  if (inferred.endsWith('Response') && ctx.apiSurface?.interfaces) {\n    const stripped = inferred.slice(0, -'Response'.length);\n    if (stripped && ctx.apiSurface.interfaces[stripped]) {\n      inferred = stripped;\n    }\n  }\n  return inferred;\n}\n\n/**\n * Per-run registry making structural name resolution INJECTIVE: live-surface\n * name → the single IR model name allowed to claim it. Built lazily from\n * `ctx.spec.models` on first use and cached per ctx.\n *\n * Cache-correctness invariant (relied on, not assumed): the `ctx` reaching\n * this function is always the memoized `nodeCtx` from `withNodeOperationOverrides`\n * — every emitter hook derives it as its first step and threads it through\n * `getSurface`/`resolveInterfaceName`, and that helper returns one stable\n * object per run. `nodeCtx.spec` is built once via spread and `spec.models` is\n * never reassigned or mutated in place anywhere (enrichment pushes only onto a\n * pre-enrichment local collector). So the cached value can never drift from\n * the `spec.models` it was computed from. Do not begin mutating `spec.models`\n * under a live ctx without invalidating this cache.\n *\n * Without it, the structural fallback could map two distinct IR models onto\n * one live declaration. workos-node AuditLogs evidence: IR\n * `AuditLogEventActor` and `AuditLogEventTarget` (near-identical shapes) both\n * resolved to the hand-written `AuditLogActor`, so\n * `audit-log-event-target.interface.ts` was emitted declaring\n * `export interface AuditLogActor` (file stem and declaration disagree),\n * with duplicate imports/`describe` blocks and two `serializeAuditLogActor`\n * definitions downstream. The raw engine overlay is injective on its own\n * names, but the resolver's `Serialized*`/`*Response` normalization below can\n * collapse two distinct raw matches onto one bare name — the claims registry\n * gates the final, post-normalization answer.\n *\n * Claim order:\n *  1. Exact-name overrides (`overlayLookup.interfaceByName`) claim first.\n *  2. Identity structural matches (IR name === live name) claim their own name.\n *  3. Contested renames go to the claimant with the higher field-overlap\n *     similarity; ties break toward the closer name (edit distance), then\n *     lexicographically for determinism. Losers are NEVER unified — they keep\n *     their canonical IR-derived names.\n */\nconst structuralClaimsCache = new WeakMap<EmitterContext, Map<string, string>>();\n\n/** Jaccard similarity between two normalized field-name sets. */\nfunction fieldJaccard(a: Set<string>, b: Set<string>): number {\n  if (a.size === 0 && b.size === 0) return 0;\n  let intersection = 0;\n  for (const item of a) if (b.has(item)) intersection++;\n  const union = a.size + b.size - intersection;\n  return union === 0 ? 0 : intersection / union;\n}\n\n/** Levenshtein distance over lowercased names (tie-break for contested claims). */\nfunction nameDistance(a: string, b: string): number {\n  const s = a.toLowerCase();\n  const t = b.toLowerCase();\n  if (s === t) return 0;\n  let prev = Array.from({ length: t.length + 1 }, (_, i) => i);\n  for (let i = 1; i <= s.length; i++) {\n    const curr = [i];\n    for (let j = 1; j <= t.length; j++) {\n      const cost = s[i - 1] === t[j - 1] ? 0 : 1;\n      curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);\n    }\n    prev = curr;\n  }\n  return prev[t.length];\n}\n\n/** Normalized field-name signature of an IR model. */\nfunction irFieldSignature(model: { fields: { name: string }[] }): Set<string> {\n  return new Set(model.fields.map((f) => toSnakeCase(f.name)));\n}\n\n/** Normalized field-name signature of a live-surface interface, if known. */\nfunction liveFieldSignature(ctx: EmitterContext, liveName: string): Set<string> | undefined {\n  const iface = ctx.apiSurface?.interfaces?.[liveName] as { fields?: Record<string, unknown> } | undefined;\n  if (!iface?.fields) return undefined;\n  return new Set(Object.keys(iface.fields).map((f) => toSnakeCase(f)));\n}\n\nfunction getStructuralNameClaims(ctx: EmitterContext): Map<string, string> {\n  const cached = structuralClaimsCache.get(ctx);\n  if (cached) return cached;\n  const claims = new Map<string, string>();\n\n  // 1. Exact-name overrides claim first (mirrors resolveInterfaceName step 1).\n  for (const [irName, liveName] of ctx.overlayLookup?.interfaceByName ?? new Map<string, string>()) {\n    if (!claims.has(liveName)) claims.set(liveName, irName);\n  }\n\n  // 2. Identity matches claim their own name; renames queue up per live name.\n  const contested = new Map<string, string[]>();\n  const modelsByName = new Map<string, { fields: { name: string }[] }>();\n  for (const model of ctx.spec.models) {\n    modelsByName.set(model.name, model);\n    if (ctx.overlayLookup?.interfaceByName?.has(model.name)) continue;\n    const inferred = inferStructuralRename(model.name, ctx);\n    if (!inferred) continue;\n    if (inferred === model.name) {\n      if (!claims.has(inferred)) claims.set(inferred, model.name);\n      continue;\n    }\n    const group = contested.get(inferred);\n    if (group) group.push(model.name);\n    else contested.set(inferred, [model.name]);\n  }\n\n  // 3. Award each contested live name to exactly one structural claimant.\n  for (const [liveName, irNames] of contested) {\n    if (claims.has(liveName)) continue; // exact/identity claims preempt renames\n    let winner = irNames[0];\n    if (irNames.length > 1) {\n      const liveFields = liveFieldSignature(ctx, liveName);\n      const scoreOf = (irName: string): number => {\n        const model = modelsByName.get(irName);\n        if (!model || !liveFields) return 0;\n        return fieldJaccard(irFieldSignature(model), liveFields);\n      };\n      winner = [...irNames].sort((a, b) => {\n        const scoreDiff = scoreOf(b) - scoreOf(a);\n        if (scoreDiff !== 0) return scoreDiff;\n        const distDiff = nameDistance(a, liveName) - nameDistance(b, liveName);\n        if (distDiff !== 0) return distDiff;\n        return a < b ? -1 : a > b ? 1 : 0;\n      })[0];\n    }\n    claims.set(liveName, winner);\n  }\n\n  structuralClaimsCache.set(ctx, claims);\n  return claims;\n}\n\n/**\n * Wire/response interface name.\n *\n * Resolution order:\n *  1. `Serialized${domainName}` if it exists in the baseline (legacy\n *     workos-node convention; lets hand-written serializer files keep\n *     compiling).\n *  2. `${domainName}Wire` when the domain ends in `Response` AND the\n *     baseline actually has a `*Wire` interface (avoids\n *     `FooResponseResponse` stutter).\n *  3. The bare `domainName` itself when it already ends in `Response` and\n *     no `*Wire` variant exists — this happens when the structural matcher\n *     maps an IR model to a baseline-wire-shaped interface\n *     (`AuditLogSchemaJson` → `AuditLogSchemaResponse`) and the baseline\n *     has no separate domain/wire split.\n *  4. `${domainName}Response` for the standard fresh-emit case.\n */\nexport function wireInterfaceName(domainName: string): string {\n  const serialized = `Serialized${domainName}`;\n  if (baselineSerializedNames.has(serialized)) return serialized;\n\n  if (domainName.endsWith('Response')) {\n    const wireForm = `${domainName}Wire`;\n    if (baselineInterfaceNames.has(wireForm)) return wireForm;\n    // Single-form case (#3 in the docstring): only fire when the resolver\n    // structurally renamed an IR model to this baseline name. Otherwise a\n    // fresh `CreateDataKeyResponse`-style IR model would collapse onto its\n    // own name as soon as one buggy regen wrote `CreateDataKeyResponse` to\n    // the baseline, perpetuating the duplicate-interface emission.\n    if (structurallyRenamedDomainNames.has(domainName) && baselineInterfaceNames.has(domainName)) {\n      return domainName;\n    }\n    return wireForm;\n  }\n  return `${domainName}Response`;\n}\n\n/** kebab-case service directory name. */\nexport function serviceDirName(name: string): string {\n  return toKebabCase(name);\n}\n\n/** camelCase property name for service accessors on the client. */\nexport function servicePropertyName(name: string): string {\n  return toCamelCase(name);\n}\n\n/**\n * Resolve the effective service name, using the overlay-resolved class name\n * when available.\n */\nexport function resolveServiceName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n/**\n * Build the set of model + enum class names exported by the SDK. Used to\n * detect collisions with operation-client class names — a colliding service\n * gets a `Service` suffix appended.\n */\nexport function buildExportedClassNameSet(ctx: EmitterContext): Set<string> {\n  return buildExportedClassNameSetShared(ctx, className);\n}\n\n/**\n * Resolve a service's mount-target identifier, appending `Service` on\n * collision with an exported model/enum class. The result feeds `className`\n * and `fileName` so both the `export class` declaration and its file name\n * stay aligned (e.g. `OrganizationMembershipService` /\n * `organization-membership-service.ts`).\n */\nexport function resolveServiceTarget(target: string, exportedClasses: Set<string>): string {\n  return resolveServiceTargetShared(target, exportedClasses, className);\n}\n\n/**\n * Build a map from IR service name -> resolved service name.\n */\nexport function buildServiceNameMap(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of services) {\n    map.set(service.name, resolveServiceName(service, ctx));\n  }\n  return map;\n}\n\n/** Resolve the output directory for a service. */\nexport function resolveServiceDir(resolvedServiceName: string): string {\n  return serviceDirName(resolvedServiceName);\n}\n\n/** Resolve the SDK method name for an operation, using resolved operations first. */\nexport function resolveMethodName(op: Operation, _service: Service, ctx: EmitterContext): string {\n  const lookup = buildResolvedLookup(ctx);\n  const resolved = lookupMethodName(op, lookup);\n  if (resolved) return toCamelCase(resolved);\n  const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const existing = ctx.overlayLookup?.methodByOperation?.get(httpKey);\n  if (existing) return existing.methodName;\n  return toCamelCase(op.name);\n}\n\n/** Resolve the SDK class name for a service, using resolved ops mountOn as canonical. */\nexport function resolveClassName(service: Service, ctx: EmitterContext): string {\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (r.service.name === service.name) return r.mountOn;\n  }\n  if (ctx.overlayLookup?.methodByOperation) {\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const existing = ctx.overlayLookup.methodByOperation.get(httpKey);\n      if (existing) return existing.className;\n    }\n  }\n  return toPascalCase(service.name);\n}\n\n/**\n * Resolve the interface name for a model, checking overlay first.\n *\n * Lookup order:\n *  1. `overlayLookup.interfaceByName` — exact-name overrides from the live SDK.\n *  2. `overlayLookup.modelNameByIR` — structurally-inferred matches (e.g., IR\n *     `ValidateApiKey` with one field `value: string` → live SDK interface\n *     `ValidateApiKeyOptions`), gated by the injective claims registry: each\n *     live name goes to at most one IR model (see `getStructuralNameClaims`).\n *  3. Type-alias resolution (when an alias points to an interface).\n *  4. Suffix-fallback heuristic for the workos-node `*Options` convention:\n *     when the IR name `X` has no baseline match but `XOptions` does, use\n *     `XOptions`. The convention is widely used for request-body interfaces\n *     in workos-node (CreateOrganizationOptions, ListUsersOptions, etc.).\n *  5. Default — clean and PascalCase the IR name.\n */\nexport function resolveInterfaceName(name: string, ctx: EmitterContext, opts?: { skipTypeAlias?: boolean }): string {\n  const existing = ctx.overlayLookup?.interfaceByName?.get(name);\n  if (existing) return existing;\n\n  let inferred = inferStructuralRename(name, ctx);\n  if (inferred !== undefined) {\n    // Injectivity gate: a structurally-renamed live name may be claimed by\n    // at most one IR model per run. When another model holds the claim, the\n    // rename is dropped and this model keeps its canonical IR-derived name.\n    if (inferred !== name) {\n      const claimant = getStructuralNameClaims(ctx).get(inferred);\n      if (claimant !== undefined && claimant !== name) {\n        inferred = undefined;\n      }\n    }\n    if (inferred !== undefined) return inferred;\n  }\n\n  if (!opts?.skipTypeAlias && ctx.apiSurface?.typeAliases) {\n    const alias = ctx.apiSurface.typeAliases[name] as { value?: string } | undefined;\n    if (alias?.value && ctx.apiSurface.interfaces?.[alias.value]) {\n      return alias.value;\n    }\n  }\n\n  // Suffix-fallback for the workos-node `*Options` convention, restricted to\n  // the case where the baseline `${name}Options` interface lives in the file\n  // we'd compute from the IR name itself (e.g. `validate-api-key.interface.ts`\n  // exports `ValidateApiKeyOptions`). Without this restriction, we'd re-point\n  // every IR name with an `*Options` baseline to a different file (e.g.\n  // `CreateOrganizationApiKey` → `…Options` lives in\n  // `create-organization-api-key-options.interface.ts`, NOT\n  // `create-organization-api-key.interface.ts`).\n  if (ctx.apiSurface?.interfaces) {\n    const ifaces = ctx.apiSurface.interfaces;\n    if (!ifaces[name]) {\n      const optionsCandidate = `${name}Options`;\n      const optionsInfo = ifaces[optionsCandidate] as { sourceFile?: string } | undefined;\n      if (optionsInfo?.sourceFile) {\n        const expectedStem = toKebabCase(stripUrnPrefix(name));\n        if (optionsInfo.sourceFile.endsWith(`/${expectedStem}.interface.ts`)) {\n          return optionsCandidate;\n        }\n      }\n    }\n  }\n\n  const cleaned = ctx.apiSurface ? name : stripNoiseSuffixes(name);\n  return toPascalCase(stripUrnPrefix(cleaned));\n}\n","import type { TypeRef, PrimitiveType, UnionType } from '@workos/oagen';\nimport { mapTypeRef as irMapTypeRef } from '@workos/oagen';\nimport { wireInterfaceName } from './naming.js';\n\nexport interface MapTypeRefOpts {\n  genericDefaults?: Map<string, string>;\n}\n\n/**\n * Map of enum name → inlined string-union TS source.\n *\n * Set by `index.ts` once per generation run, sourced from `spec.enums` for\n * enums that have no baseline definition in the live SDK. When populated,\n * `mapTypeRef`/`mapWireTypeRef` substitute the union directly at the\n * reference site instead of emitting a separate import — this collapses\n * ~100 single-line enum files into inline literal types.\n */\nlet inlineEnumUnions: Map<string, string> = new Map();\nexport function setInlineEnumUnions(map: Map<string, string>): void {\n  inlineEnumUnions = map;\n}\nexport function isInlineEnum(name: string): boolean {\n  return inlineEnumUnions.has(name);\n}\n\n/**\n * Optional callback that resolves an IR model name to its live-SDK interface\n * name. Set by `index.ts` once per run. When present, `mapTypeRef` and\n * `mapWireTypeRef` use it instead of the raw IR name in their `model:` cases\n * — keeping field-type references in sync with import statements that the\n * caller emits via the same resolver. Without this, a structural match like\n * IR `AuditLogSchemaJson` → live `AuditLogSchemaResponse` would produce\n * `schema: AuditLogSchemaJson` in the body but\n * `import type { AuditLogSchemaResponse }` in the imports, leaving\n * `AuditLogSchemaJson` unbound.\n */\nlet domainNameResolver: ((irName: string) => string) | null = null;\nexport function setDomainNameResolver(fn: ((irName: string) => string) | null): void {\n  domainNameResolver = fn;\n}\nfunction resolveDomainName(irName: string): string {\n  return domainNameResolver ? domainNameResolver(irName) : irName;\n}\n\n/**\n * Map an IR TypeRef to a TypeScript domain type string.\n * Domain types use PascalCase model names (e.g., `Organization`).\n */\nexport function mapTypeRef(ref: TypeRef, opts?: MapTypeRefOpts): string {\n  const genericDefaults = opts?.genericDefaults;\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (_r, items) => `${parenthesizeUnion(items)}[]`,\n    model: (r) => resolveDomainName(r.name) + (genericDefaults?.get(r.name) ?? ''),\n    enum: (r) => inlineEnumUnions.get(r.name) ?? r.name,\n    union: (r, variants) => joinUnionVariants(r, variants),\n    nullable: (_r, inner) => `${inner} | null`,\n    literal: (r) => (typeof r.value === 'string' ? `'${r.value}'` : String(r.value)),\n    map: (_r, value) => `Record<string, ${value}>`,\n  });\n}\n\n/**\n * Map an IR TypeRef to a TypeScript wire/response type string.\n * Model references get the `Response` suffix (e.g., `OrganizationResponse`).\n */\nexport function mapWireTypeRef(ref: TypeRef, opts?: { genericDefaults?: Map<string, string> }): string {\n  const genericDefaults = opts?.genericDefaults;\n  return irMapTypeRef<string>(ref, {\n    primitive: mapWirePrimitive,\n    array: (_r, items) => `${parenthesizeUnion(items)}[]`,\n    model: (r) => wireInterfaceName(resolveDomainName(r.name)) + (genericDefaults?.get(r.name) ?? ''),\n    enum: (r) => inlineEnumUnions.get(r.name) ?? r.name,\n    union: (r, variants) => joinUnionVariants(r, variants),\n    nullable: (_r, inner) => `${inner} | null`,\n    literal: (r) => (typeof r.value === 'string' ? `'${r.value}'` : String(r.value)),\n    map: (_r, value) => `Record<string, ${value}>`,\n  });\n}\n\nfunction mapPrimitive(ref: PrimitiveType): string {\n  if (ref.format) {\n    switch (ref.format) {\n      case 'date-time':\n        return 'Date';\n      case 'int64':\n        return 'bigint';\n    }\n  }\n  switch (ref.type) {\n    case 'string':\n      return 'string';\n    case 'integer':\n    case 'number':\n      return 'number';\n    case 'boolean':\n      return 'boolean';\n    case 'unknown':\n      return 'any';\n  }\n}\n\nfunction mapWirePrimitive(ref: PrimitiveType): string {\n  switch (ref.type) {\n    case 'string':\n      return 'string';\n    case 'integer':\n    case 'number':\n      return 'number';\n    case 'boolean':\n      return 'boolean';\n    case 'unknown':\n      return 'any';\n  }\n}\n\nfunction joinUnionVariants(ref: UnionType, variants: string[]): string {\n  const unique = [...new Set(variants)];\n  if (ref.compositionKind === 'allOf') {\n    return unique.join(' & ');\n  }\n  if (unique.length === 1) return unique[0];\n  return unique.join(' | ');\n}\n\nfunction parenthesizeUnion(type: string): string {\n  return type.includes(' | ') || type.includes(' & ') ? `(${type})` : type;\n}\n","import type { EmitterContext, Operation, OperationPlan } from '@workos/oagen';\nimport { planOperation } from '@workos/oagen';\n\nexport interface OperationOverride {\n  methodName?: string;\n  mountOn?: string;\n  optionsType?: string;\n  bodyFieldMap?: Record<string, string>;\n  /**\n   * Rename spec path parameters to the SDK options-object field they should be\n   * exposed as. Keys are the camelCase identifier the param resolves to via\n   * `fieldName(param.name)` — NOT the raw (possibly snake_case) spec key — since\n   * the lookup is keyed on that camelCase form (e.g. `{ resourceId: 'targetId' }`,\n   * even for a `resource_id` spec param). Applied to the destructure, the URL\n   * template binding, and generated tests so a published SDK field name can\n   * diverge from the spec path-param name without a global spec rewrite (which\n   * would ripple across every language).\n   */\n  pathFieldMap?: Record<string, string>;\n  returnType?: string;\n  returnDataProperty?: string;\n  returnTypeImports?: string[];\n  returnExpression?: string;\n  /**\n   * Override the response model the operation deserializes, by model name.\n   * Replaces the spec-derived response model so the resource (and its test)\n   * reference a different wire type / deserializer — e.g. mapping\n   * Authorization's role responses to the full `OrganizationRole` instead of\n   * the slim `Role`/`RoleResponse` shape shared with SSO and UserManagement.\n   * Node-only; never affects the global spec or other SDKs.\n   */\n  responseModel?: string;\n}\n\nexport interface NodeEmitterOptions {\n  /**\n   * Existing SDK mode normally drops brand-new paths to avoid large accidental\n   * generations. When enabled, brand-new top-level service directories whose\n   * services are absent from the SDK are adopted from the spec.\n   */\n  adoptMissingServices?: boolean;\n  /**\n   * Existing tracked service directories to move under oagen ownership.\n   *\n   * Entries may be IR service names or resolved resource class names\n   * (for example, \"Groups\"). Owned service files are allowed to overwrite\n   * tracked, non-autogenerated files so the service can be migrated into the\n   * manifest one service at a time.\n   */\n  ownedServices?: string[];\n  /**\n   * Regenerate tests and fixtures for owned services. Non-owned service tests\n   * and fixtures remain hand-owned.\n   */\n  regenerateOwnedTests?: boolean;\n  /**\n   * Node-specific operation overrides keyed by \"METHOD /path\".\n   * Allows renaming methods or remounting operations for the Node SDK\n   * without affecting other languages.\n   */\n  operationOverrides?: Record<string, OperationOverride>;\n  /**\n   * Type/model names whose hand-written declarations are authoritative even\n   * inside an owned service. The emitter will NOT generate an interface or\n   * serializer for these names; instead it treats them like a baseline type,\n   * routing imports and barrel exports to the existing hand-written file.\n   *\n   * Use this to keep hand-owned generics the OpenAPI spec cannot express\n   * (for example `DirectoryUserWithGroups<TCustomAttributes>`) while still\n   * letting oagen own the rest of the service.\n   */\n  handOwnedTypes?: string[];\n}\n\nexport function nodeOptions(ctx: EmitterContext): NodeEmitterOptions {\n  return ((ctx as EmitterContext & { emitterOptions?: Record<string, unknown> }).emitterOptions ??\n    {}) as NodeEmitterOptions;\n}\n\nfunction normalizeServiceName(name: string): string {\n  return name.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n}\n\nfunction ownedLookupNames(name: string): string[] {\n  const names = [name];\n  const baselineDirPrefix = '__baseline_dir__:';\n  if (name.startsWith(baselineDirPrefix)) {\n    names.push(name.slice(baselineDirPrefix.length));\n  }\n  return names;\n}\n\nexport function isNodeOwnedService(ctx: EmitterContext, ...names: Array<string | undefined>): boolean {\n  const configured = nodeOptions(ctx).ownedServices ?? [];\n  if (configured.length === 0) return false;\n\n  const owned = new Set(configured.map(normalizeServiceName));\n  return names.some((name) =>\n    name !== undefined ? ownedLookupNames(name).some((candidate) => owned.has(normalizeServiceName(candidate))) : false,\n  );\n}\n\n/**\n * True when `name` is a hand-owned type (see {@link NodeEmitterOptions.handOwnedTypes}).\n * Hand-owned types are never generated; the emitter defers to the existing\n * hand-written declaration and routes imports/barrel exports to it.\n */\nexport function isHandOwnedType(ctx: EmitterContext, name: string | undefined): boolean {\n  if (name === undefined) return false;\n  const configured = nodeOptions(ctx).handOwnedTypes;\n  if (!configured || configured.length === 0) return false;\n  return configured.includes(name);\n}\n\n/**\n * Resolve the Node operation override for an operation, keyed by \"METHOD /path\".\n */\nexport function operationOverrideFor(ctx: EmitterContext, op: Operation): OperationOverride | undefined {\n  return nodeOptions(ctx).operationOverrides?.[`${op.httpMethod.toUpperCase()} ${op.path}`];\n}\n\n/**\n * `planOperation` plus the Node `responseModel` override. When an operation\n * override supplies `responseModel`, the resolved response model name is\n * replaced so the resource and its generated test reference the desired wire\n * type and deserializer. Use this everywhere the Node emitter would otherwise\n * call `planOperation(op)` directly so resource and test stay in lockstep.\n */\nexport function planOperationFor(op: Operation, ctx: EmitterContext): OperationPlan {\n  const plan = planOperation(op);\n  const responseModel = operationOverrideFor(ctx, op)?.responseModel;\n  if (responseModel && responseModel !== plan.responseModelName) {\n    return { ...plan, responseModelName: responseModel, isModelResponse: true };\n  }\n  return plan;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { execFileSync } from 'node:child_process';\n\n/**\n * Snapshot of the live target SDK gathered by walking `--output` once.\n *\n * Replaces the heavier `--api-surface` extract step for the Node emitter.\n * Only declaration *names* are extracted (regex-based, no AST). That is\n * enough to drive \"skip if already present\" filtering in models, resources,\n * and serializers.\n */\nexport interface LiveSurface {\n  /** Absolute root the surface was built from (e.g. workos-node repo root). */\n  rootDir: string;\n  /** Set of file paths (relative to rootDir, POSIX separators) that exist on disk. */\n  files: Set<string>;\n  /**\n   * Git-tracked paths under the SDK root.\n   *\n   * When non-empty, this is the canonical baseline surface for \"existing SDK\"\n   * decisions. It excludes prior bad generations that left untracked files in\n   * the tree, which lets the emitter stop re-emitting that junk so manifest\n   * pruning can clean it up on the next run.\n   */\n  trackedFiles: Set<string>;\n  /** Files marked `@oagen-ignore-file`: never emit on top of these. */\n  protectedFiles: Set<string>;\n  /**\n   * Files whose first lines contain the `auto-generated by oagen` header.\n   * These were produced by a prior generation and should be regenerated when\n   * the spec changes (e.g. parameter renames). Letting the engine see them\n   * in the new output list is what enables that update path — dropping them\n   * would freeze them at their last-generated content.\n   */\n  autogenFiles: Set<string>;\n  /** Class name → relative file path. */\n  classes: Map<string, ClassInfo>;\n  /** Interface or type-alias name → relative file path. */\n  interfaces: Map<string, InterfaceInfo>;\n  /** Function name → relative file path (for serializers, helpers). */\n  functions: Map<string, string>;\n  /**\n   * `export const X = {...} as const` declarations on disk → ordered\n   * member-name → literal-value mapping. Used by `enums.ts` to preserve\n   * acronym casing (e.g. `DSync: 'dsync'`) on regeneration; without this,\n   * `toPascalCase('dsync')` would emit `Dsync` and silently break call\n   * sites that referenced `EnumName.DSync`.\n   */\n  constObjectEnums: Map<string, Map<string, string>>;\n}\n\nexport interface ClassInfo {\n  filePath: string;\n  methods: Set<string>;\n}\n\nexport interface InterfaceInfo {\n  filePath: string;\n  fields: Set<string>;\n}\n\nconst SRC_DIR = 'src';\n\n/**\n * Walk `${rootDir}/src/` and build a live-surface snapshot.\n *\n * If `${rootDir}/src/` does not exist, returns an empty surface (greenfield).\n * Reads each `.ts` file once; ignores `.spec.ts` and `.test.ts`.\n */\nexport function buildLiveSurface(rootDir: string): LiveSurface {\n  const surface: LiveSurface = {\n    rootDir,\n    files: new Set(),\n    trackedFiles: loadGitTrackedFiles(rootDir),\n    protectedFiles: new Set(),\n    autogenFiles: new Set(),\n    classes: new Map(),\n    interfaces: new Map(),\n    functions: new Map(),\n    constObjectEnums: new Map(),\n  };\n\n  const srcRoot = path.join(rootDir, SRC_DIR);\n  if (!fs.existsSync(srcRoot) || !fs.statSync(srcRoot).isDirectory()) {\n    return surface;\n  }\n\n  for (const absPath of walk(srcRoot)) {\n    const rel = toPosix(path.relative(rootDir, absPath));\n    surface.files.add(rel);\n    if (!rel.endsWith('.ts')) continue;\n    if (surface.trackedFiles.size > 0 && !surface.trackedFiles.has(rel)) continue;\n\n    let text: string;\n    try {\n      text = fs.readFileSync(absPath, 'utf8');\n    } catch {\n      continue;\n    }\n\n    if (isProtected(text)) {\n      surface.protectedFiles.add(rel);\n    } else if (isAutogen(text)) {\n      surface.autogenFiles.add(rel);\n    }\n\n    if (rel.endsWith('.spec.ts') || rel.endsWith('.test.ts')) continue;\n\n    extractDeclarations(text, rel, surface);\n  }\n\n  return surface;\n}\n\n/**\n * Module-level snapshot of the active live-surface, set by `index.ts` once per\n * generation run. Used by callers that don't have a clean way to thread\n * `EmitterContext` through (e.g. deeply-nested helpers in `resources.ts`\n * that decide whether to inline a serializer call).\n */\nlet activeSurface: LiveSurface | null = null;\nexport function setActiveLiveSurface(surface: LiveSurface): void {\n  activeSurface = surface;\n}\nexport function liveSurfaceHasFunction(name: string): boolean {\n  return activeSurface?.functions.has(name) ?? false;\n}\n/** Returns the relative file path containing the function, if known. */\nexport function liveSurfaceFunctionPath(name: string): string | undefined {\n  return activeSurface?.functions.get(name);\n}\nexport function liveSurfaceHasFile(relPath: string): boolean {\n  return activeSurface?.files.has(relPath) ?? false;\n}\nexport function liveSurfaceHasManagedFile(relPath: string): boolean {\n  const surface = activeSurface;\n  if (!surface) return false;\n  const managedPaths = surface.trackedFiles.size > 0 ? surface.trackedFiles : surface.files;\n  return managedPaths.has(relPath);\n}\nexport function liveSurfaceHasAutogenFile(relPath: string): boolean {\n  return activeSurface?.autogenFiles.has(relPath) ?? false;\n}\nexport function liveSurfaceHasExistingSdk(): boolean {\n  const surface = activeSurface;\n  if (!surface) return false;\n  const managedPaths = surface.trackedFiles.size > 0 ? surface.trackedFiles : surface.files;\n  return managedPaths.size > 0;\n}\n\n/** Empty surface — used as a default when no outputDir is available. */\nexport function emptyLiveSurface(): LiveSurface {\n  return {\n    rootDir: '',\n    files: new Set(),\n    trackedFiles: new Set(),\n    protectedFiles: new Set(),\n    autogenFiles: new Set(),\n    classes: new Map(),\n    interfaces: new Map(),\n    functions: new Map(),\n    constObjectEnums: new Map(),\n  };\n}\n\n/** Returns the existing member-name → value map for a const-object enum, if any. */\nexport function liveSurfaceConstEnumMembers(name: string): Map<string, string> | undefined {\n  return activeSurface?.constObjectEnums.get(name);\n}\nexport function liveSurfaceInterfacePath(name: string): string | undefined {\n  return activeSurface?.interfaces.get(name)?.filePath;\n}\n\n/** Should the emitter avoid writing this relative path on disk? */\nexport function shouldSkipPath(surface: LiveSurface, relPath: string): boolean {\n  return surface.protectedFiles.has(relPath);\n}\n\n/** Does the live SDK already contain a file at this relative path? */\nexport function pathExists(surface: LiveSurface, relPath: string): boolean {\n  return surface.files.has(relPath);\n}\n\nfunction* walk(dir: string): Generator<string> {\n  let entries: fs.Dirent[];\n  try {\n    entries = fs.readdirSync(dir, { withFileTypes: true });\n  } catch {\n    return;\n  }\n  for (const entry of entries) {\n    const abs = path.join(dir, entry.name);\n    if (entry.isDirectory()) {\n      if (entry.name === 'node_modules' || entry.name === '.git') continue;\n      yield* walk(abs);\n    } else if (entry.isFile()) {\n      yield abs;\n    }\n  }\n}\n\nfunction toPosix(p: string): string {\n  return p.split(path.sep).join('/');\n}\n\nfunction loadGitTrackedFiles(rootDir: string): Set<string> {\n  try {\n    const stdout = execFileSync('git', ['-C', rootDir, 'ls-files', '--', 'src'], {\n      encoding: 'utf8',\n      stdio: ['ignore', 'pipe', 'ignore'],\n    });\n    return new Set(\n      stdout\n        .split(/\\r?\\n/)\n        .map((line) => line.trim())\n        .filter(Boolean)\n        .map(toPosix),\n    );\n  } catch {\n    return new Set();\n  }\n}\n\nfunction isProtected(text: string): boolean {\n  // Look in the first 800 chars only — markers belong at file top.\n  const head = text.slice(0, 800);\n  return /@oagen-ignore-file\\b/.test(head);\n}\n\nfunction isAutogen(text: string): boolean {\n  // Same locality assumption — the auto-generated header is always at top.\n  const head = text.slice(0, 400);\n  return /auto-generated by oagen/i.test(head);\n}\n\nconst CLASS_RE = /^\\s*export\\s+(?:abstract\\s+)?class\\s+([A-Z][\\w$]*)/gm;\nconst INTERFACE_RE = /^\\s*export\\s+interface\\s+([A-Z][\\w$]*)/gm;\nconst TYPE_ALIAS_RE = /^\\s*export\\s+type\\s+([A-Z][\\w$]*)\\s*=/gm;\n// Picks up both standard declarations (`export function deserializeX(...)`)\n// and arrow-style consts (`export const deserializeX = (...) =>`). The\n// latter is the workos-node house style for serializers, including the\n// generic-arrow form `export const deserializeProfile = <T extends ...>(`.\nconst FUNCTION_RE = /^\\s*export\\s+(?:async\\s+)?function\\s+([a-zA-Z_$][\\w$]*)/gm;\nconst CONST_FN_RE = /^\\s*export\\s+const\\s+([a-zA-Z_$][\\w$]*)\\s*(?::\\s*[^=]+)?=\\s*(?:async\\s+)?(?:<[^>]*>\\s*)?\\(/gm;\n// For methods, match a class member declaration (rough — picks up async + plain methods).\nconst METHOD_RE =\n  /^\\s{2,}(?:public\\s+|private\\s+|protected\\s+|readonly\\s+)*(?:async\\s+)?([a-zA-Z_$][\\w$]*)\\s*(?:<[^>]*>)?\\s*\\(/gm;\n\nfunction extractDeclarations(text: string, relPath: string, surface: LiveSurface): void {\n  // Classes\n  for (const m of text.matchAll(CLASS_RE)) {\n    const name = m[1];\n    const body = sliceClassBody(text, m.index ?? 0);\n    const methods = new Set<string>();\n    if (body) {\n      for (const mm of body.matchAll(METHOD_RE)) {\n        const methodName = mm[1];\n        // Filter out keywords accidentally captured.\n        if (METHOD_KEYWORD_BLOCKLIST.has(methodName)) continue;\n        methods.add(methodName);\n      }\n    }\n    surface.classes.set(name, { filePath: relPath, methods });\n  }\n\n  // Interfaces\n  for (const m of text.matchAll(INTERFACE_RE)) {\n    const name = m[1];\n    const fields = extractInterfaceFields(text, m.index ?? 0);\n    surface.interfaces.set(name, { filePath: relPath, fields });\n  }\n\n  // Type aliases (treated as interfaces for skip purposes; field set is empty).\n  for (const m of text.matchAll(TYPE_ALIAS_RE)) {\n    const name = m[1];\n    if (!surface.interfaces.has(name)) {\n      surface.interfaces.set(name, { filePath: relPath, fields: new Set() });\n    }\n  }\n\n  // Top-level exported functions (both `function` and arrow-const styles).\n  for (const m of text.matchAll(FUNCTION_RE)) {\n    surface.functions.set(m[1], relPath);\n  }\n  for (const m of text.matchAll(CONST_FN_RE)) {\n    surface.functions.set(m[1], relPath);\n  }\n\n  // `export const X = { Member: 'value', ... } as const;` — capture the\n  // member-name → literal-value mapping so enum regeneration can preserve\n  // existing casing (e.g. `DSync: 'dsync'` instead of `Dsync: 'dsync'`).\n  for (const m of text.matchAll(CONST_OBJECT_ENUM_RE)) {\n    const enumName = m[1];\n    const body = m[2];\n    const members = new Map<string, string>();\n    for (const memberMatch of body.matchAll(CONST_OBJECT_MEMBER_RE)) {\n      const memberName = memberMatch[1] ?? memberMatch[2] ?? memberMatch[3];\n      const value = memberMatch[4];\n      if (memberName && value !== undefined) {\n        members.set(value, memberName);\n      }\n    }\n    if (members.size > 0) {\n      surface.constObjectEnums.set(enumName, members);\n    }\n  }\n}\n\n// `export const X = { ... } as const`\nconst CONST_OBJECT_ENUM_RE = /^\\s*export\\s+const\\s+([A-Z][\\w$]*)\\s*=\\s*\\{([\\s\\S]*?)\\}\\s*as\\s+const\\s*;/gm;\n// Member entries inside the object body — supports unquoted, single-quoted,\n// and double-quoted keys. Captures key (group 1/2/3) → string value (group 4).\nconst CONST_OBJECT_MEMBER_RE = /(?:'([^']+)'|\"([^\"]+)\"|([a-zA-Z_$][\\w$]*))\\s*:\\s*'([^']*)'/g;\n\nconst METHOD_KEYWORD_BLOCKLIST = new Set([\n  'if',\n  'for',\n  'while',\n  'switch',\n  'catch',\n  'return',\n  'throw',\n  'constructor', // tracked separately if needed\n]);\n\n// ---------------------------------------------------------------------------\n// Partial-emission merge\n//\n// For a service that is NOT owned and NOT a missing-service adoption,\n// `resources.ts` intentionally emits a PARTIAL resource class: operations\n// already covered by the baseline class are filtered out, leaving only the\n// new methods. Overwriting the on-disk file with that partial class would\n// delete every existing public method (this deleted four methods from\n// workos-node's api-keys.ts when the spec gained one operation). The helpers\n// below let `applyLiveSurface` detect that case and merge instead: keep the\n// existing file text verbatim and append only the generated-only methods\n// (plus any imports they need).\n// ---------------------------------------------------------------------------\n\ninterface ParsedClassLines {\n  name: string;\n  /** Line index of the `export class` declaration. */\n  declLine: number;\n  /** Line index of the line containing the class body's closing brace. */\n  closeLine: number;\n  /** Method names declared directly on the class body, in source order. */\n  methods: string[];\n}\n\n// Class members sit at exactly two-space indent in both generated output and\n// prettier-formatted SDK files; deeper-indented lines are method bodies.\nconst CLASS_MEMBER_RE =\n  /^ {2}(?:(?:public|private|protected|readonly|static)\\s+)*(?:async\\s+)?([a-zA-Z_$][\\w$]*)\\s*(?:<[^>]*>)?\\s*\\(/;\n\ninterface BraceScan {\n  /** Net code-brace balance accumulated so far. */\n  depth: number;\n  /** Whether any code `{` has been seen — distinguishes \"not yet opened\" from \"balanced and closed\". */\n  opened: boolean;\n  /** Whether we are mid `/* … *​/` block comment (spans lines). */\n  inBlockComment: boolean;\n  /**\n   * Interpolation-brace depth for each active template literal; a non-empty\n   * stack means we are inside a template, and the top being 0 means we are in\n   * its raw text (vs. inside a `${ … }` interpolation).\n   */\n  templates: number[];\n}\n\n/**\n * Advance a brace-balance scan across one `line`, mutating `s`. Counts only\n * braces that live in *code* — including template `${ … }` interpolation,\n * whose braces are self-balancing — and ignores braces inside string/template\n * text, line comments, and block comments. State threads across lines so block\n * comments and multi-line template literals are tracked correctly.\n *\n * Naive character counting (the prior approach) would clip a method block at a\n * `}` that merely sat inside a comment (`// returns when done }`) or a string\n * (`'closing brace: }'`), appending a truncated, unbalanced body. Regex\n * literals are intentionally not modelled: distinguishing `/` division from a\n * regex needs full tokenization, and a regex whose braces are net-unbalanced\n * does not occur in generated or hand-edited SDK code (`{n,m}` quantifiers are\n * always balanced).\n */\nfunction advanceBraceScan(line: string, s: BraceScan): void {\n  for (let i = 0; i < line.length; i++) {\n    const c = line[i];\n    if (s.inBlockComment) {\n      if (c === '*' && line[i + 1] === '/') {\n        s.inBlockComment = false;\n        i++;\n      }\n      continue;\n    }\n    const tdepth = s.templates.length;\n    if (tdepth > 0 && s.templates[tdepth - 1] === 0) {\n      // Raw template text: only an escape, a closing backtick, or the start of\n      // an interpolation matters; everything else (braces included) is literal.\n      if (c === '\\\\') {\n        i++;\n      } else if (c === '`') {\n        s.templates.pop();\n      } else if (c === '$' && line[i + 1] === '{') {\n        s.templates[tdepth - 1] = 1;\n        s.depth++;\n        s.opened = true;\n        i++;\n      }\n      continue;\n    }\n    // Code context: top level, or inside a template interpolation.\n    if (c === '/' && line[i + 1] === '/') break; // line comment runs to EOL\n    if (c === '/' && line[i + 1] === '*') {\n      s.inBlockComment = true;\n      i++;\n      continue;\n    }\n    if (c === \"'\" || c === '\"') {\n      const quote = c;\n      i++;\n      while (i < line.length && line[i] !== quote) {\n        if (line[i] === '\\\\') i++;\n        i++;\n      }\n      continue;\n    }\n    if (c === '`') {\n      s.templates.push(0);\n      continue;\n    }\n    if (c === '{') {\n      s.depth++;\n      s.opened = true;\n      if (tdepth > 0) s.templates[tdepth - 1]++;\n    } else if (c === '}') {\n      s.depth--;\n      if (tdepth > 0) s.templates[tdepth - 1]--;\n    }\n  }\n}\n\nfunction parseClassesByLine(lines: string[]): ParsedClassLines[] {\n  const classes: ParsedClassLines[] = [];\n  for (let i = 0; i < lines.length; i++) {\n    const decl = lines[i].match(/^export\\s+(?:abstract\\s+)?class\\s+([A-Z][\\w$]*)/);\n    if (!decl) continue;\n\n    const scan: BraceScan = { depth: 0, opened: false, inBlockComment: false, templates: [] };\n    let closeLine = -1;\n    for (let j = i; j < lines.length; j++) {\n      advanceBraceScan(lines[j], scan);\n      if (scan.opened && scan.depth <= 0) {\n        closeLine = j;\n        break;\n      }\n    }\n    if (closeLine < 0) continue;\n\n    const methods: string[] = [];\n    for (let j = i + 1; j < closeLine; j++) {\n      const member = lines[j].match(CLASS_MEMBER_RE);\n      if (!member) continue;\n      const name = member[1];\n      if (name === 'constructor' || METHOD_KEYWORD_BLOCKLIST.has(name)) continue;\n      if (!methods.includes(name)) methods.push(name);\n    }\n    classes.push({ name: decl[1], declLine: i, closeLine, methods });\n    i = closeLine;\n  }\n  return classes;\n}\n\n/**\n * Extract the full source block of `method` (attached comments included) from\n * a parsed class. Returns null if the block cannot be delimited.\n */\nfunction extractMethodBlock(lines: string[], cls: ParsedClassLines, method: string): string[] | null {\n  for (let j = cls.declLine + 1; j < cls.closeLine; j++) {\n    const member = lines[j].match(CLASS_MEMBER_RE);\n    if (!member || member[1] !== method) continue;\n\n    // Pull in the contiguous comment block directly above the signature.\n    let start = j;\n    while (start > cls.declLine + 1) {\n      const above = lines[start - 1].trim();\n      if (above.startsWith('//') || above.startsWith('/*') || above.startsWith('*')) start--;\n      else break;\n    }\n\n    // The member ends where the brace depth opened by its signature returns to\n    // zero. `advanceBraceScan` counts only code braces — ignoring those inside\n    // strings, template text, and comments — so it is robust to inner closures,\n    // object literals, and template interpolation nested at any indentation, as\n    // well as a stray `}` in a comment or string. The previous \"first\n    // two-space-indented `}`\" heuristic clipped the block at a nested brace at\n    // method-close indentation; raw character counting clipped it at a `}` that\n    // merely sat in a comment or string. Either appends a truncated body and\n    // orphans the real closing brace.\n    const scan: BraceScan = { depth: 0, opened: false, inBlockComment: false, templates: [] };\n    for (let end = j; end < cls.closeLine; end++) {\n      advanceBraceScan(lines[end], scan);\n      if (scan.opened && scan.depth <= 0) return lines.slice(start, end + 1);\n    }\n    return null;\n  }\n  return null;\n}\n\n// Multi-line tolerant: prettier wraps long named-import lists across lines.\nconst IMPORT_STMT_RE =\n  /^import\\s+(type\\s+)?(?:([A-Za-z_$][\\w$]*)\\s*,?\\s*)?(?:\\{([\\s\\S]*?)\\}\\s*)?(?:\\*\\s+as\\s+([A-Za-z_$][\\w$]*)\\s+)?from\\s+['\"]([^'\"]+)['\"];?/gm;\n\nfunction importLocalName(entry: string): string {\n  const asMatch = entry.match(/\\s+as\\s+([A-Za-z_$][\\w$]*)\\s*$/);\n  if (asMatch) return asMatch[1];\n  return entry.replace(/^type\\s+/, '').trim();\n}\n\nfunction collectImportedLocalNames(text: string): Set<string> {\n  const names = new Set<string>();\n  for (const m of text.matchAll(IMPORT_STMT_RE)) {\n    if (m[2]) names.add(m[2]);\n    if (m[4]) names.add(m[4]);\n    for (const entry of (m[3] ?? '').split(',')) {\n      const trimmed = entry.trim();\n      if (trimmed) names.add(importLocalName(trimmed));\n    }\n  }\n  return names;\n}\n\n/** Import statements from `generatedText` whose names `existingText` lacks. */\nfunction missingImportStatements(existingText: string, generatedText: string): string[] {\n  const existingNames = collectImportedLocalNames(existingText);\n  const statements: string[] = [];\n  for (const m of generatedText.matchAll(IMPORT_STMT_RE)) {\n    const [stmt, typeOnly, defaultName, named, namespaceName, moduleSpec] = m;\n    if (defaultName || namespaceName) {\n      // Default/namespace imports: append verbatim when the local is missing.\n      const local = defaultName ?? namespaceName;\n      if (local && !existingNames.has(local)) statements.push(stmt.endsWith(';') ? stmt : `${stmt};`);\n      continue;\n    }\n    const missing = (named ?? '')\n      .split(',')\n      .map((entry) => entry.trim())\n      .filter((entry) => entry && !existingNames.has(importLocalName(entry)));\n    if (missing.length === 0) continue;\n    statements.push(`import ${typeOnly ? 'type ' : ''}{ ${missing.join(', ')} } from '${moduleSpec}';`);\n  }\n  return statements;\n}\n\n/**\n * Merge a partial class emission into the existing on-disk file content.\n *\n * Acts only when a class declared in BOTH texts has methods on disk that the\n * generated content drops — the signature of a \"new operations only\" partial\n * emission. Returns the existing text with the generated-only methods appended\n * to the class body (and missing imports added), preserving every existing\n * method and import verbatim.\n *\n * Returns null when the generated content does not drop any existing method;\n * callers should then proceed with their normal (overwrite) path so full\n * regenerations keep propagating emitter improvements and spec renames.\n */\nexport function mergeGeneratedClassMethodsIntoExisting(existingText: string, generatedText: string): string | null {\n  const existingLines = existingText.split('\\n');\n  const generatedLines = generatedText.split('\\n');\n  const existingClasses = parseClassesByLine(existingLines);\n  if (existingClasses.length === 0) return null;\n  const generatedClasses = new Map(parseClassesByLine(generatedLines).map((cls) => [cls.name, cls]));\n\n  let dropsExistingMethod = false;\n  const insertions: Array<{ atLine: number; blocks: string[][] }> = [];\n  for (const existing of existingClasses) {\n    const generated = generatedClasses.get(existing.name);\n    if (!generated) continue;\n    const generatedMethods = new Set(generated.methods);\n    if (!existing.methods.some((method) => !generatedMethods.has(method))) continue;\n    dropsExistingMethod = true;\n\n    const existingMethods = new Set(existing.methods);\n    const blocks: string[][] = [];\n    for (const method of generated.methods) {\n      if (existingMethods.has(method)) continue;\n      const block = extractMethodBlock(generatedLines, generated, method);\n      if (block) blocks.push(block);\n    }\n    if (blocks.length > 0) insertions.push({ atLine: existing.closeLine, blocks });\n  }\n  if (!dropsExistingMethod) return null;\n\n  const merged = [...existingLines];\n  // Bottom-up so earlier insertions don't shift later line indices. Imports\n  // sit above every class body, so the import insertion point (computed on\n  // the original text) stays valid after these splices.\n  insertions.sort((a, b) => b.atLine - a.atLine);\n  for (const insertion of insertions) {\n    const blockLines: string[] = [];\n    for (const block of insertion.blocks) {\n      blockLines.push('', ...block);\n    }\n    merged.splice(insertion.atLine, 0, ...blockLines);\n  }\n\n  const importStatements = missingImportStatements(existingText, generatedText);\n  if (importStatements.length > 0) {\n    let lastImportLine = -1;\n    for (let i = 0; i < existingLines.length; i++) {\n      if (\n        /from\\s+['\"][^'\"]+['\"];?\\s*$/.test(existingLines[i]) ||\n        /^import\\s+['\"][^'\"]+['\"];?\\s*$/.test(existingLines[i])\n      ) {\n        lastImportLine = i;\n      }\n    }\n    if (lastImportLine >= 0) {\n      merged.splice(lastImportLine + 1, 0, ...importStatements);\n    } else {\n      // No imports yet: place them after the leading comment block.\n      let insertAt = 0;\n      while (insertAt < existingLines.length) {\n        const line = existingLines[insertAt].trim();\n        if (line === '' || line.startsWith('//') || line.startsWith('/*') || line.startsWith('*')) insertAt++;\n        else break;\n      }\n      merged.splice(insertAt, 0, ...importStatements, '');\n    }\n  }\n\n  return merged.join('\\n');\n}\n\n/**\n * Given the start index of a class declaration, return the brace-delimited body\n * as a substring. Returns '' if the body cannot be located.\n */\nfunction sliceClassBody(text: string, start: number): string {\n  const open = text.indexOf('{', start);\n  if (open < 0) return '';\n  let depth = 0;\n  for (let i = open; i < text.length; i++) {\n    const c = text[i];\n    if (c === '{') depth++;\n    else if (c === '}') {\n      depth--;\n      if (depth === 0) {\n        return text.slice(open + 1, i);\n      }\n    }\n  }\n  return '';\n}\n\n/**\n * Pull field names from an interface body. Conservative: only matches simple\n * declarations of the form `name?: ...;` or `name: ...;`. Generics, methods,\n * and computed property names are skipped (they don't influence skip decisions).\n */\nfunction extractInterfaceFields(text: string, start: number): Set<string> {\n  const fields = new Set<string>();\n  const open = text.indexOf('{', start);\n  if (open < 0) return fields;\n  let depth = 0;\n  let close = -1;\n  for (let i = open; i < text.length; i++) {\n    const c = text[i];\n    if (c === '{') depth++;\n    else if (c === '}') {\n      depth--;\n      if (depth === 0) {\n        close = i;\n        break;\n      }\n    }\n  }\n  if (close < 0) return fields;\n  const body = text.slice(open + 1, close);\n  const fieldRe = /^\\s*(?:readonly\\s+)?(?:'([^']+)'|\"([^\"]+)\"|([a-zA-Z_$][\\w$]*))\\s*\\??\\s*:/gm;\n  for (const m of body.matchAll(fieldRe)) {\n    const name = m[1] ?? m[2] ?? m[3];\n    if (name) fields.add(name);\n  }\n  return fields;\n}\n","import type { Model, EmitterContext, Service, Operation, TypeRef } from '@workos/oagen';\nimport { toPascalCase } from '@workos/oagen';\nexport {\n  collectModelRefs,\n  collectEnumRefs,\n  assignModelsToServices,\n  collectFieldDependencies,\n  collectRequestBodyModels,\n} from '@workos/oagen';\nimport { mapTypeRef } from './type-map.js';\nimport {\n  resolveInterfaceName,\n  fieldName,\n  fileName,\n  resolveServiceDir,\n  resolveMethodName,\n  buildServiceNameMap,\n} from './naming.js';\nimport { getMountTarget, groupByMount } from '../shared/resolved-ops.js';\nimport { assignModelsToServices, collectModelRefs, collectFieldDependencies } from '@workos/oagen';\nimport { isNodeOwnedService } from './options.js';\nimport { liveSurfaceHasExistingSdk, liveSurfaceHasFile } from './live-surface.js';\n\n/**\n * Compute a relative import path between two files within the generated SDK.\n */\nexport function relativeImport(fromFile: string, toFile: string): string {\n  const fromDir = fromFile.split('/').slice(0, -1);\n  const toFileParts = toFile.split('/');\n  const toDir = toFileParts.slice(0, -1);\n  const toFileName = toFileParts[toFileParts.length - 1];\n\n  let common = 0;\n  while (common < fromDir.length && common < toDir.length && fromDir[common] === toDir[common]) {\n    common++;\n  }\n\n  const ups = fromDir.length - common;\n  const downs = toDir.slice(common);\n  const parts = [...Array(ups).fill('..'), ...downs, toFileName];\n  let result = parts.join('/');\n  result = result.replace(/\\.ts$/, '');\n  if (!result.startsWith('.')) result = './' + result;\n  return result;\n}\n\n/**\n * Render a JSDoc comment block from a description string.\n */\nexport function docComment(description: string, indent = 0): string[] {\n  const pad = ' '.repeat(indent);\n  const descLines = description.split('\\n');\n  if (descLines.length === 1) {\n    return [`${pad}/** ${descLines[0]} */`];\n  }\n  const lines: string[] = [`${pad}/**`];\n  for (const line of descLines) {\n    lines.push(line === '' ? `${pad} *` : `${pad} * ${line}`);\n  }\n  lines.push(`${pad} */`);\n  return lines;\n}\n\n/**\n * Build a map from model name -> default type args string for generic models.\n */\nexport function buildGenericModelDefaults(models: Model[]): Map<string, string> {\n  const result = new Map<string, string>();\n  for (const model of models) {\n    if (!model.typeParams?.length) continue;\n    const defaults = model.typeParams.map((tp) => (tp.default ? mapTypeRef(tp.default) : 'unknown'));\n    result.set(model.name, `<${defaults.join(', ')}>`);\n  }\n  return result;\n}\n\n/**\n * Remove unused imports from generated source code.\n */\nexport function pruneUnusedImports(lines: string[]): string[] {\n  const importLines: string[] = [];\n  const bodyLines: string[] = [];\n  let inBody = false;\n  for (const line of lines) {\n    if (!inBody && (line.startsWith('import ') || line === '')) {\n      importLines.push(line);\n    } else {\n      inBody = true;\n      bodyLines.push(line);\n    }\n  }\n\n  const body = bodyLines.join('\\n');\n  const kept: string[] = [];\n\n  for (const line of importLines) {\n    if (line === '') {\n      kept.push(line);\n      continue;\n    }\n    const match = line.match(/\\{([^}]+)\\}/);\n    if (!match) {\n      kept.push(line);\n      continue;\n    }\n    const names = match[1]\n      .split(',')\n      .map((n) => n.trim())\n      .filter(Boolean);\n    const usedNames = names.filter((name) => {\n      const re = new RegExp(`\\\\b${name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`);\n      return re.test(body);\n    });\n    if (usedNames.length === 0) continue;\n    if (usedNames.length === names.length) {\n      kept.push(line);\n    } else {\n      const isTypeImport = line.startsWith('import type');\n      const fromMatch = line.match(/from\\s+['\"]([^'\"]+)['\"]/);\n      if (fromMatch) {\n        const prefix = isTypeImport ? 'import type' : 'import';\n        kept.push(`${prefix} { ${usedNames.join(', ')} } from '${fromMatch[1]}';`);\n      } else {\n        kept.push(line);\n      }\n    }\n  }\n\n  return [...kept, ...bodyLines];\n}\n\n/** Built-in TypeScript types that are always available. */\nexport const TS_BUILTINS = new Set([\n  'Record',\n  'Promise',\n  'Array',\n  'Map',\n  'Set',\n  'Date',\n  'string',\n  'number',\n  'boolean',\n  'void',\n  'null',\n  'undefined',\n  'any',\n  'never',\n  'unknown',\n  'true',\n  'false',\n]);\n\n/**\n * Detect whether the existing SDK uses string representation for date-time fields.\n */\nexport function detectStringDateConvention(models: Model[], ctx: EmitterContext): boolean {\n  if (!ctx.apiSurface?.interfaces) return false;\n  for (const model of models) {\n    const domainName = resolveInterfaceName(model.name, ctx);\n    const baseline = ctx.apiSurface.interfaces[domainName];\n    if (!baseline?.fields) continue;\n    for (const field of model.fields) {\n      if (field.type.kind !== 'primitive' || field.type.format !== 'date-time') continue;\n      const baselineField = baseline.fields[fieldName(field.name)];\n      if (baselineField && !baselineField.type.includes('Date')) {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\n/**\n * Build a comprehensive set of all known type names from the IR and baseline.\n */\nexport function buildKnownTypeNames(models: Model[], ctx: EmitterContext): Set<string> {\n  const knownNames = new Set<string>();\n  for (const m of models) knownNames.add(resolveInterfaceName(m.name, ctx));\n  for (const e of ctx.spec.enums) knownNames.add(e.name);\n  if (ctx.apiSurface?.interfaces) {\n    for (const name of Object.keys(ctx.apiSurface.interfaces)) knownNames.add(name);\n  }\n  if (ctx.apiSurface?.typeAliases) {\n    for (const name of Object.keys(ctx.apiSurface.typeAliases)) knownNames.add(name);\n  }\n  if (ctx.apiSurface?.enums) {\n    for (const name of Object.keys(ctx.apiSurface.enums)) knownNames.add(name);\n  }\n  return knownNames;\n}\n\n/**\n * Create a service directory resolver bundle.\n *\n * When `ctx.apiSurface` is populated, the baseline `sourceFile` of an\n * existing interface wins over the IR-derived first-reference assignment.\n * This keeps generated imports pointing at the existing live SDK location\n * instead of duplicating a model into a different service directory.\n */\nexport function createServiceDirResolver(\n  models: Model[],\n  services: Service[],\n  ctx: EmitterContext,\n): {\n  modelToService: Map<string, string>;\n  serviceNameMap: Map<string, string>;\n  resolveDir: (irService: string | undefined) => string;\n} {\n  const modelToService = assignModelsToEmittableServices(models, services, ctx);\n  const serviceNameMap = buildServiceNameMap(services, ctx);\n\n  // Per-name → directory override, harvested from the live SDK surface.\n  // Stored under a sentinel \"\" service key in modelToService so resolveDir\n  // can dispatch on it without a separate map. Implementation: model name ->\n  // baseline directory string (e.g., \"user-management\"). The override map is\n  // attached by tagging the model name with a directory prefix that bypasses\n  // the IR-service lookup. Concretely we keep a side map.\n  const baselineDirByModel = harvestBaselineDirByModel(ctx);\n\n  // Override modelToService for any IR model that has a baseline sourceFile.\n  // We invent a synthetic IR-service key that maps directly to the baseline\n  // directory via serviceNameMap so resolveDir returns the correct dir.\n  for (const [modelName] of modelToService) {\n    const dir = baselineDirByModel.get(modelName);\n    if (!dir) continue;\n    const synthetic = `__baseline_dir__:${dir}`;\n    modelToService.set(modelName, synthetic);\n    if (!serviceNameMap.has(synthetic)) {\n      // resolveServiceDir is identity on already-kebab-case names, so storing\n      // the dir directly keeps round-tripping through the resolver clean.\n      serviceNameMap.set(synthetic, dir);\n    }\n  }\n\n  const resolveDir = (irService: string | undefined) => {\n    if (!irService) return 'common';\n    if (irService.startsWith('__baseline_dir__:')) return irService.slice('__baseline_dir__:'.length);\n    return resolveServiceDir(serviceNameMap.get(irService) ?? irService);\n  };\n  return { modelToService, serviceNameMap, resolveDir };\n}\n\n/**\n * Map baseline interface / type-alias names to the top-level `src/<dir>/`\n * their `sourceFile` lives in. Both kinds can shadow IR model names — e.g.\n * `type Role = EnvironmentRole | OrganizationRole;` is the live SDK's\n * canonical Role definition even though the IR represents Role as a model.\n */\nfunction harvestBaselineDirByModel(ctx: EmitterContext): Map<string, string> {\n  const baselineDirByModel = new Map<string, string>();\n  const recordSource = (name: string, info: { sourceFile?: string } | undefined) => {\n    const sourceFile = info?.sourceFile;\n    if (!sourceFile) return;\n    const m = sourceFile.match(/^src\\/([^/]+)\\//);\n    if (!m) return;\n    baselineDirByModel.set(name, m[1]);\n  };\n  for (const [name, info] of Object.entries(ctx.apiSurface?.interfaces ?? {})) {\n    recordSource(name, info as { sourceFile?: string });\n  }\n  for (const [name, info] of Object.entries(ctx.apiSurface?.typeAliases ?? {})) {\n    if (!baselineDirByModel.has(name)) {\n      recordSource(name, info as { sourceFile?: string });\n    }\n  }\n  return baselineDirByModel;\n}\n\n/**\n * `assignModelsToServices` plus an owned-service correction pass.\n *\n * The engine's assignment is first-reference-wins: a model referenced by both\n * Organizations and AuditLogs lands in `organizations/` even when only\n * AuditLogs is owned this run. Against an existing SDK, `applyLiveSurface`\n * then drops the model file (a non-owned, non-adopted directory cannot\n * receive new paths) while the owned resource still imports\n * `../organizations/interfaces/<model>.interface` — an import that resolves\n * to nothing (TS2307).\n *\n * The correction re-homes such models to the owned service that references\n * them, so emission and import planning agree on a directory that is allowed\n * to receive files. It only fires when:\n *  1. `ownedServices` is configured and the run targets an existing SDK;\n *  2. the model has no baseline `sourceFile` (otherwise the baseline-dir\n *     override keeps imports pointing at the on-disk location);\n *  3. the model's computed interface path does not already exist on disk;\n *  4. the assigned service is neither owned itself nor sharing a directory\n *     with an owned service.\n */\nexport function assignModelsToEmittableServices(\n  models: Model[],\n  services: Service[],\n  ctx?: EmitterContext,\n): Map<string, string> {\n  const modelToService = assignModelsToServices(models, services, ctx?.modelHints);\n  if (ctx) {\n    reassignOwnedServiceDependencies(modelToService, models, services, ctx);\n  }\n  return modelToService;\n}\n\nfunction reassignOwnedServiceDependencies(\n  modelToService: Map<string, string>,\n  models: Model[],\n  services: Service[],\n  ctx: EmitterContext,\n): void {\n  const serviceNameMap = buildServiceNameMap(services, ctx);\n  // Ownership is a property of the MOUNT target, not the IR service: an op\n  // can live on a non-owned IR service (e.g. Organizations, because its path\n  // starts with /organizations) while being mounted on an owned service via\n  // `resolvedOperations` (e.g. AuditLogs' retention endpoints). Walking only\n  // IR services misses such ops entirely, so the models they reference stay\n  // assigned to the unemittable IR directory and are never emitted anywhere.\n  // Regroup by mount target when resolved operations exist — same as\n  // `buildGeneratedResourceModelUsage` and `computeOwnedServiceDirs`.\n  const mountGroups = groupByMount(ctx);\n  const candidateServices: Service[] =\n    mountGroups.size > 0 ? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations })) : services;\n  const ownedServices = candidateServices.filter((s) => isNodeOwnedService(ctx, s.name, serviceNameMap.get(s.name)));\n  if (ownedServices.length === 0) return;\n  // Greenfield generation emits every directory; nothing is unemittable.\n  if (!liveSurfaceHasExistingSdk()) return;\n\n  const dirOf = (irService: string | undefined): string =>\n    irService ? resolveServiceDir(serviceNameMap.get(irService) ?? irService) : 'common';\n  const ownedDirs = new Set(ownedServices.map((s) => dirOf(s.name)));\n  const baselineDirByModel = harvestBaselineDirByModel(ctx);\n  const modelsByName = new Map(models.map((m) => [m.name, m]));\n\n  for (const service of ownedServices) {\n    for (const name of collectServiceModelClosure(service, modelsByName)) {\n      if (!modelsByName.has(name)) continue;\n      if (baselineDirByModel.has(name)) continue; // declared in the baseline → on disk\n      const assigned = modelToService.get(name);\n      if (assigned && isNodeOwnedService(ctx, assigned, serviceNameMap.get(assigned))) continue;\n      const assignedDir = dirOf(assigned);\n      if (ownedDirs.has(assignedDir)) continue;\n      if (liveSurfaceHasFile(`src/${assignedDir}/interfaces/${fileName(name)}.interface.ts`)) continue;\n      modelToService.set(name, service.name);\n    }\n  }\n}\n\n/** Model names referenced by a service's operations, expanded through fields. */\nfunction collectServiceModelClosure(service: Service, modelsByName: Map<string, Model>): Set<string> {\n  const referenced = new Set<string>();\n  const add = (ref: TypeRef | undefined): void => {\n    if (!ref) return;\n    for (const name of collectModelRefs(ref)) referenced.add(name);\n  };\n  for (const op of service.operations) {\n    add(op.requestBody);\n    add(op.response);\n    for (const param of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n      add(param.type);\n    }\n    if (op.pagination) add(op.pagination.itemType);\n  }\n\n  const queue = [...referenced];\n  while (queue.length > 0) {\n    const name = queue.pop()!;\n    const model = modelsByName.get(name);\n    if (!model) continue;\n    for (const dep of collectFieldDependencies(model).models) {\n      if (!referenced.has(dep)) {\n        referenced.add(dep);\n        queue.push(dep);\n      }\n    }\n  }\n  return referenced;\n}\n\n/**\n * Check if baseline interface fields appear to contain generic type parameters.\n *\n * Heuristic: strip string literals first (so `'GoogleSAML'` is not mistaken\n * for a type name), then look for any PascalCase token that isn't a known\n * type — those indicate an unbound generic parameter like `TCustomAttributes`.\n */\nexport function isBaselineGeneric(fields: Record<string, unknown>, knownNames: Set<string>): boolean {\n  for (const [, bf] of Object.entries(fields)) {\n    const rawType = (bf as { type: string }).type;\n    const stripped = rawType.replace(/'[^']*'/g, '').replace(/\"[^\"]*\"/g, '');\n    const typeNames = stripped.match(/\\b[A-Z][a-zA-Z0-9]*\\b/g);\n    if (!typeNames) continue;\n    for (const tn of typeNames) {\n      if (TS_BUILTINS.has(tn)) continue;\n      if (knownNames.has(tn)) continue;\n      return true;\n    }\n  }\n  return false;\n}\n\nexport {\n  isListMetadataModel,\n  isListWrapperModel,\n  collectNonPaginatedResponseModelNames,\n  collectReferencedListMetadataModels,\n} from '../shared/model-utils.js';\n\nfunction modelFingerprint(model: Model): string {\n  const fields = model.fields.map((f) => `${f.name}:${JSON.stringify(f.type)}:${f.required}`).sort();\n  return fields.join('|');\n}\n\n/**\n * Find structurally identical models and build a deduplication map.\n */\nexport function buildDeduplicationMap(\n  models: Model[],\n  ctx?: EmitterContext,\n  reachable?: Set<string>,\n): Map<string, string> {\n  const dedup = new Map<string, string>();\n\n  // Pass 1: structural fingerprint dedup\n  const fingerprints = new Map<string, string>();\n  for (const model of models) {\n    if (model.fields.length === 0) continue;\n    const fp = modelFingerprint(model);\n    const existing = fingerprints.get(fp);\n    if (existing) {\n      if (reachable && !reachable.has(existing) && reachable.has(model.name)) {\n        dedup.delete(existing);\n        dedup.set(existing, model.name);\n        fingerprints.set(fp, model.name);\n      } else {\n        dedup.set(model.name, existing);\n      }\n    } else {\n      fingerprints.set(fp, model.name);\n    }\n  }\n\n  // Pass 2: name-based dedup\n  if (ctx) {\n    const byDomainName = new Map<string, Model[]>();\n    for (const model of models) {\n      if (model.fields.length === 0) continue;\n      if (dedup.has(model.name)) continue;\n      const domainName = resolveInterfaceName(model.name, ctx);\n      const group = byDomainName.get(domainName);\n      if (group) {\n        group.push(model);\n      } else {\n        byDomainName.set(domainName, [model]);\n      }\n    }\n    for (const [, group] of byDomainName) {\n      if (group.length < 2) continue;\n      group.sort((a, b) => {\n        if (reachable) {\n          const aReach = reachable.has(a.name) ? 0 : 1;\n          const bReach = reachable.has(b.name) ? 0 : 1;\n          if (aReach !== bReach) return aReach - bReach;\n        }\n        return b.fields.length - a.fields.length || a.name.localeCompare(b.name);\n      });\n      const canonical = group[0];\n      for (let i = 1; i < group.length; i++) {\n        dedup.set(group[i].name, canonical.name);\n      }\n    }\n  }\n\n  return dedup;\n}\n\n/**\n * Check whether a service's endpoints are already fully covered by existing\n * hand-written service classes.\n */\nexport function isServiceCoveredByExisting(service: Service, ctx: EmitterContext): boolean {\n  const mountTarget = getMountTarget(service, ctx);\n  if (mountTarget !== toPascalCase(service.name)) return true;\n\n  const overlay = ctx.overlayLookup?.methodByOperation;\n  if (!overlay || overlay.size === 0) return false;\n  if (service.operations.length === 0) return false;\n\n  const baselineClasses = ctx.apiSurface?.classes;\n  if (!baselineClasses) return false;\n  const existingClassNames = new Set(Object.keys(baselineClasses));\n\n  return service.operations.every((op: Operation) => {\n    const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n    const match = overlay.get(httpKey);\n    if (!match) return false;\n    return existingClassNames.has(match.className);\n  });\n}\n\n/**\n * Check whether a fully-covered service has operations whose overlay-mapped\n * methods are missing from the baseline class.\n */\nexport function hasMethodsAbsentFromBaseline(service: Service, ctx: EmitterContext): boolean {\n  const baselineClasses = ctx.apiSurface?.classes;\n  if (!baselineClasses) return false;\n\n  const mountTarget = getMountTarget(service, ctx);\n  if (mountTarget !== toPascalCase(service.name)) {\n    const cls = baselineClasses[mountTarget];\n    if (!cls) return true;\n    for (const op of service.operations) {\n      const method = resolveMethodName(op, service, ctx);\n      if (!cls.methods?.[method]) return true;\n    }\n    return false;\n  }\n\n  const overlay = ctx.overlayLookup?.methodByOperation;\n  if (!overlay) return false;\n\n  for (const op of service.operations) {\n    const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n    const match = overlay.get(httpKey);\n    if (!match) continue;\n    const cls = baselineClasses[match.className];\n    if (!cls) continue;\n    if (!cls.methods?.[match.methodName]) return true;\n  }\n  return false;\n}\n\n/**\n * Check whether an IR model has fields not present in the baseline interface.\n *\n * When the live SDK exposes the same name as a type alias (e.g.\n * `type Role = EnvironmentRole | OrganizationRole;`), treat it as already\n * fully covered — generating an interface against an existing alias would\n * collide. The alias's referenced types still get generated independently\n * and serve as the canonical implementation.\n */\nexport function modelHasNewFields(model: Model, ctx: EmitterContext): boolean {\n  if (!ctx.apiSurface?.interfaces && !ctx.apiSurface?.typeAliases) return true;\n\n  const domainName = resolveInterfaceName(model.name, ctx);\n\n  if (ctx.apiSurface?.typeAliases?.[domainName]) {\n    return false;\n  }\n\n  const baseline = ctx.apiSurface?.interfaces?.[domainName];\n  if (!baseline?.fields) return true;\n\n  for (const field of model.fields) {\n    const camelName = fieldName(field.name);\n    if (!baseline.fields[camelName]) return true;\n  }\n\n  return false;\n}\n\n/**\n * Return operations in a service that are NOT covered by existing hand-written\n * service classes.\n */\nexport function uncoveredOperations(service: Service, ctx: EmitterContext): Operation[] {\n  const overlay = ctx.overlayLookup?.methodByOperation;\n  if (!overlay || overlay.size === 0) return service.operations;\n\n  const baselineClasses = ctx.apiSurface?.classes;\n  if (!baselineClasses) return service.operations;\n  const existingClassNames = new Set(Object.keys(baselineClasses));\n\n  return service.operations.filter((op: Operation) => {\n    const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n    const match = overlay.get(httpKey);\n    if (!match) return true;\n    return !existingClassNames.has(match.className);\n  });\n}\n\n/**\n * Compute the set of model names reachable from non-event service operations.\n */\nexport function computeNonEventReachable(services: Service[], models: Model[]): Set<string> {\n  const seeds = new Set<string>();\n  for (const svc of services) {\n    if (svc.name.toLowerCase() === 'events') continue;\n    for (const op of svc.operations) {\n      const collectFromRef = (t: TypeRef | undefined): void => {\n        if (!t) return;\n        if (t.kind === 'model') seeds.add(t.name);\n        if (t.kind === 'array') collectFromRef(t.items);\n        if (t.kind === 'nullable') collectFromRef(t.inner);\n        if (t.kind === 'union') t.variants.forEach(collectFromRef);\n      };\n      collectFromRef(op.response);\n      collectFromRef(op.requestBody);\n      if (op.pagination?.itemType) collectFromRef(op.pagination.itemType);\n    }\n  }\n  const modelMap = new Map(models.map((m) => [m.name, m]));\n  const reachable = new Set<string>();\n  const queue = [...seeds];\n  while (queue.length > 0) {\n    const name = queue.pop()!;\n    if (reachable.has(name)) continue;\n    reachable.add(name);\n    const m = modelMap.get(name);\n    if (!m) continue;\n    for (const field of m.fields) {\n      const walk = (t: TypeRef): void => {\n        if (t.kind === 'model' && !reachable.has(t.name)) queue.push(t.name);\n        if (t.kind === 'array') walk(t.items);\n        if (t.kind === 'nullable') walk(t.inner);\n        if (t.kind === 'union') t.variants.forEach(walk);\n      };\n      walk(field.type);\n    }\n  }\n  return reachable;\n}\n","import type { Enum, EmitterContext, GeneratedFile, Model, Service } from '@workos/oagen';\nimport { collectFieldDependencies, toPascalCase, walkTypeRef } from '@workos/oagen';\nimport { fileName, resolveServiceDir, buildServiceNameMap } from './naming.js';\nimport { docComment, assignModelsToEmittableServices } from './utils.js';\nimport { isInlineEnum } from './type-map.js';\nimport { isNodeOwnedService } from './options.js';\nimport { liveSurfaceConstEnumMembers, liveSurfaceInterfacePath } from './live-surface.js';\nimport { isEnumInScope } from '../shared/resolved-ops.js';\n\nexport function generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n  if (enums.length === 0) return [];\n\n  const enumToService = assignEnumsToServices(enums, ctx.spec.services, ctx.spec.models, ctx);\n  const serviceNameMap = buildServiceNameMap(ctx.spec.services, ctx);\n  const resolveDir = (irService: string | undefined) =>\n    irService ? resolveServiceDir(serviceNameMap.get(irService) ?? irService) : 'common';\n  const files: GeneratedFile[] = [];\n\n  for (const enumDef of enums) {\n    // Inlined enums get expanded at usage sites by `type-map`. No file needed.\n    if (isInlineEnum(enumDef.name)) continue;\n\n    const service = enumToService.get(enumDef.name);\n    const dirName = resolveDir(service);\n\n    const baselineEnum = ctx.apiSurface?.enums?.[enumDef.name];\n    const baselineAlias = ctx.apiSurface?.typeAliases?.[enumDef.name];\n    const generatedPath = `src/${dirName}/interfaces/${fileName(enumDef.name)}.interface.ts`;\n\n    const baselineSourceFile =\n      (baselineEnum as any)?.sourceFile ?? (baselineAlias as any)?.sourceFile ?? liveSurfaceInterfacePath(enumDef.name);\n    if (dirName === 'common' && !baselineSourceFile && (ctx.outputDir || ctx.targetDir || ctx.apiSurface)) {\n      continue;\n    }\n    // The declared-elsewhere skip must not fire for OWNED services: the\n    // \"elsewhere\" is typically the very interface file the owned-service\n    // regeneration is simultaneously overwriting (e.g. legacy enums declared\n    // inline in organization-domain.interface.ts), so skipping here leaves\n    // the names referenced by generated code but declared nowhere. Under\n    // ownership the canonical per-service module is the source of truth —\n    // emit it; the model emitter plans its import from the same path.\n    const isOwnedEnumService = isNodeOwnedService(ctx, service, service ? serviceNameMap.get(service) : undefined);\n    if (baselineSourceFile && baselineSourceFile !== generatedPath && !isOwnedEnumService) {\n      continue;\n    }\n\n    const lines: string[] = [];\n    let hasNewValues = false;\n\n    if (baselineEnum?.members) {\n      const existingValues = new Set(Object.values(baselineEnum.members).map(String));\n      const irValues = enumDef.values.map((v) => String(v.value));\n      const missingValues = irValues.filter((v) => !existingValues.has(v));\n      hasNewValues = missingValues.length > 0;\n\n      lines.push(`export enum ${enumDef.name} {`);\n      for (const [memberName, memberValue] of Object.entries(baselineEnum.members)) {\n        const valueStr = typeof memberValue === 'string' ? `'${memberValue}'` : String(memberValue);\n        lines.push(`  ${memberName} = ${valueStr},`);\n      }\n      for (const val of missingValues) {\n        const memberName = toPascalCase(val);\n        lines.push(`  ${memberName} = '${val}',`);\n      }\n      lines.push('}');\n    } else if (baselineAlias?.value) {\n      const baselineValues = extractLiteralUnionValues(baselineAlias.value);\n      const irValues = enumDef.values.map((v) => String(v.value));\n      const missing = irValues.filter((v) => !baselineValues.has(v));\n      hasNewValues = missing.length > 0;\n      if (missing.length > 0) {\n        const allValues = [...baselineValues, ...missing];\n        const parts = allValues.map((v) => `'${v}'`);\n        lines.push(`export type ${enumDef.name} = ${parts.join(' | ')};`);\n      } else {\n        lines.push(`export type ${enumDef.name} = ${baselineAlias.value};`);\n      }\n    } else {\n      // No baseline form available — emit the workos-node house style:\n      //\n      //   export const X = { Member: 'value', ... } as const;\n      //   export type X = (typeof X)[keyof typeof X];\n      //\n      // This dual declaration lets callers use either the type (`X`) or the\n      // namespace (`X.Member`) without paying for a TypeScript `enum`'s\n      // runtime overhead. Emitting only the type alias would compile but\n      // break hand-written test files that import the enum as a value.\n      //\n      // Member name resolution, per value:\n      //   1. If the live SDK already declares this enum as a const-object\n      //      with a member for this exact value, reuse the existing member\n      //      name. This preserves acronym casing (`DSync`, `SAML`, `JWT`)\n      //      that the simpler `toPascalCase` would otherwise flatten.\n      //   2. Otherwise PascalCase the value.\n      //   3. Skip duplicate values and duplicate member names — the union\n      //      type derived from the const captures every kept value.\n      const values = enumDef.values;\n      const existingMembers = liveSurfaceConstEnumMembers(enumDef.name);\n      const seenMembers = new Set<string>();\n      const seenValues = new Set<string>();\n      lines.push(`export const ${enumDef.name} = {`);\n      for (const v of values) {\n        const valueKey = String(v.value);\n        if (seenValues.has(valueKey)) continue;\n        seenValues.add(valueKey);\n        const memberName = existingMembers?.get(valueKey) ?? toPascalCase(valueKey);\n        if (seenMembers.has(memberName)) continue;\n        seenMembers.add(memberName);\n        const valueStr = typeof v.value === 'string' ? `'${v.value}'` : String(v.value);\n        if (v.description || v.deprecated) {\n          const parts: string[] = [];\n          if (v.description) parts.push(v.description);\n          if (v.deprecated) parts.push('@deprecated');\n          lines.push(...docComment(parts.join('\\n'), 2));\n        }\n        lines.push(`  ${memberName}: ${valueStr},`);\n      }\n      lines.push(`} as const;`);\n      lines.push('');\n      lines.push(`export type ${enumDef.name} =`);\n      lines.push(`  (typeof ${enumDef.name})[keyof typeof ${enumDef.name}];`);\n    }\n\n    if (isEnumInScope(enumDef.name, ctx)) {\n      files.push({\n        path: `src/${dirName}/interfaces/${fileName(enumDef.name)}.interface.ts`,\n        content: lines.join('\\n'),\n        skipIfExists: !hasNewValues,\n      });\n    }\n  }\n\n  return files;\n}\n\nfunction extractLiteralUnionValues(aliasValue: string): Set<string> {\n  const values = new Set<string>();\n  const regex = /'([^']+)'/g;\n  let match;\n  while ((match = regex.exec(aliasValue)) !== null) {\n    values.add(match[1]);\n  }\n  return values;\n}\n\nexport function assignEnumsToServices(\n  enums: Enum[],\n  services: Service[],\n  models: Model[] = [],\n  ctx?: EmitterContext,\n): Map<string, string> {\n  const enumToService = new Map<string, string>();\n  const enumNames = new Set(enums.map((e) => e.name));\n\n  for (const service of services) {\n    for (const op of service.operations) {\n      const refs = new Set<string>();\n      const collect = (ref: any) => {\n        walkTypeRef(ref, { enum: (r: any) => refs.add(r.name) });\n      };\n      if (op.requestBody) collect(op.requestBody);\n      collect(op.response);\n      for (const p of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n        collect(p.type);\n      }\n      for (const name of refs) {\n        if (enumNames.has(name) && !enumToService.has(name)) {\n          enumToService.set(name, service.name);\n        }\n      }\n    }\n  }\n\n  if (models.length > 0) {\n    // Use the emittable-services assignment (not the raw engine one) so an\n    // enum referenced through a model that was re-homed into an owned\n    // service directory follows the model — `generateEnums` emission and the\n    // model's enum imports must agree on the directory.\n    const modelToService = assignModelsToEmittableServices(models, services, ctx);\n    for (const model of models) {\n      const service = modelToService.get(model.name);\n      if (!service) continue;\n\n      for (const name of collectFieldDependencies(model).enums) {\n        if (enumNames.has(name) && !enumToService.has(name)) {\n          enumToService.set(name, service);\n        }\n      }\n    }\n  }\n\n  // A shared enum that already has a canonical declaration under `src/common/`\n  // must stay there. `common` is a shared module that owned-service\n  // regeneration never overwrites, so it is always the source of truth for\n  // these names. Without this, owning a service that references such an enum\n  // would emit a SECOND copy into the owned module's `interfaces/` dir (via the\n  // owned-service exception in `generateEnums`) while the `common` copy\n  // remains, and `src/index.ts` re-exports both barrels — a duplicate\n  // `export *` (TS2308). Unassigning the enum makes every consumer\n  // (`generateEnums`, model imports, barrels) resolve it to `common`.\n  if (ctx) {\n    const serviceNameMap = buildServiceNameMap(services, ctx);\n    const toUnassign: string[] = [];\n    for (const [name, service] of enumToService) {\n      if (!isNodeOwnedService(ctx, service, serviceNameMap.get(service))) continue;\n      const home =\n        (ctx.apiSurface?.enums?.[name] as any)?.sourceFile ??\n        (ctx.apiSurface?.typeAliases?.[name] as any)?.sourceFile ??\n        liveSurfaceInterfacePath(name);\n      if (home && home.startsWith('src/common/')) toUnassign.push(name);\n    }\n    for (const name of toUnassign) enumToService.delete(name);\n  }\n\n  return enumToService;\n}\n","import type { Model, Field, EmitterContext, TypeRef, UnionType, PrimitiveType } from '@workos/oagen';\nimport { mapTypeRef as tsMapTypeRef } from './type-map.js';\nimport { fieldName, wireFieldName, fileName, resolveInterfaceName, wireInterfaceName } from './naming.js';\nimport {\n  relativeImport,\n  buildKnownTypeNames,\n  isBaselineGeneric,\n  createServiceDirResolver,\n  modelHasNewFields,\n  assignModelsToServices,\n} from './utils.js';\nimport {\n  liveSurfaceHasFunction,\n  liveSurfaceHasFile,\n  liveSurfaceFunctionPath,\n  liveSurfaceHasAutogenFile,\n} from './live-surface.js';\nimport { isNodeOwnedService } from './options.js';\n\n// ---------------------------------------------------------------------------\n// Guard strategy\n// ---------------------------------------------------------------------------\n\ntype GuardStrategy =\n  | { kind: 'direct' }\n  | { kind: 'null-check'; fallback: string }\n  | { kind: 'coalesce'; fallback: string }\n  | { kind: 'non-null-assert' };\n\ninterface BaselineFieldInfo {\n  type: string;\n  optional: boolean;\n}\n\ninterface BaselineInterface {\n  fields?: Record<string, BaselineFieldInfo>;\n  sourceFile?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Expression builders\n// ---------------------------------------------------------------------------\n\n/**\n * Decide whether a `deserialize${X}` / `serialize${X}` helper will be\n * resolvable at compile time. A helper is callable when:\n *   - the live SDK already exports it (live-surface knows), OR\n *   - the emitter is producing the dep model's serializer this run, which\n *     happens when `modelHasNewFields(dep, ctx)` says the dep needs\n *     regeneration.\n *\n * When neither condition holds, expression builders fall back to passing\n * the value through unchanged — `deserializeX(wire)` and `serializeX(model)`\n * become `wire` / `model` respectively. Safe because elided cases imply\n * the wire and domain shapes are identical (no IR additions).\n */\nfunction helperExists(helperName: string, depModelName: string, ctx: EmitterContext): boolean {\n  if (liveSurfaceHasFunction(helperName)) return true;\n  const depModel = ctx.spec.models.find((m) => m.name === depModelName);\n  if (!depModel) return false;\n  const modelToService = assignModelsToServices(ctx.spec.models, ctx.spec.services, ctx.modelHints);\n  const depService = modelToService.get(depModelName);\n  const resolvedName = resolveInterfaceName(depModelName, ctx);\n  const siblingPrefix = helperName.startsWith('serialize') ? 'deserialize' : 'serialize';\n  const siblingPath = liveSurfaceFunctionPath(`${siblingPrefix}${resolvedName}`);\n  if (siblingPath && liveSurfaceHasFile(siblingPath) && !liveSurfaceHasAutogenFile(siblingPath)) return false;\n  const sourceFile = (ctx.apiSurface?.interfaces?.[resolvedName] as { sourceFile?: string } | undefined)?.sourceFile;\n  const { resolveDir } = createServiceDirResolver(ctx.spec.models, ctx.spec.services, ctx);\n  const candidate = sourceFile\n    ? sourceFile.replace('/interfaces/', '/serializers/').replace('.interface.ts', '.serializer.ts')\n    : `src/${resolveDir(depService)}/serializers/${fileName(depModelName)}.serializer.ts`;\n  if (liveSurfaceHasFile(candidate) && !liveSurfaceHasAutogenFile(candidate)) return false;\n  if (isNodeOwnedService(ctx, depService)) return true;\n  return modelHasNewFields(depModel, ctx);\n}\n\nexport function deserializeExpression(\n  ref: TypeRef,\n  wireExpr: string,\n  ctx: EmitterContext,\n  nullFallback = 'null',\n): string {\n  switch (ref.kind) {\n    case 'primitive':\n      return deserializePrimitive(ref, wireExpr);\n    case 'literal':\n    case 'enum':\n      return wireExpr;\n    case 'model': {\n      const name = resolveInterfaceName(ref.name, ctx);\n      // The deserialize helper may not exist if its serializer file was\n      // elided (no baseline serializer + no new fields ⇒ no generation).\n      // Fall back to passing the wire value through — the runtime shape\n      // is identical to the domain shape in those cases.\n      if (!helperExists(`deserialize${name}`, ref.name, ctx)) return wireExpr;\n      return `deserialize${name}(${wireExpr})`;\n    }\n    case 'array':\n      if (ref.items.kind === 'model') {\n        const name = resolveInterfaceName(ref.items.name, ctx);\n        if (!helperExists(`deserialize${name}`, ref.items.name, ctx)) return wireExpr;\n        return `${wireExpr}.map(deserialize${name})`;\n      }\n      return wireExpr;\n    case 'nullable': {\n      const innerExpr = deserializeExpression(ref.inner, wireExpr, ctx, nullFallback);\n      if (innerExpr !== wireExpr) {\n        return `${wireExpr} != null ? ${innerExpr} : ${nullFallback}`;\n      }\n      return `${wireExpr} ?? ${nullFallback}`;\n    }\n    case 'union': {\n      if (ref.discriminator) {\n        return renderDiscriminatorSwitch(ref, wireExpr, 'deserialize', ctx);\n      }\n      if (ref.compositionKind === 'allOf') {\n        return renderAllOfMerge(ref, wireExpr, 'deserialize', ctx);\n      }\n      const models = uniqueModelVariants(ref);\n      if (models.length === 1) {\n        const name = resolveInterfaceName(models[0], ctx);\n        return `deserialize${name}(${wireExpr})`;\n      }\n      return wireExpr;\n    }\n    case 'map':\n      return wireExpr;\n  }\n}\n\nexport function serializeExpression(\n  ref: TypeRef,\n  domainExpr: string,\n  ctx: EmitterContext,\n  nullFallback = 'null',\n): string {\n  switch (ref.kind) {\n    case 'primitive':\n      return serializePrimitive(ref, domainExpr);\n    case 'literal':\n    case 'enum':\n      return domainExpr;\n    case 'model': {\n      const name = resolveInterfaceName(ref.name, ctx);\n      if (!helperExists(`serialize${name}`, ref.name, ctx)) return domainExpr;\n      return `serialize${name}(${domainExpr})`;\n    }\n    case 'array':\n      if (ref.items.kind === 'model') {\n        const name = resolveInterfaceName(ref.items.name, ctx);\n        if (!helperExists(`serialize${name}`, ref.items.name, ctx)) return domainExpr;\n        return `${domainExpr}.map(serialize${name})`;\n      }\n      return domainExpr;\n    case 'nullable': {\n      const innerExpr = serializeExpression(ref.inner, domainExpr, ctx, nullFallback);\n      if (innerExpr !== domainExpr) {\n        return `${domainExpr} != null ? ${innerExpr} : ${nullFallback}`;\n      }\n      return domainExpr;\n    }\n    case 'union': {\n      if (ref.discriminator) {\n        return renderDiscriminatorSwitch(ref, domainExpr, 'serialize', ctx);\n      }\n      if (ref.compositionKind === 'allOf') {\n        return renderAllOfMerge(ref, domainExpr, 'serialize', ctx);\n      }\n      const models = uniqueModelVariants(ref);\n      if (models.length === 1) {\n        const name = resolveInterfaceName(models[0], ctx);\n        return `serialize${name}(${domainExpr})`;\n      }\n      return domainExpr;\n    }\n    case 'map':\n      return domainExpr;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Primitive format conversions\n// ---------------------------------------------------------------------------\n\nfunction deserializePrimitive(ref: PrimitiveType, wireExpr: string): string {\n  if (ref.format === 'date-time') return `new Date(${wireExpr})`;\n  if (ref.format === 'int64') return `BigInt(${wireExpr})`;\n  return wireExpr;\n}\n\nfunction serializePrimitive(ref: PrimitiveType, domainExpr: string): string {\n  if (ref.format === 'date-time') return `${domainExpr}.toISOString()`;\n  if (ref.format === 'int64') return `String(${domainExpr})`;\n  return domainExpr;\n}\n\n// ---------------------------------------------------------------------------\n// Union helpers\n// ---------------------------------------------------------------------------\n\nexport function uniqueModelVariants(ref: UnionType): string[] {\n  const modelNames = new Set<string>();\n  for (const v of ref.variants) {\n    if (v.kind === 'model') modelNames.add(v.name);\n  }\n  return [...modelNames];\n}\n\nfunction renderDiscriminatorSwitch(\n  ref: UnionType,\n  expr: string,\n  direction: 'deserialize' | 'serialize',\n  ctx: EmitterContext,\n): string {\n  const disc = ref.discriminator!;\n  const cases: string[] = [];\n  for (const [value, modelName] of Object.entries(disc.mapping)) {\n    const resolved = resolveInterfaceName(modelName, ctx);\n    const fn = `${direction}${resolved}`;\n    cases.push(`case '${value}': return ${fn}(${expr} as any)`);\n  }\n  // No mapping → passthrough. Without this guard, an empty `disc.mapping`\n  // emits `switch { ; default: ... }` which is invalid TypeScript syntax\n  // (the leading `;` looks like a stray statement before the first case).\n  if (cases.length === 0) return expr;\n  return `(() => { switch ((${expr} as any).${disc.property}) { ${cases.join('; ')}; default: return ${expr} } })()`;\n}\n\nfunction renderAllOfMerge(\n  ref: UnionType,\n  expr: string,\n  direction: 'deserialize' | 'serialize',\n  ctx: EmitterContext,\n): string {\n  const models = uniqueModelVariants(ref);\n  if (models.length === 0) return expr;\n  const spreads = models.map((name) => {\n    const resolved = resolveInterfaceName(name, ctx);\n    return `...${direction}${resolved}(${expr} as any)`;\n  });\n  return `({ ${spreads.join(', ')} })`;\n}\n\n// ---------------------------------------------------------------------------\n// Type inspection helpers\n// ---------------------------------------------------------------------------\n\nexport function needsNullGuard(ref: TypeRef): boolean {\n  switch (ref.kind) {\n    case 'model':\n      return true;\n    case 'primitive':\n      return hasFormatConversion(ref);\n    case 'array':\n      return ref.items.kind === 'model';\n    case 'nullable':\n      return needsNullGuard(ref.inner);\n    case 'union':\n      if (ref.discriminator) return true;\n      if (ref.compositionKind === 'allOf' && uniqueModelVariants(ref).length > 0) return true;\n      return uniqueModelVariants(ref).length === 1;\n    default:\n      return false;\n  }\n}\n\nexport function hasFormatConversion(ref: TypeRef): boolean {\n  switch (ref.kind) {\n    case 'primitive':\n      return ref.format === 'date-time' || ref.format === 'int64';\n    case 'nullable':\n      return hasFormatConversion(ref.inner);\n    default:\n      return false;\n  }\n}\n\nexport function hasDateTimeConversion(ref: TypeRef): boolean {\n  switch (ref.kind) {\n    case 'primitive':\n      return ref.format === 'date-time';\n    case 'nullable':\n      return hasDateTimeConversion(ref.inner);\n    default:\n      return false;\n  }\n}\n\nexport function collectSerializedModelRefs(ref: TypeRef): string[] {\n  switch (ref.kind) {\n    case 'model':\n      return [ref.name];\n    case 'array':\n      if (ref.items.kind === 'model') return [ref.items.name];\n      return collectSerializedModelRefs(ref.items);\n    case 'nullable':\n      return collectSerializedModelRefs(ref.inner);\n    case 'union': {\n      const models = uniqueModelVariants(ref);\n      if (ref.discriminator && models.length > 0) return models;\n      if (ref.compositionKind === 'allOf' && models.length > 0) return models;\n      if (models.length === 1) return models;\n      return [];\n    }\n    case 'map':\n    case 'primitive':\n    case 'literal':\n    case 'enum':\n      return [];\n  }\n}\n\nexport function defaultForType(ref: TypeRef): string | null {\n  switch (ref.kind) {\n    case 'literal':\n      return typeof ref.value === 'string' ? `'${ref.value}'` : String(ref.value);\n    case 'enum':\n      return null;\n    case 'map':\n      return '{}';\n    case 'nullable':\n      return 'null';\n    case 'primitive':\n      switch (ref.type) {\n        case 'boolean':\n          return 'false';\n        case 'string':\n          return \"''\";\n        case 'integer':\n        case 'number':\n          return '0';\n        default:\n          return null;\n      }\n    case 'array':\n      return '[]';\n    default:\n      return null;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Serializer type params\n// ---------------------------------------------------------------------------\n\nexport function renderSerializerTypeParams(model: Model, ctx?: EmitterContext): { decl: string; usage: string } {\n  if (model.typeParams?.length) {\n    const params = model.typeParams.map((tp) => {\n      const def = tp.default ? ` = ${tsMapTypeRef(tp.default)}` : '';\n      return `${tp.name}${def}`;\n    });\n    const names = model.typeParams.map((tp) => tp.name);\n    return { decl: `<${params.join(', ')}>`, usage: `<${names.join(', ')}>` };\n  }\n  if (ctx?.apiSurface?.interfaces) {\n    const domainName = resolveInterfaceName(model.name, ctx);\n    const baseline = ctx.apiSurface.interfaces[domainName];\n    if (baseline?.fields) {\n      const baselineSourceFile = (baseline as any).sourceFile as string | undefined;\n      const { modelToService, resolveDir } = createServiceDirResolver(ctx.spec.models, ctx.spec.services, ctx);\n      const generatedPath = `src/${resolveDir(modelToService.get(model.name))}/interfaces/${fileName(model.name)}.interface.ts`;\n      const pathMatches = !baselineSourceFile || baselineSourceFile === generatedPath;\n      const knownNames = buildKnownTypeNames(ctx.spec.models, ctx);\n      if (pathMatches && isBaselineGeneric(baseline.fields, knownNames)) {\n        return {\n          decl: '<GenericType extends Record<string, unknown> = Record<string, unknown>>',\n          usage: '<GenericType>',\n        };\n      }\n    }\n  }\n  return { decl: '', usage: '' };\n}\n\n// ---------------------------------------------------------------------------\n// Baseline incompatibility detection\n// ---------------------------------------------------------------------------\n\nexport function serializerHasBaselineIncompatibility(\n  model: Model,\n  baselineResponse: BaselineInterface | undefined,\n  baselineDomain?: BaselineInterface,\n  ctx?: EmitterContext,\n): boolean {\n  if (!baselineResponse?.fields) return false;\n\n  const irWireFields = new Set<string>();\n  const irDomainFields = new Set<string>();\n  for (const field of model.fields) {\n    irWireFields.add(wireFieldName(field.name));\n    irDomainFields.add(fieldName(field.domainName ?? field.name));\n  }\n\n  for (const [wireField2, fieldDef] of Object.entries(baselineResponse.fields)) {\n    if (fieldDef.optional) continue;\n    if (!irWireFields.has(wireField2)) {\n      return true;\n    }\n  }\n\n  if (baselineDomain?.fields) {\n    const baselineRequiredFields = Object.entries(baselineDomain.fields)\n      .filter(([, f]) => !f.optional)\n      .map(([name]) => name);\n    const unmatchedCount = baselineRequiredFields.filter((n) => !irDomainFields.has(n)).length;\n    if (unmatchedCount > 0 && baselineRequiredFields.length > 0) {\n      const unmatchedRatio = unmatchedCount / baselineRequiredFields.length;\n      if (unmatchedRatio > 0.3) {\n        return true;\n      }\n    }\n  }\n\n  if (ctx?.apiSurface?.interfaces) {\n    const modelSourceFile = (baselineResponse as any)?.sourceFile as string | undefined;\n    const responseDir = modelSourceFile ? modelSourceFile.split('/').slice(0, 2).join('/') : null;\n\n    for (const field of model.fields) {\n      let fieldType = field.type;\n      if (fieldType.kind === 'nullable') fieldType = fieldType.inner;\n      if (fieldType.kind !== 'array' && fieldType.kind !== 'model') continue;\n      const innerType = fieldType.kind === 'array' ? fieldType.items : fieldType;\n      if (innerType.kind !== 'model') continue;\n\n      const nestedWireName = wireInterfaceName(resolveInterfaceName(innerType.name, ctx));\n      const wireField3 = wireFieldName(field.name);\n      const baselineWireField2 = baselineResponse.fields![wireField3];\n      if (!baselineWireField2) continue;\n\n      const baselineTypeNames: string[] = baselineWireField2.type.match(/\\b[A-Z][a-zA-Z0-9]*Response\\b/g) || [];\n      if (baselineTypeNames.length > 0 && !baselineTypeNames.includes(nestedWireName)) {\n        return true;\n      }\n\n      if (baselineWireField2.type.includes(nestedWireName) || baselineWireField2.type.match(/\\b[A-Z]\\w*Response\\b/)) {\n        const typeNames: string[] = baselineWireField2.type.match(/\\b[A-Z][a-zA-Z0-9]*\\b/g) || [];\n        for (const typeName of typeNames) {\n          if (typeName === 'Record' || typeName === 'Array') continue;\n          const nestedIface = ctx.apiSurface!.interfaces![typeName];\n          if (!nestedIface) continue;\n          const nestedSrc = (nestedIface as any).sourceFile as string | undefined;\n          if (!nestedSrc || !responseDir) continue;\n          const nestedDir = nestedSrc.split('/').slice(0, 2).join('/');\n          if (nestedDir !== responseDir) {\n            return true;\n          }\n        }\n      }\n    }\n  }\n\n  return false;\n}\n\n// ---------------------------------------------------------------------------\n// Field assignment planning\n// ---------------------------------------------------------------------------\n\nexport function planDeserializeField(\n  field: Field,\n  baselineDomain: BaselineInterface | undefined,\n  baselineResponse: BaselineInterface | undefined,\n  skipFormatFields: Set<string>,\n  ctx: EmitterContext,\n): { line: string; skip: boolean } {\n  const domain = fieldName(field.domainName ?? field.name);\n  const wire = wireFieldName(field.name);\n  const wireAccess = `response.${wire}`;\n  const skip = skipFormatFields.has(field.name);\n\n  // Fallback selection considers both the IR field type and the baseline\n  // domain field. When baseline declares the field as `optional`\n  // (undefined-permitting) but the IR is nullable (null-only), prefer\n  // `undefined` so the deserialize output matches the baseline interface\n  // signature. Otherwise the assignment becomes\n  // `Record<...> | null → Record<...> | undefined` (TS2322).\n  const baselineDomainField = baselineDomain?.fields?.[domain];\n  const baselineDomainAcceptsNull = baselineDomainField?.type?.includes('null') ?? false;\n  let fallbackForNullable: string;\n  if (field.type.kind === 'nullable') {\n    fallbackForNullable =\n      baselineDomainField && baselineDomainField.optional && !baselineDomainAcceptsNull ? 'undefined' : 'null';\n  } else {\n    fallbackForNullable = 'undefined';\n  }\n  let expr = skip ? wireAccess : deserializeExpression(field.type, wireAccess, ctx, fallbackForNullable);\n\n  // Baseline-declared Date for an IR `string` field: the interface body\n  // uses the baseline's `Date` (line 392 in models.ts), so the serializer\n  // must convert with `new Date(...)`. The IR type doesn't carry the\n  // `format: date-time` here (the spec just said `type: string`), so\n  // `deserializeExpression` would otherwise return the raw wire access.\n  const baselineField = baselineDomain?.fields?.[domain];\n  if (\n    !skip &&\n    expr === wireAccess &&\n    baselineField?.type === 'Date' &&\n    field.type.kind === 'primitive' &&\n    field.type.type === 'string'\n  ) {\n    expr = `new Date(${wireAccess})`;\n  }\n\n  const isNewField = baselineDomain && !baselineDomain.fields?.[domain];\n  const effectivelyOptional = !field.required || isNewField;\n\n  const guard = planDeserializeGuard(field, expr, wireAccess, effectivelyOptional, isNewField, baselineResponse);\n  return { line: emitAssignment(domain, expr, wireAccess, guard), skip: false };\n}\n\nfunction planDeserializeGuard(\n  field: Field,\n  expr: string,\n  wireAccess: string,\n  effectivelyOptional: boolean | null | undefined,\n  isNewField: boolean | null | undefined,\n  baselineResponse: BaselineInterface | undefined,\n): GuardStrategy {\n  if (effectivelyOptional && expr !== wireAccess && needsNullGuard(field.type)) {\n    const fallback = field.type.kind === 'nullable' ? 'null' : 'undefined';\n    return { kind: 'null-check', fallback };\n  }\n\n  if (field.required && expr === wireAccess) {\n    const wire = wireFieldName(field.name);\n    const responseFieldInfo = baselineResponse?.fields?.[wire];\n    const responseFieldOptional = responseFieldInfo?.optional ?? false;\n    const needsFallback = responseFieldOptional || !!isNewField;\n    const fallback = needsFallback ? defaultForType(field.type) : null;\n    if (fallback) {\n      return { kind: 'coalesce', fallback };\n    }\n  }\n\n  return { kind: 'direct' };\n}\n\nexport function planSerializeField(\n  field: Field,\n  baselineDomain: BaselineInterface | undefined,\n  baselineResponse: BaselineInterface | undefined,\n  skipFormatFields: Set<string>,\n  ctx: EmitterContext,\n): { line: string; skip: boolean } {\n  const wire = wireFieldName(field.name);\n  const domain = fieldName(field.domainName ?? field.name);\n  const domainAccess = `model.${domain}`;\n  const skip = skipFormatFields.has(field.name);\n\n  // Symmetric to `planDeserializeField`: when the baseline wire is\n  // `optional` (undefined) but the IR is nullable, fall back to\n  // `undefined` so the serialized output matches the baseline wire shape.\n  const baselineWireField = baselineResponse?.fields?.[wire];\n  const baselineWireAcceptsNull = baselineWireField?.type?.includes('null') ?? false;\n  let fallbackForNullable: string;\n  if (field.type.kind === 'nullable') {\n    fallbackForNullable =\n      baselineWireField && baselineWireField.optional && !baselineWireAcceptsNull ? 'undefined' : 'null';\n  } else {\n    fallbackForNullable = 'undefined';\n  }\n  let expr = skip ? domainAccess : serializeExpression(field.type, domainAccess, ctx, fallbackForNullable);\n\n  // Symmetric to `planDeserializeField`: when the baseline declares the\n  // domain field as `Date` but the IR carries a plain `string`, the\n  // serializer must call `.toISOString()` so the wire form gets a string\n  // back. Without this, the serializer assigns a `Date` model field into\n  // a `string` wire field — TS2322.\n  const baselineField = baselineDomain?.fields?.[domain];\n  if (\n    !skip &&\n    expr === domainAccess &&\n    baselineField?.type === 'Date' &&\n    field.type.kind === 'primitive' &&\n    field.type.type === 'string'\n  ) {\n    expr = field.required ? `${domainAccess}.toISOString()` : `${domainAccess}?.toISOString()`;\n  }\n\n  const isNewSerField = baselineDomain && !baselineDomain.fields?.[domain];\n  const effectivelyOptionalSer = !field.required || isNewSerField;\n\n  const guard = planSerializeGuard(\n    field,\n    expr,\n    domainAccess,\n    effectivelyOptionalSer,\n    isNewSerField,\n    baselineDomain,\n    baselineResponse,\n  );\n  return { line: emitAssignment(wire, expr, domainAccess, guard), skip: false };\n}\n\nfunction planSerializeGuard(\n  field: Field,\n  expr: string,\n  domainAccess: string,\n  effectivelyOptionalSer: boolean | null | undefined,\n  isNewSerField: boolean | null | undefined,\n  baselineDomain: BaselineInterface | undefined,\n  baselineResponse: BaselineInterface | undefined,\n): GuardStrategy {\n  const wire = wireFieldName(field.name);\n  const domain = fieldName(field.name);\n\n  const shouldGuardSer = effectivelyOptionalSer || field.type.kind === 'nullable';\n  if (expr !== domainAccess && needsNullGuard(field.type) && shouldGuardSer) {\n    let fallback: string = field.type.kind === 'nullable' ? 'null' : 'undefined';\n    // If the wire side is required but the field guard would otherwise emit\n    // `undefined`, the assignment becomes `string | undefined → string`.\n    // Pick a non-undefined fallback that satisfies the wire type:\n    //   - `null` when the wire type accepts null\n    //   - the string-defaulting `defaultForType(field.type)` (e.g. `''`)\n    //     for required-string wires\n    const baselineWireField = baselineResponse?.fields?.[wire];\n    const wireRequired = baselineWireField ? !baselineWireField.optional : field.required;\n    if (fallback === 'undefined' && wireRequired) {\n      const wireAcceptsNull = baselineWireField?.type?.includes('null');\n      fallback = wireAcceptsNull ? 'null' : (defaultForType(field.type) ?? 'undefined');\n    }\n    return { kind: 'null-check', fallback };\n  }\n\n  const baselineWireField = baselineResponse?.fields?.[wire];\n  const baselineDomainField = baselineDomain?.fields?.[domain];\n  const isNewFieldOnExistingDomain = baselineDomain && !baselineDomainField;\n  const domainFieldIsOptional =\n    !field.required || (baselineDomainField?.optional ?? false) || !!isNewFieldOnExistingDomain;\n  const wireFieldIsRequired = baselineWireField ? !baselineWireField.optional : field.required;\n  const needsUndefinedCoalesce = domainFieldIsOptional && wireFieldIsRequired && expr === domainAccess;\n\n  if (needsUndefinedCoalesce) {\n    const wireHasNull = baselineWireField?.type?.includes('null') || field.type.kind === 'nullable';\n    if (wireHasNull) {\n      return { kind: 'coalesce', fallback: 'null' };\n    }\n    return { kind: 'non-null-assert' };\n  }\n\n  if (field.type.kind === 'nullable' && expr === domainAccess) {\n    const domainWireField2 = wireFieldName(field.name);\n    const responseBaselineField2 = baselineResponse?.fields?.[domainWireField2];\n    const baselineDomainField2 = baselineDomain?.fields?.[domain];\n    const domainResponseMismatch =\n      baselineDomainField2 &&\n      !baselineDomainField2.optional &&\n      responseBaselineField2 &&\n      responseBaselineField2.optional;\n    const fieldEffectivelyOptional = !field.required || !!isNewSerField || !!domainResponseMismatch;\n    if (fieldEffectivelyOptional) {\n      // The wire side may not accept `null` (e.g. `metadata?: Record<...>`).\n      // Fall back to `undefined` in that case so the assignment matches the\n      // baseline wire field's actual type.\n      const wireAcceptsNull = responseBaselineField2?.type?.includes('null') ?? true;\n      const fallback = wireAcceptsNull ? 'null' : 'undefined';\n      return { kind: 'coalesce', fallback };\n    }\n  }\n\n  return { kind: 'direct' };\n}\n\nfunction emitAssignment(lhs: string, expr: string, accessExpr: string, guard: GuardStrategy): string {\n  switch (guard.kind) {\n    case 'direct':\n      return `  ${lhs}: ${expr},`;\n    case 'null-check':\n      if (expr.includes(`${accessExpr} != null ?`)) {\n        return `  ${lhs}: ${expr},`;\n      }\n      return `  ${lhs}: ${accessExpr} != null ? ${expr} : ${guard.fallback},`;\n    case 'coalesce':\n      return `  ${lhs}: ${expr} ?? ${guard.fallback},`;\n    case 'non-null-assert':\n      return `  ${lhs}: ${expr}!,`;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Serializer file emission helpers\n// ---------------------------------------------------------------------------\n\ninterface SerializerContext {\n  modelToService: Map<string, string>;\n  resolveDir: (irService: string | undefined) => string;\n  dedup: Map<string, string>;\n  skippedSerializeModels: Set<string>;\n  /** Models reachable from any response — anything outside this set is\n   *  request-only and won't have a `deserialize<X>` emitted. `undefined`\n   *  means \"no usage info available, assume deserialize exists\". */\n  responseReachableModels: Set<string> | undefined;\n  ctx: EmitterContext;\n}\n\nexport function buildSerializerImports(\n  model: Model,\n  serializerPath: string,\n  dirName: string,\n  domainName: string,\n  responseName: string,\n  sctx: SerializerContext,\n): string[] {\n  const lines: string[] = [];\n  const interfacePath = `src/${dirName}/interfaces/${fileName(model.name)}.interface.ts`;\n  // Single-form baselines (`wireInterfaceName` returns the same name as\n  // `domainName`) only export one symbol — don't duplicate the import.\n  const symbols = domainName === responseName ? domainName : `${domainName}, ${responseName}`;\n  lines.push(`import type { ${symbols} } from '${relativeImport(serializerPath, interfacePath)}';`);\n\n  const nestedModelRefs = new Set<string>();\n  for (const field of model.fields) {\n    for (const ref of collectSerializedModelRefs(field.type)) {\n      if (ref !== model.name) nestedModelRefs.add(ref);\n    }\n  }\n\n  for (const dep of nestedModelRefs) {\n    const depService = sctx.modelToService.get(dep);\n    const depDir = sctx.resolveDir(depService);\n    const depName = resolveInterfaceName(dep, sctx.ctx);\n    const depIsOwned = isNodeOwnedService(sctx.ctx, depService);\n\n    // Locate the serializer file, in priority order:\n    //   1. The actual file containing `deserialize${depName}` per\n    //      live-surface (e.g. `deserializeAuditLogSchema` lives in\n    //      `create-audit-log-schema.serializer.ts`, not in the predictable\n    //      `audit-log-schema.serializer.ts`).\n    //   2. The baseline interface's adjacent serializer file path.\n    //   3. The IR-name path — this is where the emitter writes the\n    //      serializer it's producing this run.\n    const baselineSrc = depIsOwned\n      ? undefined\n      : (sctx.ctx.apiSurface?.interfaces?.[depName] as { sourceFile?: string } | undefined)?.sourceFile;\n    const baselineSerializerPath = baselineSrc\n      ? baselineSrc.replace('/interfaces/', '/serializers/').replace('.interface.ts', '.serializer.ts')\n      : null;\n    const irNameSerializerPath = `src/${depDir}/serializers/${fileName(dep)}.serializer.ts`;\n\n    const liveDeserPath = depIsOwned ? undefined : liveSurfaceFunctionPath(`deserialize${depName}`);\n    const liveSerPath = depIsOwned ? undefined : liveSurfaceFunctionPath(`serialize${depName}`);\n    const depSerializerPath =\n      liveDeserPath ??\n      liveSerPath ??\n      (baselineSerializerPath && liveSurfaceHasFile(baselineSerializerPath)\n        ? baselineSerializerPath\n        : irNameSerializerPath);\n\n    const rel = relativeImport(serializerPath, depSerializerPath);\n    const canon = sctx.dedup.get(dep);\n    const depSkipSerialize =\n      sctx.skippedSerializeModels.has(dep) || (canon != null && sctx.skippedSerializeModels.has(canon));\n    const depSkipDeserialize =\n      sctx.responseReachableModels !== undefined &&\n      !sctx.responseReachableModels.has(dep) &&\n      (canon == null || !sctx.responseReachableModels.has(canon));\n\n    // Decide whether this serializer is reachable at runtime:\n    //   - file on disk → honor what it exports (hasDeser/hasSer)\n    //   - file NOT on disk → only safe to import if the emitter is\n    //     producing the dep's serializer this run, which only happens\n    //     when `modelHasNewFields` says the dep needs regeneration.\n    //\n    // Skip the import otherwise. The serializer body falls back to a\n    // pass-through expression when it can't call the helper.\n    const hasDeser = liveSurfaceHasFunction(`deserialize${depName}`);\n    const hasSer = liveSurfaceHasFunction(`serialize${depName}`);\n    const fileExists = !depIsOwned && liveSurfaceHasFile(depSerializerPath);\n    if (fileExists && !hasDeser && !hasSer) continue;\n    if (!fileExists) {\n      const depModel = sctx.ctx.spec.models.find((m) => m.name === dep);\n      const willGenerateSerializer = depModel ? depIsOwned || modelHasNewFields(depModel, sctx.ctx) : true;\n      if (!willGenerateSerializer) continue;\n    }\n\n    // Mixed: file exists, only one of the pair is exported. Import only\n    // what's present so we don't synthesize a missing symbol. The body\n    // emitter's `bodyArgExpr` already falls through when it sees a missing\n    // serialize function.\n    if (fileExists && depSkipSerialize) {\n      if (hasDeser) lines.push(`import { deserialize${depName} } from '${rel}';`);\n      continue;\n    }\n    if (fileExists && !hasSer) {\n      lines.push(`import { deserialize${depName} } from '${rel}';`);\n      continue;\n    }\n    if (fileExists && !hasDeser) {\n      lines.push(`import { serialize${depName} } from '${rel}';`);\n      continue;\n    }\n\n    if (depSkipSerialize && depSkipDeserialize) continue;\n    if (depSkipSerialize) {\n      lines.push(`import { deserialize${depName} } from '${rel}';`);\n    } else if (depSkipDeserialize) {\n      lines.push(`import { serialize${depName} } from '${rel}';`);\n    } else {\n      lines.push(`import { deserialize${depName}, serialize${depName} } from '${rel}';`);\n    }\n  }\n  lines.push('');\n  return lines;\n}\n\nexport function buildSkipFormatFields(model: Model, baselineDomain: BaselineInterface | undefined): Set<string> {\n  const skipFormatFields = new Set<string>();\n  if (baselineDomain) {\n    for (const field of model.fields) {\n      if (skipFormatFields.has(field.name)) continue;\n      const baselineField = baselineDomain.fields?.[fieldName(field.name)];\n      if (baselineField && !baselineField.type.includes('Date') && hasFormatConversion(field.type)) {\n        if (hasDateTimeConversion(field.type)) continue;\n        skipFormatFields.add(field.name);\n      }\n    }\n  }\n  return skipFormatFields;\n}\n\nexport function shouldSkipSerializeForModel(\n  model: Model,\n  baselineResponse: BaselineInterface | undefined,\n  baselineDomain: BaselineInterface | undefined,\n  dedup: Map<string, string>,\n  skippedSerializeModels: Set<string>,\n  ctx: EmitterContext,\n): boolean {\n  let shouldSkip =\n    serializerHasBaselineIncompatibility(model, baselineResponse, baselineDomain, ctx) ||\n    hasUnsafeSerializePassthrough(model, baselineDomain, baselineResponse, ctx);\n  if (!shouldSkip) {\n    for (const field of model.fields) {\n      for (const ref of collectSerializedModelRefs(field.type)) {\n        if (skippedSerializeModels.has(ref)) {\n          shouldSkip = true;\n          break;\n        }\n        const canon = dedup.get(ref);\n        if (canon && skippedSerializeModels.has(canon)) {\n          shouldSkip = true;\n          break;\n        }\n        const resolved = resolveInterfaceName(ref, ctx);\n        if (wireInterfaceName(resolved) !== resolved && !helperExists(`serialize${resolved}`, ref, ctx)) {\n          shouldSkip = true;\n          break;\n        }\n      }\n      if (shouldSkip) break;\n    }\n  }\n  return shouldSkip;\n}\n\nexport function emitSerializerBody(\n  model: Model,\n  domainName: string,\n  responseName: string,\n  typeParams: { decl: string; usage: string },\n  baselineDomain: BaselineInterface | undefined,\n  baselineResponse: BaselineInterface | undefined,\n  skipFormatFields: Set<string>,\n  shouldSkipSerialize: boolean,\n  shouldSkipDeserialize: boolean,\n  ctx: EmitterContext,\n): string[] {\n  const lines: string[] = [];\n  const effectiveShouldSkipSerialize =\n    shouldSkipSerialize || hasUnsafeSerializePassthrough(model, baselineDomain, baselineResponse, ctx);\n\n  if (!shouldSkipDeserialize) {\n    const seenDeserFields = new Set<string>();\n    const deserParamPrefix = model.fields.length === 0 ? '_' : '';\n    lines.push(`export const deserialize${domainName} = ${typeParams.decl}(`);\n    lines.push(`  ${deserParamPrefix}response: ${responseName}${typeParams.usage},`);\n    lines.push(`): ${domainName}${typeParams.usage} => ({`);\n    for (const field of model.fields) {\n      const domain = fieldName(field.name);\n      if (seenDeserFields.has(domain)) continue;\n      seenDeserFields.add(domain);\n      const plan = planDeserializeField(field, baselineDomain, baselineResponse, skipFormatFields, ctx);\n      if (!plan.skip) lines.push(plan.line);\n    }\n    lines.push('});');\n  }\n\n  if (!effectiveShouldSkipSerialize) {\n    if (!shouldSkipDeserialize) lines.push('');\n    const serParamPrefix = model.fields.length === 0 ? '_' : '';\n    lines.push(`export const serialize${domainName} = ${typeParams.decl}(`);\n    lines.push(`  ${serParamPrefix}model: ${domainName}${typeParams.usage},`);\n    lines.push(`): ${responseName}${typeParams.usage} => ({`);\n    const seenSerFields = new Set<string>();\n    for (const field of model.fields) {\n      const wire = wireFieldName(field.name);\n      if (seenSerFields.has(wire)) continue;\n      seenSerFields.add(wire);\n      const plan = planSerializeField(field, baselineDomain, baselineResponse, skipFormatFields, ctx);\n      if (!plan.skip) lines.push(plan.line);\n    }\n    lines.push('});');\n  }\n\n  return lines;\n}\n\nfunction hasUnsafeSerializePassthrough(\n  model: Model,\n  baselineDomain: BaselineInterface | undefined,\n  baselineResponse: BaselineInterface | undefined,\n  ctx: EmitterContext,\n): boolean {\n  if (!baselineDomain?.fields || !baselineResponse?.fields) return false;\n\n  for (const field of model.fields) {\n    const domain = fieldName(field.name);\n    const wire = wireFieldName(field.name);\n    const domainField = baselineDomain.fields[domain];\n    const wireField = baselineResponse.fields[wire];\n    if (!domainField || !wireField || domainField.type === wireField.type) continue;\n\n    const domainAccess = `model.${domain}`;\n    if (serializeExpression(field.type, domainAccess, ctx) === domainAccess) {\n      return true;\n    }\n  }\n\n  return false;\n}\n","import type { SdkBehavior } from '@workos/oagen';\n\nconst NODE_EXCEPTION_KIND_OVERRIDES: Record<string, string> = {\n  Authentication: 'Unauthorized',\n};\n\nconst DEFAULT_STATUS_CODE_MAP: Record<string, string> = {\n  '400': 'BadRequest',\n  '401': 'Authentication',\n  '403': 'Authorization',\n  '404': 'NotFound',\n  '409': 'Conflict',\n  '422': 'UnprocessableEntity',\n  '429': 'RateLimitExceeded',\n};\n\nexport function buildNodeStatusExceptions(sdk?: SdkBehavior): Record<number, string> {\n  const statusCodeMap = sdk?.errors?.statusCodeMap ?? DEFAULT_STATUS_CODE_MAP;\n  return Object.fromEntries(\n    Object.entries(statusCodeMap).map(([code, kind]) => {\n      const nodeKind = NODE_EXCEPTION_KIND_OVERRIDES[kind] ?? kind;\n      return [Number(code), `${nodeKind}Exception`];\n    }),\n  );\n}\n","import type { EmitterContext, Field, ResolvedWrapper } from '@workos/oagen';\nimport { toSnakeCase } from '@workos/oagen';\nimport { enrichModelsFromSpec } from './model-utils.js';\n\n/**\n * A resolved wrapper parameter with its variant model field and optional status.\n * Pre-computed once per wrapper so emitters don't repeat the lookup.\n */\nexport interface ResolvedWrapperParam {\n  /** Wire name of the param (e.g., \"email\", \"grant_type\"). */\n  paramName: string;\n  /** The field from the variant model, or null if not found in the spec. */\n  field: Field | null;\n  /** Whether this param should be optional in the generated SDK. */\n  isOptional: boolean;\n}\n\n/**\n * Resolve the variant model's fields for a wrapper's exposed params.\n *\n * Encapsulates the three-step lookup every emitter needs:\n * 1. Find the variant model via wrapper.targetVariant in ctx.spec.models\n * 2. Match each exposed param to its field in the variant\n * 3. Classify as required or optional using wrapper.optionalParams + field.required\n *\n * Field matching uses exact name first, then falls back to snake_case normalization\n * to handle cases where wire names and model field names differ in casing.\n */\nexport function resolveWrapperParams(wrapper: ResolvedWrapper, ctx: EmitterContext): ResolvedWrapperParam[] {\n  let variantModel = ctx.spec.models.find((m) => m.name === wrapper.targetVariant);\n\n  // If the variant model has no fields, try enriching from the raw spec.\n  // Some oneOf variants have 0 IR fields until enrichModelsFromSpec backfills them.\n  if (!variantModel || variantModel.fields.length === 0) {\n    const enriched = enrichModelsFromSpec(ctx.spec.models);\n    variantModel = enriched.find((m) => m.name === wrapper.targetVariant) ?? variantModel;\n  }\n\n  const variantFields = variantModel?.fields ?? [];\n  const optionalSet = new Set(wrapper.optionalParams);\n\n  return wrapper.exposedParams.map((paramName) => {\n    const field =\n      variantFields.find((f) => f.name === paramName || toSnakeCase(f.name) === toSnakeCase(paramName)) ?? null;\n    // Default to required: a wrapper exists to make a specific call shape work,\n    // and exposedParams is the contract for that shape. Mark optional only when\n    // (a) the wrapper hint explicitly says so, or (b) the IR variant model\n    // resolves and reports the field as not required.\n    let isOptional: boolean;\n    if (optionalSet.has(paramName)) {\n      isOptional = true;\n    } else if (field) {\n      isOptional = !field.required;\n    } else {\n      isOptional = false;\n    }\n    return { paramName, field, isOptional };\n  });\n}\n\n/**\n * Format a snake_case wrapper name into a human-readable description.\n * \"authenticate_with_password\" → \"Authenticate with password\"\n */\nexport function formatWrapperDescription(name: string): string {\n  return name\n    .split('_')\n    .map((w, i) => (i === 0 ? w.charAt(0).toUpperCase() + w.slice(1) : w))\n    .join(' ');\n}\n","/**\n * Helpers for parsing OpenAPI path templates into structured segments that\n * each language emitter can render with proper per-segment URL encoding.\n *\n * SECURITY CONTEXT: every emitted path-parameter interpolation must wrap the\n * runtime value in a URL-encoding call (e.g. `rawurlencode` in PHP,\n * `encodeURIComponent` in TypeScript, `urllib.parse.quote(..., safe=\"\")` in\n * Python, a path-segment helper in Kotlin). Without per-segment encoding, a\n * caller-supplied id containing \"../\" is silently normalized by libcurl\n * (RFC 3986 dot-segment removal) before transmission, so the request reaches a\n * different endpoint of the WorkOS API while still authenticated with the\n * application's bearer token — i.e. forged cross-resource API requests under\n * the application's API key. See workos-php HttpClient hardening for the\n * defense-in-depth runtime guard; this module is the structural fix.\n */\n\nexport type PathSegment = { kind: 'literal'; value: string } | { kind: 'param'; name: string };\n\nexport interface ParsePathOptions {\n  /** When true, drop a single leading \"/\" before parsing. */\n  stripLeadingSlash?: boolean;\n}\n\n/**\n * Parse an OpenAPI path template into an ordered list of literal and\n * parameter segments. Adjacent literals are coalesced into a single segment\n * (the only way two literals can be adjacent is if the input had `{}{}`\n * which is malformed; we still handle it deterministically).\n *\n * Examples:\n *   \"/orgs/{id}/users/{uid}\" → [\n *     { kind: 'literal', value: '/orgs/' },\n *     { kind: 'param',   name:  'id' },\n *     { kind: 'literal', value: '/users/' },\n *     { kind: 'param',   name:  'uid' },\n *   ]\n *   \"/health\"               → [{ kind: 'literal', value: '/health' }]\n *   \"\"                      → []\n */\nexport function parsePathTemplate(path: string, options: ParsePathOptions = {}): PathSegment[] {\n  const normalized = options.stripLeadingSlash && path.startsWith('/') ? path.slice(1) : path;\n  if (normalized === '') return [];\n\n  const segments: PathSegment[] = [];\n  const re = /\\{([^{}]+)\\}/g;\n  let cursor = 0;\n  let m: RegExpExecArray | null;\n  while ((m = re.exec(normalized)) !== null) {\n    if (m.index > cursor) {\n      segments.push({ kind: 'literal', value: normalized.slice(cursor, m.index) });\n    }\n    segments.push({ kind: 'param', name: m[1] });\n    cursor = m.index + m[0].length;\n  }\n  if (cursor < normalized.length) {\n    segments.push({ kind: 'literal', value: normalized.slice(cursor) });\n  }\n  return segments;\n}\n\n/** True when at least one segment is a parameter placeholder. */\nexport function hasPathParams(segments: PathSegment[]): boolean {\n  return segments.some((s) => s.kind === 'param');\n}\n","import { parsePathTemplate, hasPathParams, type PathSegment } from '../shared/path-template.js';\nimport { fieldName } from './naming.js';\n\n/**\n * Build the TypeScript expression that the SDK passes as the request path.\n *\n * Every {paramName} placeholder becomes `${encodeURIComponent(name)}` inside a\n * template literal. encodeURIComponent is used (not encodeURI) because we want\n * \"/\" to be encoded too — otherwise a caller-supplied id containing \"../\" can\n * be normalized by the underlying HTTP transport (libcurl, fetch, etc.) into\n * a different endpoint of the WorkOS API while still authenticated with the\n * application's API key.\n *\n *   \"/orgs\"            → `'orgs'`\n *   \"/orgs/{id}\"       → `` `orgs/${encodeURIComponent(id)}` ``\n *   \"/orgs/{id}/foo\"   → `` `orgs/${encodeURIComponent(id)}/foo` ``\n *\n * `paramNameMap` lets a caller override the local variable name used for a\n * spec parameter — used by the options-object code path so the URL template\n * references the SDK's public field name (e.g. `organizationMembershipId`)\n * instead of the spec's path-param name (e.g. `omId`), avoiding a\n * destructure rename in the method body.\n */\nexport function buildNodePathExpression(rawPath: string, paramNameMap?: Map<string, string>): string {\n  const segments = parsePathTemplate(rawPath);\n  if (!hasPathParams(segments)) {\n    return `'${rawPath}'`;\n  }\n\n  let body = '';\n  for (const seg of segments) {\n    body += renderSegment(seg, paramNameMap);\n  }\n  return `\\`${body}\\``;\n}\n\nfunction renderSegment(seg: PathSegment, paramNameMap?: Map<string, string>): string {\n  if (seg.kind === 'literal') {\n    // Template-literal-safe escapes: backtick, backslash, ${\n    return seg.value.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`').replace(/\\$\\{/g, '\\\\${');\n  }\n  const localName = paramNameMap?.get(seg.name) ?? fieldName(seg.name);\n  return `\\${encodeURIComponent(${localName})}`;\n}\n","import type { EmitterContext, ResolvedOperation, ResolvedWrapper } from '@workos/oagen';\nimport { toCamelCase } from '@workos/oagen';\nimport { fieldName, resolveInterfaceName, wireInterfaceName } from './naming.js';\nimport { mapTypeRef } from './type-map.js';\nimport { resolveWrapperParams, formatWrapperDescription } from '../shared/wrapper-utils.js';\nimport { buildNodePathExpression } from './path-expression.js';\n\n/**\n * Generate TypeScript wrapper method lines for union split operations.\n */\nexport function generateWrapperMethods(resolvedOp: ResolvedOperation, ctx: EmitterContext): string[] {\n  if (!resolvedOp.wrappers || resolvedOp.wrappers.length === 0) return [];\n\n  const lines: string[] = [];\n\n  for (const wrapper of resolvedOp.wrappers) {\n    lines.push('');\n    emitWrapperMethod(lines, resolvedOp, wrapper, ctx);\n  }\n\n  return lines;\n}\n\n/**\n * Collect response model names referenced by wrappers on a resolved operation.\n */\nexport function collectWrapperResponseModels(resolvedOp: ResolvedOperation): Set<string> {\n  const models = new Set<string>();\n  for (const wrapper of resolvedOp.wrappers ?? []) {\n    if (wrapper.responseModelName) {\n      models.add(wrapper.responseModelName);\n    }\n  }\n  return models;\n}\n\nfunction emitWrapperMethod(\n  lines: string[],\n  resolvedOp: ResolvedOperation,\n  wrapper: ResolvedWrapper,\n  ctx: EmitterContext,\n): void {\n  const op = resolvedOp.operation;\n  const method = toCamelCase(wrapper.name);\n  const wrapperParams = resolveWrapperParams(wrapper, ctx);\n\n  const paramParts: string[] = [];\n\n  for (const p of op.pathParams) {\n    paramParts.push(`${fieldName(p.name)}: string`);\n  }\n\n  for (const { paramName, field, isOptional } of wrapperParams) {\n    if (isOptional) continue;\n    const tsName = fieldName(paramName);\n    const tsType = field ? mapTypeRef(field.type) : 'string';\n    paramParts.push(`${tsName}: ${tsType}`);\n  }\n\n  for (const { paramName, field, isOptional } of wrapperParams) {\n    if (!isOptional) continue;\n    const tsName = fieldName(paramName);\n    const tsType = field ? mapTypeRef(field.type) : 'string';\n    paramParts.push(`${tsName}?: ${tsType}`);\n  }\n\n  const responseTypeName = wrapper.responseModelName ? resolveInterfaceName(wrapper.responseModelName, ctx) : null;\n  const wireType = responseTypeName ? wireInterfaceName(responseTypeName) : null;\n  const returnType = responseTypeName ?? 'void';\n\n  // JSDoc\n  const docParts: string[] = [];\n  docParts.push(formatWrapperDescription(wrapper.name) + '.');\n\n  for (const p of op.pathParams) {\n    if (p.description) {\n      docParts.push(`@param ${fieldName(p.name)} - ${p.description}`);\n    }\n  }\n\n  for (const { paramName, field } of wrapperParams) {\n    const tsName = fieldName(paramName);\n    if (field?.description) {\n      docParts.push(`@param ${tsName} - ${field.description}`);\n    }\n  }\n\n  if (responseTypeName) {\n    docParts.push(`@returns {Promise<${returnType}>}`);\n  }\n\n  if (docParts.length === 1) {\n    lines.push(`  /** ${docParts[0]} */`);\n  } else {\n    lines.push('  /**');\n    for (const part of docParts) {\n      for (const line of part.split('\\n')) {\n        lines.push(line === '' ? '   *' : `   * ${line}`);\n      }\n    }\n    lines.push('   */');\n  }\n\n  lines.push(`  async ${method}(${paramParts.join(', ')}): Promise<${returnType}> {`);\n\n  lines.push('    const body: Record<string, unknown> = {');\n\n  for (const [key, value] of Object.entries(wrapper.defaults)) {\n    lines.push(`      ${key}: ${tsLiteral(value)},`);\n  }\n\n  for (const field of wrapper.inferFromClient) {\n    const expr = clientFieldExpression(field);\n    lines.push(`      ${field}: ${expr},`);\n  }\n\n  for (const { paramName, isOptional } of wrapperParams) {\n    if (isOptional) continue;\n    lines.push(`      ${paramName}: ${fieldName(paramName)},`);\n  }\n\n  lines.push('    };');\n\n  for (const { paramName, isOptional } of wrapperParams) {\n    if (!isOptional) continue;\n    const tsName = fieldName(paramName);\n    lines.push(`    if (${tsName} !== undefined) body.${paramName} = ${tsName};`);\n  }\n\n  const pathStr = buildPathStr(op);\n\n  if (responseTypeName) {\n    lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}>(${pathStr}, body);`);\n    lines.push(`    return deserialize${responseTypeName}(data);`);\n  } else {\n    lines.push(`    await this.workos.${op.httpMethod}(${pathStr}, body);`);\n  }\n\n  lines.push('  }');\n}\n\nfunction buildPathStr(op: { path: string; pathParams: Array<{ name: string }> }): string {\n  return buildNodePathExpression(op.path);\n}\n\nfunction tsLiteral(value: string | number | boolean): string {\n  if (typeof value === 'string') return `'${value.replace(/'/g, \"\\\\'\")}'`;\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  return String(value);\n}\n\nfunction clientFieldExpression(field: string): string {\n  switch (field) {\n    case 'client_id':\n      return 'this.workos.options.clientId';\n    case 'client_secret':\n      return 'this.workos.key';\n    default:\n      return `this.workos.${toCamelCase(field)}`;\n  }\n}\n","// @oagen-ignore: Operation.async — all TypeScript SDK methods are async by nature\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type {\n  Service,\n  Operation,\n  EmitterContext,\n  GeneratedFile,\n  TypeRef,\n  Model,\n  ResolvedOperation,\n} from '@workos/oagen';\nimport { toPascalCase, toCamelCase } from '@workos/oagen';\nimport type { OperationPlan } from '@workos/oagen';\nimport { mapTypeRef, isInlineEnum } from './type-map.js';\nimport {\n  liveSurfaceHasFunction,\n  liveSurfaceHasFile,\n  liveSurfaceHasAutogenFile,\n  liveSurfaceInterfacePath,\n} from './live-surface.js';\n\n/**\n * Render the request-body argument for an HTTP call.\n *\n * Three cases:\n *  1. `serialize${T}` is in the live SDK's serializer functions → call it.\n *  2. The serializer file exists on disk but does *not* export `serialize${T}`\n *     (e.g. workos-node's `validate-api-key.serializer.ts` ships only the\n *     response deserializer). The user owns the file; we cannot add to it,\n *     so pass `payload` straight through. `*Options` interfaces in\n *     workos-node are already wire-shaped (primitives or pre-snake_cased\n *     keys), so this preserves correctness for the workos-node convention.\n *  3. Otherwise the emitter is producing the serializer this run → call.\n */\nfunction bodyArgExpr(irModelName: string, resolvedName: string, ctx: EmitterContext, paramName = 'payload'): string {\n  const ser = `serialize${resolvedName}`;\n  if (liveSurfaceHasFunction(ser)) return `${ser}(${paramName})`;\n\n  const sourceFile = (ctx.apiSurface?.interfaces?.[resolvedName] as { sourceFile?: string } | undefined)?.sourceFile;\n  const candidate = sourceFile\n    ? sourceFile.replace('/interfaces/', '/serializers/').replace('.interface.ts', '.serializer.ts')\n    : `src/${defaultModelDir(irModelName, ctx)}/serializers/${fileName(irModelName)}.serializer.ts`;\n  if (liveSurfaceHasFile(candidate) && !liveSurfaceHasAutogenFile(candidate)) return paramName;\n\n  return `${ser}(${paramName})`;\n}\n\nfunction defaultModelDir(irModelName: string, ctx: EmitterContext): string {\n  const { modelToService, resolveDir } = createServiceDirResolver(ctx.spec.models, ctx.spec.services, ctx);\n  return resolveDir(modelToService.get(irModelName));\n}\nimport {\n  fieldName,\n  wireFieldName,\n  fileName,\n  resolveServiceDir,\n  resolveMethodName,\n  resolveInterfaceName,\n  resolveServiceName,\n  wireInterfaceName,\n  buildExportedClassNameSet,\n  resolveServiceTarget,\n} from './naming.js';\nimport {\n  docComment,\n  createServiceDirResolver,\n  isServiceCoveredByExisting,\n  hasMethodsAbsentFromBaseline,\n  uncoveredOperations,\n  relativeImport,\n} from './utils.js';\nimport { assignEnumsToServices } from './enums.js';\nimport { unwrapListModel } from './fixtures.js';\nimport { buildNodeStatusExceptions } from './sdk-errors.js';\nimport {\n  buildResolvedLookup,\n  lookupResolved,\n  groupByMount,\n  isMountInScope,\n  getOpDefaults,\n  getOpInferFromClient,\n} from '../shared/resolved-ops.js';\nimport { generateWrapperMethods, collectWrapperResponseModels } from './wrappers.js';\nimport { buildNodePathExpression } from './path-expression.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { isNodeOwnedService, operationOverrideFor, planOperationFor } from './options.js';\n\n/**\n * Check whether the baseline (hand-written) class has a constructor compatible\n * with the generated pattern `constructor(private readonly workos: WorkOS)`.\n * Returns true when no baseline exists (fresh generation) or when compatible.\n */\nexport function hasCompatibleConstructor(className: string, ctx: EmitterContext): boolean {\n  const baselineClass = ctx.apiSurface?.classes?.[className];\n  if (!baselineClass) return true; // No baseline — fresh generation\n  const params = baselineClass.constructorParams;\n  if (!params || params.length === 0) return true; // No-arg constructor is compatible\n  // Compatible if there is a single `workos` param whose type contains \"WorkOS\"\n  return params.some((p) => p.name === 'workos' && p.type.includes('WorkOS'));\n}\n\n/**\n * Resolve the resource class name for a service, accounting for constructor\n * compatibility with the baseline class.\n *\n * When the overlay-resolved class has an incompatible constructor (e.g., a\n * hand-written `Webhooks` class that takes `CryptoProvider` instead of `WorkOS`),\n * falls back to the IR name (`toPascalCase(service.name)`). If the IR name\n * collides with the overlay name, appends an `Endpoints` suffix.\n */\nexport function resolveResourceClassName(service: Service, ctx: EmitterContext): string {\n  const overlayName = resolveServiceName(service, ctx);\n  let base: string;\n  if (hasCompatibleConstructor(overlayName, ctx)) {\n    base = overlayName;\n  } else {\n    // Incompatible constructor — fall back to IR name, with `Endpoints` suffix\n    // if it would collide with the overlay name.\n    const irName = toPascalCase(service.name);\n    base = irName === overlayName ? `${irName}Endpoints` : irName;\n  }\n  // Cross-language `Service` suffix when the chosen class name would shadow\n  // an exported model/enum (e.g. tag `OrganizationMembership` + schema\n  // `OrganizationMembership`).\n  return resolveServiceTarget(base, buildExportedClassNameSet(ctx));\n}\n\nexport function resolveResourceDir(service: Service, ctx: EmitterContext): string {\n  const resolvedName = resolveResourceClassName(service, ctx);\n  if (resolvedName === 'WebhooksEndpoints') return 'webhooks';\n  // Drop the collision-`Service` suffix when picking the directory so the\n  // resource and its model-interfaces share a folder (e.g.\n  // `organization-membership/` houses both `OrganizationMembershipService`\n  // and `OrganizationMembership`'s interface files).\n  const overlayName = resolveServiceName(service, ctx);\n  const dirBase = resolvedName === `${overlayName}Service` ? overlayName : resolvedName;\n  return resolveServiceDir(dirBase);\n}\n\n/** Standard pagination query params handled by PaginationOptions — not imported individually. */\nconst PAGINATION_PARAM_NAMES = new Set(['limit', 'before', 'after', 'order']);\n\n/** Map HTTP status codes to their corresponding exception class names for @throws docs.\n *  Built from sdk.errors.statusCodeMap with Node-specific naming overrides. */\nconst STATUS_TO_EXCEPTION_NAME: Record<number, string> = buildNodeStatusExceptions();\n\n/**\n * Compute the options interface name for a paginated method.\n * When the method name is simply \"list\", prefix with the service name to avoid\n * naming collisions at barrel-export level (e.g. \"ConnectionsListOptions\"\n * instead of the generic \"ListOptions\").\n */\nfunction paginatedOptionsName(method: string, resolvedServiceName: string): string {\n  if (method === 'list') {\n    return `${toPascalCase(resolvedServiceName)}ListOptions`;\n  }\n  return toPascalCase(method) + 'Options';\n}\n\ntype BaselineMethod = {\n  params: Array<{ name: string; type: string; optional?: boolean; passingStyle?: string }>;\n  returnType?: string;\n};\n\ntype OptionsObjectParam = {\n  name: 'options';\n  type: string;\n  optional: boolean;\n  generated: boolean;\n};\n\ntype GeneratedOptionInterfaceExport = {\n  stem: string;\n  typeName: string;\n};\n\nfunction recordGeneratedOptionInterface(ctx: EmitterContext, serviceDir: string, stem: string, typeName: string): void {\n  const key = '_nodeGeneratedOptionInterfaceExports';\n  const registry = ((ctx as any)[key] ??= new Map<string, GeneratedOptionInterfaceExport[]>()) as Map<\n    string,\n    GeneratedOptionInterfaceExport[]\n  >;\n  const exports = registry.get(serviceDir) ?? [];\n  if (!exports.some((entry) => entry.stem === stem && entry.typeName === typeName)) {\n    exports.push({ stem, typeName });\n  }\n  registry.set(serviceDir, exports);\n}\n\nfunction existingInterfaceBarrelExports(ctx: EmitterContext, serviceDir: string, stem: string): boolean {\n  const root = ctx.outputDir ?? ctx.targetDir;\n  if (!root) return false;\n  const barrelPath = path.join(root, 'src', serviceDir, 'interfaces', 'index.ts');\n  let content: string;\n  try {\n    content = fs.readFileSync(barrelPath, 'utf8');\n  } catch {\n    return false;\n  }\n  const escapedStem = stem.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n  return new RegExp(`export\\\\s+(?:type\\\\s+)?(?:\\\\*|\\\\{[^}]+\\\\})\\\\s+from\\\\s+['\"]\\\\./${escapedStem}['\"]`).test(content);\n}\n\nfunction baselineMethodFor(service: Service, method: string, ctx: EmitterContext): BaselineMethod | undefined {\n  const serviceClass = resolveResourceClassName(service, ctx);\n  return ctx.apiSurface?.classes?.[serviceClass]?.methods?.[method]?.[0] as BaselineMethod | undefined;\n}\n\nexport function ignoredResourceMethodNames(ctx: EmitterContext, resourcePath: string): Set<string> {\n  const root = ctx.outputDir ?? ctx.targetDir;\n  if (!root) return new Set();\n\n  let content: string;\n  try {\n    content = fs.readFileSync(path.join(root, resourcePath), 'utf8');\n  } catch {\n    return new Set();\n  }\n\n  const methods = new Set<string>();\n  for (const block of content.matchAll(/@oagen-ignore-start[\\s\\S]*?@oagen-ignore-end/g)) {\n    for (const line of block[0].split('\\n')) {\n      // Match the method name followed by `(` or by `<` — the latter covers\n      // generic methods (`getProfile<T extends ...>(...)`), including\n      // multi-line type-parameter lists where the line ends right after `<`.\n      // Matching only up to the opening bracket sidesteps balancing nested\n      // angle brackets like `<T extends Record<string, unknown> = ...>`.\n      const match = line.match(/^\\s{2}(?:(?:public|private|protected)\\s+)?(?:async\\s+)?([A-Za-z_$][\\w$]*)\\s*[<(]/);\n      if (match) methods.add(match[1]);\n    }\n  }\n  return methods;\n}\n\nfunction optionsObjectParam(method: BaselineMethod | undefined): OptionsObjectParam | undefined {\n  if (!method || method.params.length !== 1) return undefined;\n  const [param] = method.params;\n  if (param.name !== 'options') return undefined;\n  if (param.passingStyle && param.passingStyle !== 'options_object') return undefined;\n  // An optional param's surface type is `Options | undefined`; the optionality\n  // is carried by `param.optional`, so strip the nullable arm to recover the\n  // bare type NAME (used for `serialize${type}` + imports). Leaving it in emits\n  // `serializeOptions | undefined` — a syntax error.\n  const type = param.type?.replace(/(?:\\s*\\|\\s*(?:undefined|null))+\\s*$/, '').trim();\n  if (!type || /^(Record|object|any|unknown)\\b/.test(type)) return undefined;\n  return { name: 'options', type, optional: param.optional === true, generated: false };\n}\n\nfunction methodOptionsName(method: string, resolvedServiceName: string): string {\n  if (method === 'list') return `${toPascalCase(resolvedServiceName)}ListOptions`;\n  return `${toPascalCase(method)}Options`;\n}\n\nfunction hiddenParamsFor(resolvedOp?: ResolvedOperation): Set<string> {\n  return new Set<string>([...Object.keys(getOpDefaults(resolvedOp)), ...getOpInferFromClient(resolvedOp)]);\n}\n\nfunction visibleQueryParamsForOptions(op: Operation, plan: OperationPlan, resolvedOp?: ResolvedOperation) {\n  const hidden = hiddenParamsFor(resolvedOp);\n  return op.queryParams.filter((param) => {\n    if (hidden.has(param.name)) return false;\n    if (plan.isPaginated && PAGINATION_PARAM_NAMES.has(param.name)) return false;\n    return true;\n  });\n}\n\nfunction optionsObjectShouldBeOptional(op: Operation, plan: OperationPlan, resolvedOp?: ResolvedOperation): boolean {\n  if (plan.hasBody) return false;\n  if (op.pathParams.length > 0) return false;\n  return visibleQueryParamsForOptions(op, plan, resolvedOp).every((param) => !param.required);\n}\n\nfunction operationHasOptionsInput(op: Operation, plan: OperationPlan, resolvedOp?: ResolvedOperation): boolean {\n  return (\n    op.pathParams.length > 0 ||\n    plan.hasBody ||\n    plan.isPaginated ||\n    visibleQueryParamsForOptions(op, plan, resolvedOp).length > 0\n  );\n}\n\n// True only when the type is a SINGLE closed object literal (`{ ... }`), not\n// the head of a compound type such as `{ ... } & X` or `{ ... } | Y`. Counting\n// brace depth locates the literal's matching close brace (handling nesting like\n// `{ a: { b: string } }`); any non-whitespace after it means the type is not a\n// pure literal and must be preserved verbatim rather than replaced by a named\n// request interface.\nfunction isClosedObjectLiteral(type: string): boolean {\n  const t = type.trim();\n  if (!t.startsWith('{')) return false;\n  let depth = 0;\n  for (let i = 0; i < t.length; i++) {\n    const ch = t[i];\n    if (ch === '{') depth++;\n    else if (ch === '}' && --depth === 0) return i === t.length - 1;\n  }\n  return false;\n}\n\nfunction optionsObjectInfo(\n  service: Service,\n  method: string,\n  op: Operation,\n  plan: OperationPlan,\n  ctx: EmitterContext,\n  baselineMethod: BaselineMethod | undefined,\n  resolvedOp?: ResolvedOperation,\n): OptionsObjectParam | undefined {\n  const baseline = optionsObjectParam(baselineMethod);\n  if (baseline) {\n    // A baseline param whose type is a pure inline object literal\n    // (e.g. `{ intent?: GenerateLinkIntent; organization: string; ... }`)\n    // cannot be referenced as a named import and routinely diverges from the\n    // spec-derived request interface that the generated serializer expects —\n    // field renames (`adminEmails` -> `itContactEmails`), widened enums\n    // (`string` vs `'GoogleSAML'`), differing optionality — which makes the\n    // generated `serialize${Model}(payload)` call fail to typecheck. When the\n    // operation owns a named request-body model, adopt that interface so the\n    // method signature, the serializer, and the request model all agree.\n    // Named baseline types (`CreateOrganizationApiKeyOptions`) and compound\n    // intersections (`X & { ... }` or `{ ... } & X`) are still preserved\n    // verbatim — only a single, closed object literal is eligible for adoption.\n    if (\n      isClosedObjectLiteral(baseline.type) &&\n      isNodeOwnedService(ctx, service.name, resolveResourceClassName(service, ctx))\n    ) {\n      const body = extractRequestBodyType(op, ctx);\n      if (body?.kind === 'model') {\n        return {\n          name: 'options',\n          type: resolveInterfaceName(body.name, ctx),\n          optional: optionsObjectShouldBeOptional(op, plan, resolvedOp),\n          generated: false,\n        };\n      }\n    }\n    return baseline;\n  }\n\n  const overrideType = operationOverrideFor(ctx, op)?.optionsType;\n  if (overrideType) {\n    return {\n      name: 'options',\n      type: overrideType,\n      optional: optionsObjectShouldBeOptional(op, plan, resolvedOp),\n      generated: baselineTypeSourceFile(ctx, overrideType) === undefined,\n    };\n  }\n\n  if (!operationHasOptionsInput(op, plan, resolvedOp)) return undefined;\n\n  const resolvedService = resolveResourceClassName(service, ctx);\n  let optionsType = methodOptionsName(method, resolvedService);\n  // A bare `${Method}Options` name (e.g. `GetGroupOptions`) can collide with a\n  // same-named baseline type owned by a DIFFERENT service (for example the\n  // Groups module's `GetGroupOptions`, shaped `{ organizationId, groupId }`).\n  // Reusing it by name would import a foreign shape. When the existing\n  // declaration lives in another service directory, qualify the name with the\n  // service (mirroring the `list` -> `${Service}ListOptions` rule) so this\n  // service generates and imports its own options type.\n  if (method !== 'list') {\n    const baselineFile = baselineTypeSourceFile(ctx, optionsType);\n    const baselineDir = baselineFile?.match(/^src\\/([^/]+)\\//)?.[1];\n    if (baselineDir && baselineDir !== resolveResourceDir(service, ctx)) {\n      optionsType = `${toPascalCase(resolvedService)}${toPascalCase(method)}Options`;\n    }\n  }\n\n  return {\n    name: 'options',\n    type: optionsType,\n    optional: optionsObjectShouldBeOptional(op, plan, resolvedOp),\n    generated: true,\n  };\n}\n\nfunction renderOptionsParam(param: OptionsObjectParam): string {\n  return `options${param.optional ? '?' : ''}: ${param.type}`;\n}\n\n/**\n * Whether a baseline-derived type reference is a plain TypeScript identifier\n * that can appear in a named import. Baseline (live-SDK) method params can\n * carry inline object-literal TYPES (e.g. `{ intent: GenerateLinkIntent; ... }`);\n * treating that literal text as a type NAME would slugify it into a filename\n * and emit a named import of a brace-expression — both invalid. Literal types\n * are kept inline in the emitted signature instead and never imported.\n */\nfunction isValidTypeIdentifier(name: string): boolean {\n  return /^[A-Za-z_$][\\w$]*$/.test(name);\n}\n\n/**\n * Extract candidate named type references from a compound type expression such\n * as `GetAccessTokenOptions & { provider: string }`. PascalCase tokens are type\n * names worth importing; lowercase tokens are property keys or primitives and\n * are skipped. The caller only imports the ones that resolve to a known source\n * file, so unrecognized PascalCase tokens (e.g. `Date`, `Record`) are harmless.\n */\nfunction extractNamedTypeRefs(typeExpr: string): string[] {\n  const matches = typeExpr.match(/\\b[A-Z][A-Za-z0-9_$]*\\b/g) ?? [];\n  return [...new Set(matches)];\n}\n\nfunction autoPaginatableItemType(returnType: string | undefined): string | undefined {\n  // Match both AutoPaginatable<T> and the legacy List<T> pattern so baseline\n  // item types are extracted even when the hand-written code predates AutoPaginatable.\n  return returnType?.match(/\\b(?:AutoPaginatable|List)<\\s*([A-Za-z_$][\\w$]*)/)?.[1];\n}\n\nfunction baselineTypeSourceFile(ctx: EmitterContext, typeName: string): string | undefined {\n  const surface = ctx.apiSurface as\n    | {\n        interfaces?: Record<string, { sourceFile?: string }>;\n        typeAliases?: Record<string, { sourceFile?: string }>;\n        enums?: Record<string, { sourceFile?: string }>;\n      }\n    | undefined;\n  return (\n    surface?.interfaces?.[typeName]?.sourceFile ??\n    surface?.typeAliases?.[typeName]?.sourceFile ??\n    surface?.enums?.[typeName]?.sourceFile\n  );\n}\n\nfunction preferredBaselineTypeName(ctx: EmitterContext, typeName: string | undefined): string | undefined {\n  if (!typeName) return undefined;\n  const surface = ctx.apiSurface as\n    | {\n        typeAliases?: Record<string, { value?: string; sourceFile?: string }>;\n        interfaces?: Record<string, { sourceFile?: string }>;\n      }\n    | undefined;\n  const sourceFile = baselineTypeSourceFile(ctx, typeName);\n  for (const [alias, info] of Object.entries(surface?.typeAliases ?? {})) {\n    if (info.value !== typeName) continue;\n    if (sourceFile && info.sourceFile !== sourceFile) continue;\n    if (liveSurfaceHasFunction(`deserialize${alias}`)) return alias;\n  }\n  return typeName;\n}\n\nfunction preferredBaselineReturnType(ctx: EmitterContext, returnType: string | undefined): string | undefined {\n  if (!returnType) return undefined;\n  // Only preserve baseline return types that already use AutoPaginatable.\n  // Legacy patterns like List<T> can't be used as-is since the generated\n  // method body returns new AutoPaginatable(...).\n  if (!/\\bAutoPaginatable\\b/.test(returnType)) return undefined;\n  const itemType = autoPaginatableItemType(returnType);\n  if (!itemType) return undefined;\n  const preferred = preferredBaselineTypeName(ctx, itemType);\n  if (!preferred || preferred === itemType) return returnType;\n  return returnType.replace(new RegExp(`\\\\b${itemType}\\\\b`, 'g'), preferred);\n}\n\nfunction requestEntityType(bodyExpr: string, requestType: string): string {\n  return bodyExpr === 'payload' ? requestType : wireInterfaceName(requestType);\n}\n\nfunction unionEntityType(modelNames: string[], ctx: EmitterContext): string {\n  return modelNames.map((name) => wireInterfaceName(resolveInterfaceName(name, ctx))).join(' | ');\n}\n\n/** HTTP methods that require a body argument even when the spec has no request body. */\nfunction httpMethodNeedsBody(method: string): boolean {\n  return method === 'post' || method === 'put' || method === 'patch';\n}\n\n// ---------------------------------------------------------------------------\n// Method-name deduplication helpers\n// ---------------------------------------------------------------------------\n\n/** Split a camelCase/PascalCase name into lowercase word parts. */\nfunction splitCamelWords(name: string): string[] {\n  const parts: string[] = [];\n  let start = 0;\n  for (let i = 1; i < name.length; i++) {\n    if (name[i] >= 'A' && name[i] <= 'Z') {\n      parts.push(name.slice(start, i).toLowerCase());\n      start = i;\n    }\n  }\n  parts.push(name.slice(start).toLowerCase());\n  return parts;\n}\n\n/** Naive singularize: strip trailing 's' unless it ends in 'ss'. */\nfunction singularize(word: string): string {\n  return word.endsWith('s') && !word.endsWith('ss') ? word.slice(0, -1) : word;\n}\n\n/**\n * Deduplicate method names within the plans array.\n *\n * When `disambiguateOperationNames()` in `@workos/oagen` fails (e.g., for\n * single-segment paths like `/organizations`), two operations can resolve to\n * the same method name. Disambiguate by appending a path-derived suffix.\n */\nfunction deduplicateMethodNames(\n  plans: Array<{ op: Operation; plan: OperationPlan; method: string }>,\n  _ctx: EmitterContext,\n): void {\n  const nameCount = new Map<string, number>();\n  for (const p of plans) {\n    nameCount.set(p.method, (nameCount.get(p.method) ?? 0) + 1);\n  }\n\n  for (const [name, count] of nameCount) {\n    if (count <= 1) continue;\n    const dupes = plans.filter((p) => p.method === name);\n\n    // If all duplicates are on the SAME base path (different HTTP methods),\n    // trust the names — they represent the same resource.\n    const basePaths = new Set(dupes.map((d) => d.op.path.replace(/\\/\\{[^}]+\\}$/, '')));\n    if (basePaths.size <= 1) continue;\n\n    // Disambiguate: keep the name for the plan whose path best matches,\n    // append path suffix for the others.\n    // Score: how many words in the method name appear in the path segments\n    const nameWords = new Set(splitCamelWords(name).map(singularize));\n    const scored = dupes.map((d) => {\n      const pathWords = d.op.path\n        .split('/')\n        .filter((s) => s && !s.startsWith('{'))\n        .flatMap((s) => s.split('_'))\n        .map(singularize);\n      const overlap = pathWords.filter((w) => nameWords.has(w)).length;\n      return { plan: d, score: overlap };\n    });\n    scored.sort((a, b) => b.score - a.score);\n\n    // The best-scoring plan keeps the name; others get disambiguated\n    for (let i = 1; i < scored.length; i++) {\n      const dupe = scored[i].plan;\n      const segments = dupe.op.path.split('/').filter((s) => s && !s.startsWith('{'));\n      // Use first segment as suffix (the resource collection name)\n      const suffix = segments[0] ?? '';\n      if (suffix) {\n        dupe.method = toCamelCase(`${name}_${suffix}`);\n      }\n    }\n\n    // If still colliding after suffix, append index\n    const stillDuped = new Map<string, typeof dupes>();\n    for (const dupe of dupes) {\n      const group = stillDuped.get(dupe.method) ?? [];\n      group.push(dupe);\n      stillDuped.set(dupe.method, group);\n    }\n    for (const [, group] of stillDuped) {\n      if (group.length <= 1) continue;\n      for (let i = 1; i < group.length; i++) {\n        group[i].method = `${group[i].method}${i + 1}`;\n      }\n    }\n  }\n}\n\n/**\n * Emit one interface/type file per generated options-object operation.\n * Placing the options type under `interfaces/` lets the per-service barrel\n * pick it up via `export * from './interfaces'`.\n */\nfunction generateOptionsInterfaces(service: Service, ctx: EmitterContext, specEnumNames: Set<string>): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const serviceDir = resolveResourceDir(service, ctx);\n  const resolvedLookup = buildResolvedLookup(ctx);\n\n  const plans = service.operations.map((op) => ({\n    op,\n    plan: planOperationFor(op, ctx),\n    method: resolveMethodName(op, service, ctx),\n  }));\n\n  for (const { op, plan, method } of plans) {\n    const resolvedOp = lookupResolved(op, resolvedLookup);\n    const baselineMethod = baselineMethodFor(service, method, ctx);\n    const optionInfo = optionsObjectInfo(service, method, op, plan, ctx, baselineMethod, resolvedOp);\n    if (!optionInfo?.generated) continue;\n    // A baseline type of the same name normally means \"hand-owned / preserved —\n    // do not regenerate\" (guards the alias-feedback loop). But when the op has\n    // path params, the modernized resource folds them INTO the options object\n    // (`const { organizationId, ...payload } = options`), so a body-only\n    // baseline interface (from a legacy `(pathParam, options)` signature) is\n    // definitionally incompatible. Regenerate it to include the path params.\n    if (op.pathParams.length === 0 && baselineTypeSourceFile(ctx, optionInfo.type)) continue;\n\n    const optionsName = optionInfo.type;\n    const optionFileStem = `${fileName(optionsName)}.interface`;\n    const filePath = `src/${serviceDir}/interfaces/${optionFileStem}.ts`;\n    if (!liveSurfaceHasFile(filePath) || existingInterfaceBarrelExports(ctx, serviceDir, optionFileStem)) {\n      recordGeneratedOptionInterface(ctx, serviceDir, optionFileStem, optionsName);\n    }\n\n    const optEnums = new Set<string>();\n    const optModels = new Set<string>();\n    for (const param of [...op.pathParams, ...visibleQueryParamsForOptions(op, plan, resolvedOp)]) {\n      collectParamTypeRefs(param.type, optEnums, optModels);\n    }\n    const bodyInfo = extractRequestBodyType(op, ctx);\n    if (bodyInfo?.kind === 'model') {\n      const bodyModel = ctx.spec.models.find((m) => m.name === bodyInfo.name);\n      if (bodyModel) {\n        for (const field of bodyModel.fields) {\n          collectParamTypeRefs(field.type, optEnums, optModels);\n        }\n      }\n    } else if (bodyInfo?.kind === 'union') {\n      for (const name of bodyInfo.modelNames) {\n        optModels.add(name);\n      }\n    }\n\n    const lines: string[] = [];\n    if (plan.isPaginated) {\n      lines.push(\"import type { PaginationOptions } from '../../common/interfaces/pagination-options.interface';\");\n    }\n    const { modelToService, resolveDir } = createServiceDirResolver(ctx.spec.models, ctx.spec.services, ctx);\n    if (optEnums.size > 0) {\n      const enumToService = assignEnumsToServices(ctx.spec.enums, ctx.spec.services, ctx.spec.models, ctx);\n      for (const name of optEnums) {\n        if (!specEnumNames.has(name)) continue;\n        if (isInlineEnum(name)) continue;\n        const enumDir = resolveDir(enumToService.get(name));\n        const relPath =\n          enumDir === serviceDir\n            ? `./${fileName(name)}.interface`\n            : `../../${enumDir}/interfaces/${fileName(name)}.interface`;\n        lines.push(`import type { ${name} } from '${relPath}';`);\n      }\n    }\n    for (const name of optModels) {\n      const modelDir = resolveDir(modelToService.get(name));\n      const relPath =\n        modelDir === serviceDir\n          ? `./${fileName(name)}.interface`\n          : `../../${modelDir}/interfaces/${fileName(name)}.interface`;\n      lines.push(`import type { ${resolveInterfaceName(name, ctx)} } from '${relPath}';`);\n    }\n    lines.push('');\n\n    const headerParts: string[] = [];\n    const pushField = (name: string, required: boolean, type: string, description?: string, deprecated?: boolean) => {\n      const opt = !required ? '?' : '';\n      if (description || deprecated) {\n        const parts: string[] = [];\n        if (description) parts.push(description);\n        if (deprecated) parts.push('@deprecated');\n        headerParts.push(...docComment(parts.join('\\n'), 2));\n      }\n      headerParts.push(`  ${name}${opt}: ${type};`);\n    };\n\n    const optionsPathFieldMap = operationOverrideFor(ctx, op)?.pathFieldMap;\n    for (const param of op.pathParams) {\n      pushField(\n        optionsPathFieldMap?.[fieldName(param.name)] ?? fieldName(param.name),\n        true,\n        mapParamType(param.type, specEnumNames),\n        param.description,\n        param.deprecated,\n      );\n    }\n    for (const param of visibleQueryParamsForOptions(op, plan, resolvedOp)) {\n      pushField(\n        fieldName(param.name),\n        param.required,\n        mapParamType(param.type, specEnumNames),\n        param.description,\n        param.deprecated,\n      );\n    }\n\n    if (bodyInfo?.kind === 'model') {\n      const bodyModel = ctx.spec.models.find((m) => m.name === bodyInfo.name);\n      if (bodyModel) {\n        for (const field of bodyModel.fields) {\n          pushField(\n            fieldName(field.name),\n            field.required,\n            mapParamType(field.type, specEnumNames),\n            field.description,\n            field.deprecated,\n          );\n        }\n      }\n      lines.push(`export interface ${optionsName}${plan.isPaginated ? ' extends PaginationOptions' : ''} {`);\n      lines.push(...headerParts);\n      lines.push('}');\n    } else if (bodyInfo?.kind === 'union') {\n      const baseType = headerParts.length > 0 ? `{\\n${headerParts.join('\\n')}\\n}` : '{}';\n      lines.push(`export type ${optionsName} = ${baseType} & (${bodyInfo.typeStr});`);\n    } else {\n      if (plan.isPaginated && headerParts.length === 0) {\n        lines.push(`export type ${optionsName} = PaginationOptions;`);\n      } else {\n        lines.push(`export interface ${optionsName}${plan.isPaginated ? ' extends PaginationOptions' : ''} {`);\n        lines.push(...headerParts);\n        lines.push('}');\n      }\n    }\n\n    files.push({\n      path: filePath,\n      content: lines.join('\\n'),\n    });\n  }\n\n  return files;\n}\n\nexport function generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n  if (services.length === 0) return [];\n  const files: GeneratedFile[] = [];\n\n  // Group services by mount target to avoid file path collisions when\n  // multiple IR services mount to the same resource class.\n  const mountGroups = groupByMount(ctx);\n  const mergedServices: Service[] =\n    mountGroups.size > 0 || ctx.scopedServices?.size\n      ? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations }))\n      : services;\n\n  const topLevelEnumNames = new Set(ctx.spec.enums.map((e) => e.name));\n\n  for (const service of mergedServices) {\n    // Scope gate: in a scoped (`--services`) run, only emit per-service resource\n    // files for the selected post-mount names. `service.name` is the mount-group\n    // key (the POST-MOUNT name that matches `ctx.scopedServices`). Applied as an\n    // additional early continue ahead of the node-owned/coverage skip logic.\n    if (!isMountInScope(service.name, ctx)) continue;\n    const isOwnedService = isNodeOwnedService(ctx, service.name, resolveResourceClassName(service, ctx));\n    if (!isOwnedService && isServiceCoveredByExisting(service, ctx)) {\n      if (!hasMethodsAbsentFromBaseline(service, ctx)) {\n        continue; // Fully covered, no new methods -- skip entirely\n      }\n      // Partially covered -- has new methods that need to be added.\n      const file = generateResourceClass(service, ctx);\n      if (!file) continue;\n      delete file.skipIfExists;\n      // Suppress auto-generated header — the file is a merge target\n      // containing hand-written code, not a fully generated file.\n      file.headerPlacement = 'skip';\n      files.push(file);\n      continue;\n    }\n\n    const ops = isOwnedService ? service.operations : uncoveredOperations(service, ctx);\n    if (ops.length === 0) continue;\n\n    if (ops.length < service.operations.length) {\n      // Partial coverage: generate with ALL operations so JSDoc is available\n      // for both covered and uncovered methods.  Remove skipIfExists so the\n      // merger adds new methods AND refreshes existing JSDoc.\n      const file = generateResourceClass(service, ctx);\n      if (!file) continue;\n      delete file.skipIfExists;\n      // Suppress auto-generated header — the file is a merge target\n      // containing hand-written code, not a fully generated file.\n      file.headerPlacement = 'skip';\n      files.push(file);\n    } else {\n      // Purely oagen-managed: no baseline class exists, so the file is owned\n      // end-to-end by the emitter.  Remove skipIfExists so regeneration always\n      // overwrites — emitter improvements (serializer dispatch, JSDoc, etc.)\n      // must propagate without manual intervention.\n      const file = generateResourceClass(service, ctx);\n      if (!file) continue;\n      delete file.skipIfExists;\n      files.push(file);\n    }\n  }\n\n  // Emit paginated list options interfaces AFTER the resource classes so\n  // tests and manifest ordering that index `files[0]` as the class stay\n  // stable.  Placing them under `interfaces/` lets the per-service barrel\n  // pick them up automatically.\n  for (const service of mergedServices) {\n    // Scope gate: keep the per-service options interfaces aligned with the\n    // resource files emitted above — only the selected post-mount names.\n    if (!isMountInScope(service.name, ctx)) continue;\n    const isOwnedService = isNodeOwnedService(ctx, service.name, resolveResourceClassName(service, ctx));\n    if (!isOwnedService && isServiceCoveredByExisting(service, ctx) && !hasMethodsAbsentFromBaseline(service, ctx))\n      continue;\n    files.push(...generateOptionsInterfaces(service, ctx, topLevelEnumNames));\n  }\n\n  return files;\n}\n\nfunction generateResourceClass(service: Service, ctx: EmitterContext): GeneratedFile | null {\n  const resolvedName = resolveResourceClassName(service, ctx);\n  const serviceDir = resolveResourceDir(service, ctx);\n  const serviceClass = resolvedName;\n  const resourcePath = `src/${serviceDir}/${fileName(resolvedName)}.ts`;\n\n  let plans = service.operations.map((op) => ({\n    op,\n    plan: planOperationFor(op, ctx),\n    method: resolveMethodName(op, service, ctx),\n  }));\n\n  // Resolved operations already produce correct method names via the\n  // centralized hint map — no per-emitter reconciliation needed.\n\n  // Deduplicate method names within the class (e.g., two operations both\n  // resolving to \"create\" for different paths).\n  deduplicateMethodNames(plans, ctx);\n\n  // Sort plans to match the existing file's method order.\n  // When the merger integrates generated content with existing files, its\n  // URL-fingerprint fallback (pass 2) matches by position among methods that\n  // share the same endpoint path.  If the spec lists POST before GET for a\n  // path (common in OpenAPI) but the existing class has them in a different\n  // order, JSDoc comments get attached to the wrong methods (list↔create,\n  // add↔set swaps).  Sorting by the overlay's method order ensures the\n  // generated output matches the existing file's method order.\n  //\n  // We build the order from HTTP operation keys (e.g., \"GET /organizations\")\n  // rather than method names, because resolveMethodName may return a different\n  // name than the overlay's methodName (e.g., when the hint map overrides it),\n  // causing the lookup to fail and the sort to produce wrong order.\n  if (ctx.overlayLookup?.methodByOperation) {\n    const httpKeyOrder = new Map<string, number>();\n    let pos = 0;\n    for (const [httpKey] of ctx.overlayLookup.methodByOperation) {\n      httpKeyOrder.set(httpKey, pos++);\n    }\n    if (httpKeyOrder.size > 0) {\n      plans.sort((a, b) => {\n        const aKey = `${a.op.httpMethod.toUpperCase()} ${a.op.path}`;\n        const bKey = `${b.op.httpMethod.toUpperCase()} ${b.op.path}`;\n        const aPos = httpKeyOrder.get(aKey) ?? Number.MAX_SAFE_INTEGER;\n        const bPos = httpKeyOrder.get(bKey) ?? Number.MAX_SAFE_INTEGER;\n        return aPos - bPos;\n      });\n    }\n  }\n\n  // Filter out operations whose method name already exists in the baseline\n  // class. The user's `@oagen-ignore-start`/`@oagen-ignore-end` blocks in\n  // the existing file preserve those method bodies; emitting them again\n  // would duplicate the symbol after the engine appends the preserved block\n  // (engine writeFiles → overwriteWithPreservedRegions appends, doesn't\n  // replace, when the block is method-level not class-level).\n  //\n  // Direct check against `apiSurface.classes[serviceClass].methods` rather\n  // than `uncoveredOperations`, which routes through `overlayLookup` that\n  // isn't always populated.\n  //\n  // Done after dedup + sort so the rendered methods keep their stable names.\n  // Imports below filter through `plans`, so they automatically narrow to\n  // the kept operations only — no orphan imports.\n  const ignoredMethodNames = ignoredResourceMethodNames(ctx, resourcePath);\n  const baselineMethodNames = new Set(Object.keys(ctx.apiSurface?.classes?.[serviceClass]?.methods ?? {}));\n  const planCountBeforeFilter = plans.length;\n  if (ignoredMethodNames.size > 0) {\n    plans = plans.filter((p) => !ignoredMethodNames.has(p.method));\n  }\n  if (!isNodeOwnedService(ctx, service.name, serviceClass) && baselineMethodNames.size > 0) {\n    plans = plans.filter((p) => !baselineMethodNames.has(p.method));\n  }\n  const filteredOut = planCountBeforeFilter - plans.length;\n\n  // Skip emitting the file altogether when every operation already exists in\n  // baseline AND the existing class is preserved via `@oagen-ignore-start`\n  // blocks. The autogen-overwrite path would otherwise write an empty class\n  // shell that the engine's region preservation would have to reconstruct.\n  if (plans.length === 0 && filteredOut > 0) {\n    return null;\n  }\n\n  const hasPaginated = plans.some((p) => p.plan.isPaginated);\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const needsPaginationOptionsImport = plans.some((p) => {\n    const baseline = baselineMethodFor(service, p.method, ctx);\n    const optionInfo = optionsObjectInfo(\n      service,\n      p.method,\n      p.op,\n      p.plan,\n      ctx,\n      baseline,\n      lookupResolved(p.op, resolvedLookup),\n    );\n    const extraParams = p.op.queryParams.filter((param) => !PAGINATION_PARAM_NAMES.has(param.name));\n    const needsWireSerializer = extraParams.some((param) => fieldName(param.name) !== wireFieldName(param.name));\n    return (\n      p.plan.isPaginated &&\n      (needsWireSerializer ||\n        !optionInfo ||\n        /\\bPaginationOptions\\b/.test(\n          preferredBaselineReturnType(ctx, baselineMethodFor(service, p.method, ctx)?.returnType) ?? '',\n        ))\n    );\n  });\n  const modelMap = new Map(ctx.spec.models.map((m) => [m.name, m]));\n\n  // Collect models for imports — only include models that are actually used\n  // in method signatures (not all union variants from the spec)\n  const responseModels = new Set<string>();\n  const responseModelsForSignature = new Set<string>();\n  const requestModels = new Set<string>();\n  const requestModelsForSignature = new Set<string>();\n  const paramEnums = new Set<string>();\n  const paramModels = new Set<string>();\n  const optionObjectTypes = new Set<string>();\n  const returnTypeImports = new Set<string>();\n  const baselineResponseTypes = new Set<string>();\n  for (const { op, plan, method } of plans) {\n    const baselineMethod = baselineMethodFor(service, method, ctx);\n    const existingOptions = optionsObjectInfo(\n      service,\n      method,\n      op,\n      plan,\n      ctx,\n      baselineMethod,\n      lookupResolved(op, resolvedLookup),\n    );\n    if (existingOptions) optionObjectTypes.add(existingOptions.type);\n    for (const typeName of operationOverrideFor(ctx, op)?.returnTypeImports ?? []) {\n      returnTypeImports.add(typeName);\n    }\n\n    // Collect param type refs only when params appear directly in this\n    // resource method. Options-object methods import a single options type;\n    // that generated interface owns its own enum/model imports.\n    if (!existingOptions) {\n      const queryParams = plan.isPaginated ? [] : op.queryParams;\n      for (const param of [...queryParams, ...op.pathParams]) {\n        collectParamTypeRefs(param.type, paramEnums, paramModels);\n      }\n    }\n\n    // Always collect imports for every rendered method.  Earlier versions\n    // skipped baseline methods on the assumption the AST merger would keep\n    // their existing imports — but the autogen-aware writer in\n    // `node/index.ts` overwrites previously-generated files in full so spec\n    // renames propagate. With overwrite, missing imports become real\n    // compile errors. Redundant imports are harmless (eslint --fix prunes\n    // them post-generation via `formatCommand`).\n\n    const baselinePaginatedItemType = existingOptions\n      ? preferredBaselineTypeName(ctx, autoPaginatableItemType(baselineMethod?.returnType))\n      : undefined;\n    if (plan.isPaginated && baselinePaginatedItemType) {\n      baselineResponseTypes.add(baselinePaginatedItemType);\n    } else if (plan.isPaginated && op.pagination?.itemType.kind === 'model') {\n      // For paginated operations, import the item type (e.g., Connection)\n      // rather than the list wrapper type (e.g., ConnectionList).\n      // fetchAndDeserialize handles the list envelope internally.\n      // The IR's itemType may point to a list wrapper model — unwrap to the actual item.\n      let itemName = op.pagination.itemType.name;\n      const itemModel = modelMap.get(itemName);\n      if (itemModel) {\n        const unwrapped = unwrapListModel(itemModel, modelMap);\n        if (unwrapped) {\n          itemName = unwrapped.name;\n        }\n      }\n      responseModels.add(itemName);\n      responseModelsForSignature.add(itemName);\n    } else if (plan.responseModelName) {\n      responseModels.add(plan.responseModelName);\n      const override = operationOverrideFor(ctx, op);\n      const resolvedResponseName = resolveInterfaceName(plan.responseModelName, ctx);\n      if (!override?.returnType || override.returnType.includes(resolvedResponseName)) {\n        responseModelsForSignature.add(plan.responseModelName);\n      }\n    }\n    // Import request body model(s) — handles both single models and union variants.\n    const bodyInfo = extractRequestBodyType(op, ctx);\n    if (bodyInfo?.kind === 'model') {\n      requestModels.add(bodyInfo.name);\n      if (!existingOptions) requestModelsForSignature.add(bodyInfo.name);\n    } else if (bodyInfo?.kind === 'union') {\n      if (bodyInfo.discriminator) {\n        // Discriminated union: import variant models with serializers so we can\n        // dispatch to the correct serializer at runtime based on the discriminator.\n        for (const name of bodyInfo.modelNames) {\n          requestModels.add(name);\n          if (!existingOptions) requestModelsForSignature.add(name);\n        }\n      } else {\n        // Non-discriminated union: import variant models with serializers so we\n        // can dispatch to the correct serializer at runtime via field guards.\n        for (const name of bodyInfo.modelNames) {\n          requestModels.add(name);\n          if (!existingOptions) requestModelsForSignature.add(name);\n        }\n      }\n    }\n  }\n\n  // Collect response models from union split wrappers so their types and\n  // deserializers are imported alongside the primary operation models.\n  // Also collect models referenced in wrapper param signatures (e.g.,\n  // `redirect_uris: RedirectUriInput[]`) — otherwise the wrapper emits a\n  // reference to a type it never imported.\n  for (const { op } of plans) {\n    const resolved = lookupResolved(op, resolvedLookup);\n    if (resolved) {\n      for (const name of collectWrapperResponseModels(resolved)) {\n        responseModels.add(name);\n      }\n      for (const wrapper of resolved.wrappers ?? []) {\n        for (const { field } of resolveWrapperParams(wrapper, ctx)) {\n          if (field) collectParamTypeRefs(field.type, paramEnums, paramModels);\n        }\n      }\n    }\n  }\n\n  const allModels = new Set([...responseModelsForSignature, ...requestModelsForSignature, ...paramModels]);\n\n  const lines: string[] = [];\n\n  // Imports\n  lines.push(\"import type { WorkOS } from '../workos';\");\n  if (hasPaginated) {\n    if (needsPaginationOptionsImport) {\n      lines.push(\"import type { PaginationOptions } from '../common/interfaces/pagination-options.interface';\");\n    }\n    lines.push(\"import { AutoPaginatable } from '../common/utils/pagination';\");\n    lines.push(\"import { fetchAndDeserialize } from '../common/utils/fetch-and-deserialize';\");\n  }\n  // URL-builder methods serialize their query string client-side via toQueryString.\n  const needsQueryStringImport = plans.some((p) => {\n    const r = lookupResolved(p.op, resolvedLookup);\n    if (!r?.urlBuilder) return false;\n    const hidden = hiddenParamsFor(r);\n    return (\n      p.op.queryParams.some((qp) => !hidden.has(qp.name)) ||\n      Object.keys(getOpDefaults(r)).length > 0 ||\n      getOpInferFromClient(r).length > 0\n    );\n  });\n  if (needsQueryStringImport) {\n    lines.push(\"import { toQueryString } from '../common/utils/query-string';\");\n  }\n  const shouldEmitVaultCryptoHelpers =\n    serviceClass === 'Vault' && !ignoredMethodNames.has('encrypt') && !ignoredMethodNames.has('decrypt');\n  if (shouldEmitVaultCryptoHelpers) {\n    lines.push(\"import { base64ToUint8Array, uint8ArrayToBase64 } from '../common/utils/base64';\");\n  }\n\n  // Check if any operation needs PostOptions (idempotent POST or custom encoding)\n  const hasIdempotentPost = plans.some((p) => p.plan.isIdempotentPost);\n  const hasCustomEncoding = plans.some(\n    (p) => p.op.requestBodyEncoding && p.op.requestBodyEncoding !== 'json' && p.plan.hasBody,\n  );\n  if (hasIdempotentPost || hasCustomEncoding) {\n    lines.push(\"import type { PostOptions } from '../common/interfaces/post-options.interface';\");\n  }\n\n  const importedTypeNames = new Set<string>();\n  // `PaginationOptions` is already imported once above when any method\n  // paginates; a method whose options type IS `PaginationOptions` would\n  // otherwise re-import it here (TS2300 duplicate identifier).\n  if (needsPaginationOptionsImport) importedTypeNames.add('PaginationOptions');\n  for (const optionType of optionObjectTypes) {\n    if (isValidTypeIdentifier(optionType)) {\n      if (importedTypeNames.has(optionType)) continue;\n      importedTypeNames.add(optionType);\n      const sourceFile = baselineTypeSourceFile(ctx, optionType);\n      const relPath = sourceFile\n        ? relativeImport(resourcePath, sourceFile)\n        : `./interfaces/${fileName(optionType)}.interface`;\n      lines.push(`import type { ${optionType} } from '${relPath}';`);\n      continue;\n    }\n    // Compound option types (e.g. a baseline `GetAccessTokenOptions & { provider:\n    // string }`) keep their inline object literal inline, but the named type(s)\n    // they reference must still be imported. Only import names that resolve to a\n    // known source file — inline literals, primitives, and property keys have no\n    // importable source and are skipped.\n    for (const typeName of extractNamedTypeRefs(optionType)) {\n      if (importedTypeNames.has(typeName)) continue;\n      const sourceFile = baselineTypeSourceFile(ctx, typeName) ?? liveSurfaceInterfacePath(typeName);\n      if (!sourceFile) continue;\n      importedTypeNames.add(typeName);\n      lines.push(`import type { ${typeName} } from '${relativeImport(resourcePath, sourceFile)}';`);\n    }\n  }\n  for (const typeName of returnTypeImports) {\n    if (importedTypeNames.has(typeName)) continue;\n    const sourceFile = baselineTypeSourceFile(ctx, typeName) ?? liveSurfaceInterfacePath(typeName);\n    if (!sourceFile) continue;\n    importedTypeNames.add(typeName);\n    lines.push(`import type { ${typeName} } from '${relativeImport(resourcePath, sourceFile)}';`);\n  }\n\n  // Compute model-to-service mapping for correct cross-service import paths\n  const { modelToService, resolveDir } = createServiceDirResolver(ctx.spec.models, ctx.spec.services, ctx);\n\n  // Wire (Response) types are only needed for models used as response types in method signatures.\n  // Request models and param models only need the domain type.\n  const usedWireTypes = new Set<string>();\n  for (const name of responseModels) {\n    usedWireTypes.add(resolveInterfaceName(name, ctx));\n  }\n  for (const name of requestModels) {\n    const resolved = resolveInterfaceName(name, ctx);\n    const bodyExpr = bodyArgExpr(name, resolved, ctx);\n    if (requestEntityType(bodyExpr, resolved) !== resolved) {\n      usedWireTypes.add(resolved);\n    }\n  }\n\n  // Track imported resolved names to prevent duplicate type name collisions\n  for (const name of allModels) {\n    const resolved = resolveInterfaceName(name, ctx);\n    if (importedTypeNames.has(resolved)) continue; // Skip duplicate resolved names\n    importedTypeNames.add(resolved);\n    const modelDir = modelToService.get(name);\n    const modelServiceDir = resolveDir(modelDir);\n    const relPath =\n      modelServiceDir === serviceDir\n        ? `./interfaces/${fileName(name)}.interface`\n        : `../${modelServiceDir}/interfaces/${fileName(name)}.interface`;\n    if (usedWireTypes.has(resolved)) {\n      const wireName = wireInterfaceName(resolved);\n      // When the wire name collapsed onto the domain name (single-form\n      // structural-rename emission), import once — otherwise we ship\n      // `import type { ReadObjectResponse, ReadObjectResponse }`.\n      if (wireName === resolved) {\n        lines.push(`import type { ${resolved} } from '${relPath}';`);\n      } else {\n        lines.push(`import type { ${resolved}, ${wireName} } from '${relPath}';`);\n      }\n    } else {\n      lines.push(`import type { ${resolved} } from '${relPath}';`);\n    }\n  }\n\n  for (const name of requestModels) {\n    if (allModels.has(name)) continue;\n    const resolved = resolveInterfaceName(name, ctx);\n    if (!usedWireTypes.has(resolved)) continue;\n    const wireName = wireInterfaceName(resolved);\n    if (importedTypeNames.has(wireName)) continue;\n    const modelDir = modelToService.get(name);\n    const modelServiceDir = resolveDir(modelDir);\n    const relPath =\n      modelServiceDir === serviceDir\n        ? `./interfaces/${fileName(name)}.interface`\n        : `../${modelServiceDir}/interfaces/${fileName(name)}.interface`;\n    lines.push(`import type { ${wireName} } from '${relPath}';`);\n    importedTypeNames.add(wireName);\n  }\n\n  for (const name of responseModels) {\n    if (allModels.has(name)) continue;\n    const resolved = resolveInterfaceName(name, ctx);\n    if (!usedWireTypes.has(resolved)) continue;\n    const wireName = wireInterfaceName(resolved);\n    if (importedTypeNames.has(wireName)) continue;\n    const modelDir = modelToService.get(name);\n    const modelServiceDir = resolveDir(modelDir);\n    const relPath =\n      modelServiceDir === serviceDir\n        ? `./interfaces/${fileName(name)}.interface`\n        : `../${modelServiceDir}/interfaces/${fileName(name)}.interface`;\n    lines.push(`import type { ${wireName} } from '${relPath}';`);\n    importedTypeNames.add(wireName);\n  }\n\n  for (const name of baselineResponseTypes) {\n    if (importedTypeNames.has(name)) continue;\n    const wireName = wireInterfaceName(name);\n    const sourceFile = baselineTypeSourceFile(ctx, name) ?? baselineTypeSourceFile(ctx, wireName);\n    if (!sourceFile) continue;\n    const importNames = wireName === name ? name : `${name}, ${wireName}`;\n    lines.push(`import type { ${importNames} } from '${relativeImport(resourcePath, sourceFile)}';`);\n    importedTypeNames.add(name);\n    importedTypeNames.add(wireName);\n  }\n\n  // Collect serializer imports by module path so we can merge deserialize and\n  // serialize imports from the same module into a single import statement.\n  const serializerImportsByPath = new Map<string, string[]>();\n\n  const importedDeserializers = new Set<string>();\n  for (const name of responseModels) {\n    const resolved = resolveInterfaceName(name, ctx);\n    if (importedDeserializers.has(resolved)) continue;\n    importedDeserializers.add(resolved);\n    const modelDir = modelToService.get(name);\n    const modelServiceDir = resolveDir(modelDir);\n    const relPath =\n      modelServiceDir === serviceDir\n        ? `./serializers/${fileName(name)}.serializer`\n        : `../${modelServiceDir}/serializers/${fileName(name)}.serializer`;\n    const existing = serializerImportsByPath.get(relPath) ?? [];\n    existing.push(`deserialize${resolved}`);\n    serializerImportsByPath.set(relPath, existing);\n  }\n  for (const name of baselineResponseTypes) {\n    if (importedDeserializers.has(name)) continue;\n    importedDeserializers.add(name);\n    const sourceFile = baselineTypeSourceFile(ctx, name) ?? baselineTypeSourceFile(ctx, wireInterfaceName(name));\n    if (!sourceFile) continue;\n    const serializerPath = sourceFile\n      .replace('/interfaces/', '/serializers/')\n      .replace(/\\.interface\\.ts$/, '.serializer.ts');\n    const relPath = relativeImport(resourcePath, serializerPath);\n    const existing = serializerImportsByPath.get(relPath) ?? [];\n    existing.push(`deserialize${name}`);\n    serializerImportsByPath.set(relPath, existing);\n  }\n\n  const importedSerializers = new Set<string>();\n  for (const name of requestModels) {\n    const resolved = resolveInterfaceName(name, ctx);\n    if (importedSerializers.has(resolved)) continue;\n    importedSerializers.add(resolved);\n\n    // If `bodyArgExpr` will fall through to passing `payload` directly\n    // (because the live SDK has the serializer file but no `serialize${T}`\n    // function), don't generate an import for a function that doesn't exist.\n    const ser = `serialize${resolved}`;\n    if (!liveSurfaceHasFunction(ser)) {\n      const sourceFile = (ctx.apiSurface?.interfaces?.[resolved] as { sourceFile?: string } | undefined)?.sourceFile;\n      const candidate = sourceFile\n        ? sourceFile.replace('/interfaces/', '/serializers/').replace('.interface.ts', '.serializer.ts')\n        : `src/${resolveDir(modelToService.get(name))}/serializers/${fileName(name)}.serializer.ts`;\n      if (liveSurfaceHasFile(candidate) && !liveSurfaceHasAutogenFile(candidate)) continue;\n    }\n\n    const modelDir = modelToService.get(name);\n    const modelServiceDir = resolveDir(modelDir);\n    const relPath =\n      modelServiceDir === serviceDir\n        ? `./serializers/${fileName(name)}.serializer`\n        : `../${modelServiceDir}/serializers/${fileName(name)}.serializer`;\n    const existing = serializerImportsByPath.get(relPath) ?? [];\n    existing.push(ser);\n    serializerImportsByPath.set(relPath, existing);\n  }\n\n  // Emit merged serializer imports\n  for (const [relPath, specifiers] of serializerImportsByPath) {\n    lines.push(`import { ${specifiers.join(', ')} } from '${relPath}';`);\n  }\n\n  // Build a set of global enum names — used to distinguish named enums (with files)\n  // from inline enums (no file, must be rendered as string literal unions).\n  const specEnumNames = new Set(ctx.spec.enums.map((e) => e.name));\n\n  // Import enum types referenced in query/path parameters.\n  // Only import enums that actually exist in the spec's global enums list —\n  // inline string unions may have kind 'enum' but no corresponding file.\n  if (paramEnums.size > 0) {\n    const enumToService = assignEnumsToServices(ctx.spec.enums, ctx.spec.services, ctx.spec.models, ctx);\n    for (const name of paramEnums) {\n      if (allModels.has(name)) continue; // Already imported as a model\n      if (!specEnumNames.has(name)) continue; // No file generated for this enum\n      if (isInlineEnum(name)) continue; // Inlined at usage sites — no import needed\n      const enumDir = enumToService.get(name);\n      const enumServiceDir = resolveDir(enumDir);\n      const relPath =\n        enumServiceDir === serviceDir\n          ? `./interfaces/${fileName(name)}.interface`\n          : `../${enumServiceDir}/interfaces/${fileName(name)}.interface`;\n      lines.push(`import type { ${name} } from '${relPath}';`);\n    }\n  }\n\n  lines.push('');\n\n  // Per-operation helpers (wire-format option serializers etc.) emitted\n  // alongside the resource class.  The options interfaces themselves live\n  // in separate files under `interfaces/` so the per-service barrel can\n  // re-export them; see the earlier import block at the top of the file.\n  for (const { op, plan, method } of plans) {\n    const resolved = lookupResolved(op, resolvedLookup);\n    const baselineMethod = baselineMethodFor(service, method, ctx);\n    const optionInfo = optionsObjectInfo(service, method, op, plan, ctx, baselineMethod, resolved);\n    if (plan.isPaginated) {\n      // Skip deprecated query params: the typed options interface omits them\n      // (the curated baseline drops deprecated params), so the wire serializer\n      // must not reference a field that does not exist on the options type.\n      const extraParams = op.queryParams.filter((p) => !PAGINATION_PARAM_NAMES.has(p.name) && !p.deprecated);\n      if (extraParams.length > 0) {\n        const optionsName = optionInfo?.type ?? paginatedOptionsName(method, resolvedName);\n\n        // When any extension param has a camelCase domain name that differs\n        // from its snake_case wire name, emit a serializer that translates\n        // the user-facing options into the wire query shape.  Without this,\n        // the query string uses camelCase keys (e.g. `organizationId=...`)\n        // that the API silently ignores — the filter becomes a no-op.\n        const needsWireSerializer = extraParams.some((p) => fieldName(p.name) !== wireFieldName(p.name));\n        if (needsWireSerializer) {\n          const serializerName = `serialize${optionsName}`;\n          lines.push(`const ${serializerName} = (options: ${optionsName}): PaginationOptions => {`);\n          // Pagination fields pass through unchanged (limit/before/after/order\n          // share spelling in both cases).  Spread first so that wire-named\n          // extension fields land on top and the camelCase keys don't also\n          // leak into the query string.\n          lines.push('  const wire: Record<string, unknown> = {');\n          const baselineFields = (\n            ctx.apiSurface?.interfaces as Record<string, { fields?: Record<string, unknown> }> | undefined\n          )?.[optionsName]?.fields;\n          for (const p of PAGINATION_PARAM_NAMES) {\n            if (baselineFields && !(p in baselineFields) && !baselineFields[toCamelCase(p)]) continue;\n            lines.push(`    ${p}: options.${p},`);\n          }\n          lines.push('  };');\n          for (const param of extraParams) {\n            const camel = fieldName(param.name);\n            const snake = wireFieldName(param.name);\n            lines.push(`  if (options.${camel} !== undefined) wire.${snake} = options.${camel};`);\n          }\n          lines.push('  return wire as PaginationOptions;');\n          lines.push('};');\n          lines.push('');\n        }\n      }\n    } else if (!optionInfo && !plan.isPaginated && !plan.hasBody && !plan.isDelete && op.queryParams.length > 0) {\n      // Non-paginated GET or void methods with query params get a typed options interface\n      // instead of falling back to Record<string, unknown>.\n      // Filter out hidden params (defaults and inferFromClient fields)\n      const resolved = lookupResolved(op, resolvedLookup);\n      const opHiddenParams = new Set<string>([\n        ...Object.keys(getOpDefaults(resolved)),\n        ...getOpInferFromClient(resolved),\n      ]);\n      const visibleParams = op.queryParams.filter((p) => !opHiddenParams.has(p.name));\n      if (visibleParams.length > 0) {\n        const optionsName = toPascalCase(method) + 'Options';\n        lines.push(`export interface ${optionsName} {`);\n        for (const param of visibleParams) {\n          const opt = !param.required ? '?' : '';\n          if (param.description || param.deprecated) {\n            const parts: string[] = [];\n            if (param.description) parts.push(param.description);\n            if (param.deprecated) parts.push('@deprecated');\n            lines.push(...docComment(parts.join('\\n'), 2));\n          }\n          lines.push(`  ${fieldName(param.name)}${opt}: ${mapParamType(param.type, specEnumNames)};`);\n        }\n        lines.push('}');\n        lines.push('');\n      }\n    }\n  }\n\n  if (shouldEmitVaultCryptoHelpers) {\n    lines.push('export interface VaultEncryptedData {');\n    lines.push('  ciphertext: string;');\n    lines.push('  encryptedKeys: string;');\n    lines.push('  iv: string;');\n    lines.push('  tag: string;');\n    lines.push('}');\n    lines.push('');\n  }\n\n  // Resource class\n  if (service.description) {\n    lines.push(...docComment(service.description));\n  }\n  lines.push(`export class ${serviceClass} {`);\n  lines.push('  constructor(private readonly workos: WorkOS) {}');\n\n  for (const { op, plan, method } of plans) {\n    lines.push('');\n    const resolved = lookupResolved(op, resolvedLookup);\n    lines.push(...renderMethod(op, plan, method, service, ctx, modelMap, specEnumNames, resolved));\n\n    // Emit union split wrapper methods (typed convenience methods for each variant)\n    if (resolved?.wrappers && resolved.wrappers.length > 0) {\n      lines.push(...generateWrapperMethods(resolved, ctx));\n    }\n  }\n\n  if (shouldEmitVaultCryptoHelpers) {\n    lines.push('');\n    lines.push(...renderVaultCryptoMethods());\n  }\n\n  lines.push('}');\n\n  return { path: resourcePath, content: lines.join('\\n'), skipIfExists: true };\n}\n\nfunction renderVaultCryptoMethods(): string[] {\n  return [\n    '  async encrypt(',\n    '    plaintext: string,',\n    '    context: Record<string, string>,',\n    '    aad?: string,',\n    '  ): Promise<VaultEncryptedData> {',\n    '    const dataKeyPair = await this.createDataKey({ context });',\n    '    const encodedPlaintext = new TextEncoder().encode(plaintext);',\n    '    const encodedAad = aad ? new TextEncoder().encode(aad) : undefined;',\n    '    const encrypted = await this.workos.getCryptoProvider().encrypt(',\n    '      encodedPlaintext,',\n    '      base64ToUint8Array(dataKeyPair.dataKey.key),',\n    '      undefined,',\n    '      encodedAad,',\n    '    );',\n    '',\n    '    return {',\n    '      ciphertext: uint8ArrayToBase64(encrypted.ciphertext),',\n    '      encryptedKeys: dataKeyPair.encryptedKeys,',\n    '      iv: uint8ArrayToBase64(encrypted.iv),',\n    '      tag: uint8ArrayToBase64(encrypted.tag),',\n    '    };',\n    '  }',\n    '',\n    '  async decrypt(',\n    '    encryptedData: VaultEncryptedData,',\n    '    aad?: string,',\n    '  ): Promise<string> {',\n    '    const dataKey = await this.decryptDataKey({',\n    '      keys: encryptedData.encryptedKeys,',\n    '    });',\n    '    const encodedAad = aad ? new TextEncoder().encode(aad) : undefined;',\n    '    const decrypted = await this.workos.getCryptoProvider().decrypt(',\n    '      base64ToUint8Array(encryptedData.ciphertext),',\n    '      base64ToUint8Array(dataKey.key),',\n    '      base64ToUint8Array(encryptedData.iv),',\n    '      base64ToUint8Array(encryptedData.tag),',\n    '      encodedAad,',\n    '    );',\n    '',\n    '    return new TextDecoder().decode(decrypted);',\n    '  }',\n  ];\n}\n\nfunction renderMethod(\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  service: Service,\n  ctx: EmitterContext,\n  modelMap: Map<string, Model>,\n  specEnumNames?: Set<string>,\n  resolvedOp?: ResolvedOperation,\n): string[] {\n  const lines: string[] = [];\n  const responseModel = plan.responseModelName ? resolveInterfaceName(plan.responseModelName, ctx) : null;\n\n  const pathStr = buildPathStr(op);\n\n  // Build the set of params hidden from the method signature\n  // (injected from client config or as constant defaults)\n  const hiddenParams = new Set<string>([\n    ...Object.keys(getOpDefaults(resolvedOp)),\n    ...getOpInferFromClient(resolvedOp),\n  ]);\n\n  // Build set of valid param names to filter @param tags.\n  // Prefer the overlay (existing method signature) if available;\n  // otherwise compute from what the render path will actually include.\n  const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const baselineClassMethod = baselineMethodFor(service, method, ctx);\n  const optionInfo = optionsObjectInfo(service, method, op, plan, ctx, baselineClassMethod, resolvedOp);\n\n  // URL-builder operations (e.g. GET /sso/authorize) are spec-marked client-side\n  // URL constructors: emit a synchronous method that returns the request URL as\n  // a string without performing any I/O. This bypasses the HTTP method dispatch\n  // and the Promise-typed JSDoc below.\n  if (resolvedOp?.urlBuilder) {\n    renderUrlBuilderMethod(lines, op, method, pathStr, optionInfo, specEnumNames, resolvedOp);\n    return lines;\n  }\n\n  const overlayMethod = ctx.overlayLookup?.methodByOperation?.get(httpKey) ?? baselineClassMethod;\n  let validParamNames: Set<string> | null = null;\n  if (optionInfo) {\n    validParamNames = new Set(['options']);\n  } else if (overlayMethod) {\n    validParamNames = new Set(overlayMethod.params.map((p) => p.name));\n  } else {\n    // Compute actual params based on render path to avoid documenting params\n    // that won't appear in the method signature\n    const actualParams = new Set<string>();\n    for (const p of op.pathParams) actualParams.add(fieldName(p.name));\n    if (plan.hasBody) actualParams.add('payload');\n    if (plan.isPaginated) actualParams.add('options');\n    // renderGetMethod/renderVoidMethod add options when there are visible non-paginated query params\n    const visibleQueryCount = op.queryParams.filter((q) => !hiddenParams.has(q.name)).length;\n    if (!plan.isPaginated && visibleQueryCount > 0 && !plan.isDelete) {\n      actualParams.add('options');\n    }\n    validParamNames = actualParams;\n  }\n\n  // Always generate JSDoc for all methods (both existing and new).\n  // The merger matches docstrings by member name — if we skip JSDoc for\n  // existing methods, previously misplaced docstrings can never be corrected.\n  // Hand-written docs (e.g., @deprecated, PKCE flow descriptions) are\n  // preserved by the merger's @deprecated-preservation and @oagen-ignore\n  // mechanisms instead.\n  {\n    const docParts: string[] = [];\n    if (op.description) docParts.push(op.description);\n    for (const param of op.pathParams) {\n      const paramName = fieldName(param.name);\n      // When the overlay folds a path param into the options object,\n      // document it as @param options.paramName instead of top-level.\n      const folded = validParamNames && !validParamNames.has(paramName) && validParamNames.has('options');\n      if (validParamNames && !validParamNames.has(paramName) && !folded) continue;\n      const docName = folded ? `options.${paramName}` : paramName;\n      const deprecatedPrefix = param.deprecated ? '(deprecated) ' : '';\n      if (param.description) {\n        docParts.push(`@param ${docName} - ${deprecatedPrefix}${param.description}`);\n      } else if (param.deprecated) {\n        docParts.push(`@param ${docName} - (deprecated)`);\n      }\n      if (param.default !== undefined) docParts.push(`@default ${JSON.stringify(param.default)}`);\n      if (param.example !== undefined) docParts.push(`@example ${JSON.stringify(param.example)}`);\n    }\n    // Document query params for non-paginated operations\n    if (!plan.isPaginated) {\n      // Only document query params if the method will have an options parameter\n      if (validParamNames && (validParamNames.has('options') || overlayMethod)) {\n        for (const param of op.queryParams) {\n          if (hiddenParams.has(param.name)) continue;\n          const paramName = `options.${fieldName(param.name)}`;\n          if (validParamNames && !validParamNames.has('options') && !validParamNames.has(fieldName(param.name)))\n            continue;\n          const deprecatedPrefix = param.deprecated ? '(deprecated) ' : '';\n          if (param.description) {\n            docParts.push(`@param ${paramName} - ${deprecatedPrefix}${param.description}`);\n          } else if (param.deprecated) {\n            docParts.push(`@param ${paramName} - (deprecated)`);\n          }\n          if (param.default !== undefined) docParts.push(`@default ${JSON.stringify(param.default)}`);\n          if (param.example !== undefined) docParts.push(`@example ${JSON.stringify(param.example)}`);\n        }\n      }\n    }\n    // Skip header and cookie params in JSDoc — they are not exposed in the method signature.\n    // The SDK handles headers and cookies internally, so documenting them would be misleading.\n    // Document payload/body parameter when there is a request body.\n    // Detect the actual param name from the overlay — the hand-written SDK may\n    // fold the body into an 'options' param instead of the generated 'payload'.\n    let bodyDocParamName: string | null = null;\n    if (plan.hasBody) {\n      let bodyParamName = 'payload';\n      let overlayHadUnusableName = false;\n      if (validParamNames && !validParamNames.has('payload') && overlayMethod) {\n        const pathNames = new Set(op.pathParams.map((p) => fieldName(p.name)));\n        const candidates = overlayMethod.params.filter((p) => !pathNames.has(p.name) && p.name !== 'requestOptions');\n        // Filter out destructuring artifacts (e.g., __0) from extracted param names\n        const isUsableName = (name: string) => !/^__\\d+$/.test(name);\n        if (candidates.length === 1 && isUsableName(candidates[0].name)) {\n          bodyParamName = candidates[0].name;\n        } else if (candidates.length === 1 && !isUsableName(candidates[0].name)) {\n          overlayHadUnusableName = true;\n        } else if (candidates.length > 1) {\n          // Multiple non-path params — match by type against the request body model\n          const bodyInfo = extractRequestBodyType(op, ctx);\n          if (bodyInfo?.kind === 'model') {\n            const bodyTypeName = resolveInterfaceName(bodyInfo.name, ctx);\n            const typeMatch = candidates.find((p) => p.type === bodyTypeName && isUsableName(p.name));\n            if (typeMatch) {\n              bodyParamName = typeMatch.name;\n            } else {\n              // Type names diverge (overlay vs spec). Fall back to matching\n              // overlay param names against body model field names so each\n              // extracted param gets documented individually.\n              const bodyModel = ctx.spec.models.find((m) => m.name === bodyInfo.name);\n              if (bodyModel) {\n                const fieldMap = new Map(bodyModel.fields.map((f) => [fieldName(f.name), f]));\n                for (const candidate of candidates) {\n                  const matchingField = fieldMap.get(candidate.name);\n                  if (matchingField?.description) {\n                    docParts.push(`@param ${candidate.name} - ${matchingField.description}`);\n                    if (matchingField.example !== undefined)\n                      docParts.push(`@example ${JSON.stringify(matchingField.example)}`);\n                  }\n                }\n                bodyDocParamName = '__multi__'; // prevent duplicate body doc below\n              }\n            }\n          }\n        }\n      }\n\n      // When the overlay had an unusable param name (e.g., destructured __0),\n      // force documentation under 'payload' so the body isn't silently dropped.\n      if (\n        bodyDocParamName !== '__multi__' &&\n        (overlayHadUnusableName || !validParamNames || validParamNames.has(bodyParamName))\n      ) {\n        bodyDocParamName = bodyParamName;\n        const bodyInfo = extractRequestBodyType(op, ctx);\n        if (bodyInfo?.kind === 'model') {\n          const bodyModel = ctx.spec.models.find((m) => m.name === bodyInfo.name);\n          let bodyDesc: string;\n          if (bodyModel?.description) {\n            bodyDesc = `@param ${bodyParamName} - ${bodyModel.description}`;\n          } else if (bodyModel) {\n            // When the model lacks a description, list its required fields to help\n            // callers understand what must be provided.\n            const requiredFieldNames = bodyModel.fields.filter((f) => f.required).map((f) => fieldName(f.name));\n            bodyDesc =\n              requiredFieldNames.length > 0\n                ? `@param ${bodyParamName} - Object containing ${requiredFieldNames.join(', ')}.`\n                : `@param ${bodyParamName} - The request body.`;\n          } else {\n            bodyDesc = `@param ${bodyParamName} - The request body.`;\n          }\n          docParts.push(bodyDesc);\n\n          // When the body is folded into an options-style param (not 'payload'),\n          // expand individual fields so IDEs surface per-field documentation.\n          if (bodyParamName !== 'payload' && bodyModel) {\n            for (const bField of bodyModel.fields) {\n              const fName = `${bodyParamName}.${fieldName(bField.name)}`;\n              const deprecatedPrefix = bField.deprecated ? '(deprecated) ' : '';\n              if (bField.description) {\n                docParts.push(`@param ${fName} - ${deprecatedPrefix}${bField.description}`);\n              } else if (bField.deprecated) {\n                docParts.push(`@param ${fName} - (deprecated)`);\n              }\n              if (bField.example !== undefined) docParts.push(`@example ${JSON.stringify(bField.example)}`);\n            }\n          }\n        } else {\n          docParts.push(`@param ${bodyParamName} - The request body.`);\n        }\n      }\n    }\n    // Document options parameter for paginated operations\n    const hasOptionsSummary = () => docParts.some((p) => /^@param options(\\s|$)/.test(p));\n    if (plan.isPaginated) {\n      docParts.push('@param options - Pagination and filter options.');\n    } else if (!hasOptionsSummary() && op.queryParams.filter((q) => !hiddenParams.has(q.name)).length > 0) {\n      docParts.push('@param options - Additional query options.');\n    }\n    // Ensure an @param options summary exists when there are @param options.xxx\n    // entries (from folded path/body params) or when the overlay exposes an\n    // options param that wasn't otherwise documented.\n    if (validParamNames?.has('options') && !hasOptionsSummary()) {\n      const hasOptionsDotEntries = docParts.some((p) => p.startsWith('@param options.'));\n      if (hasOptionsDotEntries || overlayMethod) {\n        docParts.push('@param options - The request options.');\n      }\n    }\n    // Reorder: ensure @param options summary comes before any @param options.xxx entries\n    {\n      const summaryIdx = docParts.findIndex((p) => /^@param options(\\s|$)/.test(p));\n      const firstDotIdx = docParts.findIndex((p) => p.startsWith('@param options.'));\n      if (summaryIdx > firstDotIdx && firstDotIdx >= 0) {\n        const [summary] = docParts.splice(summaryIdx, 1);\n        docParts.splice(firstDotIdx, 0, summary);\n      }\n    }\n    // @returns for the primary response model.\n    // When an overlay method exists, prefer its return type so the JSDoc\n    // matches the actual TypeScript signature (the overlay may use a\n    // different model name than the OpenAPI schema).\n    const documentedReturnType =\n      preferredBaselineReturnType(ctx, baselineClassMethod?.returnType) ??\n      preferredBaselineReturnType(ctx, overlayMethod?.returnType);\n    if (documentedReturnType) {\n      docParts.push(`@returns {${documentedReturnType}}`);\n    } else if (plan.isPaginated && op.pagination?.itemType.kind === 'model') {\n      // Unwrap list wrapper models to match the actual return type — the method returns\n      // AutoPaginatable<ItemType>, not the list wrapper.\n      let itemRawName = op.pagination.itemType.name;\n      const pModel = modelMap.get(itemRawName);\n      if (pModel) {\n        const unwrapped = unwrapListModel(pModel, modelMap);\n        if (unwrapped) itemRawName = unwrapped.name;\n      }\n      const baselineItemType =\n        autoPaginatableItemType(baselineClassMethod?.returnType) ?? autoPaginatableItemType(overlayMethod?.returnType);\n      const itemTypeName = preferredBaselineTypeName(ctx, baselineItemType) ?? resolveInterfaceName(itemRawName, ctx);\n      docParts.push(`@returns {Promise<AutoPaginatable<${itemTypeName}>>}`);\n    } else if (responseModel) {\n      const returnTypeDoc = plan.isArrayResponse ? `${responseModel}[]` : responseModel;\n      docParts.push(`@returns {Promise<${returnTypeDoc}>}`);\n    } else {\n      docParts.push('@returns {Promise<void>}');\n    }\n    // @throws for error responses\n    for (const err of op.errors) {\n      const exceptionName = STATUS_TO_EXCEPTION_NAME[err.statusCode];\n      if (exceptionName) {\n        docParts.push(`@throws {${exceptionName}} ${err.statusCode}`);\n      }\n    }\n    if (op.deprecated) docParts.push('@deprecated');\n\n    if (docParts.length > 0) {\n      // Flatten all parts, splitting multiline descriptions into individual lines\n      const allLines: string[] = [];\n      for (const part of docParts) {\n        for (const line of part.split('\\n')) {\n          allLines.push(line);\n        }\n      }\n      if (allLines.length === 1) {\n        lines.push(`  /** ${allLines[0]} */`);\n      } else {\n        lines.push('  /**');\n        for (const line of allLines) {\n          lines.push(line === '' ? '   *' : `   * ${line}`);\n        }\n        lines.push('   */');\n      }\n    }\n  }\n\n  if (\n    renderOptionsObjectMethod(\n      lines,\n      op,\n      plan,\n      method,\n      service,\n      ctx,\n      modelMap,\n      specEnumNames,\n      baselineClassMethod,\n      resolvedOp,\n    )\n  ) {\n    return lines;\n  }\n\n  const preDecisionCount = lines.length;\n\n  if (plan.isPaginated && op.pagination && op.httpMethod === 'get') {\n    // For paginated operations, use the item type from pagination metadata\n    // (e.g., Connection) rather than the list wrapper type (e.g., ConnectionList).\n    // Unwrap list wrapper models to get the actual item type name.\n    let paginatedItemRawName = op.pagination.itemType.kind === 'model' ? op.pagination.itemType.name : null;\n    if (paginatedItemRawName) {\n      const pModel = modelMap.get(paginatedItemRawName);\n      if (pModel) {\n        const unwrapped = unwrapListModel(pModel, modelMap);\n        if (unwrapped) {\n          paginatedItemRawName = unwrapped.name;\n        }\n      }\n    }\n    const paginatedItemType = paginatedItemRawName ? resolveInterfaceName(paginatedItemRawName, ctx) : responseModel;\n    if (paginatedItemType) {\n      const resolvedServiceNameForPaginated = resolveServiceName(service, ctx);\n      renderPaginatedMethod(\n        lines,\n        op,\n        plan,\n        method,\n        paginatedItemType,\n        pathStr,\n        resolvedServiceNameForPaginated,\n        specEnumNames,\n      );\n    }\n  } else if (plan.isPaginated && plan.hasBody && responseModel) {\n    // Non-GET paginated operation (e.g., PUT with list response) — treat as body method\n    renderBodyMethod(lines, op, plan, method, responseModel, pathStr, ctx, specEnumNames);\n  } else if (plan.isDelete && plan.hasBody) {\n    renderDeleteWithBodyMethod(lines, op, plan, method, pathStr, ctx, specEnumNames);\n  } else if (plan.isDelete) {\n    renderDeleteMethod(lines, op, plan, method, pathStr, specEnumNames);\n  } else if (plan.hasBody && responseModel) {\n    renderBodyMethod(lines, op, plan, method, responseModel, pathStr, ctx, specEnumNames);\n  } else if (responseModel) {\n    renderGetMethod(lines, op, plan, method, responseModel, pathStr, specEnumNames, resolvedOp);\n  } else {\n    renderVoidMethod(lines, op, plan, method, pathStr, ctx, specEnumNames, resolvedOp);\n  }\n\n  // Defensive: if no render function produced a method body, emit a stub\n  if (lines.length === preDecisionCount) {\n    const params = buildPathParams(op, specEnumNames);\n    lines.push(`  async ${method}(${params}): Promise<void> {`);\n    lines.push(\n      `    await this.workos.${op.httpMethod}(${pathStr}${httpMethodNeedsBody(op.httpMethod) ? ', {}' : ''});`,\n    );\n    lines.push('  }');\n  }\n\n  return lines;\n}\n\nfunction renderOptionsObjectMethod(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  service: Service,\n  ctx: EmitterContext,\n  modelMap: Map<string, Model>,\n  specEnumNames: Set<string> | undefined,\n  baselineMethod: BaselineMethod | undefined,\n  resolvedOp: ResolvedOperation | undefined,\n): boolean {\n  const optionParam = optionsObjectInfo(service, method, op, plan, ctx, baselineMethod, resolvedOp);\n  if (!optionParam) return false;\n\n  const responseModel = plan.responseModelName ? resolveInterfaceName(plan.responseModelName, ctx) : null;\n  const pathBindings = buildOptionsObjectPathBindings(op, optionParam.type, ctx);\n  const pathStr = buildPathStr(op, buildOptionsObjectPathParamMap(op, optionParam.type, ctx));\n  const override = operationOverrideFor(ctx, op);\n  const bodyFieldMap = override?.bodyFieldMap;\n  const visibleQueryParams = visibleQueryParamsForOptions(op, plan, resolvedOp);\n  const queryBindings = visibleQueryParams.map((param) => fieldName(param.name));\n  const hasQuery =\n    visibleQueryParams.length > 0 ||\n    Object.keys(getOpDefaults(resolvedOp)).length > 0 ||\n    getOpInferFromClient(resolvedOp).length > 0;\n  const queryOptionsArg = hasQuery\n    ? `, { query: ${renderQueryExprWithOptions(visibleQueryParams, optionParam.optional, resolvedOp)} }`\n    : '';\n\n  if (plan.isPaginated && op.pagination && op.httpMethod === 'get') {\n    let itemRawName = op.pagination.itemType.kind === 'model' ? op.pagination.itemType.name : null;\n    if (itemRawName) {\n      const pModel = modelMap.get(itemRawName);\n      if (pModel) {\n        const unwrapped = unwrapListModel(pModel, modelMap);\n        if (unwrapped) itemRawName = unwrapped.name;\n      }\n    }\n    const itemType =\n      preferredBaselineTypeName(ctx, autoPaginatableItemType(baselineMethod?.returnType)) ??\n      (itemRawName ? resolveInterfaceName(itemRawName, ctx) : responseModel);\n    if (!itemType) return false;\n    const wireType = wireInterfaceName(itemType);\n    const extraParams = op.queryParams.filter((p) => !PAGINATION_PARAM_NAMES.has(p.name));\n    const needsWireSerializer = extraParams.some((p) => fieldName(p.name) !== wireFieldName(p.name));\n    // When path params are destructured out of the options object, the value\n    // passed to AutoPaginatable (and to fetchAndDeserialize) is the REST\n    // object — typed Omit<FullOptions, pathFields> — not the full options\n    // interface. Declaring the full interface as the second type argument\n    // fails TS2322 because the rest object lacks the required path-param\n    // fields, so parameterize over the rest type actually passed.\n    const restOptionsType =\n      pathBindings.length > 0\n        ? `Omit<${optionParam.type}, ${pathBindings.map((b) => `'${b}'`).join(' | ')}>`\n        : optionParam.type;\n    const paginationType = needsWireSerializer ? 'PaginationOptions' : restOptionsType;\n    const returnType = needsWireSerializer\n      ? `Promise<AutoPaginatable<${itemType}, ${paginationType}>>`\n      : (preferredBaselineReturnType(ctx, baselineMethod?.returnType) ??\n        `Promise<AutoPaginatable<${itemType}, ${paginationType}>>`);\n    const listOptionsExpr = needsWireSerializer\n      ? `options ? serialize${optionParam.type}(options) : undefined`\n      : 'paginationOptions';\n    lines.push(`  async ${method}(${renderOptionsParam(optionParam)}): ${returnType} {`);\n    renderOptionsObjectDestructure(lines, pathBindings, needsWireSerializer ? undefined : 'paginationOptions');\n    lines.push(`    return new AutoPaginatable(`);\n    lines.push(`      await fetchAndDeserialize<${wireType}, ${itemType}>(`);\n    lines.push(`        this.workos,`);\n    lines.push(`        ${pathStr},`);\n    lines.push(`        deserialize${itemType},`);\n    lines.push(`        ${listOptionsExpr},`);\n    lines.push(`      ),`);\n    lines.push(`      (params) =>`);\n    lines.push(`        fetchAndDeserialize<${wireType}, ${itemType}>(`);\n    lines.push(`          this.workos,`);\n    lines.push(`          ${pathStr},`);\n    lines.push(`          deserialize${itemType},`);\n    lines.push(`          params,`);\n    lines.push(`        ),`);\n    lines.push(`      ${listOptionsExpr},`);\n    lines.push(`    );`);\n    lines.push('  }');\n    return true;\n  }\n\n  if (plan.isDelete && !plan.hasBody) {\n    lines.push(`  async ${method}(${renderOptionsParam(optionParam)}): Promise<void> {`);\n    renderOptionsObjectDestructure(lines, pathBindings);\n    lines.push(`    await this.workos.delete(${pathStr}${queryOptionsArg});`);\n    lines.push('  }');\n    return true;\n  }\n\n  if (plan.hasBody) {\n    const bodyInfo = extractRequestBodyType(op, ctx);\n    let requestType: string;\n    let bodyExpr: string;\n    let entityType: string;\n    if (bodyInfo?.kind === 'model') {\n      requestType = resolveInterfaceName(bodyInfo.name, ctx);\n      bodyExpr = bodyArgExpr(bodyInfo.name, requestType, ctx, 'payload');\n      entityType = requestEntityType(bodyExpr, requestType);\n    } else if (bodyInfo?.kind === 'union') {\n      requestType = bodyInfo.typeStr;\n      bodyExpr = bodyInfo.discriminator\n        ? renderUnionBodySerializer(bodyInfo.discriminator, ctx)\n        : renderNonDiscriminatedUnionBodySerializer(bodyInfo.modelNames, ctx);\n      entityType = unionEntityType(bodyInfo.modelNames, ctx);\n    } else {\n      requestType = 'Record<string, unknown>';\n      bodyExpr = 'payload';\n      entityType = requestType;\n    }\n\n    if (plan.isDelete) {\n      lines.push(`  async ${method}(${renderOptionsParam(optionParam)}): Promise<void> {`);\n      renderOptionsObjectDestructure(lines, [...pathBindings, ...queryBindings], 'payload');\n      const bodyParam = renderOptionsObjectBodyFieldMap(lines, bodyFieldMap);\n      bodyExpr = bodyArgExprWithParam(bodyExpr, bodyParam);\n      lines.push(`    await this.workos.deleteWithBody<${entityType}>(${pathStr}, ${bodyExpr}${queryOptionsArg});`);\n      lines.push('  }');\n      return true;\n    }\n\n    if (!responseModel) {\n      lines.push(`  async ${method}(${renderOptionsParam(optionParam)}): Promise<void> {`);\n      renderOptionsObjectDestructure(lines, [...pathBindings, ...queryBindings], 'payload');\n      const bodyParam = renderOptionsObjectBodyFieldMap(lines, bodyFieldMap);\n      bodyExpr = bodyArgExprWithParam(bodyExpr, bodyParam);\n      lines.push(\n        `    await this.workos.${op.httpMethod}<void, ${entityType}>(${pathStr}, ${bodyExpr}${queryOptionsArg});`,\n      );\n      lines.push('  }');\n      return true;\n    }\n\n    const returnType = plan.isArrayResponse ? `${responseModel}[]` : responseModel;\n    const methodReturnType = override?.returnType ?? `Promise<${returnType}>`;\n    const wireType = plan.isArrayResponse ? `${wireInterfaceName(responseModel)}[]` : wireInterfaceName(responseModel);\n    const returnExpr = plan.isArrayResponse\n      ? `data.map(deserialize${responseModel})`\n      : `deserialize${responseModel}(data)`;\n    const finalReturnExpr = override?.returnDataProperty ? `${returnExpr}.${override.returnDataProperty}` : returnExpr;\n\n    lines.push(`  async ${method}(${renderOptionsParam(optionParam)}): ${methodReturnType} {`);\n    renderOptionsObjectDestructure(lines, [...pathBindings, ...queryBindings], 'payload');\n    const bodyParam = renderOptionsObjectBodyFieldMap(lines, bodyFieldMap);\n    bodyExpr = bodyArgExprWithParam(bodyExpr, bodyParam);\n    lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}, ${entityType}>(`);\n    lines.push(`      ${pathStr},`);\n    lines.push(`      ${bodyExpr}${queryOptionsArg},`);\n    lines.push('    );');\n    if (override?.returnExpression) {\n      lines.push(`    const result = ${returnExpr};`);\n      lines.push(`    return ${override.returnExpression};`);\n    } else {\n      lines.push(`    return ${finalReturnExpr};`);\n    }\n    lines.push('  }');\n    return true;\n  }\n\n  if (responseModel) {\n    const returnType = plan.isArrayResponse ? `${responseModel}[]` : responseModel;\n    const methodReturnType = override?.returnType ?? `Promise<${returnType}>`;\n    const wireType = plan.isArrayResponse ? `${wireInterfaceName(responseModel)}[]` : wireInterfaceName(responseModel);\n    const returnExpr = plan.isArrayResponse\n      ? `data.map(deserialize${responseModel})`\n      : `deserialize${responseModel}(data)`;\n    const finalReturnExpr = override?.returnDataProperty ? `${returnExpr}.${override.returnDataProperty}` : returnExpr;\n\n    lines.push(`  async ${method}(${renderOptionsParam(optionParam)}): ${methodReturnType} {`);\n    renderOptionsObjectDestructure(lines, pathBindings);\n    // POST/PUT/PATCH require the entity argument even without a request body —\n    // the client signature is `post(path, entity, options?)`, so a body-less\n    // call must still pass `{}` or the generated code fails with TS2554.\n    const emptyBodyArg = httpMethodNeedsBody(op.httpMethod) ? ', {}' : '';\n    lines.push(\n      `    const { data } = await this.workos.${op.httpMethod}<${wireType}>(${pathStr}${emptyBodyArg}${queryOptionsArg});`,\n    );\n    if (override?.returnExpression) {\n      lines.push(`    const result = ${returnExpr};`);\n      lines.push(`    return ${override.returnExpression};`);\n    } else {\n      lines.push(`    return ${finalReturnExpr};`);\n    }\n    lines.push('  }');\n    return true;\n  }\n\n  // Body-less, response-less mutation with path params and/or query folded into\n  // the options object (e.g. POST /feature-flags/{slug}/targets/{targetId} -> 204).\n  // The DELETE equivalent is handled above; this covers POST/PUT/PATCH (and any\n  // other verb) that returns no content. Without this branch such operations\n  // fall through to the positional renderVoidMethod, which is inconsistent with\n  // the options-object surface the rest of an owned service uses.\n  {\n    lines.push(`  async ${method}(${renderOptionsParam(optionParam)}): Promise<void> {`);\n    renderOptionsObjectDestructure(lines, pathBindings);\n    const emptyBodyArg = httpMethodNeedsBody(op.httpMethod) ? ', {}' : '';\n    lines.push(`    await this.workos.${op.httpMethod}(${pathStr}${emptyBodyArg}${queryOptionsArg});`);\n    lines.push('  }');\n    return true;\n  }\n}\n\nfunction renderOptionsObjectDestructure(lines: string[], pathBindings: string[], restName?: string): void {\n  if (pathBindings.length > 0 && restName) {\n    lines.push(`    const { ${pathBindings.join(', ')}, ...${restName} } = options;`);\n  } else if (pathBindings.length > 0) {\n    lines.push(`    const { ${pathBindings.join(', ')} } = options;`);\n  } else if (restName) {\n    lines.push(`    const ${restName} = options;`);\n  }\n}\n\nfunction renderOptionsObjectBodyFieldMap(lines: string[], bodyFieldMap: Record<string, string> | undefined): string {\n  const entries = Object.entries(bodyFieldMap ?? {});\n  if (entries.length === 0) return 'payload';\n\n  lines.push('    const requestPayload = {');\n  lines.push('      ...payload,');\n  for (const [source, target] of entries) {\n    lines.push(`      ${target}: payload.${source},`);\n  }\n  lines.push('    };');\n  return 'requestPayload';\n}\n\nfunction bodyArgExprWithParam(bodyExpr: string, paramName: string): string {\n  return paramName === 'payload' ? bodyExpr : bodyExpr.replace(/\\bpayload\\b/g, paramName);\n}\n\nfunction buildOptionsObjectPathBindings(op: Operation, optionType: string, ctx: EmitterContext): string[] {\n  // Return resolved SDK field names directly — the URL template uses these\n  // names too (via the param-name map threaded into buildNodePathExpression),\n  // so the destructure no longer needs `optionField: localName` renames.\n  const pathFieldMap = operationOverrideFor(ctx, op)?.pathFieldMap;\n  return op.pathParams.map((param) => resolveOptionsObjectField(fieldName(param.name), optionType, ctx, pathFieldMap));\n}\n\n/**\n * Map spec path-param names (e.g. `omId`) to the SDK field name exposed on\n * the options interface (e.g. `organizationMembershipId`). Empty when every\n * path param's spec name already matches the SDK field. Consumed by\n * `buildNodePathExpression` so the URL template binds to the same identifier\n * the destructure does.\n */\nfunction buildOptionsObjectPathParamMap(op: Operation, optionType: string, ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  const pathFieldMap = operationOverrideFor(ctx, op)?.pathFieldMap;\n  for (const param of op.pathParams) {\n    const localName = fieldName(param.name);\n    const sdkField = resolveOptionsObjectField(localName, optionType, ctx, pathFieldMap);\n    if (sdkField !== localName) map.set(param.name, sdkField);\n  }\n  return map;\n}\n\nfunction resolveOptionsObjectField(\n  localName: string,\n  optionType: string,\n  ctx: EmitterContext,\n  pathFieldMap?: Record<string, string>,\n): string {\n  // Operation-override rename (Node-scoped) wins unconditionally: an explicit\n  // pathFieldMap is honored even when the (freshly generated) options interface\n  // isn't in the baseline surface yet — generateOptionsInterfaces applies the\n  // same map to the emitted field, so destructure and interface stay in lockstep.\n  const mapped = pathFieldMap?.[localName];\n  if (mapped) return mapped;\n  const fields = ctx.apiSurface?.interfaces?.[optionType]?.fields;\n  if (!fields) return localName;\n  if (fields[localName]) return localName;\n  if (localName === 'omId' && fields.organizationMembershipId) return 'organizationMembershipId';\n  return localName;\n}\n\nfunction renderPaginatedMethod(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  itemType: string,\n  pathStr: string,\n  resolvedServiceName: string,\n  specEnumNames?: Set<string>,\n): void {\n  const extraParams = op.queryParams.filter((p) => !PAGINATION_PARAM_NAMES.has(p.name));\n  const optionsType = extraParams.length > 0 ? paginatedOptionsName(method, resolvedServiceName) : 'PaginationOptions';\n  // When any extension param has a camelCase/snake_case divergence, the\n  // resource file emits a `serialize<OptionsName>` helper — pass it to\n  // createPaginatedList so the wire query uses snake_case keys.\n  const needsWireSerializer = extraParams.some((p) => fieldName(p.name) !== wireFieldName(p.name));\n  const serializerArg = needsWireSerializer ? `, serialize${optionsType}` : '';\n\n  const pathParams = buildPathParams(op, specEnumNames);\n  const allParams = pathParams ? `${pathParams}, options?: ${optionsType}` : `options?: ${optionsType}`;\n\n  const wireType = wireInterfaceName(itemType);\n  const serializeCall = serializerArg ? `options ? serialize${optionsType}(options) : undefined` : 'options';\n\n  const paginationType = needsWireSerializer ? 'PaginationOptions' : optionsType;\n  lines.push(`  async ${method}(${allParams}): Promise<AutoPaginatable<${itemType}, ${paginationType}>> {`);\n  lines.push(`    return new AutoPaginatable(`);\n  lines.push(`      await fetchAndDeserialize<${wireType}, ${itemType}>(`);\n  lines.push(`        this.workos,`);\n  lines.push(`        ${pathStr},`);\n  lines.push(`        deserialize${itemType},`);\n  lines.push(`        ${serializeCall},`);\n  lines.push(`      ),`);\n  lines.push(`      (params) =>`);\n  lines.push(`        fetchAndDeserialize<${wireType}, ${itemType}>(`);\n  lines.push(`          this.workos,`);\n  lines.push(`          ${pathStr},`);\n  lines.push(`          deserialize${itemType},`);\n  lines.push(`          params,`);\n  lines.push(`        ),`);\n  lines.push(`      ${serializeCall},`);\n  lines.push(`    );`);\n  lines.push('  }');\n}\n\nfunction renderDeleteMethod(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  pathStr: string,\n  specEnumNames?: Set<string>,\n): void {\n  const params = buildPathParams(op, specEnumNames);\n  lines.push(`  async ${method}(${params}): Promise<void> {`);\n  lines.push(`    await this.workos.delete(${pathStr});`);\n  lines.push('  }');\n}\n\nfunction renderDeleteWithBodyMethod(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  pathStr: string,\n  ctx: EmitterContext,\n  specEnumNames?: Set<string>,\n): void {\n  const bodyInfo = extractRequestBodyType(op, ctx);\n  let requestType: string;\n  let bodyExpr: string;\n  let entityType: string;\n  if (bodyInfo?.kind === 'model') {\n    requestType = resolveInterfaceName(bodyInfo.name, ctx);\n    bodyExpr = bodyArgExpr(bodyInfo.name, requestType, ctx);\n    entityType = requestEntityType(bodyExpr, requestType);\n  } else if (bodyInfo?.kind === 'union') {\n    requestType = bodyInfo.typeStr;\n    if (bodyInfo.discriminator) {\n      bodyExpr = renderUnionBodySerializer(bodyInfo.discriminator, ctx);\n    } else {\n      bodyExpr = renderNonDiscriminatedUnionBodySerializer(bodyInfo.modelNames, ctx);\n    }\n    entityType = unionEntityType(bodyInfo.modelNames, ctx);\n  } else {\n    requestType = 'Record<string, unknown>';\n    bodyExpr = 'payload';\n    entityType = requestType;\n  }\n\n  const paramParts: string[] = [];\n  for (const param of op.pathParams) {\n    paramParts.push(\n      `${fieldName(param.name)}: ${specEnumNames ? mapParamType(param.type, specEnumNames) : mapTypeRef(param.type)}`,\n    );\n  }\n  paramParts.push(`payload: ${requestType}`);\n\n  lines.push(`  async ${method}(${paramParts.join(', ')}): Promise<void> {`);\n  lines.push(`    await this.workos.deleteWithBody<${entityType}>(${pathStr}, ${bodyExpr});`);\n  lines.push('  }');\n}\n\nfunction renderBodyMethod(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  responseModel: string,\n  pathStr: string,\n  ctx: EmitterContext,\n  specEnumNames?: Set<string>,\n): void {\n  const bodyInfo = extractRequestBodyType(op, ctx);\n  let requestType: string;\n  let bodyExpr: string;\n  let entityType: string;\n  if (bodyInfo?.kind === 'model') {\n    requestType = resolveInterfaceName(bodyInfo.name, ctx);\n    bodyExpr = bodyArgExpr(bodyInfo.name, requestType, ctx);\n    entityType = requestEntityType(bodyExpr, requestType);\n  } else if (bodyInfo?.kind === 'union') {\n    requestType = bodyInfo.typeStr;\n    if (bodyInfo.discriminator) {\n      bodyExpr = renderUnionBodySerializer(bodyInfo.discriminator, ctx);\n    } else {\n      bodyExpr = renderNonDiscriminatedUnionBodySerializer(bodyInfo.modelNames, ctx);\n    }\n    entityType = unionEntityType(bodyInfo.modelNames, ctx);\n  } else {\n    requestType = 'Record<string, unknown>';\n    bodyExpr = 'payload';\n    entityType = requestType;\n  }\n\n  const paramParts: string[] = [];\n\n  // Always pass path params as individual parameters (matches existing SDK pattern)\n  for (const param of op.pathParams) {\n    paramParts.push(\n      `${fieldName(param.name)}: ${specEnumNames ? mapParamType(param.type, specEnumNames) : mapTypeRef(param.type)}`,\n    );\n  }\n\n  paramParts.push(`payload: ${requestType}`);\n\n  if (plan.isIdempotentPost) {\n    paramParts.push('requestOptions: PostOptions = {}');\n  }\n\n  const paramsStr = paramParts.join(', ');\n\n  // Fix 2: Pass encoding option when requestBodyEncoding is non-json\n  const encoding = op.requestBodyEncoding;\n  const encodingOption = encoding && encoding !== 'json' ? `, encoding: '${encoding}' as const` : '';\n  const hasCustomEncoding = encodingOption !== '';\n\n  const returnType = plan.isArrayResponse ? `${responseModel}[]` : responseModel;\n  const wireType = plan.isArrayResponse ? `${wireInterfaceName(responseModel)}[]` : wireInterfaceName(responseModel);\n  const returnExpr = plan.isArrayResponse\n    ? `data.map(deserialize${responseModel})`\n    : `deserialize${responseModel}(data)`;\n\n  lines.push(`  async ${method}(${paramsStr}): Promise<${returnType}> {`);\n  if (plan.isIdempotentPost) {\n    if (hasCustomEncoding) {\n      lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}, ${entityType}>(`);\n      lines.push(`      ${pathStr},`);\n      lines.push(`      ${bodyExpr},`);\n      lines.push(`      { ...requestOptions${encodingOption} },`);\n      lines.push('    );');\n    } else {\n      lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}, ${entityType}>(`);\n      lines.push(`      ${pathStr},`);\n      lines.push(`      ${bodyExpr},`);\n      lines.push('      requestOptions,');\n      lines.push('    );');\n    }\n  } else {\n    if (hasCustomEncoding) {\n      lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}, ${entityType}>(`);\n      lines.push(`      ${pathStr},`);\n      lines.push(`      ${bodyExpr},`);\n      lines.push(`      { ${encodingOption.slice(2)} },`);\n      lines.push('    );');\n    } else {\n      lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}, ${entityType}>(`);\n      lines.push(`      ${pathStr},`);\n      lines.push(`      ${bodyExpr},`);\n      lines.push('    );');\n    }\n  }\n  lines.push(`    return ${returnExpr};`);\n  lines.push('  }');\n}\n\nfunction renderGetMethod(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  responseModel: string,\n  pathStr: string,\n  specEnumNames?: Set<string>,\n  resolvedOp?: ResolvedOperation,\n): void {\n  const hiddenParams = new Set<string>([\n    ...Object.keys(getOpDefaults(resolvedOp)),\n    ...getOpInferFromClient(resolvedOp),\n  ]);\n\n  const params = buildPathParams(op, specEnumNames);\n  const visibleQueryParams = op.queryParams.filter((p) => !hiddenParams.has(p.name));\n  const hasVisibleQuery = visibleQueryParams.length > 0 && !plan.isPaginated;\n  const hasDefaults = Object.keys(getOpDefaults(resolvedOp)).length > 0;\n  const hasInferred = getOpInferFromClient(resolvedOp).length > 0;\n  const hasInjected = hasDefaults || hasInferred;\n  const hasQuery = (op.queryParams.length > 0 && !plan.isPaginated) || hasInjected;\n  const optionsType = hasVisibleQuery ? toPascalCase(method) + 'Options' : null;\n\n  const allParams = optionsType\n    ? params\n      ? `${params}, options?: ${optionsType}`\n      : `options?: ${optionsType}`\n    : params;\n\n  const returnType = plan.isArrayResponse ? `${responseModel}[]` : responseModel;\n  const wireType = plan.isArrayResponse ? `${wireInterfaceName(responseModel)}[]` : wireInterfaceName(responseModel);\n  const returnExpr = plan.isArrayResponse\n    ? `data.map(deserialize${responseModel})`\n    : `deserialize${responseModel}(data)`;\n\n  lines.push(`  async ${method}(${allParams}): Promise<${returnType}> {`);\n  if (hasQuery) {\n    if (hasInjected) {\n      // Build the query object with visible params, defaults, and inferred fields\n      const queryParts: string[] = [];\n\n      // Regular visible query params (from options)\n      if (hasVisibleQuery) {\n        for (const param of visibleQueryParams) {\n          const camel = fieldName(param.name);\n          const snake = wireFieldName(param.name);\n          if (camel === snake) {\n            if (param.required) {\n              queryParts.push(`${camel}: options.${camel}`);\n            } else {\n              queryParts.push(`...(options?.${camel} !== undefined && { ${camel}: options.${camel} })`);\n            }\n          } else {\n            if (param.required) {\n              queryParts.push(`${snake}: options.${camel}`);\n            } else {\n              queryParts.push(`...(options?.${camel} !== undefined && { ${snake}: options.${camel} })`);\n            }\n          }\n        }\n      }\n\n      // Constant defaults (e.g., response_type: 'code')\n      for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n        queryParts.push(`${key}: ${tsLiteral(value)}`);\n      }\n\n      // Inferred fields from client config (e.g., client_id from this.workos.options.clientId)\n      for (const field of getOpInferFromClient(resolvedOp)) {\n        queryParts.push(`${field}: ${clientFieldExpression(field)}`);\n      }\n\n      lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}>(${pathStr}, {`);\n      lines.push(`      query: { ${queryParts.join(', ')} },`);\n      lines.push('    });');\n    } else {\n      const queryExpr = renderQueryExpr(visibleQueryParams);\n      lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}>(${pathStr}, {`);\n      lines.push(`      query: ${queryExpr},`);\n      lines.push('    });');\n    }\n  } else if (httpMethodNeedsBody(op.httpMethod)) {\n    // PUT/PATCH/POST require a body argument even when the spec has no request body\n    lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}>(${pathStr}, {});`);\n  } else {\n    lines.push(`    const { data } = await this.workos.${op.httpMethod}<${wireType}>(${pathStr});`);\n  }\n  lines.push(`    return ${returnExpr};`);\n  lines.push('  }');\n}\n\n/** Convert a JS value to a TypeScript literal. */\nfunction tsLiteral(value: string | number | boolean): string {\n  if (typeof value === 'string') return `'${value.replace(/'/g, \"\\\\'\")}'`;\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  return String(value);\n}\n\n/** Get the TypeScript expression for reading a client config field. */\nfunction clientFieldExpression(field: string): string {\n  switch (field) {\n    case 'client_id':\n      return 'this.workos.options.clientId';\n    case 'client_secret':\n      return 'this.workos.key';\n    default:\n      return `this.workos.${toCamelCase(field)}`;\n  }\n}\n\n/**\n * Compose a `` `${this.workos.baseURL}<path>[?${query}]` `` template literal from\n * a path expression produced by {@link buildPathStr}. The path expression is\n * either a single-quoted static literal (`'/sso/authorize'`) or a backtick\n * template with interpolated path params; either way its inner body is spliced\n * into the URL template.\n */\nfunction urlTemplateLiteral(pathExpr: string, hasQuery: boolean): string {\n  let inner: string;\n  if ((pathExpr.startsWith('`') && pathExpr.endsWith('`')) || (pathExpr.startsWith(\"'\") && pathExpr.endsWith(\"'\"))) {\n    inner = pathExpr.slice(1, -1);\n  } else {\n    inner = '${' + pathExpr + '}';\n  }\n  return '`${this.workos.baseURL}' + inner + (hasQuery ? '?${query}' : '') + '`';\n}\n\n/**\n * Emit a URL-builder method for an operation marked with the `urlBuilder` hint\n * (OAuth-style redirect endpoints such as `/sso/authorize`). The method is\n * synchronous, returns the constructed URL as a string, and makes no HTTP call.\n * Visible query params, constant `defaults`, and `inferFromClient` fields are\n * serialized via `toQueryString` (wire-name keyed), matching the SDK's\n * hand-written URL builders.\n */\nfunction renderUrlBuilderMethod(\n  lines: string[],\n  op: Operation,\n  method: string,\n  pathStr: string,\n  optionInfo: OptionsObjectParam | undefined,\n  specEnumNames: Set<string> | undefined,\n  resolvedOp: ResolvedOperation | undefined,\n): void {\n  const hidden = hiddenParamsFor(resolvedOp);\n  const visibleQueryParams = op.queryParams.filter((p) => !hidden.has(p.name));\n  const hasQuery =\n    visibleQueryParams.length > 0 ||\n    Object.keys(getOpDefaults(resolvedOp)).length > 0 ||\n    getOpInferFromClient(resolvedOp).length > 0;\n\n  // Concise JSDoc — url builders return a string, not a Promise.\n  {\n    const docParts: string[] = [];\n    if (op.description) docParts.push(op.description);\n    docParts.push('@returns {string} The constructed URL.');\n    if (op.deprecated) docParts.push('@deprecated');\n    const allLines = docParts.flatMap((p) => p.split('\\n'));\n    if (allLines.length === 1) {\n      lines.push(`  /** ${allLines[0]} */`);\n    } else {\n      lines.push('  /**');\n      for (const line of allLines) lines.push(line === '' ? '   *' : `   * ${line}`);\n      lines.push('   */');\n    }\n  }\n\n  if (optionInfo) {\n    // Options-object convention (matches the surrounding generated methods).\n    lines.push(`  ${method}(${renderOptionsParam(optionInfo)}): string {`);\n    if (hasQuery) {\n      const queryExpr = renderQueryExprWithOptions(visibleQueryParams, optionInfo.optional, resolvedOp);\n      lines.push(`    const query = toQueryString(${queryExpr});`);\n      lines.push(`    return ${urlTemplateLiteral(pathStr, true)};`);\n    } else {\n      lines.push(`    return ${urlTemplateLiteral(pathStr, false)};`);\n    }\n    lines.push('  }');\n    return;\n  }\n\n  // Positional convention (path-only url builders, possibly with injected fields).\n  // Invariant: any visible query param forces the options-object branch above\n  // (operationHasOptionsInput is true whenever one exists), so a positional\n  // builder never declares query params in its signature. Fail loudly if a\n  // future spec breaks that — its query value would have to come from an\n  // undeclared parameter. Past this guard the query is assembled solely from\n  // injected defaults and inferFromClient fields.\n  if (visibleQueryParams.length > 0) {\n    throw new Error(\n      `renderUrlBuilderMethod: positional url builder \"${method}\" has visible query params ` +\n        `(${visibleQueryParams.map((p) => p.name).join(', ')}) but no options object; they would be ` +\n        'referenced without being declared. Expected the options-object convention.',\n    );\n  }\n  const params = buildPathParams(op, specEnumNames);\n  lines.push(`  ${method}(${params}): string {`);\n  if (hasQuery) {\n    const queryParts: string[] = [];\n    for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n      queryParts.push(`${key}: ${tsLiteral(value)}`);\n    }\n    for (const field of getOpInferFromClient(resolvedOp)) {\n      queryParts.push(`${field}: ${clientFieldExpression(field)}`);\n    }\n    lines.push(`    const query = toQueryString({ ${queryParts.join(', ')} });`);\n    lines.push(`    return ${urlTemplateLiteral(pathStr, true)};`);\n  } else {\n    lines.push(`    return ${urlTemplateLiteral(pathStr, false)};`);\n  }\n  lines.push('  }');\n}\n\nfunction renderVoidMethod(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  pathStr: string,\n  ctx: EmitterContext,\n  specEnumNames?: Set<string>,\n  resolvedOp?: ResolvedOperation,\n): void {\n  const hiddenParams = new Set<string>([\n    ...Object.keys(getOpDefaults(resolvedOp)),\n    ...getOpInferFromClient(resolvedOp),\n  ]);\n\n  const params = buildPathParams(op, specEnumNames);\n  const visibleQueryParams = op.queryParams.filter((p) => !hiddenParams.has(p.name));\n  const hasVisibleQuery = visibleQueryParams.length > 0 && !plan.hasBody;\n  const hasDefaults = Object.keys(getOpDefaults(resolvedOp)).length > 0;\n  const hasInferred = getOpInferFromClient(resolvedOp).length > 0;\n  const hasInjected = hasDefaults || hasInferred;\n  const hasQuery = hasVisibleQuery || (hasInjected && !plan.hasBody);\n  const optionsType = hasVisibleQuery ? toPascalCase(method) + 'Options' : null;\n\n  let bodyParam = '';\n  let bodyExpr = 'payload';\n  let entityType = 'Record<string, unknown>';\n  if (plan.hasBody) {\n    const bodyInfo = extractRequestBodyType(op, ctx);\n    if (bodyInfo?.kind === 'model') {\n      const requestType = resolveInterfaceName(bodyInfo.name, ctx);\n      bodyParam = `payload: ${requestType}`;\n      bodyExpr = bodyArgExpr(bodyInfo.name, requestType, ctx);\n      entityType = requestEntityType(bodyExpr, requestType);\n    } else if (bodyInfo?.kind === 'union') {\n      bodyParam = `payload: ${bodyInfo.typeStr}`;\n      if (bodyInfo.discriminator) {\n        bodyExpr = renderUnionBodySerializer(bodyInfo.discriminator, ctx);\n      } else {\n        bodyExpr = renderNonDiscriminatedUnionBodySerializer(bodyInfo.modelNames, ctx);\n      }\n      entityType = unionEntityType(bodyInfo.modelNames, ctx);\n    } else {\n      bodyParam = 'payload: Record<string, unknown>';\n      bodyExpr = 'payload';\n      entityType = 'Record<string, unknown>';\n    }\n  }\n\n  const paramParts: string[] = [];\n  if (params) paramParts.push(params);\n  if (bodyParam) paramParts.push(bodyParam);\n  if (optionsType) paramParts.push(`options?: ${optionsType}`);\n  const allParams = paramParts.join(', ');\n\n  lines.push(`  async ${method}(${allParams}): Promise<void> {`);\n  if (plan.hasBody) {\n    lines.push(`    await this.workos.${op.httpMethod}<void, ${entityType}>(${pathStr}, ${bodyExpr});`);\n  } else if (hasQuery) {\n    if (hasInjected) {\n      // Build query object with visible params, defaults, and inferred fields\n      const queryParts: string[] = [];\n\n      if (hasVisibleQuery) {\n        for (const param of visibleQueryParams) {\n          const camel = fieldName(param.name);\n          const snake = wireFieldName(param.name);\n          if (camel === snake) {\n            if (param.required) {\n              queryParts.push(`${camel}: options.${camel}`);\n            } else {\n              queryParts.push(`...(options?.${camel} !== undefined && { ${camel}: options.${camel} })`);\n            }\n          } else {\n            if (param.required) {\n              queryParts.push(`${snake}: options.${camel}`);\n            } else {\n              queryParts.push(`...(options?.${camel} !== undefined && { ${snake}: options.${camel} })`);\n            }\n          }\n        }\n      }\n\n      for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n        queryParts.push(`${key}: ${tsLiteral(value)}`);\n      }\n\n      for (const field of getOpInferFromClient(resolvedOp)) {\n        queryParts.push(`${field}: ${clientFieldExpression(field)}`);\n      }\n\n      lines.push(`    await this.workos.${op.httpMethod}(${pathStr}, {`);\n      lines.push(`      query: { ${queryParts.join(', ')} },`);\n      lines.push('    });');\n    } else {\n      const queryExpr = renderQueryExpr(visibleQueryParams);\n      lines.push(`    await this.workos.${op.httpMethod}(${pathStr}, {`);\n      lines.push(`      query: ${queryExpr},`);\n      lines.push('    });');\n    }\n  } else if (httpMethodNeedsBody(op.httpMethod)) {\n    lines.push(`    await this.workos.${op.httpMethod}(${pathStr}, {});`);\n  } else {\n    lines.push(`    await this.workos.${op.httpMethod}(${pathStr});`);\n  }\n  lines.push('  }');\n}\n\n/**\n * Generate an inline query serialization expression that maps camelCase option\n * keys to their snake_case wire equivalents.  When all keys already match\n * (camel === snake), returns 'options' as-is for brevity.\n */\nfunction renderQueryExpr(queryParams: { name: string; required: boolean }[]): string {\n  // Check if any key actually needs conversion\n  const needsConversion = queryParams.some((p) => fieldName(p.name) !== wireFieldName(p.name));\n  if (!needsConversion) return 'options';\n\n  const parts: string[] = [];\n  for (const param of queryParams) {\n    const camel = fieldName(param.name);\n    const snake = wireFieldName(param.name);\n    if (param.required) {\n      parts.push(`${snake}: options.${camel}`);\n    } else {\n      parts.push(`...(options.${camel} !== undefined && { ${snake}: options.${camel} })`);\n    }\n  }\n  return `options ? { ${parts.join(', ')} } : undefined`;\n}\n\nfunction renderQueryExprWithOptions(\n  queryParams: { name: string; required: boolean }[],\n  optional: boolean,\n  resolvedOp?: ResolvedOperation,\n): string {\n  const parts: string[] = [];\n  for (const param of queryParams) {\n    const camel = fieldName(param.name);\n    const snake = wireFieldName(param.name);\n    const access = optional ? `options?.${camel}` : `options.${camel}`;\n    if (param.required) {\n      parts.push(`${snake}: ${access}`);\n    } else {\n      parts.push(`...(${access} !== undefined && { ${snake}: ${access} })`);\n    }\n  }\n  for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n    parts.push(`${key}: ${tsLiteral(value)}`);\n  }\n  for (const field of getOpInferFromClient(resolvedOp)) {\n    parts.push(`${field}: ${clientFieldExpression(field)}`);\n  }\n  if (parts.length === 0) return optional ? 'options' : '{}';\n  return `{ ${parts.join(', ')} }`;\n}\n\nfunction buildPathStr(op: Operation, paramNameMap?: Map<string, string>): string {\n  return buildNodePathExpression(op.path, paramNameMap);\n}\n\nfunction buildPathParams(op: Operation, specEnumNames?: Set<string>): string {\n  // Start with declared path params\n  const declaredNames = new Set(op.pathParams.map((p) => fieldName(p.name)));\n  const params = op.pathParams.map((p) => {\n    const type = specEnumNames ? mapParamType(p.type, specEnumNames) : mapTypeRef(p.type);\n    return `${fieldName(p.name)}: ${type}`;\n  });\n\n  // Detect path template variables not in declared pathParams and add them as string params.\n  // This handles cases where the spec path has {param} but pathParams is incomplete.\n  const templateVars = [...op.path.matchAll(/\\{(\\w+)\\}/g)].map(([, name]) => fieldName(name));\n  for (const varName of templateVars) {\n    if (!declaredNames.has(varName)) {\n      params.push(`${varName}: string`);\n    }\n  }\n\n  return params.join(', ');\n}\n\n/**\n * Walk a parameter's type tree and collect enum/model names for imports.\n * Handles arrays and nullable wrappers that may contain nested enums/models.\n */\nfunction collectParamTypeRefs(type: TypeRef, enums: Set<string>, models: Set<string>): void {\n  switch (type.kind) {\n    case 'enum':\n      enums.add(type.name);\n      break;\n    case 'model':\n      models.add(type.name);\n      break;\n    case 'array':\n      collectParamTypeRefs(type.items, enums, models);\n      break;\n    case 'nullable':\n      collectParamTypeRefs(type.inner, enums, models);\n      break;\n  }\n}\n\n/**\n * Extract request body type info, supporting both single models and union types.\n * Returns structured info so callers can handle imports and serialization appropriately.\n */\n/**\n * Generate an IIFE expression that dispatches to the correct serializer for a\n * discriminated union request body.  Switches on the camelCase discriminator\n * property of the domain object and calls the appropriate serialize function\n * for each mapped model variant.\n */\nfunction renderUnionBodySerializer(\n  disc: { property: string; mapping: Record<string, string> },\n  ctx: EmitterContext,\n): string {\n  const prop = fieldName(disc.property);\n  const cases: string[] = [];\n  for (const [value, modelName] of Object.entries(disc.mapping)) {\n    const resolved = resolveInterfaceName(modelName, ctx);\n    // Switch on a typed discriminator narrows `payload` to the variant, so the\n    // serializer call type-checks without any casts.\n    cases.push(`case '${value}': return serialize${resolved}(payload)`);\n  }\n  // Assign `payload` to `never` in the default branch to get a compile-time\n  // exhaustiveness check — if a new variant is added to the union but not to\n  // the switch, the build fails here.  At runtime, we still throw so an\n  // unknown discriminator slipping through via `as any` fails loudly rather\n  // than silently forwarding camelCase to the API.\n  return `(() => { switch (payload.${prop}) { ${cases.join('; ')}; default: { const _unknown: never = payload; throw new Error(\\`Unknown ${prop}: \\${(_unknown as { ${prop}?: unknown }).${prop}}\\`) } } })()`;\n}\n\n/**\n * Generate an IIFE expression that dispatches to the correct serializer for a\n * non-discriminated union request body.  Inspects model fields to find a\n * required field unique to each variant and uses `'field' in payload` guards.\n * Falls back to `payload` only when no variant can be distinguished.\n */\nfunction renderNonDiscriminatedUnionBodySerializer(modelNames: string[], ctx: EmitterContext): string {\n  const modelMap = new Map(ctx.spec.models.map((m) => [m.name, m]));\n\n  // Try to detect an implicit discriminator: a required field present in all\n  // variants whose type is `kind: 'literal'` with a distinct value per variant.\n  // This covers oneOf unions where each variant has e.g. `grant_type: 'authorization_code'`.\n  const implicitDisc = detectImplicitDiscriminator(modelNames, modelMap);\n  if (implicitDisc) {\n    return renderUnionBodySerializer(implicitDisc, ctx);\n  }\n\n  // Collect required field names per model (using camelCase domain names).\n  const requiredFieldsByModel = new Map<string, Set<string>>();\n  for (const name of modelNames) {\n    const model = modelMap.get(name);\n    if (!model) return 'payload';\n    requiredFieldsByModel.set(name, new Set(model.fields.filter((f) => f.required).map((f) => fieldName(f.name))));\n  }\n\n  // For each model, find a required field that no other model has.\n  const guards: Array<{ modelName: string; field: string }> = [];\n  let fallbackModel: string | undefined;\n\n  for (const name of modelNames) {\n    const myFields = requiredFieldsByModel.get(name)!;\n    let uniqueField: string | undefined;\n    for (const field of myFields) {\n      const isUnique = modelNames.every((other) => other === name || !requiredFieldsByModel.get(other)?.has(field));\n      if (isUnique) {\n        uniqueField = field;\n        break;\n      }\n    }\n    if (uniqueField) {\n      guards.push({ modelName: name, field: uniqueField });\n    } else if (!fallbackModel) {\n      fallbackModel = name;\n    } else {\n      // Multiple models with no unique field — can't dispatch\n      return 'payload';\n    }\n  }\n\n  if (guards.length === 0) return 'payload';\n\n  const parts: string[] = [];\n  for (const { modelName, field } of guards) {\n    const resolved = resolveInterfaceName(modelName, ctx);\n    parts.push(`if ('${field}' in payload) return serialize${resolved}(payload as any)`);\n  }\n  if (fallbackModel) {\n    const resolved = resolveInterfaceName(fallbackModel, ctx);\n    parts.push(`return serialize${resolved}(payload as any)`);\n  } else {\n    parts.push('return payload');\n  }\n\n  return `(() => { ${parts.join('; ')} })()`;\n}\n\n/**\n * Detect an implicit discriminator from literal-typed fields.\n * Returns a discriminator descriptor if all variants share a required field\n * whose type is `kind: 'literal'` with a distinct value per variant.\n */\nfunction detectImplicitDiscriminator(\n  modelNames: string[],\n  modelMap: Map<string, Model>,\n): { property: string; mapping: Record<string, string> } | null {\n  if (modelNames.length < 2) return null;\n\n  const firstModel = modelMap.get(modelNames[0]);\n  if (!firstModel) return null;\n\n  // Candidate fields: required fields with literal type in the first model.\n  const candidates = firstModel.fields.filter((f) => f.required && f.type.kind === 'literal');\n\n  for (const candidate of candidates) {\n    const mapping: Record<string, string> = {};\n    const values = new Set<string | number | boolean | null>();\n    let valid = true;\n\n    for (const name of modelNames) {\n      const model = modelMap.get(name);\n      if (!model) {\n        valid = false;\n        break;\n      }\n      const field = model.fields.find((f) => f.name === candidate.name);\n      if (!field || !field.required || field.type.kind !== 'literal') {\n        valid = false;\n        break;\n      }\n      const val = field.type.value;\n      if (values.has(val)) {\n        valid = false;\n        break;\n      } // duplicate value\n      values.add(val);\n      mapping[String(val)] = name;\n    }\n\n    if (valid && Object.keys(mapping).length === modelNames.length) {\n      return { property: candidate.name, mapping };\n    }\n  }\n\n  return null;\n}\n\n/** Return type for extractRequestBodyType when the body is a union. */\ninterface UnionBodyInfo {\n  kind: 'union';\n  typeStr: string;\n  modelNames: string[];\n  discriminator?: { property: string; mapping: Record<string, string> };\n}\n\nfunction extractRequestBodyType(\n  op: Operation,\n  ctx: EmitterContext,\n): { kind: 'model'; name: string } | UnionBodyInfo | null {\n  if (!op.requestBody) return null;\n  if (op.requestBody.kind === 'model') return { kind: 'model', name: op.requestBody.name };\n  if (op.requestBody.kind === 'union') {\n    const modelNames: string[] = [];\n    for (const variant of op.requestBody.variants) {\n      if (variant.kind === 'model') modelNames.push(variant.name);\n    }\n    if (modelNames.length > 0) {\n      const typeStr = modelNames.map((n) => resolveInterfaceName(n, ctx)).join(' | ');\n      return {\n        kind: 'union',\n        typeStr,\n        modelNames,\n        discriminator: op.requestBody.discriminator,\n      };\n    }\n  }\n  return null;\n}\n\n/**\n * Map a parameter type to a TypeScript type string, handling inline enums\n * that don't have corresponding global enum definitions.  These would\n * otherwise emit bare names like `Type` or `Action` that are never imported.\n *\n * Recursively handles container types (arrays, nullable) so that inline\n * enums nested inside e.g. `array<enum>` are also inlined as string literal unions.\n */\nfunction mapParamType(type: TypeRef, specEnumNames: Set<string>): string {\n  if (type.kind === 'enum' && !specEnumNames.has(type.name)) {\n    // Inline enum with no generated file — render values as string literal union\n    if (type.values && type.values.length > 0) {\n      return type.values.map((v: string | number) => (typeof v === 'string' ? `'${v}'` : String(v))).join(' | ');\n    }\n    return 'string';\n  }\n  if (type.kind === 'array') {\n    const inner = mapParamType(type.items, specEnumNames);\n    // Parenthesize union types when used as array element type\n    return inner.includes(' | ') ? `(${inner})[]` : `${inner}[]`;\n  }\n  if (type.kind === 'nullable') {\n    return `${mapParamType(type.inner, specEnumNames)} | null`;\n  }\n  return mapTypeRef(type);\n}\n","import type { Model, TypeRef, Enum, EmitterContext } from '@workos/oagen';\nimport { wireFieldName, fileName, resolveServiceDir } from './naming.js';\nimport { resolveResourceClassName, resolveResourceDir } from './resources.js';\nimport {\n  createServiceDirResolver,\n  assignModelsToServices,\n  isListMetadataModel,\n  isListWrapperModel,\n  collectNonPaginatedResponseModelNames,\n  collectReferencedListMetadataModels,\n} from './utils.js';\n\nexport const ID_PREFIXES: Record<string, string> = {\n  Connection: 'conn_',\n  Organization: 'org_',\n  OrganizationMembership: 'om_',\n  User: 'user_',\n  Directory: 'directory_',\n  DirectoryGroup: 'dir_grp_',\n  DirectoryUser: 'dir_usr_',\n  Invitation: 'inv_',\n  Session: 'session_',\n  AuthenticationFactor: 'auth_factor_',\n  EmailVerification: 'email_verification_',\n  MagicAuth: 'magic_auth_',\n  PasswordReset: 'password_reset_',\n};\n\nexport function generateFixtures(\n  spec: {\n    models: Model[];\n    enums: Enum[];\n    services: any[];\n  },\n  ctx?: EmitterContext,\n): { path: string; content: string }[] {\n  if (spec.models.length === 0) return [];\n\n  const { modelToService, resolveDir } = ctx\n    ? createServiceDirResolver(spec.models, ctx.spec.services, ctx)\n    : {\n        modelToService: assignModelsToServices(spec.models, spec.services),\n        resolveDir: (irService: string | undefined) => (irService ? resolveServiceDir(irService) : 'common'),\n      };\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n  const files: { path: string; content: string }[] = [];\n\n  const fixtureSeeds = new Set<string>();\n  for (const svc of spec.services) {\n    if (svc.name.toLowerCase() === 'events') continue;\n    for (const op of svc.operations) {\n      const collectFromRef = (t: TypeRef | undefined): void => {\n        if (!t) return;\n        if (t.kind === 'model') fixtureSeeds.add(t.name);\n        if (t.kind === 'array') collectFromRef(t.items);\n        if (t.kind === 'nullable') collectFromRef(t.inner);\n        if (t.kind === 'union') t.variants.forEach(collectFromRef);\n      };\n      collectFromRef(op.response);\n      collectFromRef(op.requestBody);\n      if (op.pagination?.itemType) collectFromRef(op.pagination.itemType);\n    }\n  }\n  const fixtureModelMap = new Map(spec.models.map((m: Model) => [m.name, m]));\n  const fixtureReachable = new Set<string>();\n  const fixtureQueue = [...fixtureSeeds];\n  while (fixtureQueue.length > 0) {\n    const name = fixtureQueue.pop()!;\n    if (fixtureReachable.has(name)) continue;\n    fixtureReachable.add(name);\n    const m = fixtureModelMap.get(name);\n    if (!m) continue;\n    for (const field of m.fields) {\n      const walk = (t: TypeRef): void => {\n        if (t.kind === 'model' && !fixtureReachable.has(t.name)) fixtureQueue.push(t.name);\n        if (t.kind === 'array') walk(t.items);\n        if (t.kind === 'nullable') walk(t.inner);\n        if (t.kind === 'union') t.variants.forEach(walk);\n      };\n      walk(field.type);\n    }\n  }\n\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(spec.services);\n  const listMetadataNeeded = collectReferencedListMetadataModels(spec.models, nonPaginatedRefs);\n\n  const seenFixturePaths = new Set<string>();\n  for (const model of spec.models) {\n    if (!fixtureReachable.has(model.name)) continue;\n    if (isListMetadataModel(model) && !listMetadataNeeded.has(model.name)) continue;\n    if (isListWrapperModel(model) && !nonPaginatedRefs.has(model.name)) continue;\n\n    const service = modelToService.get(model.name);\n    const dirName = resolveDir(service);\n    const fixturePath = `src/${dirName}/fixtures/${fileName(model.name)}.json`;\n\n    if (seenFixturePaths.has(fixturePath)) continue;\n    seenFixturePaths.add(fixturePath);\n\n    const fixture = generateModelFixture(model, modelMap, enumMap);\n\n    files.push({\n      path: fixturePath,\n      content: JSON.stringify(fixture, null, 2),\n    });\n  }\n\n  for (const service of spec.services) {\n    const resolvedName = ctx ? resolveResourceClassName(service, ctx) : service.name;\n    const serviceDir = ctx ? resolveResourceDir(service, ctx) : resolveServiceDir(resolvedName);\n    for (const op of service.operations) {\n      if (op.pagination) {\n        let itemModel = op.pagination.itemType.kind === 'model' ? modelMap.get(op.pagination.itemType.name) : null;\n        if (itemModel) {\n          const unwrapped = unwrapListModel(itemModel, modelMap);\n          if (unwrapped) {\n            itemModel = unwrapped;\n          }\n          const fixture = generateModelFixture(itemModel, modelMap, enumMap);\n          const listFixture = {\n            data: [fixture],\n            list_metadata: {\n              before: null,\n              after: null,\n            },\n          };\n          files.push({\n            path: `src/${serviceDir}/fixtures/list-${fileName(itemModel.name)}.json`,\n            content: JSON.stringify(listFixture, null, 2),\n          });\n        }\n      }\n    }\n  }\n\n  return files;\n}\n\nexport function unwrapListModel(model: Model, modelMap: Map<string, Model>): Model | null {\n  const dataField = model.fields.find((f) => f.name === 'data');\n  const hasListMetadata = model.fields.some((f) => f.name === 'list_metadata' || f.name === 'listMetadata');\n  if (dataField && hasListMetadata && dataField.type.kind === 'array') {\n    const itemType = dataField.type.items;\n    if (itemType.kind === 'model') {\n      return modelMap.get(itemType.name) ?? null;\n    }\n  }\n  return null;\n}\n\nexport function generateModelFixture(\n  model: Model,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): Record<string, any> {\n  const fixture: Record<string, any> = {};\n\n  for (const field of model.fields) {\n    const wireName = wireFieldName(field.name);\n    if (field.example !== undefined) {\n      fixture[wireName] = field.example;\n    } else {\n      fixture[wireName] = generateFieldValue(field.type, field.name, model.name, modelMap, enumMap);\n    }\n  }\n\n  if (model.discriminator) {\n    const [firstValue, variantName] = Object.entries(model.discriminator.mapping)[0];\n    fixture[wireFieldName(model.discriminator.property)] = firstValue;\n    const variantModel = modelMap.get(variantName);\n    if (variantModel) {\n      for (const field of variantModel.fields) {\n        const wireName = wireFieldName(field.name);\n        if (!(wireName in fixture)) {\n          fixture[wireName] =\n            field.example !== undefined\n              ? field.example\n              : generateFieldValue(field.type, field.name, model.name, modelMap, enumMap);\n        }\n      }\n    }\n  }\n\n  return fixture;\n}\n\nfunction generateFieldValue(\n  ref: TypeRef,\n  fName: string,\n  modelName: string,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): any {\n  switch (ref.kind) {\n    case 'primitive':\n      return generatePrimitiveValue(ref.type, ref.format, fName, modelName);\n    case 'literal':\n      return ref.value;\n    case 'enum': {\n      const e = enumMap.get(ref.name);\n      return e?.values[0]?.value ?? 'unknown';\n    }\n    case 'model': {\n      const nested = modelMap.get(ref.name);\n      if (nested) return generateModelFixture(nested, modelMap, enumMap);\n      return {};\n    }\n    case 'array': {\n      if (ref.items.kind === 'enum') {\n        const e = enumMap.get(ref.items.name);\n        if (e && e.values.length > 0) {\n          return e.values.map((v) => v.value);\n        }\n      }\n      const item = generateFieldValue(ref.items, fName, modelName, modelMap, enumMap);\n      return [item];\n    }\n    case 'nullable':\n      return generateFieldValue(ref.inner, fName, modelName, modelMap, enumMap);\n    case 'union':\n      if (ref.variants.length > 0) {\n        return generateFieldValue(ref.variants[0], fName, modelName, modelMap, enumMap);\n      }\n      return null;\n    case 'map':\n      return {\n        key: generateFieldValue(ref.valueType, 'value', modelName, modelMap, enumMap),\n      };\n  }\n}\n\nfunction generatePrimitiveValue(type: string, format: string | undefined, name: string, modelName: string): any {\n  switch (type) {\n    case 'string':\n      if (format === 'date-time') return '2023-01-01T00:00:00.000Z';\n      if (format === 'date') return '2023-01-01';\n      if (format === 'uuid') return '00000000-0000-0000-0000-000000000000';\n      if (name === 'id') {\n        const prefix = ID_PREFIXES[modelName] ?? '';\n        return `${prefix}01234`;\n      }\n      if (name.includes('id')) return `${name}_01234`;\n      if (name.includes('email')) return 'test@example.com';\n      if (name.includes('url') || name.includes('uri')) return 'https://example.com';\n      if (name.includes('name')) return 'Test';\n      return `test_${name}`;\n    case 'integer':\n      return 1;\n    case 'number':\n      return 1.0;\n    case 'boolean':\n      return true;\n    case 'unknown':\n      return {};\n    default:\n      return null;\n  }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Model, Field, TypeRef, EmitterContext, GeneratedFile, Operation, Service } from '@workos/oagen';\nimport { planOperation } from '@workos/oagen';\nimport { mapTypeRef, mapWireTypeRef, isInlineEnum } from './type-map.js';\nimport {\n  fieldName,\n  wireFieldName,\n  fileName,\n  resolveInterfaceName,\n  wireInterfaceName,\n  resolveMethodName,\n  isAdoptedModelName,\n  buildServiceNameMap,\n} from './naming.js';\nimport {\n  collectFieldDependencies,\n  docComment,\n  buildGenericModelDefaults,\n  pruneUnusedImports,\n  TS_BUILTINS,\n  buildKnownTypeNames,\n  isBaselineGeneric,\n  createServiceDirResolver,\n  isListMetadataModel,\n  isListWrapperModel,\n  collectNonPaginatedResponseModelNames,\n  collectReferencedListMetadataModels,\n  buildDeduplicationMap,\n  relativeImport,\n  modelHasNewFields,\n  computeNonEventReachable,\n  isServiceCoveredByExisting,\n  hasMethodsAbsentFromBaseline,\n} from './utils.js';\nimport { assignEnumsToServices } from './enums.js';\nimport {\n  renderSerializerTypeParams,\n  buildSerializerImports,\n  buildSkipFormatFields,\n  shouldSkipSerializeForModel,\n  emitSerializerBody,\n  hasDateTimeConversion,\n} from './field-plan.js';\nimport { liveSurfaceHasExistingSdk, liveSurfaceHasManagedFile, liveSurfaceInterfacePath } from './live-surface.js';\nimport { isNodeOwnedService, isHandOwnedType } from './options.js';\nimport { unwrapListModel } from './fixtures.js';\nimport { groupByMount, buildResolvedLookup, lookupResolved, isModelInScope } from '../shared/resolved-ops.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { collectWrapperResponseModels } from './wrappers.js';\nimport { resolveResourceClassName } from './resources.js';\n\n// ---------------------------------------------------------------------------\n// Shared context\n// ---------------------------------------------------------------------------\n\ninterface SharedModelContext {\n  modelToService: Map<string, string>;\n  resolveDir: (irService: string | undefined) => string;\n  dedup: Map<string, string>;\n  genericDefaults: Map<string, string>;\n}\n\ninterface GeneratedResourceModelUsage {\n  interfaceRoots: Set<string>;\n  serializerRoots: Set<string>;\n  /** Models that are directly used as a request body. Drive `serialize<X>`. */\n  requestRoots: Set<string>;\n  /** Models that are directly used as a response body. Drive `deserialize<X>`. */\n  responseRoots: Set<string>;\n}\n\nfunction buildSharedContext(models: Model[], ctx: EmitterContext): SharedModelContext {\n  const { modelToService, resolveDir } = createServiceDirResolver(models, ctx.spec.services, ctx);\n  const genericDefaults = buildGenericModelDefaults(ctx.spec.models);\n  enrichGenericDefaultsFromBaseline(genericDefaults, models, ctx, resolveDir, modelToService);\n  const nonEventReachable = computeNonEventReachable(ctx.spec.services, models);\n  const dedup = buildDeduplicationMap(models, ctx, nonEventReachable);\n  return { modelToService, resolveDir, dedup, genericDefaults };\n}\n\nfunction enrichGenericDefaultsFromBaseline(\n  genericDefaults: Map<string, string>,\n  models: Model[],\n  ctx: EmitterContext,\n  resolveDir: (irService: string | undefined) => string,\n  modelToService: Map<string, string>,\n): void {\n  if (!ctx.apiSurface?.interfaces) return;\n  const knownNames = buildKnownTypeNames(models, ctx);\n\n  for (const model of models) {\n    if (genericDefaults.has(model.name)) continue;\n    const domainName = resolveInterfaceName(model.name, ctx);\n    const baseline = ctx.apiSurface.interfaces[domainName];\n    if (!baseline?.fields) continue;\n\n    const generatedPath = `src/${resolveDir(modelToService.get(model.name))}/interfaces/${fileName(model.name)}.interface.ts`;\n    const baselineSourceFile = (baseline as any).sourceFile as string | undefined;\n    if (baselineSourceFile && baselineSourceFile !== generatedPath) continue;\n\n    if (isBaselineGeneric(baseline.fields, knownNames)) {\n      genericDefaults.set(model.name, '<Record<string, unknown>>');\n    }\n  }\n}\n\nfunction projectModelToManagedSurface(model: Model, shared: SharedModelContext, ctx: EmitterContext): Model {\n  if (!ctx.outputDir && !ctx.targetDir) return model;\n  if (!liveSurfaceHasExistingSdk()) return model;\n  const fields = model.fields.filter((field) => isSupportedFieldType(field.type, model.name, shared, ctx));\n  return fields.length === model.fields.length ? model : { ...model, fields };\n}\n\nfunction isSupportedFieldType(\n  ref: TypeRef,\n  ownerModelName: string,\n  shared: SharedModelContext,\n  ctx: EmitterContext,\n): boolean {\n  switch (ref.kind) {\n    case 'primitive':\n    case 'literal':\n    case 'map':\n      return true;\n    case 'model': {\n      if (ref.name === ownerModelName) return true;\n      const resolvedName = resolveInterfaceName(ref.name, ctx);\n      if (ctx.apiSurface?.interfaces?.[resolvedName] || ctx.apiSurface?.typeAliases?.[resolvedName]) return true;\n      // Adopted-service models will have their interfaces emitted in this\n      // same pass, so the field reference will resolve once writing is done.\n      // Without this, fields like `UserManagementLoginRequest.user` get\n      // silently dropped on first emission because the target interface\n      // (`UserObject` under the adopted `connect/` dir) hasn't landed yet.\n      if (isAdoptedModelName(ref.name)) return true;\n      // Synthetic models produced by `enrichModelsFromSpec` (e.g. the\n      // inline-object item type for `ConnectApplication.redirect_uris`)\n      // are added to the models list passed into this generation pass —\n      // and hence into `shared.modelToService` — but won't yet exist on\n      // disk or in `apiSurface`. Accept them so their parent field\n      // survives field-projection.\n      if (shared.modelToService.has(ref.name)) return true;\n      const relPath = `src/${shared.resolveDir(shared.modelToService.get(ref.name))}/interfaces/${fileName(ref.name)}.interface.ts`;\n      return liveSurfaceHasManagedFile(relPath);\n    }\n    case 'enum': {\n      if (ctx.apiSurface?.enums?.[ref.name] || ctx.apiSurface?.typeAliases?.[ref.name]) return true;\n      const enumService = assignEnumsToServices(ctx.spec.enums, ctx.spec.services, ctx.spec.models, ctx).get(ref.name);\n      if (enumService) return true;\n      const relPath = `src/${shared.resolveDir(enumService)}/interfaces/${fileName(ref.name)}.interface.ts`;\n      return liveSurfaceHasManagedFile(relPath);\n    }\n    case 'array':\n      return isSupportedFieldType(ref.items, ownerModelName, shared, ctx);\n    case 'nullable':\n      return isSupportedFieldType(ref.inner, ownerModelName, shared, ctx);\n    case 'union':\n      return ref.variants.every((variant) => isSupportedFieldType(variant, ownerModelName, shared, ctx));\n    default:\n      return true;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Interface generation\n// ---------------------------------------------------------------------------\n\nexport function generateModels(models: Model[], ctx: EmitterContext, shared?: SharedModelContext): GeneratedFile[] {\n  if (models.length === 0) return [];\n\n  const {\n    modelToService,\n    resolveDir,\n    dedup: sharedDedup,\n    genericDefaults: sharedDefaults,\n  } = shared ?? buildSharedContext(models, ctx);\n  const genericDefaults = sharedDefaults;\n  const typeRefOpts = { genericDefaults };\n  const wireTypeRefOpts = { genericDefaults };\n  const files: GeneratedFile[] = [];\n  const dedup = sharedDedup;\n  const projectedModels = models.map((model) =>\n    projectModelToManagedSurface(model, { modelToService, resolveDir, dedup, genericDefaults }, ctx),\n  );\n  const projectedByName = new Map(projectedModels.map((model) => [model.name, model]));\n  const resourceUsage = buildGeneratedResourceModelUsage(models, ctx);\n  const interfaceEligibleModels = resourceUsage\n    ? expandModelRoots(resourceUsage.interfaceRoots, projectedByName)\n    : undefined;\n\n  const reachableModels = computeNonEventReachable(ctx.spec.services, models);\n\n  const forceGenerate = new Set<string>();\n  for (const originalModel of models) {\n    const model = projectedByName.get(originalModel.name) ?? originalModel;\n    if (!reachableModels.has(model.name)) continue;\n    if (interfaceEligibleModels && !interfaceEligibleModels.has(model.name)) continue;\n    if (!modelHasNewFields(model, ctx)) continue;\n    const service = modelToService.get(model.name);\n    const dirName = resolveDir(service);\n    const parentPath = `src/${dirName}/interfaces/${fileName(model.name)}.interface.ts`;\n    const deps = collectFieldDependencies(model);\n    for (const dep of deps.models) {\n      if (forceGenerate.has(dep)) continue;\n      const depName = resolveInterfaceName(dep, ctx);\n      const depBaseline = ctx.apiSurface?.interfaces?.[depName];\n      const depSrc = (depBaseline as any)?.sourceFile as string | undefined;\n      if (depSrc === parentPath) {\n        forceGenerate.add(dep);\n      }\n    }\n  }\n\n  const discriminatedSkip = (ctx as { _discriminatedModelNames?: Set<string> })._discriminatedModelNames;\n  // Wrappers referenced as a non-paginated response (e.g. `VersionListResponse`\n  // for `GET /vault/v1/kv/{id}/versions`) must still be emitted — the resource\n  // code references them by name and pagination iterators don't unwrap them.\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(ctx.spec.services);\n\n  // ListMetadata-shape models are usually subsumed by the SDK's shared\n  // pagination wrapper, so we blanket-skip them. But a non-paginated\n  // wrapper like vault's `VersionListResponse` keeps the reference live\n  // (`list_metadata: ListMetadata`), and skipping the emission leaves the\n  // wrapper's interface importing from a file that was never written.\n  const listMetadataNeeded = collectReferencedListMetadataModels(models, nonPaginatedRefs);\n\n  for (const originalModel of models) {\n    const model = projectedByName.get(originalModel.name) ?? originalModel;\n    if (!reachableModels.has(model.name)) continue;\n    if (interfaceEligibleModels && !interfaceEligibleModels.has(model.name)) continue;\n    const service = modelToService.get(model.name);\n    const isOwnedModel = isNodeOwnedService(ctx, service);\n    if (!isOwnedModel && !modelHasNewFields(model, ctx) && !forceGenerate.has(model.name)) continue;\n    const canonicalName = dedup.get(model.name);\n    if (canonicalName) {\n      forceGenerate.add(canonicalName);\n      if (interfaceEligibleModels) interfaceEligibleModels.add(canonicalName);\n    }\n  }\n\n  for (const originalModel of models) {\n    const model = projectedByName.get(originalModel.name) ?? originalModel;\n    if (!reachableModels.has(model.name)) continue;\n    if (interfaceEligibleModels && !interfaceEligibleModels.has(model.name)) continue;\n    if (isListMetadataModel(model) && !listMetadataNeeded.has(model.name)) continue;\n    if (isListWrapperModel(model) && !nonPaginatedRefs.has(model.name)) continue;\n    if (discriminatedSkip?.has(model.name)) continue;\n    // Hand-owned types are declared in a hand-written file (e.g. generics the\n    // spec cannot express). Never generate an interface for them; references\n    // route to the existing declaration via its baseline source file.\n    if (\n      isHandOwnedType(ctx, model.name) ||\n      isHandOwnedType(ctx, resolveInterfaceName(model.name, ctx, { skipTypeAlias: true }))\n    )\n      continue;\n    const service = modelToService.get(model.name);\n    const isOwnedModel = isNodeOwnedService(ctx, service);\n    if (!isOwnedModel && !modelHasNewFields(model, ctx) && !forceGenerate.has(model.name)) continue;\n\n    const canonicalName = dedup.get(model.name);\n    if (canonicalName && !isOwnedModel) {\n      const dirName = resolveDir(service);\n      const skipTA = { skipTypeAlias: true };\n      const domainName = resolveInterfaceName(model.name, ctx, skipTA);\n      const responseName = wireInterfaceName(domainName);\n      const canonDomainName = resolveInterfaceName(canonicalName, ctx, skipTA);\n      const canonResponseName = wireInterfaceName(canonDomainName);\n\n      const canonService = modelToService.get(canonicalName);\n      const canonDir = resolveDir(canonService);\n\n      const aliasPath = `src/${dirName}/interfaces/${fileName(model.name)}.interface.ts`;\n      const canonPath = `src/${canonDir}/interfaces/${fileName(canonicalName)}.interface.ts`;\n      if (aliasPath === canonPath) continue;\n      if (domainName === canonDomainName) continue;\n      const canonRelPath =\n        canonDir === dirName\n          ? `./${fileName(canonicalName)}.interface`\n          : `../../${canonDir}/interfaces/${fileName(canonicalName)}.interface`;\n\n      // Single-form aliases: when the resolver collapses the IR model and\n      // its wire form to the same baseline name (or the alias's own\n      // domain/wire shapes coincide), emit only the unique exports. The\n      // earlier code unconditionally emitted both `export type X = Y;` and\n      // `export type X' = Y';` lines, producing TS2300 duplicate-identifier\n      // errors when X === X' and Y === Y'.\n      const aliasExports: string[] = [];\n      const importNeeded = new Set<string>();\n      const declared = new Set<string>();\n      const pushAlias = (lhs: string, rhs: string): void => {\n        if (lhs === rhs) return;\n        if (declared.has(lhs)) return;\n        declared.add(lhs);\n        aliasExports.push(`export type ${lhs} = ${rhs};`);\n        importNeeded.add(rhs);\n      };\n      pushAlias(domainName, canonDomainName);\n      pushAlias(responseName, canonResponseName);\n      if (aliasExports.length === 0) continue;\n\n      // Only import names that are referenced on the RHS of an alias AND\n      // aren't declared locally (which would shadow / collide with the\n      // import).\n      const importSymbols = [...importNeeded]\n        .filter((n) => !declared.has(n))\n        .sort()\n        .join(', ');\n      const aliasLines = importSymbols\n        ? [`import type { ${importSymbols} } from '${canonRelPath}';`, '', ...aliasExports]\n        : [...aliasExports];\n      if (isModelInScope(model.name, ctx)) {\n        files.push({\n          path: aliasPath,\n          content: aliasLines.join('\\n'),\n          overwriteExisting: true,\n        });\n      }\n      continue;\n    }\n\n    const dirName = resolveDir(service);\n    const isDedupCanonical = [...dedup.values()].includes(model.name);\n    const domainName = resolveInterfaceName(model.name, ctx, isDedupCanonical ? { skipTypeAlias: true } : undefined);\n    const responseName = wireInterfaceName(domainName);\n    const deps = collectFieldDependencies(model);\n    const lines: string[] = [];\n\n    let modelTypeRefOpts = typeRefOpts;\n    let modelWireTypeRefOpts = wireTypeRefOpts;\n    if (genericDefaults.has(model.name)) {\n      const filteredDefaults = new Map(genericDefaults);\n      filteredDefaults.delete(model.name);\n      modelTypeRefOpts = { ...typeRefOpts, genericDefaults: filteredDefaults };\n      modelWireTypeRefOpts = { genericDefaults: filteredDefaults };\n    }\n\n    const baselineDomain = ctx.apiSurface?.interfaces?.[domainName];\n    const baselineResponse = ctx.apiSurface?.interfaces?.[responseName];\n\n    const importableNames = new Set<string>();\n    importableNames.add(domainName);\n    importableNames.add(responseName);\n    for (const dep of deps.models) {\n      const depName = resolveInterfaceName(dep, ctx);\n      importableNames.add(depName);\n      importableNames.add(wireInterfaceName(depName));\n    }\n    for (const dep of deps.enums) {\n      importableNames.add(dep);\n    }\n\n    const typeDecls = new Map<string, string>();\n    const crossServiceImports = new Map<string, { name: string; relPath: string }>();\n    const unresolvableNames = new Set<string>();\n    const enumToService = assignEnumsToServices(ctx.spec.enums, ctx.spec.services, ctx.spec.models, ctx);\n    // Resolve mounted/owned service names (e.g. IR `Directories` -> `DirectorySync`)\n    // so owned-service enum-import planning matches `generateEnums`, which keys\n    // ownership off the resolved name (see enums.ts).\n    const serviceNameMap = buildServiceNameMap(ctx.spec.services, ctx);\n    const resolvedEnumNames = new Map<string, string>();\n    for (const e of ctx.spec.enums) {\n      resolvedEnumNames.set(resolveInterfaceName(e.name, ctx), e.name);\n    }\n\n    for (const field of model.fields) {\n      const baselineFields = [\n        baselineDomain?.fields?.[fieldName(field.name)],\n        baselineResponse?.fields?.[wireFieldName(field.name)],\n      ].filter(Boolean) as { type: string; optional: boolean }[];\n\n      for (const bf of baselineFields) {\n        const names = bf.type.match(/\\b[A-Z][a-zA-Z0-9]*\\b/g);\n        if (!names) continue;\n\n        for (const name of names) {\n          if (TS_BUILTINS.has(name)) continue;\n          if (importableNames.has(name)) continue;\n          if (typeDecls.has(name)) continue;\n          if (crossServiceImports.has(name)) continue;\n          if (unresolvableNames.has(name)) continue;\n\n          const irEnumName = resolvedEnumNames.get(name);\n          if (irEnumName && !deps.enums.has(irEnumName)) {\n            const eService = enumToService.get(irEnumName);\n            const eDir = resolveDir(eService);\n            const bEnum = ctx.apiSurface?.enums?.[irEnumName];\n            const bAlias = ctx.apiSurface?.typeAliases?.[irEnumName];\n            // Same owned-service exception as the `deps.enums` loop below:\n            // `generateEnums` emits the canonical module for owned services\n            // even when the baseline declares the name elsewhere (usually in\n            // the very file being overwritten), so import planning must\n            // target the canonical path to agree with that emission.\n            const eEnumIsOwned = isNodeOwnedService(ctx, eService, eService ? serviceNameMap.get(eService) : undefined);\n            const bSrc = eEnumIsOwned ? undefined : ((bEnum as any)?.sourceFile ?? (bAlias as any)?.sourceFile);\n            const gPath = `src/${eDir}/interfaces/${fileName(irEnumName)}.interface.ts`;\n            const cPath = `src/${dirName}/interfaces/${fileName(model.name)}.interface.ts`;\n            if (bSrc === cPath) {\n              importableNames.add(name);\n              continue;\n            }\n            let relPath: string;\n            if (bSrc && bSrc !== gPath) {\n              relPath = relativeImport(cPath, bSrc).replace(/\\.ts$/, '');\n            } else {\n              relPath =\n                eDir === dirName\n                  ? `./${fileName(irEnumName)}.interface`\n                  : `../../${eDir}/interfaces/${fileName(irEnumName)}.interface`;\n            }\n            crossServiceImports.set(name, { name, relPath });\n            importableNames.add(name);\n            continue;\n          }\n\n          const candidates = [...importableNames].filter((n) => n.endsWith(name) && n !== name);\n          if (candidates.length === 1) {\n            typeDecls.set(name, candidates[0]);\n            importableNames.add(name);\n          } else {\n            unresolvableNames.add(name);\n          }\n        }\n      }\n    }\n\n    for (const dep of deps.models) {\n      const depName = resolveInterfaceName(dep, ctx);\n      const depService = modelToService.get(dep);\n      const depDir = resolveDir(depService);\n      const depIsOwned = isNodeOwnedService(ctx, depService);\n\n      // When the resolver maps the IR name to a different baseline interface\n      // (via `overlayLookup.modelNameByIR` structural match), the import\n      // path must follow the baseline's `sourceFile`. Otherwise we'd point\n      // at the IR-named file (e.g. `audit-log-event.interface`) that the\n      // emitter never generates — the canonical baseline file is at a\n      // different stem (e.g. `create-audit-log-event-options.interface`).\n      const currentFilePath = `src/${dirName}/interfaces/${fileName(model.name)}.interface.ts`;\n      const baselineSrc = depIsOwned\n        ? undefined\n        : (ctx.apiSurface?.interfaces?.[depName] as { sourceFile?: string } | undefined)?.sourceFile;\n\n      // Self-reference: the dependency lives in the file we're currently\n      // emitting. Skip the import — it's already in scope.\n      if (baselineSrc === currentFilePath) continue;\n\n      let relPath: string;\n      if (baselineSrc) {\n        relPath = relativeImport(currentFilePath, baselineSrc).replace(/\\.ts$/, '');\n      } else {\n        relPath =\n          depDir === dirName ? `./${fileName(dep)}.interface` : `../../${depDir}/interfaces/${fileName(dep)}.interface`;\n      }\n\n      // `wireInterfaceName` consults the baseline interface set so it\n      // returns the bare `depName` when the resolver mapped to a\n      // single-form interface (no separate `*Wire`). That keeps the\n      // import statement requesting only what the baseline file exports.\n      const wireName = wireInterfaceName(depName);\n      const importNames = wireName === depName ? depName : `${depName}, ${wireName}`;\n      lines.push(`import type { ${importNames} } from '${relPath}';`);\n    }\n    for (const dep of deps.enums) {\n      // Inlined enums are emitted as literal unions at the usage site\n      // (handled by type-map). Skip the import — the file does not exist.\n      if (isInlineEnum(dep)) continue;\n\n      const baselineEnum = ctx.apiSurface?.enums?.[dep];\n      const baselineAlias = ctx.apiSurface?.typeAliases?.[dep];\n      const depService = enumToService.get(dep);\n      const depEnumIsOwned = isNodeOwnedService(\n        ctx,\n        depService,\n        depService ? serviceNameMap.get(depService) : undefined,\n      );\n      // Fall back to the live-surface declaration path: `generateEnums` skips\n      // emission when the enum is already declared elsewhere in the SDK (same\n      // fallback, see enums.ts), so the import must follow that declaration —\n      // the canonical per-service file will never exist.\n      //\n      // OWNED services are the exception, mirroring enums.ts: the on-disk\n      // declaration usually lives in a file this very regeneration\n      // overwrites, `generateEnums` emits the canonical module anyway, and\n      // the import must agree with that emission — otherwise the generated\n      // interface references a name that is declared nowhere.\n      const baselineSrc = depEnumIsOwned\n        ? undefined\n        : ((baselineEnum as any)?.sourceFile ?? (baselineAlias as any)?.sourceFile ?? liveSurfaceInterfacePath(dep));\n      const depDir = resolveDir(depService);\n      const generatedPath = `src/${depDir}/interfaces/${fileName(dep)}.interface.ts`;\n      const currentFilePath = `src/${dirName}/interfaces/${fileName(model.name)}.interface.ts`;\n\n      if (baselineSrc === currentFilePath) {\n        importableNames.add(dep);\n        continue;\n      }\n\n      let relPath: string;\n      if (baselineSrc && baselineSrc !== generatedPath) {\n        relPath = relativeImport(currentFilePath, baselineSrc).replace(/\\.ts$/, '');\n      } else {\n        relPath =\n          depDir === dirName ? `./${fileName(dep)}.interface` : `../../${depDir}/interfaces/${fileName(dep)}.interface`;\n      }\n      lines.push(`import type { ${dep} } from '${relPath}';`);\n    }\n    for (const [, imp] of crossServiceImports) {\n      lines.push(`import type { ${imp.name} } from '${imp.relPath}';`);\n    }\n\n    if (lines.length > 0) lines.push('');\n\n    // Type-alias declarations are pre-collected from baseline field types.\n    // The IR-driven body may end up not using them (the body uses the\n    // resolved interface names, while aliases serve only as bridges from\n    // baseline-name references inside `baselineField.type`). Defer their\n    // emission, then filter to only those names actually referenced in\n    // the body or wire interface lines.\n    const typeDeclInsertIdx = lines.length;\n    const typeParams = renderTypeParams(model, genericDefaults);\n\n    // Domain interface\n    const seenDomainFields = new Set<string>();\n    if (model.description) {\n      lines.push(...docComment(model.description));\n    }\n    if (model.fields.length === 0) {\n      lines.push(`export type ${domainName}${typeParams} = object;`);\n    } else {\n      lines.push(`export interface ${domainName}${typeParams} {`);\n      for (const field of model.fields) {\n        // Domain identifier honors a `fieldHints` override (e.g. connection_type\n        // → type); the wire name below still derives from `field.name`.\n        const domainFieldName = fieldName(field.domainName ?? field.name);\n        if (seenDomainFields.has(domainFieldName)) continue;\n        seenDomainFields.add(domainFieldName);\n        if (field.description || field.deprecated || field.readOnly || field.writeOnly || field.default !== undefined) {\n          const parts: string[] = [];\n          if (field.description) parts.push(field.description);\n          if (field.readOnly) parts.push('@readonly');\n          if (field.writeOnly) parts.push('@writeonly');\n          if (field.default !== undefined) parts.push(`@default ${JSON.stringify(field.default)}`);\n          if (field.deprecated) parts.push('@deprecated');\n          lines.push(...docComment(parts.join('\\n'), 2));\n        }\n        const baselineField = baselineDomain?.fields?.[domainFieldName];\n        const domainWireField = wireFieldName(field.name);\n        const responseBaselineField = baselineResponse?.fields?.[domainWireField];\n        const domainResponseOptionalMismatch =\n          baselineField && !baselineField.optional && responseBaselineField && responseBaselineField.optional;\n        const readonlyPrefix = field.readOnly ? 'readonly ' : '';\n        if (\n          genericDefaults.has(model.name) &&\n          baselineField &&\n          typeReferencesUnresolvable(baselineField.type, unresolvableNames)\n        ) {\n          // Baseline typed this field with the model's generic param (e.g.\n          // `customAttributes?: CustomAttributesType`). The emitted interface\n          // renames the param to `GenericType`; remap the field so the param is\n          // actually used — otherwise it trips TS6133 (declared, never read).\n          const opt = baselineField.optional ? '?' : '';\n          lines.push(\n            `  ${readonlyPrefix}${domainFieldName}${opt}: ${substituteGenericParam(baselineField.type, unresolvableNames)};`,\n          );\n        } else if (\n          baselineField &&\n          !domainResponseOptionalMismatch &&\n          !hasDateTimeConversion(field.type) &&\n          baselineTypeResolvable(baselineField.type, importableNames) &&\n          baselineFieldCompatible(baselineField, field)\n        ) {\n          const opt = baselineField.optional ? '?' : '';\n          lines.push(`  ${readonlyPrefix}${domainFieldName}${opt}: ${baselineField.type};`);\n        } else {\n          const isNewFieldOnExistingModel = baselineDomain && !baselineField;\n          const isNewFieldOnExistingResponse = !baselineDomain && baselineResponse && !responseBaselineField;\n          // Preserve baseline-declared optionality even when we're emitting\n          // the IR-derived type (e.g. baseline `Date` for an IR string with\n          // `format: date-time`). Without this, regenerating an existing\n          // interface flips `external_id?: string` into `external_id: string\n          // | null`, which silently breaks every hand-written test fixture\n          // missing that field.\n          const baselineSaysOptional = baselineField?.optional === true;\n          const opt =\n            baselineSaysOptional ||\n            !field.required ||\n            isNewFieldOnExistingModel ||\n            domainResponseOptionalMismatch ||\n            isNewFieldOnExistingResponse\n              ? '?'\n              : '';\n          lines.push(`  ${readonlyPrefix}${domainFieldName}${opt}: ${mapTypeRef(field.type, modelTypeRefOpts)};`);\n        }\n      }\n      lines.push('}');\n    }\n    lines.push('');\n\n    // Wire/response interface — skip when the wire name collapsed onto the\n    // domain name (single-form structural-rename case, e.g. IR `Object` →\n    // `ReadObjectResponse`). Emitting the second declaration would either\n    // produce a literal duplicate `export interface ReadObjectResponse`\n    // pair or, after TypeScript's silent declaration merge, leave the\n    // call site with `import type { ReadObjectResponse, ReadObjectResponse }`.\n    if (responseName !== domainName) {\n      const seenWireFields = new Set<string>();\n      if (model.fields.length === 0) {\n        lines.push(`export type ${responseName}${typeParams} = object;`);\n      } else {\n        lines.push(`export interface ${responseName}${typeParams} {`);\n        for (const field of model.fields) {\n          const wireField = wireFieldName(field.name);\n          if (seenWireFields.has(wireField)) continue;\n          seenWireFields.add(wireField);\n          const baselineField = baselineResponse?.fields?.[wireField];\n          if (\n            genericDefaults.has(model.name) &&\n            baselineField &&\n            typeReferencesUnresolvable(baselineField.type, unresolvableNames)\n          ) {\n            // Mirror the domain side: keep the generic param wired on the\n            // response interface so `GenericType` is used, not orphaned.\n            const opt = baselineField.optional ? '?' : '';\n            lines.push(`  ${wireField}${opt}: ${substituteGenericParam(baselineField.type, unresolvableNames)};`);\n          } else if (\n            baselineField &&\n            baselineTypeResolvable(baselineField.type, importableNames) &&\n            baselineFieldCompatible(baselineField, field)\n          ) {\n            const opt = baselineField.optional ? '?' : '';\n            lines.push(`  ${wireField}${opt}: ${baselineField.type};`);\n          } else {\n            const isNewFieldOnExistingModel = baselineResponse && !baselineField;\n            // Same baseline-optional preservation as the domain side. The\n            // wire interface's optional flag drives test-fixture shape, so\n            // flipping it on regen breaks every fixture that omitted the\n            // field assuming it was optional.\n            const baselineSaysOptional = baselineField?.optional === true;\n            const opt = baselineSaysOptional || !field.required || isNewFieldOnExistingModel ? '?' : '';\n            lines.push(`  ${wireField}${opt}: ${mapWireTypeRef(field.type, modelWireTypeRefOpts)};`);\n          }\n        }\n        lines.push('}');\n      }\n    }\n\n    // Preserve inline types from existing file\n    const filePath = `src/${dirName}/interfaces/${fileName(model.name)}.interface.ts`;\n    if (ctx.apiSurface && ctx.targetDir) {\n      const generatedNames = new Set<string>();\n      for (const line of lines) {\n        const m = line.match(/^export\\s+(?:interface|type|enum|class|const|function)\\s+(\\w+)/);\n        if (m) generatedNames.add(m[1]);\n      }\n\n      try {\n        const existingContent = fs.readFileSync(path.join(ctx.targetDir, filePath), 'utf-8');\n        const inlineNames = new Set<string>();\n        const checkSurface = (items: Record<string, any> | undefined) => {\n          if (!items) return;\n          for (const [name, item] of Object.entries(items)) {\n            const src = (item as any).sourceFile as string | undefined;\n            if (src !== filePath) continue;\n            if (generatedNames.has(name)) continue;\n            const sepPath = `src/${dirName}/interfaces/${fileName(name)}.interface.ts`;\n            if (sepPath !== filePath && files.some((f) => f.path === sepPath)) continue;\n            // Owned-service enums get their canonical per-service module\n            // emitted by `generateEnums` this run, and this file imports the\n            // name (see the deps.enums loop above). Preserving the legacy\n            // inline declaration would collide with that import (TS2440).\n            if (\n              !isInlineEnum(name) &&\n              ctx.spec.enums.some((e) => e.name === name) &&\n              isNodeOwnedService(ctx, enumToService.get(name))\n            ) {\n              continue;\n            }\n            inlineNames.add(name);\n          }\n        };\n        checkSurface(ctx.apiSurface.interfaces);\n        checkSurface(ctx.apiSurface.typeAliases);\n        checkSurface(ctx.apiSurface.enums);\n\n        if (inlineNames.size > 0) {\n          const existingLines = existingContent.split('\\n');\n          let ei = 0;\n          while (ei < existingLines.length) {\n            const eline = existingLines[ei];\n            const dm = eline.match(/^(export\\s+)?(?:interface|type|enum|class|const|function)\\s+(\\w+)/);\n            if (!dm || !inlineNames.has(dm[2])) {\n              ei++;\n              continue;\n            }\n\n            const block: string[] = [eline];\n            let braces = (eline.match(/\\{/g) || []).length - (eline.match(/\\}/g) || []).length;\n            if (braces === 0 && eline.includes(';')) {\n              lines.push('');\n              lines.push(block.join('\\n'));\n              ei++;\n              continue;\n            }\n            if (braces === 0) {\n              ei++;\n              while (ei < existingLines.length) {\n                const nl = existingLines[ei];\n                block.push(nl);\n                ei++;\n                if (\n                  nl.trimEnd().endsWith(';') ||\n                  (nl.trim() !== '' && !nl.trim().startsWith('|') && !nl.trim().startsWith('&'))\n                )\n                  break;\n              }\n              lines.push('');\n              lines.push(block.join('\\n'));\n              continue;\n            }\n            ei++;\n            while (ei < existingLines.length && braces > 0) {\n              const nl = existingLines[ei];\n              block.push(nl);\n              braces += (nl.match(/\\{/g) || []).length - (nl.match(/\\}/g) || []).length;\n              ei++;\n            }\n            lines.push('');\n            lines.push(block.join('\\n'));\n          }\n        }\n      } catch {\n        // No existing file\n      }\n    }\n\n    // Splice in only the type aliases referenced by the body or wire lines.\n    if (typeDecls.size > 0) {\n      const bodyText = lines.slice(typeDeclInsertIdx).join('\\n');\n      const usedDecls: string[] = [];\n      for (const [alias, typeExpr] of typeDecls) {\n        if (new RegExp(`\\\\b${alias}\\\\b`).test(bodyText)) {\n          usedDecls.push(`type ${alias} = ${typeExpr};`);\n        }\n      }\n      if (usedDecls.length > 0) {\n        lines.splice(typeDeclInsertIdx, 0, ...usedDecls, '');\n      }\n    }\n\n    if (isModelInScope(model.name, ctx)) {\n      files.push({\n        path: filePath,\n        content: pruneUnusedImports(lines).join('\\n'),\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n\n// ---------------------------------------------------------------------------\n// Serializer generation\n// ---------------------------------------------------------------------------\n\nexport function generateSerializers(\n  models: Model[],\n  ctx: EmitterContext,\n  shared?: SharedModelContext,\n): GeneratedFile[] {\n  if (models.length === 0) return [];\n\n  const { modelToService, resolveDir, dedup } = shared ?? buildSharedContext(models, ctx);\n  const files: GeneratedFile[] = [];\n  const skippedSerializeModels = new Set<string>();\n  const projectedModels = models.map((model) =>\n    projectModelToManagedSurface(model, { modelToService, resolveDir, dedup, genericDefaults: new Map() }, ctx),\n  );\n  const projectedByName = new Map(projectedModels.map((model) => [model.name, model]));\n  const resourceUsage = buildGeneratedResourceModelUsage(models, ctx);\n  const serializerEligibleModels = resourceUsage\n    ? expandModelRoots(resourceUsage.serializerRoots, projectedByName)\n    : undefined;\n  // Models reachable from any response — only these need a `deserialize<X>`.\n  // A model used solely as a request body (e.g. `CreateWebhookEndpoint`)\n  // would otherwise emit a deserializer with a partial response shape that\n  // silently misbehaves if called. Undefined means \"no resource usage info,\n  // emit both halves\" (standalone generation, smoke tests).\n  const responseReachableModels = resourceUsage\n    ? expandModelRoots(resourceUsage.responseRoots, projectedByName)\n    : undefined;\n  // Models reachable from any request — only these need a `serialize<X>`.\n  // A model used solely as a response body can safely be deserialize-only;\n  // emitting its serialize half is both unused and brittle when it contains\n  // legacy nested response models that intentionally have no serialize helper.\n  const requestReachableModels = resourceUsage\n    ? expandModelRoots(resourceUsage.requestRoots, projectedByName)\n    : undefined;\n\n  const serializerReachable = computeNonEventReachable(ctx.spec.services, models);\n\n  // Detect models whose serializer file already exists in the live SDK but\n  // does not export a `serialize<Domain>` function. Generated serializers\n  // that reference such a model must skip their `serialize` half — calling\n  // a missing function would leave the SDK unable to compile.\n  const liveRoot = ctx.targetDir ?? ctx.outputDir;\n  if (liveRoot) {\n    for (const originalModel of models) {\n      const model = projectedByName.get(originalModel.name) ?? originalModel;\n      if (!serializerReachable.has(model.name)) continue;\n      if (serializerEligibleModels && !serializerEligibleModels.has(model.name)) continue;\n      const service = modelToService.get(model.name);\n      const dirName = resolveDir(service);\n      const domainName = resolveInterfaceName(model.name, ctx);\n      const baselineSource = (ctx.apiSurface?.interfaces?.[domainName] as { sourceFile?: string } | undefined)\n        ?.sourceFile;\n      const serializerRelPath = baselineSource\n        ? baselineSource.replace('/interfaces/', '/serializers/').replace('.interface.ts', '.serializer.ts')\n        : `src/${dirName}/serializers/${fileName(model.name)}.serializer.ts`;\n      const serializerFile = path.join(liveRoot, serializerRelPath);\n      try {\n        const content = fs.readFileSync(serializerFile, 'utf-8');\n        const isGeneratedFile =\n          ctx.priorTargetManifestPaths?.has(serializerRelPath) ||\n          /auto-generated by oagen/i.test(content.slice(0, 400));\n        if (!isGeneratedFile && !new RegExp(`\\\\bserialize${domainName}\\\\b`).test(content)) {\n          skippedSerializeModels.add(model.name);\n        }\n      } catch {\n        // Serializer doesn't exist on disk yet — fine, we'll generate one.\n      }\n    }\n  }\n\n  const forceGenerateSerializer = new Set<string>();\n  for (const originalModel of models) {\n    const model = projectedByName.get(originalModel.name) ?? originalModel;\n    if (!serializerReachable.has(model.name)) continue;\n    if (serializerEligibleModels && !serializerEligibleModels.has(model.name)) continue;\n    if (!modelHasNewFields(model, ctx)) continue;\n    const service = modelToService.get(model.name);\n    const dirName = resolveDir(service);\n    const parentPath = `src/${dirName}/interfaces/${fileName(model.name)}.interface.ts`;\n    const deps = collectFieldDependencies(model);\n    for (const dep of deps.models) {\n      const depName = resolveInterfaceName(dep, ctx);\n      const depBaseline = ctx.apiSurface?.interfaces?.[depName];\n      const depSrc = (depBaseline as any)?.sourceFile as string | undefined;\n      if (depSrc === parentPath) {\n        forceGenerateSerializer.add(dep);\n      }\n    }\n  }\n\n  const discriminatedSerializerSkip = (ctx as { _discriminatedModelNames?: Set<string> })._discriminatedModelNames;\n  const serializerNonPaginatedRefs = collectNonPaginatedResponseModelNames(ctx.spec.services);\n\n  // Mirror the interface-emission gate (see `generateModels`).\n  const serializerListMetadataNeeded = collectReferencedListMetadataModels(models, serializerNonPaginatedRefs);\n\n  for (const originalModel of models) {\n    const model = projectedByName.get(originalModel.name) ?? originalModel;\n    if (!serializerReachable.has(model.name)) continue;\n    if (serializerEligibleModels && !serializerEligibleModels.has(model.name)) continue;\n    const service = modelToService.get(model.name);\n    const isOwnedModel = isNodeOwnedService(ctx, service);\n    if (!isOwnedModel && !modelHasNewFields(model, ctx) && !forceGenerateSerializer.has(model.name)) continue;\n    const canonicalName = dedup.get(model.name);\n    if (canonicalName) {\n      forceGenerateSerializer.add(canonicalName);\n      if (serializerEligibleModels) serializerEligibleModels.add(canonicalName);\n    }\n  }\n\n  const eligibleModels: Model[] = [];\n  for (const originalModel of models) {\n    const model = projectedByName.get(originalModel.name) ?? originalModel;\n    if (!serializerReachable.has(model.name)) continue;\n    if (serializerEligibleModels && !serializerEligibleModels.has(model.name)) continue;\n    if (isListMetadataModel(model) && !serializerListMetadataNeeded.has(model.name)) continue;\n    if (isListWrapperModel(model) && !serializerNonPaginatedRefs.has(model.name)) continue;\n    if (discriminatedSerializerSkip?.has(model.name)) continue;\n    // Hand-owned types keep their hand-written serializer (see generateModels).\n    if (\n      isHandOwnedType(ctx, model.name) ||\n      isHandOwnedType(ctx, resolveInterfaceName(model.name, ctx, { skipTypeAlias: true }))\n    )\n      continue;\n    const service = modelToService.get(model.name);\n    const isOwnedModel = isNodeOwnedService(ctx, service);\n    if (!isOwnedModel && !modelHasNewFields(model, ctx) && !forceGenerateSerializer.has(model.name)) continue;\n    eligibleModels.push(model);\n  }\n  (ctx as any)._generatedSerializerModels = new Set(eligibleModels.map((model) => model.name));\n\n  // Pass 1: determine shouldSkipSerialize\n  for (const model of eligibleModels) {\n    if (dedup.has(model.name)) continue;\n    const domainName = resolveInterfaceName(model.name, ctx);\n    const responseName = wireInterfaceName(domainName);\n    const baselineResponse = ctx.apiSurface?.interfaces?.[responseName];\n    const baselineDomain = ctx.apiSurface?.interfaces?.[domainName];\n    const shouldSkip =\n      (requestReachableModels !== undefined && !requestReachableModels.has(model.name)) ||\n      shouldSkipSerializeForModel(model, baselineResponse, baselineDomain, dedup, skippedSerializeModels, ctx);\n    if (shouldSkip) {\n      skippedSerializeModels.add(model.name);\n    }\n  }\n\n  // Pass 2: generate serializer files\n  for (const model of eligibleModels) {\n    const service = modelToService.get(model.name);\n    const isOwnedModel = isNodeOwnedService(ctx, service);\n    const canonicalName = dedup.get(model.name);\n    if (canonicalName && !isOwnedModel) {\n      const dirName = resolveDir(service);\n      const skipTA = { skipTypeAlias: true };\n      const domainName = resolveInterfaceName(model.name, ctx, skipTA);\n      const canonDomainName = resolveInterfaceName(canonicalName, ctx, skipTA);\n\n      const canonService = modelToService.get(canonicalName);\n      const canonDir = resolveDir(canonService);\n      const serializerPath = `src/${dirName}/serializers/${fileName(model.name)}.serializer.ts`;\n      const canonSerializerPath = `src/${canonDir}/serializers/${fileName(canonicalName)}.serializer.ts`;\n\n      if (serializerPath === canonSerializerPath) continue;\n      if (domainName === canonDomainName) continue;\n\n      const aliasNeedsDeserialize = responseReachableModels === undefined || responseReachableModels.has(model.name);\n      const canonicalHasDeserialize =\n        responseReachableModels === undefined || responseReachableModels.has(canonicalName);\n      const canAliasToCanonical = !aliasNeedsDeserialize || canonicalHasDeserialize;\n      if (canAliasToCanonical) {\n        const rel = relativeImport(serializerPath, canonSerializerPath);\n        const canonSkipSerialize = skippedSerializeModels.has(canonicalName) || skippedSerializeModels.has(model.name);\n        const canonSkipDeserialize =\n          responseReachableModels !== undefined &&\n          !responseReachableModels.has(canonicalName) &&\n          !responseReachableModels.has(model.name);\n        if (canonSkipSerialize && canonSkipDeserialize) continue;\n        const parts: string[] = [];\n        if (!canonSkipDeserialize) {\n          parts.push(`deserialize${canonDomainName} as deserialize${domainName}`);\n        }\n        if (!canonSkipSerialize) {\n          parts.push(`serialize${canonDomainName} as serialize${domainName}`);\n        }\n        const reexportContent = `export { ${parts.join(', ')} } from '${rel}';`;\n        if (isModelInScope(model.name, ctx)) {\n          files.push({\n            path: serializerPath,\n            content: reexportContent,\n            overwriteExisting: true,\n          });\n        }\n        continue;\n      }\n      // The alias is response-reachable, but the canonical model is\n      // request-only. Generate a local serializer instead of re-exporting a\n      // deserialize helper that the canonical serializer intentionally omits.\n    }\n\n    const dirName = resolveDir(service);\n    const isDedupCanonical = [...dedup.values()].includes(model.name);\n    const domainName = resolveInterfaceName(model.name, ctx, isDedupCanonical ? { skipTypeAlias: true } : undefined);\n    const responseName = wireInterfaceName(domainName);\n    const serializerPath = `src/${dirName}/serializers/${fileName(model.name)}.serializer.ts`;\n    const typeParams = renderSerializerTypeParams(model, ctx);\n    const baselineResponse = ctx.apiSurface?.interfaces?.[responseName];\n    const baselineDomain = ctx.apiSurface?.interfaces?.[domainName];\n\n    const skipFormatFields = buildSkipFormatFields(model, baselineDomain);\n    const shouldSkipSerialize = skippedSerializeModels.has(model.name);\n    // Skip `deserialize<X>` when the model never appears as a response (and\n    // we have usage info to verify that — `undefined` means \"emit both halves\n    // conservatively\"). Cuts unused, partially-typed deserializers like\n    // `deserializeCreateWebhookEndpoint` from request-body-only models.\n    const shouldSkipDeserialize = responseReachableModels !== undefined && !responseReachableModels.has(model.name);\n    if (shouldSkipSerialize && shouldSkipDeserialize) continue;\n\n    const sctx = {\n      modelToService,\n      resolveDir,\n      dedup,\n      skippedSerializeModels,\n      responseReachableModels,\n      ctx,\n    };\n    const lines = [\n      ...buildSerializerImports(model, serializerPath, dirName, domainName, responseName, sctx),\n      ...emitSerializerBody(\n        model,\n        domainName,\n        responseName,\n        typeParams,\n        baselineDomain,\n        baselineResponse,\n        skipFormatFields,\n        shouldSkipSerialize,\n        shouldSkipDeserialize,\n        ctx,\n      ),\n    ];\n\n    if (isModelInScope(model.name, ctx)) {\n      files.push({\n        path: serializerPath,\n        content: pruneUnusedImports(lines).join('\\n'),\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  (ctx as any)._skippedSerializeModels = skippedSerializeModels;\n  // Surface the response-reachable set so the serializer-roundtrip test\n  // generator can fall back to a deserialize-skipped path for request-only\n  // models (where `deserialize<X>` was deliberately not emitted).\n  (ctx as any)._responseReachableModels = responseReachableModels;\n\n  // Emit a `serializers/index.ts` barrel per directory that received serializer\n  // files in this pass. Mirrors the per-service `interfaces/index.ts` barrel so\n  // consumers can `import { ... } from './serializers'` rather than reaching\n  // into individual `.serializer.ts` files. Also includes any pre-existing\n  // `*.serializer.ts` files in the same directory (e.g. hand-written option\n  // serializers in an owned service) so we don't strand them from the barrel.\n  const serializersByDir = new Map<string, Set<string>>();\n  for (const f of files) {\n    const match = f.path.match(/^src\\/([^/]+)\\/serializers\\/(.+)\\.serializer\\.ts$/);\n    if (!match) continue;\n    const [, dir, stem] = match;\n    if (!serializersByDir.has(dir)) serializersByDir.set(dir, new Set());\n    serializersByDir.get(dir)!.add(stem);\n  }\n  const liveRootForBarrel = ctx.outputDir ?? ctx.targetDir;\n  for (const [dir, stems] of serializersByDir) {\n    if (liveRootForBarrel) {\n      const dirIsOwned = isNodeOwnedService(ctx, dir);\n      const serializersDir = path.join(liveRootForBarrel, 'src', dir, 'serializers');\n      try {\n        for (const entry of fs.readdirSync(serializersDir)) {\n          if (!entry.endsWith('.serializer.ts')) continue;\n          const stem = entry.replace(/\\.serializer\\.ts$/, '');\n          if (stems.has(stem)) continue;\n          // Owned directories are otherwise fully regenerated. Only preserve a\n          // hand-written serializer when it belongs to a hand-owned type (i.e.\n          // exports `(de)serialize<HandOwnedType>`); stale auto-generated files\n          // should be pruned and unrelated hand-written files must not collide\n          // with generated exports.\n          if (dirIsOwned) {\n            const content = fs.readFileSync(path.join(serializersDir, entry), 'utf-8');\n            if (/auto-generated by oagen/i.test(content.slice(0, 400))) continue;\n            const serializerFns = [\n              ...content.matchAll(/export\\s+(?:const|function)\\s+((?:de)?serialize[A-Za-z0-9_]+)/g),\n            ].map((m) => m[1].replace(/^(?:de)?serialize/, ''));\n            if (!serializerFns.some((typeName) => isHandOwnedType(ctx, typeName))) continue;\n          }\n          stems.add(stem);\n        }\n      } catch {\n        // Directory doesn't exist yet — only this-pass serializers will appear.\n      }\n    }\n    const lines = [...stems].sort().map((stem) => `export * from './${stem}.serializer';`);\n    files.push({\n      path: `src/${dir}/serializers/index.ts`,\n      content: lines.join('\\n') + '\\n',\n      overwriteExisting: true,\n    });\n  }\n\n  return files;\n}\n\n// ---------------------------------------------------------------------------\n// Combined generation\n// ---------------------------------------------------------------------------\n\nexport function generateModelsAndSerializers(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n  if (models.length === 0) return [];\n  const shared = buildSharedContext(models, ctx);\n  return [...generateModels(models, ctx, shared), ...generateSerializers(models, ctx, shared)];\n}\n\nexport function generatedResourceInterfaceModelNames(models: Model[], ctx: EmitterContext): Set<string> | undefined {\n  const shared = buildSharedContext(models, ctx);\n  const projectedModels = models.map((model) => projectModelToManagedSurface(model, shared, ctx));\n  const projectedByName = new Map(projectedModels.map((model) => [model.name, model]));\n  const resourceUsage = buildGeneratedResourceModelUsage(models, ctx);\n  return resourceUsage ? expandModelRoots(resourceUsage.interfaceRoots, projectedByName) : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction buildGeneratedResourceModelUsage(\n  models: Model[],\n  ctx: EmitterContext,\n): GeneratedResourceModelUsage | undefined {\n  if (ctx.spec.services.length === 0) return undefined;\n\n  const modelMap = new Map(models.map((model) => [model.name, model]));\n  const interfaceRoots = new Set<string>();\n  const serializerRoots = new Set<string>();\n  const requestRoots = new Set<string>();\n  const responseRoots = new Set<string>();\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const mountGroups = groupByMount(ctx);\n  const services: Service[] =\n    mountGroups.size > 0\n      ? [...mountGroups].map(([name, group]) => ({\n          name,\n          operations: group.operations,\n        }))\n      : ctx.spec.services;\n\n  for (const service of services) {\n    const resourceClass = resolveResourceClassName(service, ctx);\n    const isOwnedService = isNodeOwnedService(ctx, service.name, resourceClass);\n    const baselineHasResourceClass = Boolean(ctx.apiSurface?.classes?.[resourceClass]);\n\n    if (\n      !isOwnedService &&\n      baselineHasResourceClass &&\n      isServiceCoveredByExisting(service, ctx) &&\n      !hasMethodsAbsentFromBaseline(service, ctx)\n    ) {\n      continue;\n    }\n\n    let plans = service.operations.map((op) => ({\n      op,\n      plan: planOperation(op),\n      method: resolveMethodName(op, service, ctx),\n    }));\n\n    const baselineMethodNames = new Set(Object.keys(ctx.apiSurface?.classes?.[resourceClass]?.methods ?? {}));\n    if (!isOwnedService && baselineMethodNames.size > 0) {\n      plans = plans.filter((p) => !baselineMethodNames.has(p.method));\n    }\n    if (plans.length === 0) continue;\n\n    for (const { op, plan } of plans) {\n      if (plan.isPaginated && op.pagination && op.httpMethod === 'get') {\n        let itemName = op.pagination.itemType.kind === 'model' ? op.pagination.itemType.name : undefined;\n        if (itemName) {\n          const itemModel = modelMap.get(itemName);\n          const unwrapped = itemModel ? unwrapListModel(itemModel, modelMap) : null;\n          if (unwrapped) itemName = unwrapped.name;\n          interfaceRoots.add(itemName);\n          serializerRoots.add(itemName);\n          responseRoots.add(itemName);\n        }\n      } else if (plan.responseModelName) {\n        interfaceRoots.add(plan.responseModelName);\n        serializerRoots.add(plan.responseModelName);\n        responseRoots.add(plan.responseModelName);\n      }\n\n      const bodyInfo = extractRequestBodyModels(op, ctx);\n      for (const name of bodyInfo) {\n        interfaceRoots.add(name);\n        serializerRoots.add(name);\n        requestRoots.add(name);\n      }\n\n      for (const param of [...op.pathParams, ...op.queryParams, ...op.headerParams]) {\n        collectTypeRefModels(param.type, interfaceRoots);\n      }\n\n      const resolved = lookupResolved(op, resolvedLookup);\n      if (resolved) {\n        for (const name of collectWrapperResponseModels(resolved)) {\n          interfaceRoots.add(name);\n          serializerRoots.add(name);\n          responseRoots.add(name);\n        }\n        for (const wrapper of resolved.wrappers ?? []) {\n          for (const { field } of resolveWrapperParams(wrapper, ctx)) {\n            if (field) collectTypeRefModels(field.type, interfaceRoots);\n          }\n        }\n      }\n    }\n  }\n\n  return { interfaceRoots, serializerRoots, requestRoots, responseRoots };\n}\n\nfunction extractRequestBodyModels(op: Operation, ctx: EmitterContext): string[] {\n  if (!op.requestBody) return [];\n  if (op.requestBody.kind === 'model') return [op.requestBody.name];\n  if (op.requestBody.kind !== 'union') return [];\n\n  const names: string[] = [];\n  for (const variant of op.requestBody.variants) {\n    if (variant.kind === 'model') names.push(variant.name);\n  }\n\n  return names.length > 0 ? names : collectDiscriminatorModelNames(op.requestBody.discriminator, ctx);\n}\n\nfunction collectDiscriminatorModelNames(\n  discriminator: { mapping?: Record<string, string> } | undefined,\n  ctx: EmitterContext,\n): string[] {\n  const names = new Set<string>();\n  for (const mapped of Object.values(discriminator?.mapping ?? {})) {\n    const name = mapped.split('/').pop();\n    if (name && ctx.spec.models.some((model) => model.name === name)) names.add(name);\n  }\n  return [...names];\n}\n\nfunction collectTypeRefModels(ref: TypeRef | undefined, out: Set<string>): void {\n  if (!ref) return;\n  switch (ref.kind) {\n    case 'model':\n      out.add(ref.name);\n      return;\n    case 'array':\n      collectTypeRefModels(ref.items, out);\n      return;\n    case 'nullable':\n      collectTypeRefModels(ref.inner, out);\n      return;\n    case 'union':\n      for (const variant of ref.variants) collectTypeRefModels(variant, out);\n      return;\n    default:\n      return;\n  }\n}\n\nfunction expandModelRoots(roots: Set<string>, modelsByName: Map<string, Model>): Set<string> {\n  const out = new Set<string>();\n  const queue = [...roots];\n\n  while (queue.length > 0) {\n    const name = queue.pop()!;\n    if (out.has(name)) continue;\n    const model = modelsByName.get(name);\n    if (!model) continue;\n    out.add(name);\n\n    for (const dep of collectFieldDependencies(model).models) {\n      if (!out.has(dep)) queue.push(dep);\n    }\n  }\n\n  return out;\n}\n\nfunction baselineTypeResolvable(typeStr: string, importableNames: Set<string>): boolean {\n  const matches = typeStr.match(/\\b[A-Z][a-zA-Z0-9]*\\b/g);\n  if (!matches) return true;\n\n  for (const name of matches) {\n    if (TS_BUILTINS.has(name)) continue;\n    if (importableNames.has(name)) continue;\n    return false;\n  }\n  return true;\n}\n\nfunction baselineFieldCompatible(baselineField: { type: string; optional: boolean }, irField: Field): boolean {\n  // A baseline `any` is the footprint of a previously-broken generation:\n  // api-surface extraction types a field as `any` when its import failed to\n  // resolve (e.g. the enum file hadn't been emitted yet in that run). Copying\n  // it forward would freeze the degradation — once `state: any` lands in the\n  // SDK, every later regen sees it as the baseline and re-emits it. When the\n  // IR knows the real model/enum name, always re-derive from the IR instead.\n  if (baselineTypeIsDegradedAny(baselineField.type) && hasNamedTypeReference(irField.type)) {\n    return false;\n  }\n\n  const irNullable = irField.type.kind === 'nullable';\n  const baselineHasNull = baselineField.type.includes('null');\n\n  if (irNullable && !baselineHasNull && irField.required) {\n    return false;\n  }\n\n  if (!irField.required && !baselineField.optional && !baselineField.type.includes('undefined')) {\n    return false;\n  }\n\n  if (baselineField.type === 'Record<string, unknown>' && hasSpecificIRType(irField.type)) {\n    return false;\n  }\n\n  return true;\n}\n\n/** `any`, `any[]`, `any | null`, … — shapes api-surface extraction degrades to. */\nfunction baselineTypeIsDegradedAny(typeStr: string): boolean {\n  const stripped = typeStr\n    .replace(/\\s*\\|\\s*(?:null|undefined)\\b/g, '')\n    .replace(/\\[\\]$/, '')\n    .trim();\n  return stripped === 'any';\n}\n\n/** Does the IR type reference a named model/enum anywhere (incl. arrays)? */\nfunction hasNamedTypeReference(ref: TypeRef): boolean {\n  switch (ref.kind) {\n    case 'model':\n    case 'enum':\n      return true;\n    case 'array':\n      return hasNamedTypeReference(ref.items);\n    case 'nullable':\n      return hasNamedTypeReference(ref.inner);\n    case 'union':\n      return ref.variants.some((v) => hasNamedTypeReference(v));\n    default:\n      return false;\n  }\n}\n\nfunction hasSpecificIRType(ref: TypeRef): boolean {\n  switch (ref.kind) {\n    case 'model':\n    case 'enum':\n      return true;\n    case 'union':\n      return ref.variants.some((v) => v.kind === 'model' || v.kind === 'enum');\n    case 'nullable':\n      return hasSpecificIRType(ref.inner);\n    default:\n      return false;\n  }\n}\n\n/** True when a baseline field type references one of the model's generic\n *  param identifiers (collected as `unresolvableNames` — bare type names that\n *  resolve to nothing importable, which for a generic model are its params). */\nfunction typeReferencesUnresolvable(type: string, unresolvable: Set<string>): boolean {\n  if (unresolvable.size === 0) return false;\n  const names = type.match(/\\b[A-Z][a-zA-Z0-9]*\\b/g);\n  return !!names && names.some((n) => unresolvable.has(n));\n}\n\n/** Rewrite a baseline field type so references to the model's (renamed)\n *  generic param resolve to the emitted `GenericType` param. */\nfunction substituteGenericParam(type: string, unresolvable: Set<string>): string {\n  return type.replace(/\\b[A-Z][a-zA-Z0-9]*\\b/g, (name) => (unresolvable.has(name) ? 'GenericType' : name));\n}\n\nfunction renderTypeParams(model: Model, genericDefaults?: Map<string, string>): string {\n  if (!model.typeParams?.length) {\n    if (genericDefaults?.has(model.name)) {\n      return '<GenericType extends Record<string, unknown> = Record<string, unknown>>';\n    }\n    return '';\n  }\n  const params = model.typeParams.map((tp) => {\n    const def = tp.default ? ` = ${mapTypeRef(tp.default)}` : '';\n    return `${tp.name}${def}`;\n  });\n  return `<${params.join(', ')}>`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ApiSpec, AuthScheme, EmitterContext, GeneratedFile } from '@workos/oagen';\n\nimport {\n  fileName,\n  servicePropertyName,\n  resolveInterfaceName,\n  wireInterfaceName,\n  resolveServiceName,\n} from './naming.js';\nimport { isInlineEnum } from './type-map.js';\nimport {\n  docComment,\n  createServiceDirResolver,\n  isServiceCoveredByExisting,\n  isListMetadataModel,\n  isListWrapperModel,\n  computeNonEventReachable,\n} from './utils.js';\nimport { isNodeOwnedService, nodeOptions } from './options.js';\nimport { resolveResourceClassName, resolveResourceDir } from './resources.js';\nimport { generatedResourceInterfaceModelNames } from './models.js';\nimport { assignEnumsToServices } from './enums.js';\nimport { liveSurfaceInterfacePath } from './live-surface.js';\n\nexport function generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  files.push(generateWorkOSClient(spec, ctx));\n  files.push(...generateServiceBarrels(spec, ctx));\n  files.push(generateBarrel(spec, ctx));\n  // worker barrel, package.json, tsconfig.json are now hand-maintained in the target SDK\n\n  return files;\n}\n\nfunction generateWorkOSClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile {\n  const lines: string[] = [];\n\n  // Only import WorkOSBase for fresh generation (no existing WorkOS class).\n  // When integrating into an existing SDK, the existing WorkOS already has its\n  // own base class and the WorkOSBase file may not exist.\n  const hasExistingWorkOS = !!ctx.apiSurface?.classes?.['WorkOS'];\n  if (!hasExistingWorkOS) {\n    lines.push(\"import { WorkOSBase } from './common/workos-base';\");\n  }\n\n  // Filter out services whose endpoints are already covered by existing\n  // hand-written service classes (e.g., Connections covered by SSO).\n  const coveredServices = new Set<string>();\n  for (const service of spec.services) {\n    if (isServiceCoveredByExisting(service, ctx)) {\n      coveredServices.add(service.name);\n    }\n  }\n\n  // Service imports — skip covered services\n  for (const service of spec.services) {\n    if (coveredServices.has(service.name)) continue;\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const serviceDir = resolveResourceDir(service, ctx);\n    lines.push(`import { ${resolvedName} } from './${serviceDir}/${fileName(resolvedName)}';`);\n  }\n\n  lines.push('');\n  if (spec.description) {\n    lines.push(...docComment(spec.description));\n  }\n  const extendsClause = hasExistingWorkOS ? '' : ' extends WorkOSBase';\n  lines.push(`export class WorkOS${extendsClause} {`);\n\n  // Server URL constants from spec.servers\n  if (spec.servers && spec.servers.length > 0) {\n    for (const server of spec.servers) {\n      const constName = serverConstName(server.description ?? server.url);\n      if (server.description) {\n        lines.push(...docComment(server.description, 2));\n      }\n      lines.push(`  static readonly ${constName} = '${server.url}';`);\n    }\n    lines.push('');\n  }\n\n  // Resource accessors — skip services whose property already exists\n  // in the baseline WorkOS class (e.g., `portal` covers AdminPortal,\n  // `mfa` covers MultiFactorAuth).\n  const existingProps = new Set<string>();\n  const baselineWorkOS = ctx.apiSurface?.classes?.['WorkOS'] ?? ctx.apiSurface?.classes?.['WorkOSNode'];\n  if (baselineWorkOS?.properties) {\n    for (const name of Object.keys(baselineWorkOS.properties)) {\n      existingProps.add(name);\n    }\n  }\n  // Resource accessors — skip services whose endpoints are fully covered\n  // by existing hand-written services.\n  for (const service of spec.services) {\n    if (coveredServices.has(service.name)) continue;\n    const resolvedName = resolveResourceClassName(service, ctx);\n    // Accessor name uses the un-suffixed service name so that the public API\n    // stays `client.organizationMembership` even when the class itself was\n    // renamed to `OrganizationMembershipService` to avoid a model collision.\n    const propName = servicePropertyName(resolveServiceName(service, ctx));\n    if (existingProps.has(propName)) continue;\n    // Propagate `@deprecated` from the service class to the property so\n    // IDEs surface the strikethrough at `workos.xyz` access sites, not\n    // just when users `new Xyz()` directly.  TS's deprecation-lint reads\n    // the property JSDoc, not the underlying type declaration.\n    const classDeprecation = ctx.apiSurface?.classes?.[resolvedName]?.deprecationMessage;\n    if (classDeprecation !== undefined) {\n      const body = classDeprecation ? ` ${classDeprecation}` : '';\n      lines.push(`  /** @deprecated${body} */`);\n    }\n    lines.push(`  readonly ${propName} = new ${resolvedName}(this);`);\n  }\n\n  // Auth override — only emit when auth is non-default (not bearer)\n  if (needsAuthOverride(spec.auth)) {\n    lines.push('');\n    lines.push('  protected override setAuthHeaders(headers: Record<string, string>): void {');\n    renderAuthOverride(lines, spec.auth!);\n    lines.push('  }');\n  }\n\n  lines.push('}');\n\n  return {\n    path: 'src/workos.ts',\n    content: lines.join('\\n'),\n    skipIfExists: true,\n  };\n}\n\nfunction sourceFileForExportedType(ctx: EmitterContext, typeName: string): string | undefined {\n  return (\n    (ctx.apiSurface?.interfaces?.[typeName] as { sourceFile?: string } | undefined)?.sourceFile ??\n    (ctx.apiSurface?.typeAliases?.[typeName] as { sourceFile?: string } | undefined)?.sourceFile ??\n    (ctx.apiSurface?.enums?.[typeName] as { sourceFile?: string } | undefined)?.sourceFile ??\n    liveSurfaceInterfacePath(typeName)\n  );\n}\n\nfunction exportedNamesForSource(ctx: EmitterContext, sourceFile: string): string[] {\n  const names = new Set<string>();\n  const addNamesFromSurface = (items: Record<string, unknown> | undefined) => {\n    if (!items) return;\n    for (const [name, item] of Object.entries(items)) {\n      if ((item as { sourceFile?: string }).sourceFile === sourceFile) {\n        names.add(name);\n      }\n    }\n  };\n\n  addNamesFromSurface(ctx.apiSurface?.interfaces);\n  addNamesFromSurface(ctx.apiSurface?.typeAliases);\n  addNamesFromSurface(ctx.apiSurface?.enums);\n\n  const rootDir = ctx.targetDir ?? ctx.outputDir;\n  if (rootDir) {\n    try {\n      const content = fs.readFileSync(path.join(rootDir, sourceFile), 'utf-8');\n      for (const match of content.matchAll(/export\\s+(?:interface|type|enum|class|const|function)\\s+(\\w+)/g)) {\n        names.add(match[1]);\n      }\n    } catch {\n      // The live source map is best-effort; apiSurface/livesurface names above\n      // are enough when the file is not readable.\n    }\n  }\n\n  return [...names];\n}\n\n/**\n * Generate per-service barrel files (interfaces/index.ts) that re-export\n * all interface and enum files for each service directory. This reduces\n * the root barrel from ~200+ individual type exports to one wildcard\n * re-export per service.\n */\nfunction generateServiceBarrels(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const { modelToService, resolveDir, serviceNameMap } = createServiceDirResolver(spec.models, spec.services, ctx);\n  const enumToService = assignEnumsToServices(spec.enums, spec.services, spec.models, ctx);\n\n  // Group interface files by directory, tracking exported symbol names\n  // to prevent TS2308 duplicate export errors when two files in the same\n  // directory export the same symbol (e.g., FooResponse as a wire type\n  // from one file and a domain type from another).\n  const dirExports = new Map<string, string[]>();\n  const dirSymbols = new Map<string, Set<string>>();\n  const ownedDirNames = new Set<string>();\n  for (const service of spec.services) {\n    if (isNodeOwnedService(ctx, service.name, serviceNameMap.get(service.name))) {\n      const dir = resolveDir(service.name);\n      ownedDirNames.add(dir);\n      // Ensure owned directories always get a barrel entry, even if no\n      // model interfaces are generated (hand-written files still need it).\n      if (!dirExports.has(dir)) {\n        dirExports.set(dir, []);\n        if (!dirSymbols.has(dir)) dirSymbols.set(dir, new Set());\n      }\n    }\n  }\n\n  // Pre-seed dirSymbols with names already exported by existing interface files.\n  // When the existing SDK has an interface file in a directory that already\n  // exports a name (e.g., AuditLogSchema from create-audit-log-schema-options),\n  // the generated model with the same name must be skipped to prevent the\n  // merger from adding a duplicate `export *` that causes TS2308.\n  //\n  // Also track baseline file stems per directory so we can detect when the\n  // barrel needs updating with new export lines (see hasNewExports below).\n  const dirSymbolsFromBaseline = new Map<string, Set<string>>();\n  const seedFromBaseline = (sourceFile: string, name: string) => {\n    const match = sourceFile.match(/^src\\/([^/]+)\\/interfaces\\/(.+)\\.ts$/);\n    if (!match) return;\n    const dirName = match[1];\n    if (ownedDirNames.has(dirName)) return;\n    const fileStem = match[2];\n    if (!dirSymbols.has(dirName)) dirSymbols.set(dirName, new Set());\n    dirSymbols.get(dirName)!.add(name);\n    if (!dirSymbolsFromBaseline.has(dirName)) dirSymbolsFromBaseline.set(dirName, new Set());\n    dirSymbolsFromBaseline.get(dirName)!.add(fileStem);\n  };\n  if (ctx.apiSurface?.interfaces) {\n    for (const [name, iface] of Object.entries(ctx.apiSurface.interfaces)) {\n      const sourceFile = (iface as any).sourceFile as string | undefined;\n      if (sourceFile) seedFromBaseline(sourceFile, name);\n    }\n  }\n  if (ctx.apiSurface?.enums) {\n    for (const [name, enumDef] of Object.entries(ctx.apiSurface.enums)) {\n      const sourceFile = (enumDef as any).sourceFile as string | undefined;\n      if (sourceFile) seedFromBaseline(sourceFile, name);\n    }\n  }\n  if (ctx.apiSurface?.typeAliases) {\n    for (const [name, alias] of Object.entries(ctx.apiSurface.typeAliases)) {\n      const sourceFile = (alias as any).sourceFile as string | undefined;\n      if (sourceFile) seedFromBaseline(sourceFile, name);\n    }\n  }\n\n  // Build a global set of all symbols across all directories for\n  // cross-directory deduplication.  This prevents adding a model to one\n  // directory's barrel when the same symbol already exists in another\n  // directory's barrel (e.g., Event in common vs events, DirectoryState\n  // in directory-sync vs common).\n  const globalExistingSymbols = new Set<string>();\n  for (const symbols of dirSymbols.values()) {\n    for (const sym of symbols) {\n      globalExistingSymbols.add(sym);\n    }\n  }\n\n  // Models -> service directories\n  // Skip list wrapper and list metadata models — they use shared List<T>/ListMetadata\n  // from common utils, so no per-resource interface file is generated.\n  // Also skip unreachable models — use the same non-event reachability as model\n  // generation so every barrel entry has a corresponding generated file.\n  const barrelReachable =\n    generatedResourceInterfaceModelNames(spec.models, ctx) ?? computeNonEventReachable(spec.services, spec.models);\n  for (const model of spec.models) {\n    if (isListMetadataModel(model) || isListWrapperModel(model)) continue;\n    if (!barrelReachable.has(model.name)) continue;\n    const service = modelToService.get(model.name);\n    const dirName = resolveDir(service);\n    if (!dirExports.has(dirName)) {\n      dirExports.set(dirName, []);\n      // Only initialize dirSymbols if not already pre-seeded from baseline\n      if (!dirSymbols.has(dirName)) {\n        dirSymbols.set(dirName, new Set());\n      }\n    }\n\n    // Each model file exports a domain interface and a wire interface.\n    // Track these symbols to detect cross-file collisions.\n    const domainName = resolveInterfaceName(model.name, ctx);\n    const wireName = wireInterfaceName(domainName);\n    const symbols = dirSymbols.get(dirName)!;\n\n    if (globalExistingSymbols.has(domainName) || globalExistingSymbols.has(wireName)) {\n      // Skip this model's export to avoid duplicate symbol in the barrel\n      // (checks across ALL directories, not just the target one)\n      continue;\n    }\n\n    symbols.add(domainName);\n    symbols.add(wireName);\n    // Also track in the global set so subsequent models in other directories\n    // don't re-export the same symbol (intra-generation cross-directory dedup).\n    globalExistingSymbols.add(domainName);\n    globalExistingSymbols.add(wireName);\n    dirExports.get(dirName)!.push(`export * from './${fileName(model.name)}.interface';`);\n  }\n\n  // Enums -> service directories\n  for (const enumDef of spec.enums) {\n    // Inlined enums have no file to re-export.\n    if (isInlineEnum(enumDef.name)) continue;\n\n    const enumService = enumToService.get(enumDef.name);\n    const dirName = resolveDir(enumService);\n    if (!dirExports.has(dirName)) {\n      dirExports.set(dirName, []);\n      if (!dirSymbols.has(dirName)) {\n        dirSymbols.set(dirName, new Set());\n      }\n    }\n\n    const symbols = dirSymbols.get(dirName)!;\n    if (globalExistingSymbols.has(enumDef.name)) continue;\n\n    symbols.add(enumDef.name);\n    globalExistingSymbols.add(enumDef.name);\n    dirExports.get(dirName)!.push(`export * from './${fileName(enumDef.name)}.interface';`);\n  }\n\n  const overrideWildcardSources = new Set<string>();\n  const overrideNamedExports = new Set<string>();\n  const addOverrideTypeExport = (typeName: string | undefined) => {\n    if (!typeName) return;\n    const sourceFile = sourceFileForExportedType(ctx, typeName);\n    if (!sourceFile) return;\n    const match = sourceFile?.match(/^src\\/([^/]+)\\/interfaces\\/(.+)\\.ts$/);\n    if (!match) return;\n    const dirName = match[1];\n    const stem = match[2].replace(/\\.ts$/, '');\n    if (!dirExports.has(dirName)) {\n      dirExports.set(dirName, []);\n      if (!dirSymbols.has(dirName)) {\n        dirSymbols.set(dirName, new Set());\n      }\n    }\n    const symbols = dirSymbols.get(dirName)!;\n    const sourceKey = `${dirName}/${stem}`;\n    if (overrideWildcardSources.has(sourceKey)) return;\n\n    const sourceNames = exportedNamesForSource(ctx, sourceFile);\n    const hasConflictingNeighbor = sourceNames.some((name) => name !== typeName && globalExistingSymbols.has(name));\n    if (hasConflictingNeighbor) {\n      const exportKey = `${sourceKey}:${typeName}`;\n      if (overrideNamedExports.has(exportKey)) return;\n      dirExports.get(dirName)!.push(`export type { ${typeName} } from './${stem}';`);\n      overrideNamedExports.add(exportKey);\n      symbols.add(typeName);\n      globalExistingSymbols.add(typeName);\n      return;\n    }\n\n    dirExports.get(dirName)!.push(`export * from './${stem}';`);\n    overrideWildcardSources.add(sourceKey);\n    const namesToRegister = sourceNames.length > 0 ? sourceNames : [typeName];\n    for (const name of namesToRegister) {\n      symbols.add(name);\n      globalExistingSymbols.add(name);\n    }\n  };\n\n  for (const override of Object.values(nodeOptions(ctx).operationOverrides ?? {})) {\n    addOverrideTypeExport(override.optionsType);\n    for (const typeName of override.returnTypeImports ?? []) {\n      addOverrideTypeExport(typeName);\n    }\n  }\n\n  const generatedOptionExports = (ctx as any)._nodeGeneratedOptionInterfaceExports as\n    | Map<string, Array<{ stem: string; typeName: string }>>\n    | undefined;\n  for (const [dirName, options] of generatedOptionExports ?? []) {\n    if (!dirExports.has(dirName)) {\n      dirExports.set(dirName, []);\n      if (!dirSymbols.has(dirName)) {\n        dirSymbols.set(dirName, new Set());\n      }\n    }\n    const symbols = dirSymbols.get(dirName)!;\n    for (const { stem, typeName } of options) {\n      if (globalExistingSymbols.has(typeName)) continue;\n      symbols.add(typeName);\n      globalExistingSymbols.add(typeName);\n      dirExports.get(dirName)!.push(`export * from './${stem}';`);\n    }\n  }\n\n  for (const [dirName, exports] of dirExports) {\n    const exportSet = new Set(exports);\n    const isDirOwned = ownedDirNames.has(dirName);\n\n    // When integrating into an existing SDK, include baseline exports from\n    // the api-surface so the barrel is comprehensive.  This ensures stale\n    // entries (e.g., renamed files from previous generations) are removed\n    // when overwriteExisting replaces the barrel.\n    if (ctx.apiSurface && !isDirOwned) {\n      const addBaselineExports = (items: Record<string, any> | undefined) => {\n        if (!items) return;\n        for (const item of Object.values(items)) {\n          const sourceFile = (item as any).sourceFile as string | undefined;\n          if (!sourceFile) continue;\n          const match = sourceFile.match(/^src\\/([^/]+)\\/interfaces\\/(.+)\\.ts$/);\n          if (match && match[1] === dirName) {\n            exportSet.add(`export * from './${match[2].replace(/\\.ts$/, '')}';`);\n          }\n        }\n      };\n      addBaselineExports(ctx.apiSurface.interfaces);\n      addBaselineExports(ctx.apiSurface.typeAliases);\n      addBaselineExports(ctx.apiSurface.enums);\n\n      // Preserve existing barrel entries: read the current barrel from the\n      // target directory and keep every `export * from './<stem>'` whose\n      // corresponding file still exists on disk.  This prevents dropping\n      // hand-written types (e.g., Factor in multi-factor-auth) when a\n      // generated model in the same file causes a symbol collision.\n      if (ctx.targetDir && !isDirOwned) {\n        const interfacesDir = path.join(ctx.targetDir, 'src', dirName, 'interfaces');\n        try {\n          const barrelPath = path.join(interfacesDir, 'index.ts');\n          const barrelContent = fs.readFileSync(barrelPath, 'utf-8');\n          for (const line of barrelContent.split('\\n')) {\n            const match = line.match(/^export \\* from '\\.\\/(.*?)';?$/);\n            if (!match) continue;\n            const stem = match[1];\n            const exportLine = `export * from './${stem}';`;\n            if (exportSet.has(exportLine)) continue;\n            // Verify the referenced file still exists\n            const filePath = path.join(interfacesDir, `${stem}.ts`);\n            try {\n              fs.accessSync(filePath);\n              exportSet.add(exportLine);\n            } catch {\n              // File no longer exists — don't preserve stale entry\n            }\n          }\n        } catch {\n          // No existing barrel — nothing to preserve\n        }\n\n        // Also scan for NEW interface files not in the existing barrel or\n        // apiSurface (e.g., list wrappers, hand-written types added after\n        // the last generation).\n        const symbols = dirSymbols.get(dirName) ?? new Set<string>();\n        try {\n          for (const entry of fs.readdirSync(interfacesDir)) {\n            if (entry === 'index.ts') continue;\n            if (!entry.endsWith('.ts')) continue;\n            const stem = entry.replace(/\\.ts$/, '');\n            const exportLine = `export * from './${stem}';`;\n            if (exportSet.has(exportLine)) continue;\n\n            // Extract exported symbol names from the file to check for conflicts\n            const content = fs.readFileSync(path.join(interfacesDir, entry), 'utf-8');\n            const exportedNames: string[] = [];\n            for (const m of content.matchAll(/export\\s+(?:interface|type|enum|class|const|function)\\s+(\\w+)/g)) {\n              exportedNames.push(m[1]);\n            }\n\n            // Skip if any exported name collides with a symbol already\n            // claimed by any file (same or different directory)\n            const hasCollision = exportedNames.some((name) => globalExistingSymbols.has(name));\n            if (hasCollision) continue;\n\n            // Safe to add — register symbols and include in barrel\n            for (const name of exportedNames) {\n              symbols.add(name);\n              globalExistingSymbols.add(name);\n            }\n            exportSet.add(exportLine);\n          }\n        } catch {\n          // Directory doesn't exist in target — nothing to scan\n        }\n      }\n    }\n\n    // For owned directories, scan the interfaces directory for hand-written\n    // files that still need to be in the barrel (e.g., options interfaces\n    // preserved from the baseline).\n    const ownedScanRoot = ctx.targetDir ?? ctx.outputDir;\n    if (ownedScanRoot && isDirOwned) {\n      const interfacesDir = path.join(ownedScanRoot, 'src', dirName, 'interfaces');\n      const symbols = dirSymbols.get(dirName) ?? new Set<string>();\n      try {\n        for (const entry of fs.readdirSync(interfacesDir)) {\n          if (entry === 'index.ts') continue;\n          if (!entry.endsWith('.ts')) continue;\n          const stem = entry.replace(/\\.ts$/, '');\n          const exportLine = `export * from './${stem}';`;\n          if (exportSet.has(exportLine)) continue;\n          const content = fs.readFileSync(path.join(interfacesDir, entry), 'utf-8');\n          const exportedNames: string[] = [];\n          for (const m of content.matchAll(/export\\s+(?:interface|type|enum|class|const|function)\\s+(\\w+)/g)) {\n            exportedNames.push(m[1]);\n          }\n          const hasCollision = exportedNames.some((name) => globalExistingSymbols.has(name));\n          if (hasCollision) continue;\n          for (const name of exportedNames) {\n            symbols.add(name);\n            globalExistingSymbols.add(name);\n          }\n          exportSet.add(exportLine);\n        }\n      } catch {\n        // Directory doesn't exist in target\n      }\n    }\n\n    // Deduplicate and sort\n    const uniqueExports = [...exportSet];\n    uniqueExports.sort();\n\n    if (ctx.apiSurface) {\n      // Integration mode: overwrite the barrel so stale entries are removed.\n      files.push({\n        path: `src/${dirName}/interfaces/index.ts`,\n        content: uniqueExports.join('\\n'),\n        overwriteExisting: true,\n      });\n    } else {\n      // Standalone generation: only update if there are new exports.\n      const baselineSymbols = dirSymbolsFromBaseline.get(dirName);\n      const hasNewExports = baselineSymbols\n        ? uniqueExports.some((exp) => {\n            const match = exp.match(/from '\\.\\/(.*?)'/);\n            if (!match) return false;\n            return !baselineSymbols.has(match[1]);\n          })\n        : false;\n\n      files.push({\n        path: `src/${dirName}/interfaces/index.ts`,\n        content: uniqueExports.join('\\n'),\n        skipIfExists: !hasNewExports,\n      });\n    }\n  }\n\n  return files;\n}\n\nfunction generateBarrel(spec: ApiSpec, ctx: EmitterContext): GeneratedFile {\n  const lines: string[] = [];\n  const { modelToService, resolveDir } = createServiceDirResolver(spec.models, spec.services, ctx);\n  const enumToService = assignEnumsToServices(spec.enums, spec.services, spec.models, ctx);\n\n  // Track all exported names to prevent duplicates.\n  // Pre-seed with names already exported by the existing SDK to avoid generating\n  // duplicate exports that would conflict with existing `export *` statements.\n  const exportedNames = new Set<string>();\n  if (ctx.apiSurface?.interfaces) {\n    for (const name of Object.keys(ctx.apiSurface.interfaces)) {\n      exportedNames.add(name);\n    }\n  }\n  if (ctx.apiSurface?.classes) {\n    for (const name of Object.keys(ctx.apiSurface.classes)) {\n      exportedNames.add(name);\n    }\n  }\n\n  // Collect names already exported by the existing SDK (via export * or named exports).\n  // When an explicit `export type { Foo }` would shadow a wildcard re-export that\n  // already provides a hand-written version of Foo (e.g., a discriminated union),\n  // we must skip the explicit export so the wildcard wins.\n  const existingSdkExports = new Set<string>();\n  if (ctx.apiSurface?.exports) {\n    for (const names of Object.values(ctx.apiSurface.exports)) {\n      for (const name of names) {\n        existingSdkExports.add(name);\n      }\n    }\n  }\n\n  // Common exports\n  lines.push(\"export * from './common/exceptions';\");\n  lines.push(\"export { AutoPaginatable } from './common/utils/pagination';\");\n  lines.push(\"export type { List, ListMetadata, ListResponse } from './common/utils/pagination';\");\n  lines.push(\"export type { PaginationOptions } from './common/interfaces/pagination-options.interface';\");\n  lines.push(\"export type { WorkOSOptions } from './common/interfaces/workos-options.interface';\");\n  lines.push(\"export type { PostOptions } from './common/interfaces/post-options.interface';\");\n  lines.push(\"export type { GetOptions } from './common/interfaces/get-options.interface';\");\n  lines.push('');\n  for (const name of [\n    'AutoPaginatable',\n    'List',\n    'ListMetadata',\n    'ListResponse',\n    'PaginationOptions',\n    'WorkOSOptions',\n    'PostOptions',\n    'GetOptions',\n  ]) {\n    exportedNames.add(name);\n  }\n\n  // Identify services whose endpoints are fully covered by existing hand-written\n  // classes — their resource class should not be re-exported from the barrel.\n  const coveredServicesBarrel = new Set<string>();\n  for (const service of spec.services) {\n    if (isServiceCoveredByExisting(service, ctx)) {\n      coveredServicesBarrel.add(service.name);\n    }\n  }\n\n  // Track directories that have already been wildcard-exported\n  const exportedDirs = new Set<string>();\n\n  // Pre-compute all names per interfaces directory (generated + baseline) to detect\n  // cross-directory conflicts before emitting any star exports.  A star export is\n  // unsafe when two different directories export the same name (e.g., Factor in\n  // both mfa/interfaces and user-management/interfaces).\n  const dirAllNames = new Map<string, Set<string>>();\n  for (const service of spec.services) {\n    const iDir = resolveDir(service.name);\n    if (!dirAllNames.has(iDir)) dirAllNames.set(iDir, new Set());\n    const names = dirAllNames.get(iDir)!;\n    for (const model of spec.models) {\n      if (modelToService.get(model.name) !== service.name) continue;\n      if (isListMetadataModel(model) || isListWrapperModel(model)) continue;\n      names.add(resolveInterfaceName(model.name, ctx));\n      names.add(wireInterfaceName(resolveInterfaceName(model.name, ctx)));\n    }\n  }\n  // Add baseline names per directory\n  if (ctx.apiSurface?.interfaces) {\n    for (const [name, iface] of Object.entries(ctx.apiSurface.interfaces)) {\n      const sourceFile = (iface as any).sourceFile as string | undefined;\n      if (!sourceFile) continue;\n      const match = sourceFile.match(/^src\\/([^/]+)\\/interfaces\\//);\n      if (match) {\n        const dirName = match[1];\n        if (!dirAllNames.has(dirName)) dirAllNames.set(dirName, new Set());\n        dirAllNames.get(dirName)!.add(name);\n      }\n    }\n  }\n  if (ctx.apiSurface?.typeAliases) {\n    for (const [name, alias] of Object.entries(ctx.apiSurface.typeAliases)) {\n      const sourceFile = (alias as any).sourceFile as string | undefined;\n      if (!sourceFile) continue;\n      const match = sourceFile.match(/^src\\/([^/]+)\\/interfaces\\//);\n      if (match) {\n        const dirName = match[1];\n        if (!dirAllNames.has(dirName)) dirAllNames.set(dirName, new Set());\n        dirAllNames.get(dirName)!.add(name);\n      }\n    }\n  }\n  // Detect directories with cross-directory name conflicts\n  const unsafeStarDirs = new Set<string>();\n  const allDirEntries = [...dirAllNames.entries()];\n  for (let i = 0; i < allDirEntries.length; i++) {\n    for (let j = i + 1; j < allDirEntries.length; j++) {\n      const [dirA, namesA] = allDirEntries[i];\n      const [dirB, namesB] = allDirEntries[j];\n      for (const name of namesA) {\n        if (namesB.has(name)) {\n          unsafeStarDirs.add(dirA);\n          unsafeStarDirs.add(dirB);\n          break;\n        }\n      }\n    }\n  }\n\n  // Per-service exports: service barrel + resource class\n  for (const service of spec.services) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const serviceDir = resolveResourceDir(service, ctx);\n    // The interfaces directory may differ from the resource class directory when\n    // a service's class name is remapped (e.g., WebhooksEndpoints class lives in\n    // webhooks-endpoints/ but its model interfaces live in webhooks/).\n    const interfacesDir = resolveDir(service.name);\n\n    // Check if this service has any models or enums (i.e., a barrel was generated).\n    // Exclude list wrapper and list metadata models — these are skipped during\n    // interface generation (they use shared List<T>/ListMetadata), so they don't\n    // have corresponding .interface.ts files in the output.\n    const serviceModels = spec.models.filter((m) => {\n      if (modelToService.get(m.name) !== service.name) return false;\n      if (isListMetadataModel(m) || isListWrapperModel(m)) return false;\n      return true;\n    });\n    const serviceEnums = spec.enums.filter((e) => {\n      const enumService = enumToService.get(e.name);\n      return enumService === service.name;\n    });\n\n    // Check whether any model or enum in this service conflicts with names already\n    // exported (from earlier star exports or the existing SDK baseline).  If so, fall\n    // back to individual named exports to avoid duplicate-export TS2308 errors.\n    const hasConflict =\n      serviceModels.some((m) => {\n        const name = resolveInterfaceName(m.name, ctx);\n        return existingSdkExports.has(name) || exportedNames.has(name) || exportedNames.has(wireInterfaceName(name));\n      }) || serviceEnums.some((e) => existingSdkExports.has(e.name) || exportedNames.has(e.name));\n\n    // Skip star export for covered services — their directory may have hand-written types\n    // (e.g., Factor in mfa/) that conflict with types in the covering service's directory.\n    const isCovered = coveredServicesBarrel.has(service.name);\n    if (\n      (serviceModels.length > 0 || serviceEnums.length > 0) &&\n      !exportedDirs.has(interfacesDir) &&\n      !hasConflict &&\n      !unsafeStarDirs.has(interfacesDir) &&\n      !isCovered\n    ) {\n      exportedDirs.add(interfacesDir);\n      lines.push(`export * from './${interfacesDir}/interfaces';`);\n      // Track the individual names so they don't get re-exported below\n      for (const model of serviceModels) {\n        exportedNames.add(resolveInterfaceName(model.name, ctx));\n        exportedNames.add(wireInterfaceName(resolveInterfaceName(model.name, ctx)));\n      }\n      for (const enumDef of serviceEnums) {\n        exportedNames.add(enumDef.name);\n      }\n    } else if (!hasConflict) {\n      // Fallback: emit individual model exports (e.g., when no models/enums exist)\n      for (const model of serviceModels) {\n        const name = resolveInterfaceName(model.name, ctx);\n        const wireName = wireInterfaceName(name);\n        if (exportedNames.has(name) || exportedNames.has(wireName)) continue;\n        if (existingSdkExports.has(name)) continue;\n        exportedNames.add(name);\n        exportedNames.add(wireName);\n        lines.push(\n          `export type { ${name}, ${wireName} } from './${interfacesDir}/interfaces/${fileName(model.name)}.interface';`,\n        );\n      }\n    }\n\n    // Resource class — skip if already exported or if service is fully covered\n    // by existing hand-written classes\n    if (coveredServicesBarrel.has(service.name)) {\n      // Emit a comment indicating this service is covered by an existing class\n      lines.push(`// ${resolvedName} is covered by an existing hand-written class — not re-exported.`);\n    } else if (!exportedNames.has(resolvedName)) {\n      exportedNames.add(resolvedName);\n      lines.push(`export { ${resolvedName} } from './${serviceDir}/${fileName(resolvedName)}';`);\n    }\n    lines.push('');\n  }\n\n  // Unassigned models (common) — use barrel if any exist\n  // Filter to reachable models only: oagen's generateAllFiles passes only\n  // service-referenced models to generateModels, so unreachable models\n  // never get interface files.  Exporting them here would create broken imports.\n  const reachable = computeNonEventReachable(spec.services, spec.models);\n  const unassignedModels = spec.models.filter((m) => !modelToService.has(m.name) && reachable.has(m.name));\n  const commonEnums = spec.enums.filter((e) => {\n    const enumService = enumToService.get(e.name);\n    return !enumService;\n  });\n\n  const commonHasConflict =\n    unassignedModels.some((m) => existingSdkExports.has(resolveInterfaceName(m.name, ctx))) ||\n    commonEnums.some((e) => existingSdkExports.has(e.name));\n\n  if ((unassignedModels.length > 0 || commonEnums.length > 0) && !exportedDirs.has('common') && !commonHasConflict) {\n    exportedDirs.add('common');\n    lines.push(\"export * from './common/interfaces';\");\n    for (const model of unassignedModels) {\n      exportedNames.add(resolveInterfaceName(model.name, ctx));\n      exportedNames.add(wireInterfaceName(resolveInterfaceName(model.name, ctx)));\n    }\n    for (const enumDef of commonEnums) {\n      exportedNames.add(enumDef.name);\n    }\n  } else {\n    // Fallback: individual model exports\n    for (const model of unassignedModels) {\n      const name = resolveInterfaceName(model.name, ctx);\n      const wireName = wireInterfaceName(name);\n      if (exportedNames.has(name) || exportedNames.has(wireName)) continue;\n      if (existingSdkExports.has(name)) continue;\n      exportedNames.add(name);\n      exportedNames.add(wireName);\n      lines.push(`export type { ${name}, ${wireName} } from './common/interfaces/${fileName(model.name)}.interface';`);\n    }\n  }\n\n  // Enum exports — only for enums not already covered by a service/common barrel.\n  // Skip duplicates and names already covered by existing SDK wildcards.\n  // Use value export (`export { ... }`) for actual TS enums so consumers\n  // can use them as runtime values (e.g., ConnectionType.GoogleOAuth).\n  // Use type-only export (`export type { ... }`) for string literal unions.\n  for (const enumDef of spec.enums) {\n    if (exportedNames.has(enumDef.name)) continue;\n    if (existingSdkExports.has(enumDef.name)) continue;\n    exportedNames.add(enumDef.name);\n    const enumService = enumToService.get(enumDef.name);\n    const dir = resolveDir(enumService);\n    if (!exportedDirs.has(dir)) {\n      const baselineEnum = ctx.apiSurface?.enums?.[enumDef.name];\n      const exportKeyword = baselineEnum?.members ? 'export' : 'export type';\n      lines.push(\n        `${exportKeyword} { ${enumDef.name} } from './${dir}/interfaces/${fileName(enumDef.name)}.interface';`,\n      );\n    }\n  }\n\n  lines.push('');\n  // Only emit the WorkOS re-export for standalone generation (no existing SDK).\n  // When integrating into an existing SDK, the existing barrel already exports\n  // WorkOS (often as a subclass alias like `export { WorkOSNode as WorkOS }`),\n  // and adding a second export with the same name causes a duplicate identifier error.\n  if (!ctx.apiSurface && !exportedNames.has('WorkOS')) {\n    exportedNames.add('WorkOS');\n    lines.push(\"export { WorkOS } from './workos';\");\n  }\n\n  return {\n    path: 'src/index.ts',\n    content: lines.join('\\n'),\n    skipIfExists: true,\n  };\n}\n\n/**\n * Determine whether the spec's auth scheme requires overriding the\n * default bearer auth in WorkOSBase.setAuthHeaders().\n */\nfunction needsAuthOverride(auth?: AuthScheme[]): boolean {\n  if (!auth || auth.length === 0) return false;\n  const scheme = auth[0];\n  // bearer and oauth2 match the base class default — no override needed\n  return scheme.kind === 'apiKey';\n}\n\n/**\n * Render the body of a setAuthHeaders override for non-default auth schemes.\n * Only called when needsAuthOverride() returns true.\n */\nfunction renderAuthOverride(lines: string[], auth: AuthScheme[]): void {\n  const scheme = auth[0];\n  if (scheme.kind !== 'apiKey') return;\n  switch (scheme.in) {\n    case 'header':\n      lines.push(`    headers['${scheme.name}'] = this.key;`);\n      break;\n    case 'query':\n      lines.push(`    // Auth key sent as query parameter '${scheme.name}' (see buildUrl)`);\n      break;\n    case 'cookie':\n      lines.push(`    headers['Cookie'] = \\`${scheme.name}=\\${this.key}\\`;`);\n      break;\n  }\n}\n\n/**\n * Convert a server description or URL into a SCREAMING_SNAKE_CASE constant name.\n */\nfunction serverConstName(description: string): string {\n  return (\n    'SERVER_' +\n    description\n      .replace(/https?:\\/\\//g, '')\n      .replace(/[^a-zA-Z0-9]+/g, '_')\n      .replace(/^_|_$/g, '')\n      .toUpperCase()\n  );\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type {\n  ApiSpec,\n  Service,\n  Operation,\n  Model,\n  TypeRef,\n  Parameter,\n  EmitterContext,\n  GeneratedFile,\n} from '@workos/oagen';\nimport { toCamelCase, toPascalCase } from '@workos/oagen';\nimport { unwrapListModel, ID_PREFIXES } from './fixtures.js';\nimport {\n  fieldName,\n  wireFieldName,\n  fileName,\n  resolveServiceDir,\n  servicePropertyName,\n  resolveMethodName,\n  resolveInterfaceName,\n  resolveServiceName,\n  wireInterfaceName,\n} from './naming.js';\nimport { generateFixtures } from './fixtures.js';\nimport { resolveResourceClassName, resolveResourceDir, ignoredResourceMethodNames } from './resources.js';\nimport {\n  assignModelsToServices,\n  createServiceDirResolver,\n  uncoveredOperations,\n  relativeImport,\n  isListMetadataModel,\n  isListWrapperModel,\n  modelHasNewFields,\n  computeNonEventReachable,\n} from './utils.js';\nimport { groupByMount, buildResolvedLookup, lookupResolved, isMountInScope } from '../shared/resolved-ops.js';\nimport { isNodeOwnedService, nodeOptions, planOperationFor } from './options.js';\n\ntype BaselineMethod = {\n  params: Array<{ name: string; type: string; optional?: boolean; passingStyle?: string }>;\n  returnType?: string;\n};\n\nfunction operationOverrideFor(ctx: EmitterContext, op: Operation) {\n  return nodeOptions(ctx).operationOverrides?.[`${op.httpMethod.toUpperCase()} ${op.path}`];\n}\n\nfunction baselineMethodFor(service: Service, method: string, ctx: EmitterContext): BaselineMethod | undefined {\n  const serviceClass = resolveResourceClassName(service, ctx);\n  return ctx.apiSurface?.classes?.[serviceClass]?.methods?.[method]?.[0] as BaselineMethod | undefined;\n}\n\nfunction optionsObjectParam(method: BaselineMethod | undefined): { name: string; type: string } | undefined {\n  if (!method || method.params.length !== 1) return undefined;\n  const [param] = method.params;\n  if (param.name !== 'options') return undefined;\n  if (param.passingStyle && param.passingStyle !== 'options_object') return undefined;\n  // Strip the `| undefined` arm of an optional param's surface type so the\n  // bare type name is used (mirrors resources.ts optionsObjectParam).\n  const type = param.type?.replace(/(?:\\s*\\|\\s*(?:undefined|null))+\\s*$/, '').trim();\n  if (!type || /^(Record|object|any|unknown)\\b/.test(type)) return undefined;\n  return { name: param.name, type };\n}\n\nfunction configuredOptionsMethod(ctx: EmitterContext, op: Operation): BaselineMethod | undefined {\n  const optionsType = operationOverrideFor(ctx, op)?.optionsType;\n  if (!optionsType) return undefined;\n  return {\n    params: [{ name: 'options', type: optionsType, passingStyle: 'options_object' }],\n  };\n}\n\nfunction methodOptionsName(method: string, serviceClass: string): string {\n  if (method === 'list') return `${toPascalCase(serviceClass)}ListOptions`;\n  return `${toPascalCase(method)}Options`;\n}\n\nfunction hasOptionsInput(op: Operation, plan: any): boolean {\n  return op.pathParams.length > 0 || plan.hasBody || plan.isPaginated || op.queryParams.length > 0;\n}\n\nfunction optionsMethodFor(\n  service: Service,\n  method: string,\n  op: Operation,\n  plan: any,\n  ctx: EmitterContext,\n): BaselineMethod | undefined {\n  const baseline = baselineMethodFor(service, method, ctx);\n  if (optionsObjectParam(baseline)) return baseline;\n\n  const configured = configuredOptionsMethod(ctx, op);\n  if (configured) return configured;\n\n  if (!hasOptionsInput(op, plan)) return baseline;\n  return {\n    params: [\n      {\n        name: 'options',\n        type: methodOptionsName(method, resolveResourceClassName(service, ctx)),\n        passingStyle: 'options_object',\n      },\n    ],\n  };\n}\n\nfunction autoPaginatableItemType(returnType: string | undefined): string | undefined {\n  return returnType?.match(/\\bAutoPaginatable<\\s*([A-Za-z_$][\\w$]*)/)?.[1];\n}\n\nexport function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  // Generate fixture JSON files\n  const fixtures = generateFixtures(spec, ctx);\n  for (const f of fixtures) {\n    files.push({ path: f.path, content: f.content, headerPlacement: 'skip', skipIfExists: true });\n  }\n\n  // Build model lookup for response field assertions\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n\n  // Generate test files per mount target — merges all sub-services into one\n  // test file. Skip operations already covered by existing hand-written classes.\n  const mountGroups = groupByMount(ctx);\n\n  // Build mount-target → property name map so tests use the same accessor\n  // as the generated client, even when the mount target name doesn't match\n  // any IR service name directly.\n  const mountAccessors = new Map<string, string>();\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (!mountAccessors.has(r.mountOn)) {\n      mountAccessors.set(r.mountOn, servicePropertyName(r.mountOn));\n    }\n  }\n\n  const testEntries: Array<{ name: string; operations: Operation[] }> =\n    mountGroups.size > 0 || ctx.scopedServices?.size\n      ? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations }))\n      : spec.services.map((s) => ({ name: resolveResourceClassName(s, ctx), operations: s.operations }));\n\n  // When integrating into an existing SDK, only generate tests for services\n  // that have a registered property on the WorkOS class.  The WorkOS client\n  // file uses skipIfExists, so new service properties aren't added — tests\n  // referencing workos.<service> would fail at compile time.\n  const baselineWorkOSProps = new Set<string>();\n  if (ctx.apiSurface?.classes?.['WorkOS']?.methods) {\n    // The extractor stores property accessors as methods\n    for (const name of Object.keys(ctx.apiSurface.classes['WorkOS'].methods)) {\n      baselineWorkOSProps.add(name);\n    }\n  }\n  if (ctx.apiSurface?.classes?.['WorkOS']?.properties) {\n    for (const name of Object.keys(ctx.apiSurface.classes['WorkOS'].properties)) {\n      baselineWorkOSProps.add(name);\n    }\n  }\n\n  for (const { name: mountName, operations } of testEntries) {\n    // Scope gate: in a scoped (`--services`) run, only emit per-service test\n    // files for the selected post-mount names. `mountName` is the mount-group\n    // key (the POST-MOUNT name that matches `ctx.scopedServices`). Applied as an\n    // additional early continue ahead of the node-owned/coverage skip logic.\n    if (!isMountInScope(mountName, ctx)) continue;\n    if (operations.length === 0) continue;\n    const mergedService: Service = { name: mountName, operations };\n    const isOwnedService = isNodeOwnedService(ctx, mountName, resolveResourceClassName(mergedService, ctx));\n    const ops = isOwnedService ? operations : uncoveredOperations(mergedService, ctx);\n    if (ops.length === 0) continue;\n    // Methods hand-owned inside an `@oagen-ignore` region of the resource\n    // file: resources.ts skips generating those methods, so a generated test\n    // would reference a shape that no longer matches the preserved hand-written\n    // signature (e.g. SSO's `getAuthorizationUrl` returns a string, not\n    // `{ url }`). Their `describe` blocks are skipped below, but the ops are\n    // still passed through so entity-assertion helpers their preserved\n    // hand-written test blocks rely on continue to be emitted.\n    const ignoredMethodNames = ignoredResourceMethodNames(\n      ctx,\n      `src/${resolveResourceDir(mergedService, ctx)}/${fileName(resolveResourceClassName(mergedService, ctx))}.ts`,\n    );\n\n    // Skip tests for services without a WorkOS property in the baseline\n    const propName = mountAccessors.get(mountName) ?? servicePropertyName(mountName);\n    if (ctx.apiSurface && baselineWorkOSProps.size > 0 && !baselineWorkOSProps.has(propName)) continue;\n\n    // Skip when the resource class diverges from the mount accessor — this\n    // happens for services with constructor-incompatible baselines (e.g.\n    // hand-written `Webhooks(crypto)` forks the emitted ops onto\n    // `WebhooksEndpoints`). The generated test would do\n    // `workos.<propName>.fooMethod(...)`, but those methods live on a\n    // different class, so the test would fail to compile.\n    const resourceClass = resolveResourceClassName(mergedService, ctx);\n    if (resourceClass !== mountName) continue;\n\n    const testService = ops.length < operations.length ? { ...mergedService, operations: ops } : mergedService;\n    files.push(generateServiceTest(testService, spec, ctx, modelMap, mountAccessors, ignoredMethodNames));\n  }\n\n  // Generate serializer round-trip tests\n  const serializerTests = generateSerializerTests(spec, ctx);\n  for (const f of serializerTests) {\n    files.push(f);\n  }\n\n  return files;\n}\n\nfunction generateServiceTest(\n  service: Service,\n  spec: ApiSpec,\n  ctx: EmitterContext,\n  modelMap: Map<string, Model>,\n  mountAccessors?: Map<string, string>,\n  ignoredMethodNames: Set<string> = new Set(),\n): GeneratedFile {\n  const resolvedName = resolveResourceClassName(service, ctx);\n  const serviceDir = resolveResourceDir(service, ctx);\n  const serviceClass = resolvedName;\n  // Accessor stays un-suffixed so `client.organizationMembership` resolves even\n  // when the class was renamed to dodge a model-name collision.\n  const serviceProp = mountAccessors?.get(service.name) ?? servicePropertyName(resolveServiceName(service, ctx));\n  const testPath = `src/${serviceDir}/${fileName(resolvedName)}.spec.ts`;\n\n  const allPlans = service.operations.map((op) => ({\n    op,\n    plan: planOperationFor(op, ctx),\n    method: resolveMethodName(op, service, ctx),\n  }));\n  // `plans` drives everything that becomes generated text (fixture imports,\n  // test-util imports, `describe` blocks): exclude hand-owned methods so we\n  // don't emit broken tests against their preserved signatures. `allPlans`\n  // is retained only for entity-helper counting — a hand-owned method's\n  // preserved `@oagen-ignore` test block may still rely on an\n  // `expect<Model>()` helper that the generated tests would otherwise drop.\n  //\n  // URL-builder ops (e.g. `getLogoutUrl`) return a string synchronously and\n  // make no HTTP call, so the fetch-mock test shape (`fetchMethod()` etc.)\n  // throws at runtime. Skip them — like the hand-owned URL helpers.\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const preservedScopes = methodsWithPreservedTestBlocks(ctx, testPath);\n  const plans = allPlans.filter((p) => {\n    // Keep the describe when a preserved hand-written `@oagen-ignore` test\n    // block is nested under it, so it isn't orphaned out of scope.\n    if (preservedScopes.has(p.method)) return true;\n    if (ignoredMethodNames.has(p.method)) return false;\n    if (lookupResolved(p.op, resolvedLookup)?.urlBuilder) return false;\n    return true;\n  });\n\n  // Sort plans to match the existing file's method order (same as resources.ts).\n  if (ctx.overlayLookup?.methodByOperation) {\n    const methodOrder = new Map<string, number>();\n    let pos = 0;\n    for (const [, info] of ctx.overlayLookup.methodByOperation) {\n      if (!methodOrder.has(info.methodName)) {\n        methodOrder.set(info.methodName, pos++);\n      }\n    }\n    if (methodOrder.size > 0) {\n      plans.sort((a, b) => {\n        const aPos = methodOrder.get(a.method) ?? Number.MAX_SAFE_INTEGER;\n        const bPos = methodOrder.get(b.method) ?? Number.MAX_SAFE_INTEGER;\n        return aPos - bPos;\n      });\n    }\n  }\n\n  // Compute model-to-service mapping so fixture imports use the correct cross-service path.\n  // A test for service A may reference a response model owned by service B — the fixture\n  // lives in service B's fixtures directory, not service A's.\n  const { modelToService, resolveDir } = createServiceDirResolver(spec.models, spec.services, ctx);\n\n  const lines: string[] = [];\n\n  lines.push(\"import fetch from 'jest-fetch-mock';\");\n\n  // Conditionally import test utilities based on what test types exist\n  const hasPaginated = plans.some((p) => p.plan.isPaginated);\n  const hasBody = plans.some((p) => p.plan.hasBody);\n  const testUtils = ['fetchOnce', 'fetchURL', 'fetchMethod'];\n  if (hasPaginated) testUtils.push('fetchSearchParams');\n  if (hasBody) testUtils.push('fetchBody');\n  lines.push('import {');\n  for (const util of testUtils) {\n    lines.push(`  ${util},`);\n  }\n  lines.push(\"} from '../common/utils/test-utils';\");\n  lines.push(\"import { WorkOS } from '../workos';\");\n  lines.push('');\n\n  // Import fixtures — use correct cross-service paths when the response model\n  // is owned by a different service than the current test file.\n  const fixtureImports = new Set<string>();\n  for (const { op, plan } of plans) {\n    if (plan.isPaginated && op.pagination) {\n      let itemModelName = op.pagination.itemType.kind === 'model' ? op.pagination.itemType.name : null;\n      if (itemModelName) {\n        // Unwrap list wrapper models to match the fixture file naming in fixtures.ts\n        const rawModel = modelMap.get(itemModelName);\n        if (rawModel) {\n          const unwrapped = unwrapListModel(rawModel, modelMap);\n          if (unwrapped) {\n            itemModelName = unwrapped.name;\n          }\n        }\n        // List fixtures are always generated in the current service's directory\n        // (the service owning the list operation), not in the model's home service.\n        // Always use a local import path.\n        const fixturePath = `./fixtures/list-${fileName(itemModelName)}.json`;\n        fixtureImports.add(`import list${itemModelName}Fixture from '${fixturePath}';`);\n      }\n    } else if (plan.responseModelName) {\n      const respService = modelToService.get(plan.responseModelName);\n      const respDir = resolveDir(respService);\n      const fixturePath =\n        respDir === serviceDir\n          ? `./fixtures/${fileName(plan.responseModelName)}.json`\n          : `../${respDir}/fixtures/${fileName(plan.responseModelName)}.json`;\n      fixtureImports.add(`import ${toCamelCase(plan.responseModelName)}Fixture from '${fixturePath}';`);\n    }\n    // NOTE: Request body fixtures are not imported for body tests because\n    // fixtures use wire format (snake_case) but methods expect domain types\n    // (camelCase).  Body tests use `{} as any` instead.\n  }\n  for (const imp of fixtureImports) {\n    lines.push(imp);\n  }\n\n  lines.push('');\n  lines.push(\"const workos = new WorkOS('sk_test_Sz3IQjepeSWaI4cMS4ms4sMuU');\");\n  lines.push('');\n\n  // Generate per-entity assertion helpers for models used in 2+ tests.\n  // This deduplicates the field assertion blocks that would otherwise be\n  // copy-pasted across list/find/create/update test cases. Count across\n  // `allPlans` (incl. hand-owned methods) so a helper a preserved hand test\n  // block needs survives, but only emit one that an emitted `describe` or a\n  // preserved `@oagen-ignore` block actually references — otherwise it would\n  // be an unused function.\n  const ignoreRegionText = existingTestIgnoreText(ctx, testPath);\n  const { lines: helperLines, helpers: entityHelperNames } = generateEntityHelpers(\n    service,\n    allPlans,\n    plans,\n    ignoreRegionText,\n    modelMap,\n    ctx,\n  );\n  for (const line of helperLines) {\n    lines.push(line);\n  }\n\n  lines.push(`describe('${serviceClass}', () => {`);\n  lines.push('  beforeEach(() => fetch.resetMocks());');\n\n  for (const { op, plan, method } of plans) {\n    const existingMethod = optionsMethodFor(service, method, op, plan, ctx);\n    lines.push('');\n    lines.push(`  describe('${method}', () => {`);\n\n    if (plan.isPaginated) {\n      renderPaginatedTest(lines, op, plan, method, serviceProp, modelMap, ctx, entityHelperNames, existingMethod);\n    } else if (plan.isDelete) {\n      renderDeleteTest(lines, op, plan, method, serviceProp, modelMap, ctx, existingMethod);\n    } else if (plan.hasBody && plan.responseModelName) {\n      renderBodyTest(lines, op, plan, method, serviceProp, modelMap, ctx, entityHelperNames, existingMethod);\n    } else if (plan.responseModelName) {\n      renderGetTest(lines, op, plan, method, serviceProp, modelMap, ctx, entityHelperNames, existingMethod);\n    } else {\n      renderVoidTest(lines, op, plan, method, serviceProp, modelMap, ctx, existingMethod);\n    }\n\n    lines.push('  });');\n  }\n\n  lines.push('});');\n\n  // Inject imports for real TS enums referenced as member values (e.g.\n  // `ConnectionType.ADFSSAML`). Import each from its own source file so the\n  // value's enum is the same nominal declaration the field is typed with.\n  const body = lines.join('\\n');\n  const enumImportLines: string[] = [];\n  for (const [name, info] of Object.entries(ctx.apiSurface?.enums ?? {})) {\n    if (!new RegExp(`\\\\b${name}\\\\.[A-Za-z_$]`).test(body)) continue;\n    if (new RegExp(`import\\\\b[^;]*\\\\b${name}\\\\b[^;]*from`).test(body)) continue;\n    const sourceFile = (info as { sourceFile?: string }).sourceFile;\n    const spec = sourceFile ? relativeImport(testPath, sourceFile).replace(/\\.ts$/, '') : './interfaces';\n    enumImportLines.push(`import { ${name} } from '${spec}';`);\n  }\n  if (enumImportLines.length > 0) {\n    const anchor = lines.indexOf(\"import { WorkOS } from '../workos';\");\n    const at = anchor >= 0 ? anchor + 1 : 0;\n    lines.splice(at, 0, ...enumImportLines);\n  }\n\n  return { path: testPath, content: lines.join('\\n'), overwriteExisting: true };\n}\n\n/** Compute the test value for a single path parameter.\n *  Uses distinct values per param name so multi-param paths don't all get 'test_id'.\n */\nfunction pathParamTestValue(param: { type: TypeRef; name?: string } | undefined, paramName?: string): string {\n  if (param?.type.kind === 'enum' && param.type.values?.length) {\n    const first = param.type.values[0];\n    return typeof first === 'string' ? first : String(first);\n  }\n  // Use distinct values for different path params to detect ordering bugs\n  const name = paramName ?? (param as any)?.name;\n  if (name) return `test_${fieldName(name)}`;\n  return 'test_id';\n}\n\n/** Render an example value as a valid TS literal expression.\n *  Objects and nested arrays go through JSON.stringify so map-typed params\n *  (e.g. providerQueryParams) don't coerce to the literal text `[object Object]`.\n */\nfunction renderExampleLiteral(value: unknown): string {\n  if (typeof value === 'string') return `'${value}'`;\n  if (Array.isArray(value)) {\n    return `[${value.map(renderExampleLiteral).join(', ')}]`;\n  }\n  if (value !== null && typeof value === 'object') {\n    return JSON.stringify(value);\n  }\n  return String(value);\n}\n\n/** Resolve the enum members a query-param test value must satisfy. An enum is\n *  expressed several ways: an inline `EnumRef` with `values`, an `enum`/`model`\n *  ref by name, or — when the IR flattened the param to a bare string but the\n *  hand-written options interface still types the field as an enum — the\n *  baseline options field type (e.g. `ConnectionType`). */\n/** All valid values for an enum named `name`. The extracted SDK surface is\n *  consulted first: when an options field is typed with a hand-written enum\n *  (e.g. `ConnectionType` from `connection-type.enum.ts`), that enum — not a\n *  same-named IR enum that may carry extra members like `Pending` — is what\n *  the generated test must type-check against. Falls back to the IR spec. */\nfunction enumValuesByName(name: string, ctx?: EmitterContext): (string | number)[] | undefined {\n  const members = ctx?.apiSurface?.enums?.[name]?.members;\n  if (members && Object.keys(members).length > 0) return Object.values(members);\n  const specValues = ctx?.spec.enums.find((e) => e.name === name)?.values;\n  if (specValues?.length) return specValues.map((v) => v.value);\n  return undefined;\n}\n\nfunction resolveParamEnumValues(\n  param: Parameter,\n  optionFieldType: string | undefined,\n  ctx?: EmitterContext,\n): (string | number)[] | undefined {\n  // Prefer the enum the GENERATED options field is actually typed with — the\n  // operation's own IR enum can diverge from it (e.g. the connection_type\n  // query param resolves to `ConnectionsConnectionType` whose value\n  // 'GithubOAuth' is absent from the `ConnectionType` enum the hand-written\n  // options interface uses, where the member is 'GitHubOAuth').\n  if (optionFieldType) {\n    const bare = optionFieldType\n      .replace(/\\[\\]/g, '')\n      .replace(/\\|\\s*(undefined|null)/g, '')\n      .trim();\n    if (/^[A-Za-z_$][\\w$]*$/.test(bare)) {\n      const values = enumValuesByName(bare, ctx);\n      if (values) return values;\n    }\n  }\n  if ((param.type.kind === 'enum' || param.type.kind === 'model') && param.type.name) {\n    const values = enumValuesByName(param.type.name, ctx);\n    if (values) return values;\n  }\n  if (param.type.kind === 'enum' && param.type.values?.length) return param.type.values;\n  return undefined;\n}\n\n/** When an options field is typed with a real (nominal) TS `enum` from the SDK\n *  surface, a string literal won't type-check — the value must be a member\n *  reference (`ConnectionType.ADFSSAML`). Returns the enum's name + members so\n *  the caller can both render the reference and import the right declaration. */\nfunction resolveRealEnum(\n  param: Parameter,\n  optionFieldType: string | undefined,\n  ctx?: EmitterContext,\n): { name: string; members: Record<string, string | number> } | null {\n  const candidates: string[] = [];\n  if (optionFieldType) {\n    const bare = optionFieldType\n      .replace(/\\[\\]/g, '')\n      .replace(/\\|\\s*(undefined|null)/g, '')\n      .trim();\n    if (/^[A-Za-z_$][\\w$]*$/.test(bare)) candidates.push(bare);\n  }\n  if ((param.type.kind === 'enum' || param.type.kind === 'model') && param.type.name) candidates.push(param.type.name);\n  for (const name of candidates) {\n    const members = ctx?.apiSurface?.enums?.[name]?.members;\n    if (members && Object.keys(members).length > 0) return { name, members };\n  }\n  return null;\n}\n\nfunction queryParamTestValue(\n  param: Parameter,\n  modelMap?: Map<string, Model>,\n  ctx?: EmitterContext,\n  optionFieldType?: string,\n): string {\n  // Fields typed with a real TS enum need a member reference, not a string\n  // literal (string enums are nominal). Pick the member whose value matches the\n  // example, else the first member — `enumImportsToInject` later adds the import.\n  const realEnum = resolveRealEnum(param, optionFieldType, ctx);\n  if (realEnum) {\n    const entries = Object.entries(realEnum.members);\n    const match = typeof param.example === 'string' ? entries.find(([, v]) => v === param.example) : undefined;\n    const [memberKey] = match ?? entries[0];\n    return `${realEnum.name}.${memberKey}`;\n  }\n  // Otherwise (string-literal-union enums, inline enum refs) emit a value. A\n  // spec `example` can drift from the enum (e.g. connection_type example\n  // 'GithubOAuth' vs member 'GitHubOAuth'); prefer the example only when valid.\n  const enumValues = resolveParamEnumValues(param, optionFieldType, ctx);\n  if (enumValues?.length) {\n    const valid =\n      typeof param.example === 'string' && enumValues.includes(param.example) ? param.example : enumValues[0];\n    return typeof valid === 'string' ? `'${valid}'` : String(valid);\n  }\n  if (param.example !== undefined) {\n    const isDateTime = param.type.kind === 'primitive' && param.type.format === 'date-time';\n    if (isDateTime && typeof param.example === 'string') {\n      return `new Date('${param.example}')`;\n    }\n    return renderExampleLiteral(param.example);\n  }\n  return fixtureValueForType(param.type, param.name, 'Options', modelMap) ?? \"'test'\";\n}\n\n/** Build test arguments for all path params (handles multiple path params). */\nfunction buildTestPathArgs(op: Operation): string {\n  // Detect path template variables (may be more than op.pathParams if spec is incomplete)\n  const templateVars = [...op.path.matchAll(/\\{(\\w+)\\}/g)].map(([, name]) => fieldName(name));\n  const declaredNames = new Set(op.pathParams.map((p) => fieldName(p.name)));\n  const paramByName = new Map(op.pathParams.map((p) => [fieldName(p.name), p]));\n  // Merge declared + template vars, deduplicate, preserve order\n  const allVars: string[] = [];\n  for (const p of op.pathParams) allVars.push(fieldName(p.name));\n  for (const v of templateVars) {\n    if (!declaredNames.has(v)) allVars.push(v);\n  }\n  return allVars.map((varName) => `'${pathParamTestValue(paramByName.get(varName), varName)}'`).join(', ');\n}\n\nfunction renderPaginatedTest(\n  lines: string[],\n  op: Operation,\n  plan: any,\n  method: string,\n  serviceProp: string,\n  modelMap: Map<string, Model>,\n  ctx?: EmitterContext,\n  entityHelpers?: Set<string>,\n  baselineMethod?: BaselineMethod,\n): void {\n  let itemModelName = op.pagination?.itemType.kind === 'model' ? op.pagination.itemType.name : 'Item';\n  // Unwrap list wrapper models to match the fixture file naming in fixtures.ts\n  const rawModel = itemModelName !== 'Item' ? modelMap.get(itemModelName) : null;\n  if (rawModel) {\n    const unwrapped = unwrapListModel(rawModel, modelMap);\n    if (unwrapped) {\n      itemModelName = unwrapped.name;\n    }\n  }\n  const pathArgs = buildTestPathArgs(op);\n  const optionsArg = buildOptionsObjectTestArg(op, plan, baselineMethod, modelMap, ctx);\n  const baselineItemType = autoPaginatableItemType(baselineMethod?.returnType);\n  const generatedItemType = ctx ? resolveInterfaceName(itemModelName, ctx) : null;\n  const baselineHasNonPaginatableReturn = Boolean(baselineMethod?.returnType && !baselineItemType);\n  const skipFieldAssertions =\n    baselineHasNonPaginatableReturn ||\n    Boolean(baselineItemType && generatedItemType && baselineItemType !== generatedItemType);\n\n  lines.push(\"    it('returns paginated results', async () => {\");\n  lines.push(`      fetchOnce(list${itemModelName}Fixture);`);\n  lines.push('');\n  lines.push(`      const { data, listMetadata } = await workos.${serviceProp}.${method}(${optionsArg ?? pathArgs});`);\n  lines.push('');\n  lines.push(\"      expect(fetchMethod()).toBe('GET');\");\n  // Fix #12: Full URL path assertion instead of toContain()\n  const expectedPath = buildExpectedPath(op);\n  lines.push(`      expect(new URL(String(fetchURL())).pathname).toBe('${expectedPath}');`);\n  lines.push(\"      expect(fetchSearchParams()).toHaveProperty('order');\");\n  lines.push('      expect(Array.isArray(data)).toBe(true);');\n  lines.push('      expect(listMetadata).toBeDefined();');\n\n  // Assert on first item fields — use entity helper if available\n  const paginatedHelperName = ctx ? `expect${resolveInterfaceName(itemModelName, ctx)}` : null;\n  if (skipFieldAssertions) {\n    lines.push('      expect(data.length).toBeGreaterThan(0);');\n  } else if (paginatedHelperName && entityHelpers?.has(paginatedHelperName)) {\n    lines.push('      expect(data.length).toBeGreaterThan(0);');\n    lines.push(`      ${paginatedHelperName}(data[0]);`);\n  } else {\n    const itemModel = modelMap.get(itemModelName);\n    if (itemModel) {\n      const assertions = buildFieldAssertions(itemModel, 'data[0]', modelMap);\n      if (assertions.length > 0) {\n        lines.push('      expect(data.length).toBeGreaterThan(0);');\n        for (const assertion of assertions) {\n          lines.push(`      ${assertion}`);\n        }\n      }\n    }\n  }\n\n  lines.push('    });');\n}\n\nfunction renderDeleteTest(\n  lines: string[],\n  op: Operation,\n  plan: any,\n  method: string,\n  serviceProp: string,\n  modelMap: Map<string, Model>,\n  ctx?: EmitterContext,\n  baselineMethod?: BaselineMethod,\n): void {\n  const pathArgs = buildTestPathArgs(op);\n  // Build realistic payload for body-bearing delete operations\n  const payload = plan.hasBody ? buildTestPayload(op, modelMap) : null;\n  const bodyArg = plan.hasBody ? (payload ? payload.camelCaseObj : fallbackBodyArg(op, modelMap)) : '';\n  const optionsArg = buildOptionsObjectTestArg(op, plan, baselineMethod, modelMap, ctx);\n  const args = optionsArg ?? (plan.hasBody ? (pathArgs ? `${pathArgs}, ${bodyArg}` : bodyArg) : pathArgs);\n\n  lines.push(\"    it('sends a DELETE request', async () => {\");\n  lines.push('      fetchOnce({}, { status: 204 });');\n  lines.push('');\n  lines.push(`      await workos.${serviceProp}.${method}(${args});`);\n  lines.push('');\n  lines.push(\"      expect(fetchMethod()).toBe('DELETE');\");\n  // Fix #12: Full URL path assertion instead of toContain()\n  const expectedPathDel = buildExpectedPath(op);\n  lines.push(`      expect(new URL(String(fetchURL())).pathname).toBe('${expectedPathDel}');`);\n  if (plan.hasBody) {\n    if (payload) {\n      lines.push(`      expect(fetchBody()).toEqual(expect.objectContaining(${payload.snakeCaseObj}));`);\n    } else {\n      lines.push('      expect(fetchBody()).toBeDefined();');\n    }\n  }\n  lines.push('    });');\n}\n\nfunction renderBodyTest(\n  lines: string[],\n  op: Operation,\n  plan: any,\n  method: string,\n  serviceProp: string,\n  modelMap: Map<string, Model>,\n  ctx?: EmitterContext,\n  entityHelpers?: Set<string>,\n  baselineMethod?: BaselineMethod,\n): void {\n  const responseModelName = plan.responseModelName!;\n  const fixture = `${toCamelCase(responseModelName)}Fixture`;\n  const pathArgs = buildTestPathArgs(op);\n\n  // Build realistic payload from request body model fields\n  const payload = buildTestPayload(op, modelMap);\n  const payloadArg = payload ? payload.camelCaseObj : fallbackBodyArg(op, modelMap);\n  const optionsArg = buildOptionsObjectTestArg(op, plan, baselineMethod, modelMap, ctx);\n  const allArgs = optionsArg ?? (pathArgs ? `${pathArgs}, ${payloadArg}` : payloadArg);\n\n  const isArrayResponse = !!plan.isArrayResponse;\n  const fixtureExpr = isArrayResponse ? `[${fixture}]` : fixture;\n  const accessor = isArrayResponse ? 'result[0]' : 'result';\n\n  lines.push(\"    it('sends the correct request and returns result', async () => {\");\n  lines.push(`      fetchOnce(${fixtureExpr});`);\n  lines.push('');\n  lines.push(`      const result = await workos.${serviceProp}.${method}(${allArgs});`);\n  lines.push('');\n  lines.push(`      expect(fetchMethod()).toBe('${op.httpMethod.toUpperCase()}');`);\n\n  // Fix #12: Full URL path assertion instead of toContain()\n  const expectedPath = buildExpectedPath(op);\n  lines.push(`      expect(new URL(String(fetchURL())).pathname).toBe('${expectedPath}');`);\n\n  // Fix #10: Assert serialized wire format of request body\n  if (payload) {\n    lines.push(`      expect(fetchBody()).toEqual(expect.objectContaining(${payload.snakeCaseObj}));`);\n  } else {\n    lines.push('      expect(fetchBody()).toBeDefined();');\n  }\n\n  if (isArrayResponse) {\n    lines.push('      expect(Array.isArray(result)).toBe(true);');\n  }\n\n  const override = ctx ? operationOverrideFor(ctx, op) : undefined;\n  if (override?.returnExpression || override?.returnDataProperty) {\n    lines.push('      expect(result).toBeDefined();');\n    lines.push('    });');\n    return;\n  }\n\n  // Use entity helper if available, otherwise inline assertions\n  const bodyHelperName = ctx ? `expect${resolveInterfaceName(responseModelName, ctx)}` : null;\n  if (bodyHelperName && entityHelpers?.has(bodyHelperName)) {\n    lines.push(`      ${bodyHelperName}(${accessor});`);\n  } else {\n    const responseModel = modelMap.get(responseModelName);\n    if (responseModel) {\n      const assertions = buildFieldAssertions(responseModel, accessor, modelMap);\n      if (assertions.length > 0) {\n        for (const assertion of assertions) {\n          lines.push(`      ${assertion}`);\n        }\n      } else {\n        lines.push('      expect(result).toBeDefined();');\n      }\n    } else {\n      lines.push('      expect(result).toBeDefined();');\n    }\n  }\n\n  lines.push('    });');\n}\n\nfunction renderGetTest(\n  lines: string[],\n  op: Operation,\n  plan: any,\n  method: string,\n  serviceProp: string,\n  modelMap: Map<string, Model>,\n  ctx?: EmitterContext,\n  entityHelpers?: Set<string>,\n  baselineMethod?: BaselineMethod,\n): void {\n  const responseModelName = plan.responseModelName!;\n  const fixture = `${toCamelCase(responseModelName)}Fixture`;\n  const pathArgs = buildTestPathArgs(op);\n  const optionsArg = buildOptionsObjectTestArg(op, plan, baselineMethod, modelMap, ctx);\n\n  const isArrayResponse = !!plan.isArrayResponse;\n  const fixtureExpr = isArrayResponse ? `[${fixture}]` : fixture;\n  const accessor = isArrayResponse ? 'result[0]' : 'result';\n\n  lines.push(\"    it('returns the expected result', async () => {\");\n  lines.push(`      fetchOnce(${fixtureExpr});`);\n  lines.push('');\n  lines.push(`      const result = await workos.${serviceProp}.${method}(${optionsArg ?? pathArgs});`);\n  lines.push('');\n  lines.push(`      expect(fetchMethod()).toBe('${op.httpMethod.toUpperCase()}');`);\n  // Fix #12: Full URL path assertion instead of toContain()\n  const expectedPathGet = buildExpectedPath(op);\n  lines.push(`      expect(new URL(String(fetchURL())).pathname).toBe('${expectedPathGet}');`);\n  if (isArrayResponse) {\n    lines.push('      expect(Array.isArray(result)).toBe(true);');\n  }\n\n  const returnDataProperty = ctx ? operationOverrideFor(ctx, op)?.returnDataProperty : undefined;\n  if (returnDataProperty) {\n    const responseModel = modelMap.get(responseModelName);\n    const returnedField = responseModel?.fields.find((field) => fieldName(field.name) === returnDataProperty);\n    if (returnedField?.type.kind === 'array') {\n      lines.push('      expect(Array.isArray(result)).toBe(true);');\n    } else {\n      lines.push('      expect(result).toBeDefined();');\n    }\n    lines.push('    });');\n    return;\n  }\n\n  // Use entity helper if available, otherwise inline assertions\n  const helperName = ctx ? `expect${resolveInterfaceName(responseModelName, ctx)}` : null;\n  if (helperName && entityHelpers?.has(helperName)) {\n    lines.push(`      ${helperName}(${accessor});`);\n  } else {\n    const responseModel = modelMap.get(responseModelName);\n    if (responseModel) {\n      const assertions = buildFieldAssertions(responseModel, accessor, modelMap);\n      if (assertions.length > 0) {\n        for (const assertion of assertions) {\n          lines.push(`      ${assertion}`);\n        }\n      } else {\n        lines.push('      expect(result).toBeDefined();');\n      }\n    } else {\n      lines.push('      expect(result).toBeDefined();');\n    }\n  }\n\n  lines.push('    });');\n}\n\nfunction renderVoidTest(\n  lines: string[],\n  op: Operation,\n  plan: any,\n  method: string,\n  serviceProp: string,\n  modelMap: Map<string, Model>,\n  ctx?: EmitterContext,\n  baselineMethod?: BaselineMethod,\n): void {\n  const pathArgs = buildTestPathArgs(op);\n  // Build realistic payload for body-bearing void operations\n  const payload = plan.hasBody ? buildTestPayload(op, modelMap) : null;\n  const bodyArg = plan.hasBody ? (payload ? payload.camelCaseObj : fallbackBodyArg(op, modelMap)) : '';\n  const optionsArg = buildOptionsObjectTestArg(op, plan, baselineMethod, modelMap, ctx);\n  const args = optionsArg ?? (plan.hasBody ? (pathArgs ? `${pathArgs}, ${bodyArg}` : bodyArg) : pathArgs);\n\n  lines.push(\"    it('sends the request', async () => {\");\n  lines.push('      fetchOnce({});');\n  lines.push('');\n  lines.push(`      await workos.${serviceProp}.${method}(${args});`);\n  lines.push('');\n  lines.push(`      expect(fetchMethod()).toBe('${op.httpMethod.toUpperCase()}');`);\n  // Fix #12: Full URL path assertion instead of toContain()\n  const expectedPathVoid = buildExpectedPath(op);\n  lines.push(`      expect(new URL(String(fetchURL())).pathname).toBe('${expectedPathVoid}');`);\n  if (plan.hasBody && payload) {\n    lines.push(`      expect(fetchBody()).toEqual(expect.objectContaining(${payload.snakeCaseObj}));`);\n  }\n  lines.push('    });');\n}\n\nfunction buildOptionsObjectTestArg(\n  op: Operation,\n  plan: any,\n  baselineMethod: BaselineMethod | undefined,\n  modelMap: Map<string, Model>,\n  ctx?: EmitterContext,\n): string | null {\n  const optionParam = optionsObjectParam(baselineMethod);\n  if (!optionParam) return null;\n\n  const entries: string[] = [];\n  const pathFieldMap = ctx ? operationOverrideFor(ctx, op)?.pathFieldMap : undefined;\n  for (const param of op.pathParams) {\n    const localName = fieldName(param.name);\n    const optionField = resolveOptionsObjectField(localName, optionParam.type, ctx, pathFieldMap);\n    entries.push(`${optionField}: ${JSON.stringify(pathParamTestValue(param, localName))}`);\n  }\n\n  if (plan.isPaginated) {\n    entries.push(\"order: 'desc'\");\n  }\n  const queryParams = (\n    plan.isPaginated\n      ? op.queryParams.filter((param) => !['limit', 'before', 'after', 'order'].includes(param.name))\n      : op.queryParams\n  ).filter((param) => !param.deprecated);\n  for (const param of queryParams) {\n    const localName = fieldName(param.name);\n    const optionFieldType = ctx?.apiSurface?.interfaces?.[optionParam.type]?.fields?.[localName]?.type;\n    const value = queryParamTestValue(param, modelMap, ctx, optionFieldType);\n    entries.push(`${localName}: ${value}`);\n  }\n\n  if (plan.hasBody) {\n    const payload = buildTestPayload(op, modelMap);\n    if (payload) {\n      const bodyFieldMap = ctx ? operationOverrideFor(ctx, op)?.bodyFieldMap : undefined;\n      entries.push(...mapBodyOptionEntries(objectLiteralEntries(payload.camelCaseObj), bodyFieldMap));\n    } else if (entries.length === 0) {\n      return '({} as any)';\n    }\n  }\n\n  return `{ ${entries.join(', ')} }`;\n}\n\nfunction mapBodyOptionEntries(entries: string[], bodyFieldMap: Record<string, string> | undefined): string[] {\n  const reverseMap = new Map(Object.entries(bodyFieldMap ?? {}).map(([source, target]) => [target, source]));\n  if (reverseMap.size === 0) return entries;\n\n  return entries.map((entry) => {\n    const match = entry.match(/^([A-Za-z_$][\\w$]*)\\s*:/);\n    if (!match) return entry;\n    const source = reverseMap.get(match[1]);\n    return source ? entry.replace(match[1], source) : entry;\n  });\n}\n\nfunction objectLiteralEntries(literal: string): string[] {\n  const trimmed = literal.trim();\n  if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) return [];\n  const body = trimmed.slice(1, -1).trim();\n  return body ? body.split(',').map((entry) => entry.trim()) : [];\n}\n\nfunction resolveOptionsObjectField(\n  localName: string,\n  optionType: string,\n  ctx?: EmitterContext,\n  pathFieldMap?: Record<string, string>,\n): string {\n  // An explicit pathFieldMap wins unconditionally (mirrors resources.ts) so the\n  // generated test destructures the same renamed field the resource does.\n  const mapped = pathFieldMap?.[localName];\n  if (mapped) return mapped;\n  const fields = ctx?.apiSurface?.interfaces?.[optionType]?.fields;\n  if (!fields) return localName;\n  if (fields[localName]) return localName;\n  if (localName === 'omId' && fields.organizationMembershipId) return 'organizationMembershipId';\n  return localName;\n}\n\n/**\n * Generate per-entity assertion helper functions for models used in 2+ tests.\n * Returns lines like: function expectConnection(result: any) { expect(...) }\n */\n/**\n * Generate per-entity assertion helper functions for models used in 2+ tests.\n * Returns { lines, helpers } where helpers is a Set of helper function names.\n */\n/** Describe-scope names (i.e. method names) that have an `@oagen-ignore` block\n *  nested inside them in the existing test file. Such a `describe` must keep\n *  being emitted even when the method is hand-owned — otherwise the engine has\n *  no `describe` to re-nest the preserved block under and orphans it to the top\n *  of the file (out of `beforeEach` scope), which hangs at runtime. Mirrors the\n *  engine's `findContainingDescribeScope`. */\nfunction methodsWithPreservedTestBlocks(ctx: EmitterContext, relPath: string): Set<string> {\n  const scopes = new Set<string>();\n  const root = ctx.outputDir ?? ctx.targetDir;\n  if (!root) return scopes;\n  let content: string;\n  try {\n    content = fs.readFileSync(path.join(root, relPath), 'utf8');\n  } catch {\n    return scopes;\n  }\n  const lines = content.split('\\n');\n  const indentOf = (l: string) => l.length - l.trimStart().length;\n  for (let i = 0; i < lines.length; i++) {\n    if (!lines[i].includes('@oagen-ignore-start')) continue;\n    if (/^\\S/.test(lines[i])) continue; // top-level block — no enclosing describe\n    const markerIndent = indentOf(lines[i]);\n    for (let j = i - 1; j >= 0; j--) {\n      if (indentOf(lines[j]) >= markerIndent) continue;\n      const m = lines[j].match(/^\\s*describe\\((['\"`])(.+?)\\1\\s*,/);\n      if (m) {\n        scopes.add(m[2]);\n        break;\n      }\n      if (/^\\s*(?:export\\s+)?class\\s+\\w+/.test(lines[j])) break;\n    }\n  }\n  return scopes;\n}\n\n/** Concatenated text of the existing test file's `@oagen-ignore` regions, so\n *  helper generation can see which `expect<Model>()` helpers preserved\n *  hand-written test blocks still reference. */\nfunction existingTestIgnoreText(ctx: EmitterContext, relPath: string): string {\n  const root = ctx.outputDir ?? ctx.targetDir;\n  if (!root) return '';\n  let content: string;\n  try {\n    content = fs.readFileSync(path.join(root, relPath), 'utf8');\n  } catch {\n    return '';\n  }\n  return [...content.matchAll(/@oagen-ignore-start[\\s\\S]*?@oagen-ignore-end/g)].map((m) => m[0]).join('\\n');\n}\n\nfunction generateEntityHelpers(\n  service: Service,\n  allPlans: { op: Operation; plan: any; method: string }[],\n  renderedPlans: { op: Operation; plan: any; method: string }[],\n  ignoreRegionText: string,\n  modelMap: Map<string, Model>,\n  ctx: EmitterContext,\n): { lines: string[]; helpers: Set<string> } {\n  const responseModelOf = (entry: { op: Operation; plan: any }): string | null => {\n    const { op, plan } = entry;\n    if (plan.isPaginated && op.pagination?.itemType.kind === 'model') {\n      let modelName = op.pagination.itemType.name;\n      const rawModel = modelMap.get(modelName);\n      if (rawModel) {\n        const unwrapped = unwrapListModel(rawModel, modelMap);\n        if (unwrapped) modelName = unwrapped.name;\n      }\n      return modelName;\n    }\n    return plan.responseModelName ?? null;\n  };\n\n  // Count how many tests reference each response model — across ALL plans so a\n  // model that a hand-owned method's preserved test block asserts on still\n  // clears the 2-use threshold.\n  const modelUsage = new Map<string, number>();\n  for (const entry of allPlans) {\n    const modelName = responseModelOf(entry);\n    if (modelName) modelUsage.set(modelName, (modelUsage.get(modelName) ?? 0) + 1);\n  }\n  // Models an emitted `describe` will actually assert on. A helper only earns\n  // its place if an emitted test references it or a preserved `@oagen-ignore`\n  // block names it — otherwise it's an unused function.\n  const renderedModels = new Set<string>();\n  for (const entry of renderedPlans) {\n    const modelName = responseModelOf(entry);\n    if (!modelName) continue;\n    // A paginated test that skips item field assertions (baseline returns a\n    // non-paginatable type, or a different item type than the spec) never\n    // invokes the per-item entity helper — mirror renderPaginatedTest's\n    // `skipFieldAssertions` here so we don't emit a helper no call site\n    // references (TS6133). A model also reached by a non-skipped test is still\n    // added via that entry, so a genuinely-called helper is never dropped.\n    if (entry.plan.isPaginated && entry.op.pagination?.itemType.kind === 'model') {\n      const baselineMethod = optionsMethodFor(service, entry.method, entry.op, entry.plan, ctx);\n      const baselineItemType = autoPaginatableItemType(baselineMethod?.returnType);\n      const generatedItemType = resolveInterfaceName(modelName, ctx);\n      const skipFieldAssertions =\n        Boolean(baselineMethod?.returnType && !baselineItemType) ||\n        Boolean(baselineItemType && generatedItemType && baselineItemType !== generatedItemType);\n      if (skipFieldAssertions) continue;\n    }\n    renderedModels.add(modelName);\n  }\n\n  const lines: string[] = [];\n  const helpers = new Set<string>();\n  for (const [modelName, count] of modelUsage) {\n    if (count < 2) continue;\n    const model = modelMap.get(modelName);\n    if (!model) continue;\n    const assertions = buildFieldAssertions(model, 'result', modelMap);\n    if (assertions.length === 0) continue;\n\n    const domainName = resolveInterfaceName(modelName, ctx);\n    const helperName = `expect${domainName}`;\n    if (helpers.has(helperName)) continue;\n    const referenced = renderedModels.has(modelName) || ignoreRegionText.includes(`${helperName}(`);\n    if (!referenced) continue;\n    helpers.add(helperName);\n\n    lines.push(`function ${helperName}(result: any) {`);\n    for (const assertion of assertions) {\n      lines.push(`  ${assertion}`);\n    }\n    lines.push('}');\n    lines.push('');\n  }\n  return { lines, helpers };\n}\n\n/**\n * Build field-level assertions for top-level primitive fields of a response model.\n * Returns lines like: expect(result.fieldName).toBe(fixtureValue);\n *\n * When the top level has no assertable primitive fields (e.g. wrapper types\n * whose only required fields are nested models), recurse one level into those\n * nested models so we still get meaningful assertions instead of a bare\n * `toBeDefined()`.\n */\nfunction isDateTimeFieldType(type: TypeRef): boolean {\n  if (type.kind === 'primitive') return type.format === 'date-time';\n  if (type.kind === 'nullable') return isDateTimeFieldType(type.inner);\n  return false;\n}\n\nfunction buildFieldAssertions(model: Model, accessor: string, modelMap?: Map<string, Model>): string[] {\n  const assertions: string[] = [];\n\n  for (const field of model.fields) {\n    if (!field.required) continue;\n    const domainField = fieldName(field.domainName ?? field.name);\n    // `string` + `format: 'date-time'` is deserialized to `Date` by the\n    // serializer (see `mapPrimitive` in type-map.ts). Asserting against a\n    // string literal would fail Object.is — compare via `.toISOString()`.\n    const isDateTime = isDateTimeFieldType(field.type);\n    const fieldAccessor = isDateTime ? `${accessor}.${domainField}.toISOString()` : `${accessor}.${domainField}`;\n    // When a field has an example value, use it as the expected assertion value\n    if (field.example !== undefined) {\n      // A null example on a nullable field must assert `toBeNull()` on the\n      // raw value — calling `.toISOString()` on null throws at runtime, and\n      // `.toBe(null)` against any non-null value never matches.\n      if (field.example === null) {\n        assertions.push(`expect(${accessor}.${domainField}).toBeNull();`);\n        continue;\n      }\n      if (typeof field.example === 'object') {\n        // Objects and arrays need toEqual with JSON serialization\n        assertions.push(`expect(${accessor}.${domainField}).toEqual(${JSON.stringify(field.example)});`);\n      } else {\n        const exampleLiteral =\n          isDateTime && typeof field.example === 'string'\n            ? `'${new Date(field.example).toISOString()}'`\n            : typeof field.example === 'string'\n              ? `'${field.example}'`\n              : String(field.example);\n        assertions.push(`expect(${fieldAccessor}).toBe(${exampleLiteral});`);\n      }\n      continue;\n    }\n    const value = fixtureValueForType(field.type, field.name, model.name);\n    if (value === null) continue;\n    assertions.push(`expect(${fieldAccessor}).toBe(${value});`);\n  }\n\n  // When no primitive assertions were found (e.g. wrapper types like\n  // ResetPasswordResponse { user: User }), recurse one level into nested\n  // model-type fields to generate assertions on their primitive fields.\n  if (assertions.length === 0 && modelMap) {\n    for (const field of model.fields) {\n      if (!field.required) continue;\n      if (field.type.kind === 'model') {\n        const nestedModel = modelMap.get(field.type.name);\n        if (nestedModel) {\n          const nestedAccessor = `${accessor}.${fieldName(field.name)}`;\n          // Recurse without modelMap to limit depth to one level\n          const nested = buildFieldAssertions(nestedModel, nestedAccessor);\n          assertions.push(...nested);\n        }\n      }\n    }\n  }\n\n  return assertions;\n}\n\n/**\n * Return a JS literal string for the expected fixture value of a field.\n * Returns null for types that cannot be deterministically generated.\n * When a modelMap is provided, recursively builds object literals for nested model types.\n * When wire is true, uses snake_case keys for nested model objects (wire format).\n */\nfunction fixtureValueForType(\n  ref: TypeRef,\n  name: string,\n  modelName: string,\n  modelMap?: Map<string, Model>,\n  wire?: boolean,\n): string | null {\n  switch (ref.kind) {\n    case 'primitive':\n      return fixtureValueForPrimitive(ref.type, ref.format, name, modelName, wire);\n    case 'literal':\n      return typeof ref.value === 'string' ? `'${ref.value}'` : String(ref.value);\n    case 'enum':\n      // Use the first enum value as a realistic fixture value\n      if (ref.values?.length) {\n        const first = ref.values[0];\n        return typeof first === 'string' ? `'${first}'` : String(first);\n      }\n      return null;\n    case 'array': {\n      // For arrays of primitives/enums, generate a single-element array assertion.\n      // For arrays of models/complex types, return null to skip the assertion —\n      // the fixture will have populated items that we can't predict here.\n      const itemValue = fixtureValueForType(ref.items, name, modelName, modelMap, wire);\n      if (itemValue !== null) return `[${itemValue}]`;\n      return null;\n    }\n    case 'model': {\n      if (!modelMap) return null;\n      const nested = modelMap.get(ref.name);\n      if (!nested) return null;\n      const requiredFields = nested.fields.filter((f) => f.required);\n      const entries: string[] = [];\n      for (const field of requiredFields) {\n        const value = fixtureValueForType(field.type, field.name, nested.name, modelMap, wire);\n        if (value === null) return null; // Can't build a complete object\n        const key = wire ? wireFieldName(field.name) : fieldName(field.name);\n        entries.push(`${key}: ${value}`);\n      }\n      return `{ ${entries.join(', ')} }`;\n    }\n    default:\n      return null;\n  }\n}\n\nfunction fixtureValueForPrimitive(\n  type: string,\n  format: string | undefined,\n  name: string,\n  modelName: string,\n  wire?: boolean,\n): string | null {\n  switch (type) {\n    case 'string':\n      if (format === 'date-time') return wire ? \"'2023-01-01T00:00:00.000Z'\" : \"new Date('2023-01-01T00:00:00.000Z')\";\n      if (format === 'date') return \"'2023-01-01'\";\n      if (format === 'uuid') return \"'00000000-0000-0000-0000-000000000000'\";\n      if (name === 'id') {\n        const prefix = ID_PREFIXES[modelName] ?? '';\n        return `'${prefix}01234'`;\n      }\n      if (name.includes('id')) return `'${wireFieldName(name)}_01234'`;\n      if (name.includes('email')) return \"'test@example.com'\";\n      if (name.includes('url') || name.includes('uri')) return \"'https://example.com'\";\n      if (name.includes('name')) return \"'Test'\";\n      return `'test_${wireFieldName(name)}'`;\n    case 'integer':\n      return '1';\n    case 'number':\n      return '1';\n    case 'boolean':\n      return 'true';\n    default:\n      return null;\n  }\n}\n\n/**\n * Build the expected full URL path for an operation, substituting path params\n * with their test values. Returns a string like '/organizations/test_id'.\n */\nfunction buildExpectedPath(op: Operation): string {\n  let path = op.path;\n  for (const param of op.pathParams) {\n    path = path.replace(`{${param.name}}`, pathParamTestValue(param, fieldName(param.name)));\n  }\n  return path;\n}\n\n/**\n * Build a realistic test payload for a request body model.\n * Returns { camelCaseObj, snakeCaseObj } as inline JS object literal strings,\n * or null if the request body is not a named model.\n *\n * camelCaseObj is what the SDK consumer passes (e.g. { organizationName: 'Test' })\n * snakeCaseObj is the expected wire format (e.g. { organization_name: 'Test' })\n */\nfunction buildTestPayload(\n  op: Operation,\n  modelMap: Map<string, Model>,\n): { camelCaseObj: string; snakeCaseObj: string } | null {\n  if (!op.requestBody) return null;\n\n  // For discriminated unions, build a payload from the first variant so the\n  // generated test produces a value that satisfies the union type.  Without\n  // this, emitted tests pass `{} as any` for union bodies — fine for older\n  // permissive runtimes, but the dispatch switch now throws on unknown\n  // discriminator values, so the tests would fail before hitting fetch.\n  let model: Model | undefined;\n  if (op.requestBody.kind === 'union') {\n    const firstVariant = op.requestBody.variants.find((v) => v.kind === 'model');\n    if (!firstVariant || firstVariant.kind !== 'model') return null;\n    model = modelMap.get(firstVariant.name);\n  } else if (op.requestBody.kind === 'model') {\n    model = modelMap.get(op.requestBody.name);\n  }\n  if (!model) return null;\n\n  const requiredFields = model.fields.filter((f) => f.required);\n  // Only use fields that we can generate deterministic values for (primitives, enums, and nested models)\n  const usableRequired = requiredFields.filter(\n    (f) => fixtureValueForType(f.type, f.name, model.name, modelMap) !== null,\n  );\n\n  let chosenFields: typeof model.fields;\n  if (requiredFields.length > 0) {\n    // Only generate a typed payload when ALL required fields have fixture values.\n    // A partial payload missing required fields would fail TypeScript type checking.\n    if (usableRequired.length < requiredFields.length) return null;\n    chosenFields = usableRequired;\n  } else {\n    // All-optional model (e.g. PATCH `Update<X>` bodies). Pick the first few\n    // optional fields with available fixture values so the test asserts the\n    // wire format instead of falling back to `expect(fetchBody()).toBeDefined()`.\n    const usableOptional = model.fields.filter(\n      (f) => !f.required && fixtureValueForType(f.type, f.name, model.name, modelMap) !== null,\n    );\n    if (usableOptional.length === 0) return null;\n    chosenFields = usableOptional.slice(0, 2);\n  }\n\n  const camelEntries: string[] = [];\n  const snakeEntries: string[] = [];\n\n  for (const field of chosenFields) {\n    const camelValue = fixtureValueForType(field.type, field.name, model.name, modelMap)!;\n    const wireValue = fixtureValueForType(field.type, field.name, model.name, modelMap, true)!;\n    const camelKey = fieldName(field.name);\n    const snakeKey = wireFieldName(field.name);\n    camelEntries.push(`${camelKey}: ${camelValue}`);\n    snakeEntries.push(`${snakeKey}: ${wireValue}`);\n  }\n\n  return {\n    camelCaseObj: `{ ${camelEntries.join(', ')} }`,\n    snakeCaseObj: `{ ${snakeEntries.join(', ')} }`,\n  };\n}\n\n/**\n * Compute a fallback body argument when buildTestPayload returns null.\n * If the request body model has no required fields (all optional), an empty\n * object `{}` is a valid value and doesn't need a type assertion. Otherwise,\n * fall back to `{} as any` to bypass type checking for complex required fields.\n */\nfunction fallbackBodyArg(op: Operation, modelMap: Map<string, Model>): string {\n  if (!op.requestBody) return '{} as any';\n  let model: Model | undefined;\n  if (op.requestBody.kind === 'union') {\n    const firstVariant = op.requestBody.variants.find((v) => v.kind === 'model');\n    if (firstVariant && firstVariant.kind === 'model') model = modelMap.get(firstVariant.name);\n  } else if (op.requestBody.kind === 'model') {\n    model = modelMap.get(op.requestBody.name);\n  }\n  if (!model) return '{} as any';\n  const hasRequiredFields = model.fields.some((f) => f.required);\n  return hasRequiredFields ? '{} as any' : '{}';\n}\n\n/**\n * Determine whether a model should get a round-trip serializer test.\n * Includes all models with at least one field — every model gets both\n * serialize and deserialize functions, so all benefit from round-trip testing.\n */\nfunction modelNeedsRoundTripTest(model: Model): boolean {\n  return model.fields.length > 0;\n}\n\nfunction fixtureIsHandOwned(fixturePath: string, ctx: EmitterContext): boolean {\n  const root = ctx.outputDir ?? ctx.targetDir;\n  if (!root) return false;\n  return fs.existsSync(path.join(root, fixturePath));\n}\n\n/**\n * Generate serializer round-trip tests for models that have both serialize and\n * deserialize functions and have nested types requiring non-trivial serialization.\n */\nfunction generateSerializerTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const modelToService = assignModelsToServices(spec.models, spec.services, ctx.modelHints);\n  const serviceNameMap = new Map<string, string>();\n  for (const service of spec.services) {\n    serviceNameMap.set(service.name, resolveResourceClassName(service, ctx));\n  }\n  const resolveDir = (irService: string | undefined) =>\n    irService ? resolveServiceDir(serviceNameMap.get(irService) ?? irService) : 'common';\n\n  // Only generate round-trip tests for models with fields that have serializers generated.\n  // Skip list metadata and list wrapper models since their serializers are not emitted.\n  // Skip models unchanged from baseline (no new fields) since their serializers are not regenerated.\n  // Skip models unreachable from non-event services (no model/serializer files generated).\n  const nonEventReachable = computeNonEventReachable(spec.services, spec.models);\n  const generatedSerializerModels = (ctx as any)._generatedSerializerModels as Set<string> | undefined;\n  const eligibleModels = spec.models.filter((m) => {\n    const service = modelToService.get(m.name);\n    return (\n      nonEventReachable.has(m.name) &&\n      modelNeedsRoundTripTest(m) &&\n      !isListMetadataModel(m) &&\n      !isListWrapperModel(m) &&\n      (generatedSerializerModels?.has(m.name) ?? (modelHasNewFields(m, ctx) || isNodeOwnedService(ctx, service)))\n    );\n  });\n\n  if (eligibleModels.length === 0) return files;\n\n  // Use the skipped-serialize set computed by the serializer generator.\n  // It's stashed on the context during generateSerializers.\n  const serializeSkipped: Set<string> = (ctx as any)._skippedSerializeModels ?? new Set<string>();\n  // Response-reachable models — anything outside this set is request-only\n  // and has no `deserialize<X>` to test. `undefined` means \"no usage info,\n  // assume deserialize exists\" (standalone generation, smoke tests).\n  const responseReachableModels: Set<string> | undefined = (ctx as any)._responseReachableModels;\n\n  // Group eligible models by service directory for one test file per service\n  const modelsByDir = new Map<string, Model[]>();\n  for (const model of eligibleModels) {\n    const service = modelToService.get(model.name);\n    const dirName = resolveDir(service);\n    const fixturePath = `src/${dirName}/fixtures/${fileName(model.name)}.json`;\n    if (!fixtureIsHandOwned(fixturePath, ctx)) continue;\n    if (!modelsByDir.has(dirName)) {\n      modelsByDir.set(dirName, []);\n    }\n    modelsByDir.get(dirName)!.push(model);\n  }\n\n  for (const [dirName, models] of modelsByDir) {\n    const testPath = `src/${dirName}/serializers.spec.ts`;\n    const lines: string[] = [];\n\n    // Collect imports\n    const serializerImports: string[] = [];\n    const interfaceImports: string[] = [];\n    const fixtureImports: string[] = [];\n    const deserializeOnlyModels = new Set<string>();\n    const serializeOnlyModels = new Set<string>();\n\n    for (const model of models) {\n      const domainName = resolveInterfaceName(model.name, ctx);\n      const service = modelToService.get(model.name);\n      const modelDir = resolveDir(service);\n      const serializerPath = `src/${modelDir}/serializers/${fileName(model.name)}.serializer.ts`;\n      const interfacePath = `src/${modelDir}/interfaces/${fileName(model.name)}.interface.ts`;\n      const fixturePath = `src/${modelDir}/fixtures/${fileName(model.name)}.json`;\n      // Request-only models (e.g. `CreateWebhookEndpoint`) have no\n      // `deserialize<X>` emitted, so they can only be tested via serialize.\n      // This check has to come first: a hand-owned fixture would otherwise\n      // route through the deserialize-only branch, which then imports a\n      // function that doesn't exist.\n      const isRequestOnly = responseReachableModels !== undefined && !responseReachableModels.has(model.name);\n      const deserializeOnly =\n        !isRequestOnly && (serializeSkipped.has(model.name) || fixtureIsHandOwned(fixturePath, ctx));\n      const serializeOnly = isRequestOnly;\n      if (deserializeOnly) deserializeOnlyModels.add(model.name);\n      if (serializeOnly) serializeOnlyModels.add(model.name);\n\n      if (deserializeOnly) {\n        serializerImports.push(\n          `import { deserialize${domainName} } from '${relativeImport(testPath, serializerPath)}';`,\n        );\n      } else if (serializeOnly) {\n        serializerImports.push(`import { serialize${domainName} } from '${relativeImport(testPath, serializerPath)}';`);\n      } else {\n        serializerImports.push(\n          `import { deserialize${domainName}, serialize${domainName} } from '${relativeImport(testPath, serializerPath)}';`,\n        );\n      }\n      const wireName = wireInterfaceName(domainName);\n      interfaceImports.push(`import type { ${wireName} } from '${relativeImport(testPath, interfacePath)}';`);\n      const camelName = toCamelCase(domainName);\n      fixtureImports.push(`import ${camelName}Fixture from '${relativeImport(testPath, fixturePath)}';`);\n    }\n\n    for (const imp of serializerImports) {\n      lines.push(imp);\n    }\n    for (const imp of interfaceImports) {\n      lines.push(imp);\n    }\n    for (const imp of fixtureImports) {\n      lines.push(imp);\n    }\n    lines.push('');\n\n    for (const model of models) {\n      const domainName = resolveInterfaceName(model.name, ctx);\n      const fixtureName = `${toCamelCase(domainName)}Fixture`;\n      const wireName = wireInterfaceName(domainName);\n\n      if (deserializeOnlyModels.has(model.name)) {\n        // Deserialize-only test for hand-owned fixtures or models without a serializer.\n        lines.push(`describe('${domainName}Serializer', () => {`);\n        lines.push(\"  it('deserializes correctly', () => {\");\n        lines.push(`    const fixture = ${fixtureName} as ${wireName};`);\n        lines.push(`    const deserialized = deserialize${domainName}(fixture);`);\n        lines.push('    expect(deserialized).toBeDefined();');\n        lines.push('  });');\n        lines.push('});');\n      } else if (serializeOnlyModels.has(model.name)) {\n        // Serialize-only test for request-body-only models without a deserializer.\n        lines.push(`describe('${domainName}Serializer', () => {`);\n        lines.push(\"  it('serializes correctly', () => {\");\n        lines.push(`    const fixture = ${fixtureName} as ${wireName};`);\n        lines.push(`    const serialized = serialize${domainName}(fixture as any);`);\n        lines.push('    expect(serialized).toBeDefined();');\n        lines.push('  });');\n        lines.push('});');\n      } else {\n        // Round-trip test\n        lines.push(`describe('${domainName}Serializer', () => {`);\n        lines.push(\"  it('round-trips through serialize/deserialize', () => {\");\n        lines.push(`    const fixture = ${fixtureName} as ${wireName};`);\n        lines.push(`    const deserialized = deserialize${domainName}(fixture);`);\n        lines.push(`    const reserialized = serialize${domainName}(deserialized);`);\n        lines.push('    expect(reserialized).toEqual(expect.objectContaining(fixture));');\n        lines.push('  });');\n        lines.push('});');\n      }\n      lines.push('');\n    }\n\n    files.push({\n      path: testPath,\n      content: lines.join('\\n'),\n      overwriteExisting: true,\n    });\n  }\n\n  return files;\n}\n","import type { Model, Field, TypeRef, UnionType } from '@workos/oagen';\n\n/**\n * Flatten field-level discriminated unions into a single superset model for\n * the flat-emit languages (Go, Kotlin, Node) that have no native sum type.\n *\n * Background: a property like `ApiKey.owner` is a discriminated `oneOf` whose\n * variants are inline objects — `{ type: 'organization', id }` and\n * `{ type: 'user', id, organization_id }`. The IR represents this as a `union`\n * TypeRef referencing two variant models (`ApiKeyOwner`, `UserApiKeyOwner`).\n * Languages that render such a union as \"the first variant\" — Go's\n * `unionResolverName`, Kotlin's `baseName` — silently drop every field that\n * only exists on a later variant, so `organization_id` disappears for\n * user-scoped keys. (See the SDK compat report's owner-field note.)\n *\n * This transform, applied only by the flat-emit emitters, merges every\n * variant's fields into the first variant (the union's canonical model),\n * marks any field not shared by all variants optional, widens the\n * discriminator property to the union of its per-variant literal values, and\n * rewrites the field to a plain model ref to that canonical model. The result\n * is one flat struct/data class/interface that carries every variant field,\n * with the discriminator property telling callers which variant they hold —\n * exactly how these emitters already flatten `allOf [base, oneOf]`\n * discriminated bases (see `enrichModelsFromSpec`).\n *\n * Returns a new models array; the input models are not mutated. Union-emitting\n * languages (Python, PHP, Rust, Ruby, .NET) must NOT call this — they emit a\n * real discriminated union and lose nothing.\n */\nexport function flattenDiscriminatedUnionFields(models: Model[]): Model[] {\n  const byName = new Map(models.map((m) => [m.name, m]));\n  // Canonical (first-variant) model name → its merged superset field list.\n  const mergedFieldsByCanonical = new Map<string, Field[]>();\n\n  /**\n   * Decide whether a union is a flat-flattenable discriminated union of inline\n   * object variants. When it is, record the merged field set for its canonical\n   * model and return that model's name; otherwise return null.\n   */\n  function planUnion(union: UnionType): string | null {\n    if (!union.discriminator) return null;\n\n    const variantNames = union.variants.map((v) => (v.kind === 'model' ? v.name : null));\n    // Require that *every* variant is a model ref (the inline-object oneOf\n    // shape). Untagged unions of primitives (e.g. AuditLogEvent actor\n    // metadata: string | number | boolean) carry no discriminator and never\n    // reach here, but guard anyway.\n    if (variantNames.length < 2 || variantNames.some((n) => n === null)) return null;\n\n    const variantModels = (variantNames as string[]).map((n) => byName.get(n));\n    // Every variant must resolve to a concrete data model — not a discriminator\n    // dispatcher (empty-field base with its own `discriminator`) and not a\n    // fieldless placeholder. This keeps event-style unions out of scope.\n    if (variantModels.some((m) => !m || (m as { discriminator?: unknown }).discriminator || m.fields.length === 0)) {\n      return null;\n    }\n\n    const canonical = (variantNames as string[])[0];\n    const merged = mergeVariantFields(variantModels as Model[], union.discriminator.property);\n\n    // The merge map is keyed by the first-variant model name. The same union\n    // referenced by several container fields re-plans to an identical merge\n    // (harmless). But two *distinct* unions that share a first variant would\n    // each want a different superset on that one model — pass 2 can apply only\n    // one, silently dropping the other's fields. Fail loudly instead; the spec\n    // must disambiguate (rename one union's leading variant).\n    const existing = mergedFieldsByCanonical.get(canonical);\n    if (existing && fieldListSignature(existing) !== fieldListSignature(merged)) {\n      throw new Error(\n        `flattenDiscriminatedUnionFields: model \"${canonical}\" is the first variant of two distinct ` +\n          'discriminated unions that merge to different field sets. Flattening both onto one model would ' +\n          'silently drop fields; disambiguate the variants in the spec (rename the leading variant of one union).',\n      );\n    }\n    mergedFieldsByCanonical.set(canonical, merged);\n    return canonical;\n  }\n\n  /** Rewrite a TypeRef, collapsing flattenable unions to a canonical model ref. */\n  function rewriteRef(ref: TypeRef): TypeRef {\n    switch (ref.kind) {\n      case 'union': {\n        const canonical = planUnion(ref);\n        return canonical ? { kind: 'model', name: canonical } : ref;\n      }\n      case 'nullable': {\n        // Preserve reference identity when nothing inside changed, so pass 1's\n        // `type === field.type` check doesn't flag (and rebuild) union-free fields.\n        const inner = rewriteRef(ref.inner);\n        return inner === ref.inner ? ref : { kind: 'nullable', inner };\n      }\n      case 'array': {\n        const items = rewriteRef(ref.items);\n        return items === ref.items ? ref : { kind: 'array', items };\n      }\n      default:\n        return ref;\n    }\n  }\n\n  // Pass 1: rewrite container fields, recording the merges to apply in pass 2.\n  const rewritten = models.map((model) => {\n    let changed = false;\n    const fields = model.fields.map((field) => {\n      const type = rewriteRef(field.type);\n      if (type === field.type) return field;\n      changed = true;\n      return { ...field, type };\n    });\n    return changed ? { ...model, fields } : model;\n  });\n\n  if (mergedFieldsByCanonical.size === 0) return models;\n\n  // Pass 2: replace each canonical variant model with its merged superset.\n  return rewritten.map((model) => {\n    const merged = mergedFieldsByCanonical.get(model.name);\n    return merged ? { ...model, fields: merged } : model;\n  });\n}\n\n/**\n * Build the merged field list for a discriminated union's variant models.\n *\n * - A field is required only when present-and-required in *every* variant; a\n *   field missing from some variant (e.g. the user variant's `organization_id`)\n *   becomes optional.\n * - The discriminator property is widened to the union of its per-variant\n *   literal values (`'organization' | 'user'`) so it isn't pinned to the first\n *   variant's constant. (Flat-emit type maps collapse a single-typed literal\n *   union to a plain string, so this is a no-op for Go/Kotlin and a precise\n *   `'organization' | 'user'` for Node.)\n * - Field order follows the first variant, then newly-seen fields from later\n *   variants.\n */\nfunction mergeVariantFields(variants: Model[], discriminatorProp: string): Field[] {\n  const total = variants.length;\n  const order: string[] = [];\n  const defByName = new Map<string, Field>();\n  const presence = new Map<string, number>();\n  const requiredCount = new Map<string, number>();\n\n  for (const variant of variants) {\n    for (const field of variant.fields) {\n      const seen = defByName.get(field.name);\n      if (!seen) {\n        defByName.set(field.name, field);\n        order.push(field.name);\n      } else if (field.name !== discriminatorProp && !sameTypeRef(seen.type, field.type)) {\n        // Only the first-seen definition is kept, so a shared field whose type\n        // differs across variants would be merged with the wrong type for the\n        // other variants. The discriminator is exempt (it is widened below).\n        throw new Error(\n          `flattenDiscriminatedUnionFields: field \"${field.name}\" has conflicting types across variants ` +\n            'of a discriminated union; a flat superset model cannot represent both. Align the field type ' +\n            'across variants in the spec.',\n        );\n      }\n      presence.set(field.name, (presence.get(field.name) ?? 0) + 1);\n      if (field.required) requiredCount.set(field.name, (requiredCount.get(field.name) ?? 0) + 1);\n    }\n  }\n\n  return order.map((name) => {\n    const def = defByName.get(name)!;\n\n    if (name === discriminatorProp) {\n      const literals = dedupeLiteralTypes(\n        variants.map((v) => v.fields.find((f) => f.name === name)?.type).filter((t): t is TypeRef => t != null),\n      );\n      const type: TypeRef = literals.length > 1 ? { kind: 'union', variants: literals } : (literals[0] ?? def.type);\n      return { ...def, type, required: presence.get(name) === total };\n    }\n\n    const required = presence.get(name) === total && requiredCount.get(name) === total;\n    return required === def.required ? def : { ...def, required };\n  });\n}\n\n/** Structural equality of two TypeRefs (IR refs have a stable, deterministic shape). */\nfunction sameTypeRef(a: TypeRef, b: TypeRef): boolean {\n  return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/** Stable signature of a merged field list, used to detect canonical collisions. */\nfunction fieldListSignature(fields: Field[]): string {\n  return JSON.stringify(fields.map((f) => [f.name, f.required, f.type]));\n}\n\n/** Deduplicate literal TypeRefs by value, preserving first-seen order. */\nfunction dedupeLiteralTypes(types: TypeRef[]): TypeRef[] {\n  const seen = new Set<string>();\n  const out: TypeRef[] = [];\n  for (const t of types) {\n    const key = t.kind === 'literal' ? `lit:${String(t.value)}` : JSON.stringify(t);\n    if (seen.has(key)) continue;\n    seen.add(key);\n    out.push(t);\n  }\n  return out;\n}\n","import type { EmitterContext, GeneratedFile, Model } from '@workos/oagen';\nimport { toPascalCase, toCamelCase } from '@workos/oagen';\nimport { loadRawSpec } from '../shared/model-utils.js';\nimport { fileName, wireInterfaceName } from './naming.js';\nimport { createServiceDirResolver } from './utils.js';\n\n/**\n * Discriminated `allOf [base, oneOf [variant, …]]` model support for Node.\n *\n * When a component schema matches that shape and every oneOf branch pins the\n * same property to a distinct string-const value, we emit:\n *\n *   - One interface per variant, holding the base fields plus that variant's\n *     specific fields (with the discriminator typed as the const literal).\n *   - A type alias union that ties the variants together.\n *\n * Doing this from raw spec — rather than from the IR — sidesteps the parser's\n * `detectAllOfVariantDiscriminator` failing on variants whose properties live\n * behind another `allOf` (the OAuth branch of `ConnectApplication`). That\n * limitation also breaks Python's flat dataclass output; fixing the parser is\n * the proper long-term move but riskier because it would change every\n * emitter's view of `ConnectApplication` at once. This module is contained to\n * the Node emitter.\n */\n\ninterface RawSchema {\n  type?: string | string[];\n  const?: unknown;\n  enum?: unknown[];\n  format?: string;\n  description?: string;\n  required?: string[];\n  properties?: Record<string, RawSchema>;\n  items?: RawSchema;\n  allOf?: RawSchema[];\n  oneOf?: RawSchema[];\n  anyOf?: RawSchema[];\n  $ref?: string;\n}\n\ninterface FieldSpec {\n  name: string;\n  description?: string;\n  required: boolean;\n  /** Domain (camelCase) TS type. */\n  domainType: string;\n  /** Wire (snake_case) TS type. */\n  wireType: string;\n  /** Model deps for imports — IR names (PascalCase). */\n  modelDeps: Set<string>;\n  /** Whether the field requires date parsing/formatting (format: date-time). */\n  hasDateTime: boolean;\n  /** Inline string-enum values, rendered as a literal union (e.g. `'a' | 'b'`). */\n  enumValues?: string[];\n}\n\ninterface VariantSpec {\n  /** Domain interface name suffix, e.g. `OAuth`, `M2M`. */\n  nameSuffix: string;\n  /** Discriminator value, e.g. `oauth`, `m2m`, or `true`/`false`. */\n  discriminatorValue: string;\n  /** Whether the discriminator value is a boolean literal (emit unquoted). */\n  discriminatorIsBoolean?: boolean;\n  /** Fields specific to this variant (excluding the discriminator). */\n  fields: FieldSpec[];\n}\n\ninterface DiscriminatedShape {\n  modelName: string;\n  /** Base fields common to every variant. */\n  baseFields: FieldSpec[];\n  /** Field name on the wire (snake_case). */\n  discriminatorProperty: string;\n  /** Field name in domain (camelCase). */\n  discriminatorPropertyDomain: string;\n  /** Description from the OpenAPI spec, if present. */\n  discriminatorDescription?: string;\n  variants: VariantSpec[];\n  /**\n   * Set for pure `oneOf` schemas (no `allOf` base wrapper). These are emitted\n   * as an inline anonymous union (`type X = { … } | { … }`) rather than as a\n   * set of named variant interfaces, which keeps two-variant unions — e.g. the\n   * boolean-discriminated `active: true | false` token response — readable.\n   */\n  inlineUnion?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Detection\n// ---------------------------------------------------------------------------\n\nexport function detectDiscriminatedShape(\n  modelName: string,\n  rawSchemas: Record<string, RawSchema>,\n): DiscriminatedShape | null {\n  const schema = rawSchemas[modelName];\n  if (!schema) return null;\n\n  let baseObject: RawSchema | null = null;\n  let oneOfVariants: RawSchema[] | null = null;\n  let inlineUnion = false;\n\n  if (schema.allOf) {\n    // `allOf [base, oneOf [variant, …]]`: the base contributes shared fields;\n    // the oneOf contributes variant-specific fields. Emitted as named variant\n    // interfaces (one per variant) plus a union alias.\n    for (const member of schema.allOf) {\n      const resolved = resolveRef(member, rawSchemas);\n      if (resolved.oneOf) {\n        if (oneOfVariants) return null; // unexpected: multiple oneOf branches at top\n        oneOfVariants = resolved.oneOf;\n      } else if (resolved.properties) {\n        baseObject = mergeBase(baseObject, resolved);\n      } else if (resolved.allOf) {\n        // Nested allOf at top: walk it\n        const nestedBase = flattenObjectAllOf(resolved, rawSchemas);\n        baseObject = mergeBase(baseObject, nestedBase);\n      }\n    }\n  } else if (schema.oneOf && schema.oneOf.length >= 2) {\n    // Pure `oneOf` (no base wrapper): every branch must be a plain inline\n    // object so a shared const discriminator can tell them apart. This is the\n    // discriminated-union shape the parser would otherwise flatten into a\n    // single all-optional interface (e.g. the boolean-discriminated token\n    // response `{ active: true; … } | { active: false; … }`). The\n    // mutually-exclusive-field-group oneOf (no shared discriminator) is left\n    // alone by the `findSharedDiscriminator` check below.\n    const allInlineObjects = schema.oneOf.every(\n      (v) => v.properties && !v.$ref && (v.type === 'object' || !v.type) && !v.allOf && !v.oneOf,\n    );\n    if (!allInlineObjects) return null;\n    oneOfVariants = schema.oneOf;\n    inlineUnion = true;\n  } else {\n    return null;\n  }\n  if (!oneOfVariants || oneOfVariants.length < 2) return null;\n\n  // Flatten each variant through its own allOf to get the effective property\n  // set. Variants that themselves embed a nested `oneOf` (e.g. the OAuth\n  // first-party / dynamically-registered sub-variants) merge into a single\n  // shape: any field appearing in any sub-branch is included, required only\n  // when present in every sub-branch.\n  const flattenedVariants = oneOfVariants.map((v) => flattenVariant(v, rawSchemas));\n\n  // Find a shared discriminator: a property whose value is a distinct\n  // string-const on every variant. Has to be in `alwaysProperties` of every\n  // variant.\n  const discProp = findSharedDiscriminator(flattenedVariants);\n  if (!discProp) return null;\n\n  // Build variant specs.\n  const variants: VariantSpec[] = flattenedVariants\n    .map((fv): VariantSpec | null => {\n      const discValue = readConst(fv.alwaysProperties.get(discProp));\n      if (discValue === null) return null;\n      return {\n        nameSuffix: variantNameSuffix(String(discValue)),\n        discriminatorValue: String(discValue),\n        discriminatorIsBoolean: typeof discValue === 'boolean',\n        fields: variantFields(fv, discProp, modelName),\n      };\n    })\n    .filter((v): v is VariantSpec => v !== null);\n\n  if (variants.length !== flattenedVariants.length) return null;\n\n  const baseFields = baseObject ? collectObjectFields(baseObject, modelName) : [];\n\n  const discriminatorDescription = flattenedVariants[0].alwaysProperties.get(discProp)?.description;\n\n  return {\n    modelName,\n    baseFields,\n    discriminatorProperty: discProp,\n    discriminatorPropertyDomain: toCamelCase(discProp),\n    discriminatorDescription,\n    variants,\n    inlineUnion,\n  };\n}\n\nfunction mergeBase(prev: RawSchema | null, next: RawSchema): RawSchema {\n  if (!prev) return next;\n  return {\n    type: 'object',\n    properties: { ...prev.properties, ...next.properties },\n    required: [...new Set([...(prev.required ?? []), ...(next.required ?? [])])],\n  };\n}\n\nfunction flattenObjectAllOf(schema: RawSchema, rawSchemas: Record<string, RawSchema>): RawSchema {\n  let merged: RawSchema = { type: 'object', properties: {}, required: [] };\n  for (const sub of schema.allOf ?? []) {\n    const resolved = resolveRef(sub, rawSchemas);\n    if (resolved.properties) {\n      merged = mergeBase(merged, resolved);\n    } else if (resolved.allOf) {\n      merged = mergeBase(merged, flattenObjectAllOf(resolved, rawSchemas));\n    }\n    // Ignore oneOf inside base allOf — that's a different code path.\n  }\n  return merged;\n}\n\ninterface FlattenedVariant {\n  /** Properties present unconditionally (in every sub-branch of nested oneOf). */\n  alwaysProperties: Map<string, RawSchema>;\n  /** Properties present in at least one sub-branch but not all. */\n  optionalProperties: Map<string, RawSchema>;\n  /** Required field names — must be required in every sub-branch to remain required. */\n  required: Set<string>;\n}\n\nfunction flattenVariant(variant: RawSchema, rawSchemas: Record<string, RawSchema>): FlattenedVariant {\n  const resolved = resolveRef(variant, rawSchemas);\n\n  // Leaf: plain object with properties.\n  if (resolved.properties && !resolved.allOf && !resolved.oneOf) {\n    const props = new Map<string, RawSchema>();\n    for (const [k, v] of Object.entries(resolved.properties)) props.set(k, v);\n    return {\n      alwaysProperties: props,\n      optionalProperties: new Map(),\n      required: new Set(resolved.required ?? []),\n    };\n  }\n\n  if (resolved.allOf) {\n    // Merge each allOf member's flattened view.\n    let agg: FlattenedVariant = {\n      alwaysProperties: new Map(),\n      optionalProperties: new Map(),\n      required: new Set(),\n    };\n    let initialized = false;\n    for (const member of resolved.allOf) {\n      const memberView = flattenVariant(member, rawSchemas);\n      if (!initialized) {\n        agg = {\n          alwaysProperties: new Map(memberView.alwaysProperties),\n          optionalProperties: new Map(memberView.optionalProperties),\n          required: new Set(memberView.required),\n        };\n        initialized = true;\n        continue;\n      }\n      // allOf is intersection — union of properties, union of required.\n      for (const [k, v] of memberView.alwaysProperties) {\n        if (!agg.alwaysProperties.has(k) && !agg.optionalProperties.has(k)) {\n          agg.alwaysProperties.set(k, v);\n        }\n      }\n      for (const [k, v] of memberView.optionalProperties) {\n        if (!agg.alwaysProperties.has(k) && !agg.optionalProperties.has(k)) {\n          agg.optionalProperties.set(k, v);\n        }\n      }\n      for (const r of memberView.required) agg.required.add(r);\n    }\n    return agg;\n  }\n\n  if (resolved.oneOf) {\n    // Merge each oneOf member's flattened view — union the properties, but\n    // demote anything not present in EVERY member to optional.\n    const memberViews = resolved.oneOf.map((m) => flattenVariant(m, rawSchemas));\n    const allKeys = new Set<string>();\n    for (const view of memberViews) {\n      for (const k of view.alwaysProperties.keys()) allKeys.add(k);\n      for (const k of view.optionalProperties.keys()) allKeys.add(k);\n    }\n    const always = new Map<string, RawSchema>();\n    const optional = new Map<string, RawSchema>();\n    const requiredEverywhere = new Set<string>();\n    for (const key of allKeys) {\n      const inAll = memberViews.every((v) => v.alwaysProperties.has(key) || v.optionalProperties.has(key));\n      const schemas = memberViews\n        .map((v) => v.alwaysProperties.get(key) ?? v.optionalProperties.get(key))\n        .filter((s): s is RawSchema => Boolean(s));\n      const merged = mergeFieldSchemas(schemas);\n      if (inAll) {\n        always.set(key, merged);\n      } else {\n        optional.set(key, merged);\n      }\n      if (inAll && memberViews.every((v) => v.required.has(key))) {\n        requiredEverywhere.add(key);\n      }\n    }\n    return {\n      alwaysProperties: always,\n      optionalProperties: optional,\n      required: requiredEverywhere,\n    };\n  }\n\n  return {\n    alwaysProperties: new Map(),\n    optionalProperties: new Map(),\n    required: new Set(),\n  };\n}\n\nfunction mergeFieldSchemas(schemas: RawSchema[]): RawSchema {\n  if (schemas.length === 0) return {};\n  if (schemas.length === 1) return schemas[0];\n\n  // If every schema is a boolean const, widen to boolean.\n  const boolConsts = schemas.every((s) => s.type === 'boolean' && typeof s.const === 'boolean');\n  if (boolConsts) {\n    return { type: 'boolean', description: schemas[0].description };\n  }\n\n  // If every schema is a string const with differing values, widen to a plain\n  // string (the variant interface narrows it back to the specific literal via\n  // its discriminator value, so we lose nothing here).\n  const stringConsts = schemas.every((s) => s.type === 'string' && typeof s.const === 'string');\n  if (stringConsts) {\n    const values = schemas.map((s) => s.const as string);\n    if (new Set(values).size === 1) {\n      return schemas[0];\n    }\n    return { type: 'string', description: schemas[0].description };\n  }\n\n  return schemas[0];\n}\n\nfunction findSharedDiscriminator(variants: FlattenedVariant[]): string | null {\n  if (variants.length < 2) return null;\n  const firstAlways = variants[0].alwaysProperties;\n  for (const propName of firstAlways.keys()) {\n    let allConst = true;\n    const values: string[] = [];\n    for (const v of variants) {\n      const schema = v.alwaysProperties.get(propName);\n      const val = readConst(schema);\n      if (val === null) {\n        allConst = false;\n        break;\n      }\n      values.push(String(val));\n    }\n    if (allConst && new Set(values).size === values.length) {\n      return propName;\n    }\n  }\n  return null;\n}\n\n/**\n * Read a discriminator value pinned by `const` (or a single-value `enum`).\n * Supports string and boolean literals — the latter drives the\n * `active: true | false` style token response union.\n */\nfunction readConst(schema: RawSchema | undefined | null): string | boolean | null {\n  if (!schema) return null;\n  if (typeof schema.const === 'string' || typeof schema.const === 'boolean') return schema.const;\n  if (Array.isArray(schema.enum) && schema.enum.length === 1) {\n    const only = schema.enum[0];\n    if (typeof only === 'string' || typeof only === 'boolean') return only;\n  }\n  return null;\n}\n\nfunction variantNameSuffix(constValue: string): string {\n  return toPascalCase(constValue);\n}\n\n// ---------------------------------------------------------------------------\n// Field extraction\n// ---------------------------------------------------------------------------\n\nfunction collectObjectFields(schema: RawSchema, parentName: string): FieldSpec[] {\n  const props = schema.properties ?? {};\n  const required = new Set(schema.required ?? []);\n  const fields: FieldSpec[] = [];\n  for (const [name, propSchema] of Object.entries(props)) {\n    fields.push(buildField(name, propSchema, required.has(name), parentName));\n  }\n  return fields;\n}\n\nfunction variantFields(fv: FlattenedVariant, discriminatorProperty: string, parentName: string): FieldSpec[] {\n  const fields: FieldSpec[] = [];\n  for (const [name, propSchema] of fv.alwaysProperties) {\n    if (name === discriminatorProperty) continue;\n    fields.push(buildField(name, propSchema, fv.required.has(name), parentName));\n  }\n  for (const [name, propSchema] of fv.optionalProperties) {\n    if (name === discriminatorProperty) continue;\n    fields.push(buildField(name, propSchema, false, parentName));\n  }\n  return fields;\n}\n\nfunction buildField(rawName: string, schema: RawSchema, required: boolean, parentName: string): FieldSpec {\n  const modelDeps = new Set<string>();\n  const domainType = rawSchemaToTS(schema, parentName, rawName, false, modelDeps);\n  const wireType = rawSchemaToTS(schema, parentName, rawName, true, modelDeps);\n  const enumValues =\n    Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every((e) => typeof e === 'string')\n      ? (schema.enum as string[])\n      : undefined;\n  return {\n    name: rawName,\n    description: schema.description,\n    required,\n    domainType,\n    wireType,\n    modelDeps,\n    hasDateTime: schemaHasDateTime(schema),\n    enumValues,\n  };\n}\n\nfunction schemaHasDateTime(schema: RawSchema): boolean {\n  if (schema.format === 'date-time' && typeOf(schema) === 'string') return true;\n  if (schema.items && schemaHasDateTime(schema.items)) return true;\n  return false;\n}\n\nfunction typeOf(schema: RawSchema): string | undefined {\n  if (Array.isArray(schema.type)) {\n    return schema.type.find((t) => t !== 'null');\n  }\n  return schema.type;\n}\n\nfunction isNullable(schema: RawSchema): boolean {\n  return Array.isArray(schema.type) && schema.type.includes('null');\n}\n\nfunction rawSchemaToTS(\n  schema: RawSchema,\n  parentName: string,\n  fieldName: string,\n  isWire: boolean,\n  modelDeps: Set<string>,\n): string {\n  if (schema.$ref) {\n    const refName = schema.$ref.split('/').pop()!;\n    modelDeps.add(refName);\n    const domain = toPascalCase(refName);\n    return isWire ? wireInterfaceName(domain) : domain;\n  }\n  if (typeof schema.const === 'string') {\n    return `'${schema.const}'`;\n  }\n  if (typeof schema.const === 'boolean') {\n    return String(schema.const);\n  }\n  const baseType = typeOf(schema);\n  const nullable = isNullable(schema);\n  let core: string;\n  if (baseType === 'string') {\n    core = !isWire && schema.format === 'date-time' ? 'Date' : 'string';\n  } else if (baseType === 'integer' || baseType === 'number') {\n    core = 'number';\n  } else if (baseType === 'boolean') {\n    core = 'boolean';\n  } else if (baseType === 'array' && schema.items) {\n    const items = rawSchemaToTS(schema.items, parentName, singularize(fieldName), isWire, modelDeps);\n    core = `${parenthesizeUnion(items)}[]`;\n  } else if (baseType === 'object' && schema.properties) {\n    // Inline object — refer to the synthetic model name that\n    // `enrichModelsFromSpec` produces. Pattern: `<Parent>_<fieldSingular>`.\n    const synthName = `${parentName}_${singularize(fieldName)}`;\n    modelDeps.add(synthName);\n    const domain = toPascalCase(synthName);\n    return isWire ? wireInterfaceName(domain) : domain;\n  } else {\n    core = 'unknown';\n  }\n  return nullable ? `${core} | null` : core;\n}\n\nfunction parenthesizeUnion(t: string): string {\n  return /\\s\\|\\s/.test(t) ? `(${t})` : t;\n}\n\nfunction singularize(name: string): string {\n  if (name.endsWith('ies') && name.length > 3) return `${name.slice(0, -3)}y`;\n  if (name.endsWith('s') && !name.endsWith('ss')) return name.slice(0, -1);\n  return name;\n}\n\nfunction resolveRef(schema: RawSchema, rawSchemas: Record<string, RawSchema>): RawSchema {\n  if (!schema.$ref) return schema;\n  const segments = schema.$ref.split('/');\n  const name = segments[segments.length - 1];\n  return rawSchemas[name] ?? schema;\n}\n\n// ---------------------------------------------------------------------------\n// Public emission entry points\n// ---------------------------------------------------------------------------\n\nexport interface DiscriminatedPlan {\n  shape: DiscriminatedShape;\n  modelDir: string;\n  /** Maps raw spec schema names to their resolved service directories. */\n  depDirMap: Map<string, string>;\n}\n\nexport function planDiscriminatedModels(models: Model[], ctx: EmitterContext): Map<string, DiscriminatedPlan> {\n  const plans = new Map<string, DiscriminatedPlan>();\n  const spec = loadRawSpec();\n  if (!spec?.components?.schemas) return plans;\n  const rawSchemas = spec.components.schemas as Record<string, RawSchema>;\n  const { modelToService, resolveDir } = createServiceDirResolver(models, ctx.spec.services, ctx);\n\n  // Build a lookup from IR model names to their resolved service directories.\n  const irModelDir = new Map<string, string>();\n  for (const model of models) {\n    irModelDir.set(model.name, resolveDir(modelToService.get(model.name)));\n  }\n\n  // Map raw spec schema names to service directories so discriminated model\n  // imports can point to the correct cross-service path. Raw names may differ\n  // from IR names due to schemaNameTransform (e.g. Dto stripping).\n  const depDirMap = new Map<string, string>();\n  for (const rawName of Object.keys(rawSchemas)) {\n    if (irModelDir.has(rawName)) {\n      depDirMap.set(rawName, irModelDir.get(rawName)!);\n      continue;\n    }\n    const stripped = rawName.replace(/Dto/g, '').replace(/DTO/g, '').replace(/Json$/, '');\n    if (stripped !== rawName && irModelDir.has(stripped)) {\n      depDirMap.set(rawName, irModelDir.get(stripped)!);\n    }\n  }\n  // Synthetic IR models — e.g. inline-object variant fields like the token\n  // response's nested `access_token` — have PascalCase names that never appear\n  // in rawSchemas, so the loop above misses them. Seed their directories from\n  // irModelDir so `collectImports` (which only receives `depDirMap` via the\n  // plan) can resolve a cross-service inline-object dep instead of defaulting\n  // to a possibly-wrong same-dir import.\n  for (const [irName, dir] of irModelDir) {\n    if (!depDirMap.has(irName)) depDirMap.set(irName, dir);\n  }\n\n  for (const model of models) {\n    const shape = detectDiscriminatedShape(model.name, rawSchemas);\n    if (!shape) continue;\n    // Skip models whose variant field dependencies can't all be resolved to\n    // existing interface files. EventSchema, for instance, references models\n    // from many services that may not have generated files yet.\n    const allDeps = new Set<string>();\n    for (const field of shape.baseFields) {\n      for (const d of field.modelDeps) allDeps.add(d);\n    }\n    for (const variant of shape.variants) {\n      for (const field of variant.fields) {\n        for (const d of field.modelDeps) allDeps.add(d);\n      }\n    }\n    // `modelDeps` may carry an inline-object synthetic name in raw form\n    // (`Parent_field`) while the resolution maps are keyed by the PascalCase IR\n    // model name (`ParentField`). Resolve either spelling before deciding a dep\n    // is unreachable — otherwise inline-object variant fields (e.g. the token\n    // response's nested `access_token`) would wrongly drop the whole plan.\n    const resolvable = (dep: string): boolean =>\n      depDirMap.has(dep) ||\n      irModelDir.has(dep) ||\n      depDirMap.has(toPascalCase(dep)) ||\n      irModelDir.has(toPascalCase(dep));\n    const hasUnresolvableDeps = [...allDeps].some((dep) => !resolvable(dep));\n    if (hasUnresolvableDeps) continue;\n    const modelDir = resolveDir(modelToService.get(model.name));\n    plans.set(model.name, { shape, modelDir, depDirMap });\n  }\n  return plans;\n}\n\nexport function generateDiscriminatedFiles(\n  plans: Map<string, DiscriminatedPlan>,\n  ctx: EmitterContext,\n): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  for (const plan of plans.values()) {\n    files.push(buildInterfaceFile(plan, ctx));\n    files.push(buildSerializerFile(plan, ctx));\n  }\n  return files;\n}\n\nfunction buildInterfaceFile(plan: DiscriminatedPlan, _ctx: EmitterContext): GeneratedFile {\n  const { shape, modelDir } = plan;\n  if (shape.inlineUnion) return buildInlineUnionFile(plan);\n  const domain = toPascalCase(shape.modelName);\n  const wire = wireInterfaceName(domain);\n  const lines: string[] = [];\n\n  const imports = collectImports(plan);\n  if (imports.length > 0) {\n    for (const imp of imports) {\n      lines.push(`import type { ${imp.symbols.join(', ')} } from '${imp.path}';`);\n    }\n    lines.push('');\n  }\n\n  // Variant interfaces (domain + wire) plus a union type alias.\n  for (const variant of shape.variants) {\n    const variantDomain = `${domain}${variant.nameSuffix}`;\n    const variantWire = `${variantDomain}Response`;\n    lines.push(...buildInterfaceBody(variantDomain, shape, variant, /*isWire*/ false));\n    lines.push('');\n    lines.push(...buildInterfaceBody(variantWire, shape, variant, /*isWire*/ true));\n    lines.push('');\n  }\n\n  // Union aliases\n  const variantNames = shape.variants.map((v) => `${domain}${v.nameSuffix}`);\n  lines.push(`export type ${domain} = ${variantNames.join(' | ')};`);\n  lines.push('');\n  const wireVariantNames = shape.variants.map((v) => `${domain}${v.nameSuffix}Response`);\n  lines.push(`export type ${wire} = ${wireVariantNames.join(' | ')};`);\n\n  return {\n    path: `src/${modelDir}/interfaces/${fileName(shape.modelName)}.interface.ts`,\n    content: lines.join('\\n') + '\\n',\n    overwriteExisting: true,\n  };\n}\n\n/**\n * Emit a pure-`oneOf` discriminated union as a single inline type alias\n * (`export type X = { … } | { … }`) for both the domain and wire shapes. Used\n * instead of named per-variant interfaces, which read poorly for small\n * (often two-variant, boolean-discriminated) unions like the token response.\n */\nfunction buildInlineUnionFile(plan: DiscriminatedPlan): GeneratedFile {\n  const { shape, modelDir } = plan;\n  const domain = toPascalCase(shape.modelName);\n  const wire = wireInterfaceName(domain);\n  const lines: string[] = [];\n\n  const imports = collectImports(plan);\n  if (imports.length > 0) {\n    for (const imp of imports) {\n      lines.push(`import type { ${imp.symbols.join(', ')} } from '${imp.path}';`);\n    }\n    lines.push('');\n  }\n\n  lines.push(...buildInlineUnionAlias(domain, shape, /*isWire*/ false));\n  lines.push('');\n  lines.push(...buildInlineUnionAlias(wire, shape, /*isWire*/ true));\n\n  return {\n    path: `src/${modelDir}/interfaces/${fileName(shape.modelName)}.interface.ts`,\n    content: lines.join('\\n') + '\\n',\n    overwriteExisting: true,\n  };\n}\n\nfunction buildInlineUnionAlias(name: string, shape: DiscriminatedShape, isWire: boolean): string[] {\n  const lines: string[] = [`export type ${name} =`];\n  shape.variants.forEach((variant, idx) => {\n    const isLast = idx === shape.variants.length - 1;\n    const discKey = isWire ? shape.discriminatorProperty : shape.discriminatorPropertyDomain;\n    const members = [`${discKey}: ${discLiteral(variant)}`];\n    for (const field of variant.fields) {\n      const key = isWire ? field.name : toCamelCase(field.name);\n      const opt = field.required ? '' : '?';\n      members.push(`${key}${opt}: ${inlineFieldType(field, isWire)}`);\n    }\n    lines.push(`  | { ${members.join('; ')} }${isLast ? ';' : ''}`);\n  });\n  return lines;\n}\n\nfunction buildInterfaceBody(name: string, shape: DiscriminatedShape, variant: VariantSpec, isWire: boolean): string[] {\n  const lines: string[] = [];\n  lines.push(`export interface ${name} {`);\n  // Variant fields override base fields when both define the same property\n  // (variants have narrower types, e.g. `event: 'foo'` vs base `event: string`).\n  // The discriminator is also emitted separately as a const literal below.\n  const variantFieldNames = new Set(variant.fields.map((f) => f.name));\n  for (const field of shape.baseFields) {\n    if (variantFieldNames.has(field.name)) continue;\n    if (field.name === shape.discriminatorProperty) continue;\n    pushFieldLine(lines, field, isWire);\n  }\n  // Discriminator (typed as the variant's const value)\n  const discKey = isWire ? shape.discriminatorProperty : shape.discriminatorPropertyDomain;\n  if (shape.discriminatorDescription) {\n    lines.push(`  /** ${shape.discriminatorDescription} */`);\n  }\n  lines.push(`  ${discKey}: ${discLiteral(variant)};`);\n  // Variant-specific fields\n  for (const field of variant.fields) {\n    pushFieldLine(lines, field, isWire);\n  }\n  lines.push('}');\n  return lines;\n}\n\n/**\n * The discriminator value as a TS literal: quoted for strings (`'oauth'`),\n * bare for booleans (`true`).\n */\nfunction discLiteral(variant: VariantSpec): string {\n  return variant.discriminatorIsBoolean ? variant.discriminatorValue : `'${variant.discriminatorValue}'`;\n}\n\n/**\n * Field type for an inline-union member: a literal union for inline string\n * enums, otherwise the resolved domain/wire type.\n *\n * The `enumValues` branch deliberately ignores `isWire`: `enumValues` is only\n * populated for string enums (see `buildField`), whose domain and wire\n * representations are identical literal unions. Any field whose domain/wire\n * types actually differ (model refs, dates, non-string enums) leaves\n * `enumValues` undefined and falls through to the type-specific branch.\n */\nfunction inlineFieldType(field: FieldSpec, isWire: boolean): string {\n  if (field.enumValues) {\n    return field.enumValues.map((v) => `'${v}'`).join(' | ');\n  }\n  return isWire ? field.wireType : field.domainType;\n}\n\nfunction pushFieldLine(lines: string[], field: FieldSpec, isWire: boolean): void {\n  const key = isWire ? field.name : toCamelCase(field.name);\n  const opt = field.required ? '' : '?';\n  const type = isWire ? field.wireType : field.domainType;\n  if (field.description) {\n    lines.push(`  /** ${field.description} */`);\n  }\n  lines.push(`  ${key}${opt}: ${type};`);\n}\n\ninterface ImportSpec {\n  path: string;\n  symbols: string[];\n}\n\nfunction collectImports(plan: DiscriminatedPlan): ImportSpec[] {\n  const deps = new Set<string>();\n  for (const field of plan.shape.baseFields) {\n    for (const d of field.modelDeps) deps.add(d);\n  }\n  for (const variant of plan.shape.variants) {\n    for (const field of variant.fields) {\n      for (const d of field.modelDeps) deps.add(d);\n    }\n  }\n  const result: ImportSpec[] = [];\n  for (const dep of [...deps].sort()) {\n    const domain = toPascalCase(dep);\n    const wire = wireInterfaceName(domain);\n    const symbols = wire !== domain ? [domain, wire] : [domain];\n    // `dep` may be a raw spec name or a synthetic inline-object name in snake\n    // form (`Parent_field`); `depDirMap` keys the latter under its PascalCase IR\n    // name, so fall back to that spelling before defaulting to a same-dir path.\n    const depDir = plan.depDirMap.get(dep) ?? plan.depDirMap.get(domain);\n    const baseName = fileName(toSnakeFromPascal(domain));\n    let importPath: string;\n    if (!depDir || depDir === plan.modelDir) {\n      importPath = `./${baseName}.interface`;\n    } else {\n      importPath = `../../${depDir}/interfaces/${baseName}.interface`;\n    }\n    const existing = result.find((a) => a.path === importPath);\n    if (existing) existing.symbols.push(...symbols);\n    else result.push({ path: importPath, symbols });\n  }\n  return result;\n}\n\nfunction toSnakeFromPascal(s: string): string {\n  // PascalCase → snake_case, preserving acronyms via word splits.\n  return s\n    .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')\n    .toLowerCase();\n}\n\n// ---------------------------------------------------------------------------\n// Serializer\n// ---------------------------------------------------------------------------\n\nfunction buildSerializerFile(plan: DiscriminatedPlan, _ctx: EmitterContext): GeneratedFile {\n  const { shape, modelDir } = plan;\n  const domain = toPascalCase(shape.modelName);\n  const wire = wireInterfaceName(domain);\n  const lines: string[] = [];\n\n  // Imports: domain + wire union types from the interfaces file.\n  const interfaceImportPath = `../interfaces/${fileName(shape.modelName)}.interface`;\n  lines.push(`import type { ${domain}, ${wire} } from '${interfaceImportPath}';`);\n\n  // Serializer imports for model deps\n  const allDeps = new Set<string>();\n  for (const field of shape.baseFields) for (const d of field.modelDeps) allDeps.add(d);\n  for (const variant of shape.variants)\n    for (const field of variant.fields) for (const d of field.modelDeps) allDeps.add(d);\n\n  // Pure-`oneOf` unions are response shapes (e.g. the token response): they are\n  // only ever deserialized, and their inline-object fields may have no\n  // serializer generated. Emit a deserializer only and import just the\n  // deserialize helpers — mirrors the published hand-written serializer.\n  const deserializeOnly = shape.inlineUnion === true;\n  for (const dep of [...allDeps].sort()) {\n    const depDomain = toPascalCase(dep);\n    const depFile = fileName(toSnakeFromPascal(depDomain));\n    const helpers = deserializeOnly ? `deserialize${depDomain}` : `deserialize${depDomain}, serialize${depDomain}`;\n    lines.push(`import { ${helpers} } from './${depFile}.serializer';`);\n  }\n  lines.push('');\n\n  // Deserializer\n  lines.push(`export const deserialize${domain} = (response: ${wire}): ${domain} => {`);\n  lines.push(`  switch (response.${shape.discriminatorProperty}) {`);\n  for (const variant of shape.variants) {\n    lines.push(`    case ${discLiteral(variant)}:`);\n    lines.push(`      return {`);\n    for (const field of shape.baseFields) {\n      lines.push(`        ${assignmentLine(field, /*serialize*/ false, allDeps)},`);\n    }\n    lines.push(`        ${shape.discriminatorPropertyDomain}: ${discLiteral(variant)},`);\n    for (const field of variant.fields) {\n      lines.push(`        ${assignmentLine(field, /*serialize*/ false, allDeps)},`);\n    }\n    lines.push(`      };`);\n  }\n  lines.push(`    default:`);\n  lines.push(\n    `      throw new Error(\\`Unknown ${shape.discriminatorProperty}: \\${String((response as Record<string, unknown>).${shape.discriminatorProperty})}\\`);`,\n  );\n  lines.push(`  }`);\n  lines.push(`};`);\n\n  if (!deserializeOnly) {\n    lines.push('');\n    // Serializer\n    lines.push(`export const serialize${domain} = (model: ${domain}): ${wire} => {`);\n    lines.push(`  switch (model.${shape.discriminatorPropertyDomain}) {`);\n    for (const variant of shape.variants) {\n      lines.push(`    case ${discLiteral(variant)}:`);\n      lines.push(`      return {`);\n      for (const field of shape.baseFields) {\n        lines.push(`        ${assignmentLine(field, /*serialize*/ true, allDeps)},`);\n      }\n      lines.push(`        ${shape.discriminatorProperty}: ${discLiteral(variant)},`);\n      for (const field of variant.fields) {\n        lines.push(`        ${assignmentLine(field, /*serialize*/ true, allDeps)},`);\n      }\n      lines.push(`      };`);\n    }\n    lines.push(`  }`);\n    lines.push(`};`);\n  }\n\n  return {\n    path: `src/${modelDir}/serializers/${fileName(shape.modelName)}.serializer.ts`,\n    content: lines.join('\\n') + '\\n',\n    overwriteExisting: true,\n  };\n}\n\nfunction assignmentLine(field: FieldSpec, serialize: boolean, _allDeps: Set<string>): string {\n  const camel = toCamelCase(field.name);\n  const snake = field.name;\n  const lhs = serialize ? snake : camel;\n  const rhsKey = serialize ? camel : snake;\n  const source = serialize ? `model.${rhsKey}` : `response.${rhsKey}`;\n\n  if (field.hasDateTime) {\n    if (serialize) {\n      if (field.required) return `${lhs}: ${source}.toISOString()`;\n      return `${lhs}: ${source} != null ? ${source}.toISOString() : undefined`;\n    }\n    if (field.required) return `${lhs}: new Date(${source})`;\n    return `${lhs}: ${source} != null ? new Date(${source}) : undefined`;\n  }\n\n  const arrayDep = arrayItemModelDep(field);\n  if (arrayDep) {\n    const fn = serialize ? `serialize${arrayDep}` : `deserialize${arrayDep}`;\n    if (field.required) return `${lhs}: ${source}.map(${fn})`;\n    return `${lhs}: ${source} != null ? ${source}.map(${fn}) : undefined`;\n  }\n\n  const scalarDep = scalarModelDepName(field);\n  if (scalarDep) {\n    const fn = serialize ? `serialize${scalarDep}` : `deserialize${scalarDep}`;\n    if (field.required) return `${lhs}: ${fn}(${source})`;\n    return `${lhs}: ${source} != null ? ${fn}(${source}) : undefined`;\n  }\n\n  return `${lhs}: ${source}`;\n}\n\nfunction arrayItemModelDep(field: FieldSpec): string | null {\n  const m = field.domainType.match(/^([A-Z]\\w*)\\[\\]$/);\n  if (m && field.modelDeps.size > 0) return m[1];\n  return null;\n}\n\nfunction scalarModelDepName(field: FieldSpec): string | null {\n  const stripped = field.domainType.replace(/\\s*\\|\\s*null$/, '');\n  if (/^[A-Z]\\w*$/.test(stripped) && field.modelDeps.size === 1) {\n    return toPascalCase([...field.modelDeps][0]);\n  }\n  return null;\n}\n","import type { EmitterContext, Model, ResolvedOperation } from '@workos/oagen';\nimport { enrichModelsFromSpec } from '../shared/model-utils.js';\nimport { nodeOptions } from './options.js';\n\nconst contextCache = new WeakMap<EmitterContext, EmitterContext>();\n\nfunction operationKey(resolved: ResolvedOperation): string {\n  return `${resolved.operation.httpMethod.toUpperCase()} ${resolved.operation.path}`;\n}\n\n/**\n * Apply oneOf / allOf+oneOf enrichment (flattening variant fields onto the\n * parent model, plus synthetic models/enums for inline shapes) so the rest\n * of the Node emitter sees a richer `spec.models`.\n *\n * Without this, `ConnectApplication` (and any other `allOf [base, oneOf [...]]`\n * schema whose first variant is itself wrapped in `allOf`) loses every\n * non-M2M field — the IR parser's discriminator detection silently skips\n * variants whose properties live behind another `allOf`. Mirrors what the\n * Go / Kotlin / .NET emitters already do.\n *\n * Discriminated bases produced by `enrichModelsFromSpec` get their original\n * fields restored — Node emits flat interfaces today, not TS sum types, so\n * an empty base would otherwise drop the common fields.\n */\nfunction enrichSpecModels(models: readonly Model[]): Model[] {\n  const enriched = enrichModelsFromSpec(models as Model[]);\n  const originalByName = new Map(models.map((m) => [m.name, m]));\n  return enriched.map((m) => {\n    if ((m as { discriminator?: unknown }).discriminator && m.fields.length === 0) {\n      const original = originalByName.get(m.name);\n      if (original && original.fields.length > 0) {\n        return { ...m, fields: original.fields };\n      }\n    }\n    return m;\n  });\n}\n\nexport function withNodeOperationOverrides(ctx: EmitterContext): EmitterContext {\n  const cached = contextCache.get(ctx);\n  if (cached) return cached;\n\n  const enrichedModels = enrichSpecModels(ctx.spec.models);\n  const specChanged =\n    enrichedModels.length !== ctx.spec.models.length || enrichedModels.some((m, i) => m !== ctx.spec.models[i]);\n  const enrichedSpec = specChanged ? { ...ctx.spec, models: enrichedModels } : ctx.spec;\n\n  const resolvedOperations = ctx.resolvedOperations;\n  if (!resolvedOperations?.length) {\n    const next = specChanged ? { ...ctx, spec: enrichedSpec } : ctx;\n    contextCache.set(ctx, next);\n    return next;\n  }\n\n  const configOverrides = nodeOptions(ctx).operationOverrides ?? {};\n\n  let opsChanged = false;\n  const nextResolved = resolvedOperations.map((resolved) => {\n    const override = configOverrides[operationKey(resolved)];\n    if (!override) return resolved;\n\n    const methodName = override.methodName ?? resolved.methodName;\n    const mountOn = override.mountOn ?? resolved.mountOn;\n    if (methodName === resolved.methodName && mountOn === resolved.mountOn) {\n      return resolved;\n    }\n\n    opsChanged = true;\n    return {\n      ...resolved,\n      methodName,\n      mountOn,\n    };\n  });\n\n  const next =\n    opsChanged || specChanged\n      ? {\n          ...ctx,\n          ...(opsChanged ? { resolvedOperations: nextResolved } : {}),\n          ...(specChanged ? { spec: enrichedSpec } : {}),\n        }\n      : ctx;\n  contextCache.set(ctx, next);\n  return next;\n}\n","/**\n * Canonical \"do not edit\" banner text shared by every emitter's\n * `fileHeader()`. The text is comment-syntax agnostic — each emitter prefixes\n * it with the appropriate comment marker for its language (`//`, `#`, etc.).\n *\n * Keeping this in one place prevents the wording from drifting between\n * languages (Rust previously emitted a different banner).\n *\n * Go intentionally does NOT use this constant: its header must match the\n * standard `^// Code generated .* DO NOT EDIT\\.$` marker that Go tooling\n * relies on to recognize generated files. See `src/go/index.ts`.\n */\nexport const AUTOGEN_NOTICE = 'This file is auto-generated by oagen. Do not edit.';\n","import type {\n  Emitter,\n  EmitterContext,\n  FormatCommand,\n  GeneratedFile,\n  ApiSpec,\n  Model,\n  Enum,\n  Service,\n} from '@workos/oagen';\nimport { toPascalCase } from '@workos/oagen';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { generateModelsAndSerializers } from './models.js';\nimport { generateEnums as generateEnumFiles } from './enums.js';\nimport { generateResources, resolveResourceClassName, resolveResourceDir } from './resources.js';\nimport { generateClient } from './client.js';\nimport { generateTests as generateTestFiles } from './tests.js';\nimport { enrichModelsFromSpec, getSyntheticEnums } from '../shared/model-utils.js';\nimport { flattenDiscriminatedUnionFields } from '../shared/union-flatten.js';\nimport { planDiscriminatedModels, generateDiscriminatedFiles } from './discriminated-models.js';\nimport {\n  buildLiveSurface,\n  emptyLiveSurface,\n  mergeGeneratedClassMethodsIntoExisting,\n  setActiveLiveSurface,\n  type LiveSurface,\n} from './live-surface.js';\nimport {\n  setBaselineSerializedNames,\n  setBaselineInterfaceNames,\n  setBaselineDeclaredNames,\n  setAdoptedModelNames,\n  setDiscriminatedModelNames,\n  setStructurallyRenamedDomainNames,\n  resolveInterfaceName,\n} from './naming.js';\nimport { withNodeOperationOverrides } from './node-overrides.js';\nimport { isNodeOwnedService, nodeOptions } from './options.js';\nimport { setInlineEnumUnions, setDomainNameResolver } from './type-map.js';\nimport { groupByMount } from '../shared/resolved-ops.js';\nimport { AUTOGEN_NOTICE } from '../shared/file-header.js';\nimport { assignModelsToServices, createServiceDirResolver, relativeImport } from './utils.js';\nimport { fileName } from './naming.js';\n\n/**\n * Cache live-surface per ctx — every emitter method receives the same ctx in\n * one oagen run, so we walk the target SDK once and reuse it.\n */\nconst surfaceCache = new WeakMap<EmitterContext, LiveSurface>();\n\n/**\n * Paths the node emitter has produced so far in this ctx, accumulated across\n * `applyLiveSurface` calls. Drives `carryForwardManagedFiles` so files in the\n * prior manifest that we did not re-emit this run still land in the new\n * manifest as \"still managed\" — without that, the orchestrator's prune diff\n * treats every untouched autogen file as stale.\n */\nconst emittedPathsCache = new WeakMap<EmitterContext, Set<string>>();\n\nfunction getEmittedPaths(ctx: EmitterContext): Set<string> {\n  let set = emittedPathsCache.get(ctx);\n  if (!set) {\n    set = new Set();\n    emittedPathsCache.set(ctx, set);\n  }\n  return set;\n}\n\n/**\n * Every `GeneratedFile` the node emitter has produced so far in this ctx,\n * keyed by path. All emitter hooks share one ctx (and the engine only reads\n * file contents after the last hook returns), so the final hook can run a\n * whole-run pass over files emitted by earlier hooks — see\n * `enforceEmittedImportInvariant`.\n */\nconst emittedFilesCache = new WeakMap<EmitterContext, Map<string, GeneratedFile>>();\n\nfunction getEmittedFiles(ctx: EmitterContext): Map<string, GeneratedFile> {\n  let map = emittedFilesCache.get(ctx);\n  if (!map) {\n    map = new Map();\n    emittedFilesCache.set(ctx, map);\n  }\n  return map;\n}\n\nfunction getSurface(ctx: EmitterContext): LiveSurface {\n  let surface = surfaceCache.get(ctx);\n  if (surface) return surface;\n  // Prefer --output (where we are writing) over --target (rare for node).\n  // The literal command `--output <SDK>` makes outputDir the SDK root.\n  const root = ctx.outputDir ?? ctx.targetDir;\n  surface = root ? buildLiveSurface(root) : emptyLiveSurface();\n  if (root) markPriorManifestAutogen(surface, root, ctx.priorTargetManifestPaths);\n  surfaceCache.set(ctx, surface);\n  setActiveLiveSurface(surface);\n\n  // Wire the type-map's resolver so field-type references (`schema: X`) and\n  // import statements (`import type { X }`) agree on the same name. The\n  // structural baseline match in `resolveInterfaceName` can map an IR name\n  // to a different live-SDK name (e.g. `AuditLogSchemaJson` → baseline\n  // `AuditLogSchemaResponse` via `overlayLookup.modelNameByIR`).\n  setDomainNameResolver((irName: string) => resolveInterfaceName(irName, ctx));\n\n  // Tell `naming.wireInterfaceName` which `Serialized*` interfaces exist in\n  // the live SDK so generated imports use the legacy name where applicable.\n  // Source from the api-surface JSON (richer) when present, else fall back\n  // to the disk walk.\n  const serialized = new Set<string>();\n  const ifaces = ctx.apiSurface?.interfaces;\n  if (ifaces) {\n    for (const name of Object.keys(ifaces)) {\n      if (name.startsWith('Serialized')) serialized.add(name);\n    }\n  }\n  for (const name of surface.interfaces.keys()) {\n    if (name.startsWith('Serialized')) serialized.add(name);\n  }\n  setBaselineSerializedNames(serialized);\n\n  // Full set of baseline interface names — used by `wireInterfaceName` to\n  // detect when a `Response`-suffixed name has no `*Wire` companion in\n  // the live SDK and is therefore the single-form wire interface.\n  const allInterfaces = new Set<string>();\n  if (ifaces) {\n    for (const name of Object.keys(ifaces)) allInterfaces.add(name);\n  }\n  for (const name of surface.interfaces.keys()) allInterfaces.add(name);\n  setBaselineInterfaceNames(allInterfaces);\n\n  // Every DECLARED baseline name — interfaces and type aliases, from both\n  // the api-surface JSON and the disk walk (whose `interfaces` map already\n  // includes `export type` aliases). `resolveInterfaceName` uses this to\n  // let exact-name declarations preempt structural renames: an alias-form\n  // file (`export type X = Y;`) carries no fields, so the engine's\n  // structural matcher would otherwise re-point IR model X at a similarly\n  // shaped interface and emit renamed duplicates that flip the file's form\n  // on every regeneration.\n  const declaredNames = new Set<string>(allInterfaces);\n  for (const name of Object.keys(ctx.apiSurface?.typeAliases ?? {})) declaredNames.add(name);\n  setBaselineDeclaredNames(declaredNames);\n\n  // Inline-enum optimization is intentionally disabled. workos-node emits the\n  // dual `const X = {...} as const; type X = ...` pattern so callers can use\n  // members at runtime (e.g. `GenerateLinkIntent.SSO`). Inlining the type\n  // would drop the enum's file but leave value references in hand-written\n  // test files dangling — see admin-portal.spec.ts referencing `.SSO`.\n  // Pass an empty map; type-map will fall back to emitting the symbol name.\n  setInlineEnumUnions(new Map());\n  setAdoptedModelNames(computeAdoptedModelNames(ctx, surface));\n\n  // Pre-compute which domain names the resolver reaches via structural\n  // rename so `wireInterfaceName` can tell `AuditLogSchemaJson` →\n  // `AuditLogSchemaResponse` (real single-form case) apart from\n  // `CreateDataKeyResponse` → `CreateDataKeyResponse` (fresh IR model whose\n  // own name already ends in `Response`).\n  const renamed = new Set<string>();\n  for (const model of ctx.spec.models) {\n    const resolved = resolveInterfaceName(model.name, ctx);\n    if (resolved !== model.name) renamed.add(resolved);\n  }\n  setStructurallyRenamedDomainNames(renamed);\n\n  return surface;\n}\n\n/**\n * Apply the live-surface filter to a batch of generated files.\n *\n * Three signals decide what happens to each `GeneratedFile`:\n *\n *   1. `@oagen-ignore-file` marker (`surface.protectedFiles`) — the user has\n *      taken ownership of the file, never write on top of it.\n *   2. `auto-generated by oagen` header (`surface.autogenFiles`) — the file\n *      was produced by a prior generation. Spec changes (e.g. parameter\n *      renames) must propagate, so we leave the file in the output and let\n *      the engine's AST merger update it. No skip flags.\n *   3. File on disk without either marker — treat as hand-written; drop from\n *      the output to avoid the engine prepending a header on `skipIfExists`\n *      files (see writeFiles:~4360 in @workos/oagen) or merging unrequested\n *      changes into it.\n *   4. Brand-new path in an existing SDK — drop it. For a live SDK we treat\n *      the git-tracked baseline as the managed surface; generating new files\n *      is what caused the workos-node file explosion.\n *\n * `integrateTarget: false` files (smoke-manifest.json etc.) are also dropped:\n * with no `--target` step they would otherwise land as untracked cruft.\n *\n * Note: the carry-forward step in `generateTests` re-declares prior-manifest\n * paths we didn't touch this run, so the orchestrator's prune diff stays\n * accurate without needing `--no-prune` at the call site. See\n * `carryForwardManagedFiles` below.\n */\n/**\n * `*.spec.ts`, `*.test.ts`, and JSON fixtures under `fixtures/` are owned by\n * the test author after first emission. The emitter scaffolds them on a\n * brand-new resource, but subsequent regenerations must leave them alone —\n * assertions get hand-tuned, fixture data gets stabilized, and re-emission\n * would point them at sibling serializers/interfaces that may have shape-\n * shifted under the user's feet.\n */\nfunction isUserOwnedAfterFirstEmit(relPath: string): boolean {\n  if (relPath.endsWith('.spec.ts') || relPath.endsWith('.test.ts')) return true;\n  if (/\\/fixtures\\/[^/]+\\.json$/.test(relPath)) return true;\n  return false;\n}\n\ninterface LiveSurfacePolicy {\n  managedPaths: Set<string>;\n  hasExistingSdk: boolean;\n  adoptedServiceDirs: Set<string>;\n  ownedServiceDirs: Set<string>;\n  oagenOwnedDirs: Set<string>;\n  regenerateOwnedTests: boolean;\n}\n\nfunction managedPathsFor(ctx: EmitterContext, surface: LiveSurface): Set<string> {\n  const managedPaths = new Set(surface.trackedFiles.size > 0 ? surface.trackedFiles : surface.files);\n  for (const relPath of ctx.priorTargetManifestPaths ?? []) {\n    if (relPath.startsWith('src/')) managedPaths.add(relPath);\n  }\n  return managedPaths;\n}\n\nfunction markPriorManifestAutogen(\n  surface: LiveSurface,\n  root: string,\n  priorManifestPaths: Set<string> | undefined,\n): void {\n  if (!priorManifestPaths) return;\n\n  for (const relPath of priorManifestPaths) {\n    if (!relPath.startsWith('src/')) continue;\n    if (!surface.files.has(relPath)) continue;\n    if (surface.protectedFiles.has(relPath)) continue;\n\n    if (/\\/fixtures\\/[^/]+\\.json$/.test(relPath)) {\n      surface.autogenFiles.add(relPath);\n      continue;\n    }\n\n    try {\n      const text = fs.readFileSync(path.join(root, relPath), 'utf8');\n      if (/auto-generated by oagen/i.test(text.slice(0, 400))) {\n        surface.autogenFiles.add(relPath);\n        extractManifestFunctions(text, relPath, surface);\n      }\n    } catch {\n      // File disappeared between surface walk and read; ignore it.\n    }\n  }\n}\n\nconst MANIFEST_FUNCTION_RE = /^\\s*export\\s+(?:async\\s+)?function\\s+([a-zA-Z_$][\\w$]*)/gm;\nconst MANIFEST_CONST_FN_RE =\n  /^\\s*export\\s+const\\s+([a-zA-Z_$][\\w$]*)\\s*(?::\\s*[^=]+)?=\\s*(?:async\\s+)?(?:<[^>]*>\\s*)?\\(/gm;\n\nfunction extractManifestFunctions(text: string, relPath: string, surface: LiveSurface): void {\n  for (const match of text.matchAll(MANIFEST_FUNCTION_RE)) {\n    surface.functions.set(match[1], relPath);\n  }\n  for (const match of text.matchAll(MANIFEST_CONST_FN_RE)) {\n    surface.functions.set(match[1], relPath);\n  }\n}\n\nfunction buildLiveSurfacePolicy(ctx: EmitterContext, surface: LiveSurface): LiveSurfacePolicy {\n  const managedPaths = managedPathsFor(ctx, surface);\n  const hasExistingSdk = managedPaths.size > 0;\n  const adoptedServiceDirs = nodeOptions(ctx).adoptMissingServices\n    ? computeAdoptedServiceDirs(ctx, surface)\n    : new Set<string>();\n  const ownedServiceDirs = computeOwnedServiceDirs(ctx);\n  for (const dir of ownedServiceDirs) {\n    for (const relPath of surface.files) {\n      if (topLevelDir(relPath) === dir) managedPaths.add(relPath);\n    }\n  }\n\n  return {\n    managedPaths,\n    hasExistingSdk,\n    adoptedServiceDirs,\n    ownedServiceDirs,\n    oagenOwnedDirs: topLevelDirs(surface.autogenFiles),\n    regenerateOwnedTests: nodeOptions(ctx).regenerateOwnedTests === true,\n  };\n}\n\nfunction computeOwnedServiceDirs(ctx: EmitterContext): Set<string> {\n  const dirs = new Set<string>();\n  if ((nodeOptions(ctx).ownedServices ?? []).length === 0) return dirs;\n\n  const mountGroups = groupByMount(ctx);\n  const services =\n    mountGroups.size > 0\n      ? [...mountGroups].map(([name, group]) => ({\n          name,\n          operations: group.operations,\n        }))\n      : ctx.spec.services;\n  const { resolveDir } = createServiceDirResolver(ctx.spec.models, ctx.spec.services, ctx);\n\n  for (const service of services) {\n    const resourceName = resolveResourceClassName(service, ctx);\n    if (!isNodeOwnedService(ctx, service.name, resourceName)) continue;\n    dirs.add(resolveResourceDir(service, ctx));\n    dirs.add(resolveDir(service.name));\n  }\n\n  return dirs;\n}\n\nfunction computeAdoptedServiceDirs(ctx: EmitterContext, surface: LiveSurface): Set<string> {\n  const dirs = new Set<string>();\n  const mountGroups = groupByMount(ctx);\n  const services =\n    mountGroups.size > 0\n      ? [...mountGroups].map(([name, group]) => ({\n          name,\n          operations: group.operations,\n        }))\n      : ctx.spec.services;\n  const { resolveDir } = createServiceDirResolver(ctx.spec.models, ctx.spec.services, ctx);\n\n  for (const service of services) {\n    if (service.operations.length === 0) continue;\n\n    const resourceName = resolveResourceClassName(service, ctx);\n    if (surface.classes.has(resourceName) || ctx.apiSurface?.classes?.[resourceName]) continue;\n\n    const resourceDir = resolveResourceDir(service, ctx);\n    const resourcePath = `src/${resourceDir}/${fileName(resourceName)}.ts`;\n    if (surface.protectedFiles.has(resourcePath)) continue;\n\n    dirs.add(resourceDir);\n    dirs.add(resolveDir(service.name));\n  }\n\n  return dirs;\n}\n\nfunction computeAdoptedModelNames(ctx: EmitterContext, surface: LiveSurface): Set<string> {\n  if (!nodeOptions(ctx).adoptMissingServices) return new Set();\n\n  const adoptedServiceDirs = computeAdoptedServiceDirs(ctx, surface);\n  if (adoptedServiceDirs.size === 0) return new Set();\n\n  const modelToService = assignModelsToServices(ctx.spec.models, ctx.spec.services, ctx.modelHints);\n  const { resolveDir } = createServiceDirResolver(ctx.spec.models, ctx.spec.services, ctx);\n  const names = new Set<string>();\n  for (const model of ctx.spec.models) {\n    const dirName = resolveDir(modelToService.get(model.name));\n    if (adoptedServiceDirs.has(dirName)) names.add(model.name);\n  }\n  return names;\n}\n\nfunction topLevelDirs(paths: Set<string>): Set<string> {\n  const dirs = new Set<string>();\n  for (const relPath of paths) {\n    const dir = topLevelDir(relPath);\n    if (dir) dirs.add(dir);\n  }\n  return dirs;\n}\n\nfunction topLevelDir(relPath: string): string | undefined {\n  return relPath.match(/^src\\/([^/]+)\\//)?.[1];\n}\n\nfunction canCreateNewPath(relPath: string, policy: LiveSurfacePolicy): boolean {\n  const dir = topLevelDir(relPath);\n  if (!dir) return false;\n  return policy.adoptedServiceDirs.has(dir) || policy.ownedServiceDirs.has(dir) || policy.oagenOwnedDirs.has(dir);\n}\n\nfunction isOwnedPath(relPath: string, policy: LiveSurfacePolicy): boolean {\n  const dir = topLevelDir(relPath);\n  return dir !== undefined && policy.ownedServiceDirs.has(dir);\n}\n\n/** Read the current on-disk content of a live-surface file, if present. */\nfunction readExistingSurfaceFile(surface: LiveSurface, relPath: string): string | null {\n  if (!surface.rootDir) return null;\n  try {\n    return fs.readFileSync(path.join(surface.rootDir, relPath), 'utf8');\n  } catch {\n    return null;\n  }\n}\n\nfunction extractRelativeImportPaths(content: string, fromPath: string): string[] {\n  const dir = path.dirname(fromPath);\n  const paths: string[] = [];\n  const re = /from\\s+['\"](\\.[^'\"]+)['\"]/g;\n  let match: RegExpExecArray | null;\n  while ((match = re.exec(content)) !== null) {\n    paths.push(path.normalize(path.join(dir, match[1])) + '.ts');\n  }\n  return paths;\n}\n\nfunction applyLiveSurface(files: GeneratedFile[], ctx: EmitterContext, surface: LiveSurface): GeneratedFile[] {\n  const out: GeneratedFile[] = [];\n  const policy = buildLiveSurfacePolicy(ctx, surface);\n  const filesByPath = new Map(files.map((f) => [f.path, f]));\n  const dependencyAllowedPaths = new Set<string>();\n  const queue: string[] = [];\n\n  for (const f of files) {\n    if (f.integrateTarget === false) continue;\n    if (!canCreateNewPath(f.path, policy)) continue;\n    for (const importPath of extractRelativeImportPaths(f.content, f.path)) {\n      if (\n        filesByPath.has(importPath) &&\n        !canCreateNewPath(importPath, policy) &&\n        !dependencyAllowedPaths.has(importPath)\n      ) {\n        dependencyAllowedPaths.add(importPath);\n        queue.push(importPath);\n      }\n    }\n  }\n\n  while (queue.length > 0) {\n    const relPath = queue.pop()!;\n    const file = filesByPath.get(relPath);\n    if (!file) continue;\n    for (const importPath of extractRelativeImportPaths(file.content, relPath)) {\n      if (\n        filesByPath.has(importPath) &&\n        !canCreateNewPath(importPath, policy) &&\n        !dependencyAllowedPaths.has(importPath)\n      ) {\n        dependencyAllowedPaths.add(importPath);\n        queue.push(importPath);\n      }\n    }\n  }\n\n  for (const f of files) {\n    const ownedPath = isOwnedPath(f.path, policy);\n    if (f.integrateTarget === false) continue;\n    if (surface.protectedFiles.has(f.path)) continue;\n    if (\n      policy.hasExistingSdk &&\n      !policy.managedPaths.has(f.path) &&\n      !canCreateNewPath(f.path, policy) &&\n      !dependencyAllowedPaths.has(f.path)\n    )\n      continue;\n\n    // Hand-written files (on disk, no `auto-generated by oagen` header) →\n    // drop. The engine would otherwise prepend the header on\n    // `skipIfExists: true` files (writeFiles:~4360), and the merger may\n    // try to splice generated symbols into hand-written ones.\n    if (surface.files.has(f.path) && !surface.autogenFiles.has(f.path) && !ownedPath) continue;\n\n    // Test specs and fixtures: author-owned after first emission. Once a\n    // test file or fixture exists on disk, the user owns it — the emitter\n    // re-emitting against new IR would either replace assertions/data the\n    // user has hand-tuned, or leave it pointing at sibling files that no\n    // longer have the same shape. Treat existing test/fixture files as\n    // frozen even when they carry the auto-gen header.\n    //\n    // Adopted-service directories are treated like owned dirs for this\n    // purpose: adoption means oagen created the directory from scratch, so\n    // by construction there is no hand-written content to preserve and\n    // emitting tests/fixtures is safe. Rule (a) still drops files that\n    // somehow exist hand-written.\n    if (isUserOwnedAfterFirstEmit(f.path)) {\n      const dir = topLevelDir(f.path);\n      const isAdoptedDir = dir !== undefined && policy.adoptedServiceDirs.has(dir);\n      const isManagedDir = ownedPath || isAdoptedDir;\n      if (surface.files.has(f.path) && !surface.autogenFiles.has(f.path) && !(ownedPath && policy.regenerateOwnedTests))\n        continue;\n      if (!isManagedDir && !surface.autogenFiles.has(f.path)) continue;\n      if (isManagedDir && !policy.regenerateOwnedTests) continue;\n    }\n\n    // Previously auto-generated files → fully overwrite so spec changes\n    // (e.g. parameter renames like `admin_emails` → `it_contact_emails`)\n    // propagate. The engine's default AST merger is additive and would\n    // leave the old name on existing methods. Files marked\n    // `@oagen-ignore-start`/`@oagen-ignore-end` regions inside the file\n    // are still preserved by `overwriteWithPreservedRegions` in the\n    // engine.\n    //\n    // Exception: a NOT-owned, NOT-adopted service can receive a PARTIAL\n    // resource emission — resources.ts filters out operations already\n    // covered by the baseline class, leaving only the new methods (see\n    // generateResourceClass). Forcing a full overwrite with that partial\n    // class deletes the existing public methods (workos-node's\n    // api-keys.ts lost four methods when the spec gained one operation).\n    // When the generated class would drop methods that the on-disk class\n    // declares, merge instead: keep the existing file text verbatim and\n    // append only the new methods plus the imports they need.\n    if (surface.autogenFiles.has(f.path) || ownedPath) {\n      const dir = topLevelDir(f.path);\n      const isAdoptedDirPath = dir !== undefined && policy.adoptedServiceDirs.has(dir);\n      if (!ownedPath && !isAdoptedDirPath && surface.autogenFiles.has(f.path)) {\n        const existingText = readExistingSurfaceFile(surface, f.path);\n        if (existingText !== null) {\n          const merged = mergeGeneratedClassMethodsIntoExisting(existingText, f.content);\n          if (merged !== null) f.content = merged;\n        }\n      }\n      f.overwriteExisting = true;\n      f.skipIfExists = false;\n    }\n\n    if (f.content && !f.content.endsWith('\\n')) {\n      f.content += '\\n';\n    }\n    out.push(f);\n  }\n  const emitted = getEmittedPaths(ctx);\n  const emittedFiles = getEmittedFiles(ctx);\n  for (const f of out) {\n    emitted.add(f.path);\n    emittedFiles.set(f.path, f);\n  }\n  return out;\n}\n\n// ---------------------------------------------------------------------------\n// Import-resolution invariant\n// ---------------------------------------------------------------------------\n\n/**\n * Matches single-line `import`/`export … from './relative'` statements — the\n * only form the node emitter produces. Captures: keyword, optional ` type`\n * modifier, the binding clause (`* [as ns]` or `{ … }`), and the module path.\n */\nconst RELATIVE_FROM_STMT_RE =\n  /^(import|export)(\\s+type)?\\s+(\\*(?:\\s+as\\s+[\\w$]+)?|\\{[^}]*\\})\\s+from\\s+['\"](\\.[^'\"]+)['\"];?\\s*$/;\n\nconst EXPORTED_DECL_RE =\n  /^export\\s+(?:declare\\s+)?(?:abstract\\s+)?(?:async\\s+)?(?:interface|class|enum|function|const|let|var|type)\\s+([A-Za-z_$][\\w$]*)/gm;\nconst EXPORTED_CLAUSE_RE = /^export\\s+(?:type\\s+)?\\{([^}]*)\\}/gm;\n\n/** Repo-relative paths a relative import specifier may resolve to. */\nfunction importTargetCandidates(fromPath: string, spec: string): string[] {\n  const base = path.posix.normalize(path.posix.join(path.posix.dirname(fromPath), spec));\n  return [base, `${base}.ts`, `${base}/index.ts`];\n}\n\n/** Index exported symbol → file path across this run's emitted contents. */\nfunction indexEmittedExports(files: GeneratedFile[]): Map<string, string> {\n  const index = new Map<string, string>();\n  for (const f of files) {\n    if (!f.path.endsWith('.ts') || !f.content) continue;\n    for (const m of f.content.matchAll(EXPORTED_DECL_RE)) {\n      if (!index.has(m[1])) index.set(m[1], f.path);\n    }\n    for (const m of f.content.matchAll(EXPORTED_CLAUSE_RE)) {\n      for (const raw of m[1].split(',')) {\n        const entry = raw.trim();\n        if (!entry) continue;\n        const parts = entry.split(/\\s+as\\s+/);\n        const exported = (parts[1] ?? parts[0]).replace(/^type\\s+/, '').trim();\n        if (exported && !index.has(exported)) index.set(exported, f.path);\n      }\n    }\n  }\n  return index;\n}\n\n/**\n * Enforce: every relative import/re-export path in emitted code resolves to\n * either (i) a file emitted in the same run, or (ii) a file that already\n * exists on disk in the target SDK.\n *\n * Violations observed in real generations (all TS2307 in otherwise-valid\n * output): serializer imports pointing at canonical paths while the function\n * lives in a legacy hand serializer under a different filename; barrels\n * re-exporting a module-local enum file whose declaration lives under\n * `src/common/interfaces`; barrels exporting interface files that no run\n * emits at all.\n *\n * Repair strategy, per statement whose target is neither emitted nor on\n * disk:\n *  1. Locate each imported symbol (this run's emissions first, then the\n *     live-surface declaration maps) and rewrite the path to where the\n *     symbol actually lives — splitting into one statement per location\n *     when symbols are spread across files.\n *  2. `export * from` / namespace imports carry no symbol list, so derive\n *     the expected symbol from the file stem (`foo-bar.interface` →\n *     `FooBar`, `foo.serializer` → `deserializeFoo`/`serializeFoo`).\n *  3. When a symbol exists nowhere, drop the statement and warn — a missing\n *     named export fails loudly at the usage site instead of as a phantom\n *     module, and a barrel line for a never-emitted file is pure noise.\n *\n * Mutates `f.content` in place and returns the warnings issued.\n */\nexport function enforceEmittedImportInvariant(\n  files: Iterable<GeneratedFile>,\n  emittedPaths: Set<string>,\n  surface: LiveSurface,\n): string[] {\n  const fileList = [...files];\n  const emittedSymbols = indexEmittedExports(fileList);\n  const warnings: string[] = [];\n\n  const targetExists = (fromPath: string, spec: string): boolean =>\n    importTargetCandidates(fromPath, spec).some((p) => emittedPaths.has(p) || surface.files.has(p));\n\n  const locateSymbol = (name: string): string | undefined =>\n    emittedSymbols.get(name) ??\n    surface.functions.get(name) ??\n    surface.interfaces.get(name)?.filePath ??\n    surface.classes.get(name)?.filePath;\n\n  for (const f of fileList) {\n    if (!f.path.endsWith('.ts') || !f.content) continue;\n    let changed = false;\n    const outLines: string[] = [];\n    for (const line of f.content.split('\\n')) {\n      const m = line.match(RELATIVE_FROM_STMT_RE);\n      if (!m || targetExists(f.path, m[4])) {\n        outLines.push(line);\n        continue;\n      }\n      const [, keyword, typeMod, clause, spec] = m;\n      const repaired = repairUnresolvableStatement(f.path, keyword, typeMod ?? '', clause, spec, locateSymbol);\n      changed = true;\n      outLines.push(...repaired.lines);\n      if (repaired.warning) warnings.push(repaired.warning);\n    }\n    if (changed) f.content = outLines.join('\\n');\n  }\n\n  for (const w of warnings) console.warn(w);\n  return warnings;\n}\n\nfunction repairUnresolvableStatement(\n  fromPath: string,\n  keyword: string,\n  typeMod: string,\n  clause: string,\n  spec: string,\n  locateSymbol: (name: string) => string | undefined,\n): { lines: string[]; warning?: string } {\n  if (clause.startsWith('{')) {\n    const entries = clause\n      .slice(1, -1)\n      .split(',')\n      .map((e) => e.trim())\n      .filter(Boolean);\n    const byLocation = new Map<string, string[]>();\n    const missing: string[] = [];\n    for (const entry of entries) {\n      const source = entry\n        .split(/\\s+as\\s+/)[0]\n        .replace(/^type\\s+/, '')\n        .trim();\n      const location = locateSymbol(source);\n      if (!location) {\n        missing.push(source);\n        continue;\n      }\n      if (location === fromPath) continue; // declared locally — no import needed\n      const group = byLocation.get(location);\n      if (group) {\n        group.push(entry);\n      } else {\n        byLocation.set(location, [entry]);\n      }\n    }\n    // Emit the symbols we *can* relocate; only the genuinely-missing ones are\n    // dropped (and warned about). Returning [] for the whole clause when any\n    // one symbol is missing would also discard the resolvable symbols, failing\n    // them with TS2305 at their usage sites — the breakage this pass prevents.\n    const lines = [...byLocation].map(\n      ([location, group]) =>\n        `${keyword}${typeMod} { ${group.join(', ')} } from '${relativeImport(fromPath, location)}';`,\n    );\n    const warning =\n      missing.length > 0\n        ? `oagen(node): dropped unresolvable symbol(s) from ${keyword} in ${fromPath}: '${spec}' — found neither in this run's output nor in the target SDK: ${missing.join(', ')}`\n        : undefined;\n    return { lines, warning };\n  }\n\n  // `* [as ns]` — no symbol list; derive the expected symbol from the stem.\n  const stem = spec.split('/').pop() ?? '';\n  let location: string | undefined;\n  if (stem.endsWith('.interface')) {\n    location = locateSymbol(toPascalCase(stem.slice(0, -'.interface'.length)));\n  } else if (stem.endsWith('.serializer')) {\n    const base = toPascalCase(stem.slice(0, -'.serializer'.length));\n    location = locateSymbol(`deserialize${base}`) ?? locateSymbol(`serialize${base}`);\n  }\n  if (location && location !== fromPath) {\n    return { lines: [`${keyword}${typeMod} ${clause} from '${relativeImport(fromPath, location)}';`] };\n  }\n  return {\n    lines: [],\n    warning: `oagen(node): dropped unresolvable ${keyword} in ${fromPath}: '${spec}' — module is neither emitted this run nor present in the target SDK`,\n  };\n}\n\n/**\n * Re-declare prior-manifest paths that we did not emit this run so manifest\n * pruning can tell \"intentionally removed\" from \"untouched but still managed.\"\n *\n * The node emitter only outputs files it actually wants to write each run —\n * untouched-but-up-to-date autogen files don't come back through any\n * `generateXxx` method. Without this carry-forward, the orchestrator's\n * `prevManifest.files − currentEmission` diff treats every such file as stale\n * and prunes the whole tree on a regen. That's why `scripts/sdk-generate.sh`\n * historically paired the node emitter with `--no-prune` — at the cost of\n * never pruning legitimately-removed files (e.g. an enum file orphaned by a\n * `schemaNameTransform` rename like `RadarAction` → `RadarListAction`).\n *\n * The carry-forward entry uses `skipIfExists: true`, so writer.ts skips the\n * write and only ensures the header is present (no-op for files that already\n * have it). The path still lands in `outputEmittedPaths` and therefore in the\n * new manifest, which restores correct prune semantics.\n *\n * Files dropped from the carry-forward set:\n *  - Not on disk anymore (file was hand-deleted — let prune confirm absence).\n *  - `@oagen-ignore-file` protected (user has explicitly taken ownership).\n *  - `.ts` files that no longer carry the auto-gen header (user has taken\n *    ownership in-place; the next prune cycle will clear the manifest entry).\n */\nfunction carryForwardManagedFiles(ctx: EmitterContext, surface: LiveSurface): GeneratedFile[] {\n  const priorPaths = ctx.priorTargetManifestPaths;\n  if (!priorPaths || priorPaths.size === 0) return [];\n\n  const emitted = getEmittedPaths(ctx);\n  const out: GeneratedFile[] = [];\n  for (const relPath of priorPaths) {\n    if (emitted.has(relPath)) continue;\n    if (!surface.files.has(relPath)) continue;\n    if (surface.protectedFiles.has(relPath)) continue;\n    if (relPath.endsWith('.ts') && !surface.autogenFiles.has(relPath)) continue;\n\n    out.push({\n      path: relPath,\n      content: '',\n      skipIfExists: true,\n      headerPlacement: 'skip',\n    });\n    emitted.add(relPath);\n  }\n  return out;\n}\n\n/**\n * Flatten oneOf / allOf+oneOf variant fields from the raw spec onto each\n * model. `enrichModelsFromSpec` produces (a) extra optional fields on models\n * whose schema is `allOf [base, oneOf [...]]`, and (b) synthetic models /\n * enums for inline objects encountered inside variants (e.g. the inline\n * `redirect_uris` item shape on `ConnectApplication`).\n *\n * Node, like Go / Kotlin / .NET, emits flat interfaces rather than a sum\n * type, so on `enrichModelsFromSpec`-marked discriminated bases we restore\n * the original IR fields — otherwise the base interface would be empty.\n * A future change can emit a real TS discriminated union; for now the goal\n * is parity with the other flat-emit languages so every variant field is\n * at least reachable.\n */\nfunction enrichModelsForNode(models: Model[]): Model[] {\n  const enriched = enrichModelsFromSpec(models);\n  const originalByName = new Map(models.map((m) => [m.name, m]));\n  const restored = enriched.map((m) => {\n    if ((m as { discriminator?: unknown }).discriminator && m.fields.length === 0) {\n      const original = originalByName.get(m.name);\n      if (original && original.fields.length > 0) {\n        return { ...m, fields: original.fields };\n      }\n    }\n    return m;\n  });\n  // Field-level discriminated unions (e.g. ApiKey.owner) otherwise render as\n  // `FirstVariant | SecondVariant`; collapse them to one flat superset\n  // interface so callers see every variant field (organization_id on the user\n  // owner) on a single type — parity with the other flat-emit languages.\n  return flattenDiscriminatedUnionFields(restored);\n}\n\nexport const nodeEmitter: Emitter = {\n  language: 'node',\n\n  generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n    const nodeCtx = withNodeOperationOverrides(ctx);\n    const surface = getSurface(nodeCtx);\n    const enriched = enrichModelsForNode(models);\n    // Detect `allOf [base, oneOf [variant, …]]` schemas and hand them off\n    // to the discriminated-models module. Leave the model in the standard\n    // pipeline's input so its field-type deps stay reachable, but stash the\n    // name set on ctx so models.ts skips emitting an interface/serializer —\n    // the discriminated module owns those paths instead.\n    const discPlans = planDiscriminatedModels(enriched, nodeCtx);\n    const discriminatedNames = new Set(discPlans.keys());\n    (nodeCtx as { _discriminatedModelNames?: Set<string> })._discriminatedModelNames = discriminatedNames;\n    setDiscriminatedModelNames(discriminatedNames);\n    const standardFiles = generateModelsAndSerializers(enriched, nodeCtx);\n    const discFiles = generateDiscriminatedFiles(discPlans, nodeCtx);\n    return applyLiveSurface([...standardFiles, ...discFiles], nodeCtx, surface);\n  },\n\n  generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n    const nodeCtx = withNodeOperationOverrides(ctx);\n    const surface = getSurface(nodeCtx);\n    const syntheticEnums = getSyntheticEnums();\n    return applyLiveSurface(generateEnumFiles([...enums, ...syntheticEnums], nodeCtx), nodeCtx, surface);\n  },\n\n  generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n    const nodeCtx = withNodeOperationOverrides(ctx);\n    const surface = getSurface(nodeCtx);\n    return applyLiveSurface(generateResources(services, nodeCtx), nodeCtx, surface);\n  },\n\n  generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    const nodeCtx = withNodeOperationOverrides(ctx);\n    const surface = getSurface(nodeCtx);\n    // `nodeCtx.spec` has the synthetic models that `enrichModelsFromSpec`\n    // produced (e.g. inline-object item types like `ConnectApplicationRedirectUri`).\n    // The `spec` param is the engine's pre-enrichment spec, so the barrel\n    // generator would miss those synthetic interfaces. Use the enriched one.\n    return applyLiveSurface(generateClient(nodeCtx.spec, nodeCtx), nodeCtx, surface);\n  },\n\n  // workos-node ships its own exception hierarchy under src/common/exceptions/.\n  // Re-emitting them would either skip (if files exist) or overwrite hand-edits.\n  generateErrors(_ctx: EmitterContext): GeneratedFile[] {\n    return [];\n  },\n\n  generateTypeSignatures(_spec: ApiSpec, _ctx: EmitterContext): GeneratedFile[] {\n    return [];\n  },\n\n  // Test specs and fixtures are hand-maintained except for explicitly-owned\n  // service directories.\n  //\n  // This is also the last `generateXxx` hook in `generateAllFiles`, so it's\n  // where we tack on the carry-forward set — see `carryForwardManagedFiles`.\n  generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    const nodeCtx = withNodeOperationOverrides(ctx);\n    const surface = getSurface(nodeCtx);\n    const testFiles = nodeOptions(nodeCtx).regenerateOwnedTests\n      ? applyLiveSurface(generateTestFiles(spec, nodeCtx), nodeCtx, surface)\n      : [];\n    const result = [...testFiles, ...carryForwardManagedFiles(nodeCtx, surface)];\n\n    // Final whole-run pass: this is the last generate hook, every hook shares\n    // `nodeCtx`, and the engine reads contents only after all hooks return —\n    // so the emitted-files cache now covers the complete run and repairs here\n    // reach files produced by earlier hooks. Greenfield runs are exempt: with\n    // no SDK on disk, \"resolves to an existing file\" has no meaning and the\n    // SDK core (workos.ts, common/) is intentionally not emitted.\n    if (managedPathsFor(nodeCtx, surface).size > 0) {\n      enforceEmittedImportInvariant(getEmittedFiles(nodeCtx).values(), getEmittedPaths(nodeCtx), surface);\n    }\n    return result;\n  },\n\n  // No operations map needed — the manifest belongs to the staging+target flow,\n  // which the literal `--output <SDK>` command does not use.\n  buildOperationsMap(): Record<string, never> {\n    return {};\n  },\n\n  fileHeader(): string {\n    return `// ${AUTOGEN_NOTICE}`;\n  },\n\n  formatCommand(targetDir: string): FormatCommand | null {\n    const hasPrettier = fs.existsSync(path.join(targetDir, '.prettierrc'));\n    const hasEslint =\n      fs.existsSync(path.join(targetDir, 'eslint.config.mjs')) ||\n      fs.existsSync(path.join(targetDir, 'eslint.config.js')) ||\n      fs.existsSync(path.join(targetDir, '.eslintrc.json')) ||\n      fs.existsSync(path.join(targetDir, '.eslintrc.js'));\n\n    if (hasPrettier && hasEslint) {\n      return {\n        cmd: 'bash',\n        args: [\n          '-c',\n          'npx eslint --fix --no-error-on-unmatched-pattern \"$@\" 2>/dev/null; npx prettier --write --log-level silent \"$@\"',\n          '--',\n        ],\n      };\n    }\n    if (hasPrettier) {\n      return {\n        cmd: 'npx',\n        args: ['prettier', '--write', '--log-level', 'silent'],\n      };\n    }\n    if (hasEslint) {\n      return {\n        cmd: 'npx',\n        args: ['eslint', '--fix', '--no-error-on-unmatched-pattern'],\n      };\n    }\n    return null;\n  },\n};\n","import type { Operation, Service, EmitterContext } from '@workos/oagen';\nimport { toPascalCase, toSnakeCase } from '@workos/oagen';\nimport { buildResolvedLookup, lookupMethodName, getMountTarget } from '../shared/resolved-ops.js';\nimport { stripUrnPrefix, applyAcronymFixes } from '../shared/naming-utils.js';\nimport {\n  buildExportedClassNameSet as buildExportedClassNameSetShared,\n  resolveServiceTarget as resolveServiceTargetShared,\n} from '../shared/service-name-collision.js';\n\n/**\n * Python class names that collide with builtins or typing imports.\n * When a model name resolves to one of these, suffix with \"Model\".\n */\nconst PYTHON_RESERVED_CLASS_NAMES = new Set([\n  'List',\n  'Dict',\n  'Set',\n  'Tuple',\n  'Type',\n  'Any',\n  'Optional',\n  'Union',\n  'Literal',\n  'Final',\n  'ClassVar',\n  'Callable',\n]);\n\n/** PascalCase class name with acronym preservation. */\nexport function className(name: string): string {\n  let result = applyAcronymFixes(toPascalCase(stripUrnPrefix(name)));\n  if (PYTHON_RESERVED_CLASS_NAMES.has(result)) {\n    result += 'Model';\n  }\n  return result;\n}\n\n/** snake_case file name (without extension). */\nexport function fileName(name: string): string {\n  return toSnakeCase(stripUrnPrefix(name));\n}\n\n/** snake_case method name. */\nexport function methodName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/** snake_case field name. */\nexport function fieldName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/**\n * snake_case domain field name for a model field, honoring a `domainName`\n * override (set via the `fieldHints` config) so a wire field can surface under\n * a friendlier name. The wire name (still derived from `field.name`) is\n * unaffected, so the API contract is preserved.\n */\nexport function domainFieldName(field: { name: string; domainName?: string }): string {\n  return toSnakeCase(field.domainName ?? field.name);\n}\n\n/**\n * Python builtins that should not be shadowed by parameter names.\n * When a path/query param name collides, suffix with underscore.\n */\nconst PYTHON_BUILTIN_NAMES = new Set([\n  'type',\n  'id',\n  'list',\n  'dict',\n  'set',\n  'map',\n  'filter',\n  'input',\n  'object',\n  'format',\n  'hash',\n  'range',\n  'dir',\n  'max',\n  'min',\n  'next',\n  'open',\n  'print',\n  'len',\n  'str',\n  'int',\n  'float',\n  'bool',\n  'bytes',\n  'tuple',\n  'super',\n]);\n\n/**\n * Safe parameter name for path/query params that avoids shadowing Python builtins.\n * Body field names should continue to use fieldName() to preserve wire-key compatibility.\n */\nexport function safeParamName(name: string): string {\n  const snake = toSnakeCase(name);\n  return PYTHON_BUILTIN_NAMES.has(snake) ? `${snake}_` : snake;\n}\n\n/** snake_case module/directory name. */\nexport function moduleName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/** snake_case property name for service accessors on the client. */\nexport function servicePropertyName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/**\n * Resolve the effective service name, using the overlay-resolved class name\n * when available.\n */\nexport function resolveServiceName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n/**\n * Build a map from IR service name to resolved service name.\n */\nexport function buildServiceNameMap(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of services) {\n    map.set(service.name, resolveServiceName(service, ctx));\n  }\n  return map;\n}\n\n/**\n * Resolve the output directory for a service.\n */\nexport function resolveServiceDir(resolvedServiceName: string): string {\n  return moduleName(resolvedServiceName);\n}\n\n/** Resolve the SDK method name for an operation, using resolved operations first. */\nexport function resolveMethodName(op: Operation, _service: Service, ctx: EmitterContext): string {\n  const lookup = buildResolvedLookup(ctx);\n  const resolved = lookupMethodName(op, lookup);\n  if (resolved) return resolved;\n  // Fallback to overlay, then spec-derived\n  const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const existing = ctx.overlayLookup?.methodByOperation?.get(httpKey);\n  if (existing) return toSnakeCase(existing.methodName);\n  return toSnakeCase(op.name);\n}\n\n/**\n * Build the set of model + enum class names exported by the SDK. Used to\n * detect collisions with operation-client class names — a colliding service\n * gets a `Service` suffix appended.\n */\nexport function buildExportedClassNameSet(ctx: EmitterContext): Set<string> {\n  return buildExportedClassNameSetShared(ctx, className);\n}\n\n/**\n * Resolve a service's mount-target identifier, appending `Service` on\n * collision with an exported model/enum class. Feeds `className`/`fileName`\n * so the class declaration, file, and any qualified references stay aligned.\n *\n * Accessor names (`servicePropertyName`) intentionally use the RAW target —\n * `client.organization_membership` reads better than the suffixed form.\n */\nexport function resolveServiceTarget(target: string, exportedClasses: Set<string>): string {\n  return resolveServiceTargetShared(target, exportedClasses, className);\n}\n\n/** Resolve the SDK class name for a service, using resolved operations' mountOn. */\nexport function resolveClassName(service: Service, ctx: EmitterContext): string {\n  // Use resolved ops mountOn as canonical class name (flat pattern like PHP)\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (r.service.name === service.name) return r.mountOn;\n  }\n  // Fallback to overlay, then IR name\n  if (ctx.overlayLookup?.methodByOperation) {\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const existing = ctx.overlayLookup.methodByOperation.get(httpKey);\n      if (existing) return existing.className;\n    }\n  }\n  return toPascalCase(service.name);\n}\n\n/** Resolve the type name for a model, checking overlay first. */\nexport function resolveTypeName(name: string, ctx: EmitterContext): string {\n  const existing = ctx.overlayLookup?.interfaceByName?.get(name);\n  if (existing) return existing;\n  return toPascalCase(stripUrnPrefix(name));\n}\n\n/**\n * Build a map from IR service name to mount-target directory name.\n * Every service maps to its mount target's snake_case directory.\n * Replaces the old buildServiceDirMap(grouping) which required namespace grouping.\n */\nexport function buildMountDirMap(ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of ctx.spec.services) {\n    const target = getMountTarget(service, ctx);\n    map.set(service.name, moduleName(target));\n  }\n  return map;\n}\n\n/** Convert a filesystem directory path (with /) to a Python dotted module path. */\nexport function dirToModule(dir: string): string {\n  return dir.replace(/\\//g, '.');\n}\n\n/**\n * Compute the relative import prefix (dots) to reach the namespace root from a given dir depth.\n * With the flat mount-based layout, dirs are always single-level so this returns \"..\" (2 dots).\n */\nexport function relativeImportPrefix(dirName: string): string {\n  const depth = dirName.split('/').length;\n  return '.'.repeat(depth + 1);\n}\n","import type { TypeRef, PrimitiveType, UnionType } from '@workos/oagen';\nimport { mapTypeRef as irMapTypeRef } from '@workos/oagen';\nimport { className } from './naming.js';\n\n/**\n * Map an IR TypeRef to a Python type hint string.\n * Uses standard library types: str, int, float, bool, List, Dict, Optional, Union.\n */\nexport function mapTypeRef(ref: TypeRef): string {\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (ref, items) => {\n      void ref;\n      return `List[${items}]`;\n    },\n    model: (r) => `\"${className(r.name)}\"`,\n    enum: (r) => `\"${className(r.name)}\"`,\n    union: (r, variants) => joinUnionVariants(r, variants),\n    nullable: (ref, inner) => {\n      void ref;\n      return `Optional[${inner}]`;\n    },\n    literal: (r) =>\n      typeof r.value === 'string'\n        ? `Literal[\"${r.value}\"]`\n        : r.value === null\n          ? 'None'\n          : `Literal[${toPythonLiteral(r.value)}]`,\n    map: (ref, value) => {\n      void ref;\n      return `Dict[str, ${value}]`;\n    },\n  });\n}\n\n/**\n * Map an IR TypeRef to a plain Python type string (no quotes around model/enum refs).\n * Used for import collection and direct type references.\n */\nexport function mapTypeRefUnquoted(ref: TypeRef, knownEnums?: Set<string>, allowRawEnumStrings = false): string {\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (ref, items) => {\n      void ref;\n      return `List[${items}]`;\n    },\n    model: (r) => className(r.name),\n    enum: (r) => {\n      if (knownEnums && !knownEnums.has(r.name)) return 'str';\n      const enumType = className(r.name);\n      return allowRawEnumStrings ? `Union[${enumType}, str]` : enumType;\n    },\n    union: (r, variants) => joinUnionVariants(r, variants),\n    nullable: (ref, inner) => {\n      void ref;\n      return `Optional[${inner}]`;\n    },\n    literal: (r) =>\n      typeof r.value === 'string'\n        ? `Literal[\"${r.value}\"]`\n        : r.value === null\n          ? 'None'\n          : `Literal[${toPythonLiteral(r.value)}]`,\n    map: (ref, value) => {\n      void ref;\n      return `Dict[str, ${value}]`;\n    },\n  });\n}\n\n/** Convert a JS value to a Python literal string (capitalizes booleans). */\nfunction toPythonLiteral(value: unknown): string {\n  if (typeof value === 'boolean') return value ? 'True' : 'False';\n  return String(value);\n}\n\nfunction mapPrimitive(ref: PrimitiveType): string {\n  if (ref.format) {\n    switch (ref.format) {\n      case 'binary':\n        return 'bytes';\n    }\n  }\n  switch (ref.type) {\n    case 'string':\n      return 'str';\n    case 'integer':\n      return 'int';\n    case 'number':\n      return 'float';\n    case 'boolean':\n      return 'bool';\n    case 'unknown':\n      return 'Any';\n  }\n}\n\nfunction joinUnionVariants(ref: UnionType, variants: string[]): string {\n  if (ref.compositionKind === 'allOf') {\n    // Python doesn't have intersection types; use the first variant\n    return variants[0] ?? 'Any';\n  }\n  // Deduplicate identical variants (e.g., Union[Foo, Foo] -> Foo)\n  const unique = [...new Set(variants)];\n  if (unique.length === 1) return unique[0];\n  return `Union[${unique.join(', ')}]`;\n}\n","import type { ApiSpec, EmitterContext, Enum, Model, Service } from '@workos/oagen';\nimport { assignModelsToServices, collectFieldDependencies, planOperation, walkTypeRef } from '@workos/oagen';\nimport { fileName } from './naming.js';\nimport { detectDiscriminators } from '../shared/model-utils.js';\n\n/**\n * Walk every operation across all services and tally, per schema, the set of\n * services that transitively reference it. Schemas referenced by more than one\n * service are \"shared\" — they should be emitted under common/ rather than\n * the first alphabetical service that happens to use them.\n *\n * Transitive walk for models follows model->model field references AND\n * discriminator variant mappings to a fixed point; enums are leaves.\n */\nexport function findSharedSchemas(spec: ApiSpec): { models: Set<string>; enums: Set<string> } {\n  const modelsByName = new Map(spec.models.map((m) => [m.name, m]));\n  const modelToServices = new Map<string, Set<string>>();\n  const enumToServices = new Map<string, Set<string>>();\n\n  const note = (map: Map<string, Set<string>>, name: string, service: string): void => {\n    let bucket = map.get(name);\n    if (!bucket) {\n      bucket = new Set();\n      map.set(name, bucket);\n    }\n    bucket.add(service);\n  };\n\n  for (const service of spec.services) {\n    const directModels = new Set<string>();\n    const directEnums = new Set<string>();\n    const collect = (ref: unknown): void => {\n      walkTypeRef(ref as never, {\n        model: (r) => directModels.add(r.name),\n        enum: (r) => directEnums.add(r.name),\n      });\n    };\n\n    for (const op of service.operations) {\n      if (op.requestBody) collect(op.requestBody);\n      collect(op.response);\n      for (const p of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n        collect(p.type);\n      }\n      if (op.pagination) collect(op.pagination.itemType);\n      for (const err of op.errors) {\n        if (err.type) collect(err.type);\n      }\n      for (const sr of op.successResponses ?? []) {\n        collect(sr.type);\n      }\n    }\n\n    // Transitively expand model references via field types AND discriminator\n    // variant mappings (dispatchers route to variants without listing them as\n    // fields, so plain field-walking misses them).\n    const queue = [...directModels];\n    while (queue.length > 0) {\n      const name = queue.pop()!;\n      const model = modelsByName.get(name);\n      if (!model) continue;\n      for (const field of model.fields) {\n        walkTypeRef(field.type as never, {\n          model: (r) => {\n            if (!directModels.has(r.name)) {\n              directModels.add(r.name);\n              queue.push(r.name);\n            }\n          },\n          enum: (r) => directEnums.add(r.name),\n        });\n      }\n      const disc = (model as { discriminator?: { property: string; mapping: Record<string, string> } }).discriminator;\n      if (disc?.mapping) {\n        for (const variantName of Object.values(disc.mapping)) {\n          if (!directModels.has(variantName)) {\n            directModels.add(variantName);\n            queue.push(variantName);\n          }\n        }\n      }\n    }\n\n    for (const name of directModels) note(modelToServices, name, service.name);\n    for (const name of directEnums) note(enumToServices, name, service.name);\n  }\n\n  const sharedModels = new Set<string>();\n  for (const [name, services] of modelToServices) {\n    if (services.size >= 2) sharedModels.add(name);\n  }\n  const sharedEnums = new Set<string>();\n  for (const [name, services] of enumToServices) {\n    if (services.size >= 2) sharedEnums.add(name);\n  }\n\n  return { models: sharedModels, enums: sharedEnums };\n}\n\n/**\n * Final placement decisions for every model and enum in the spec. Computed\n * once and consumed by every Python emitter pass (models, enums, resources,\n * tests) so they all agree on which symbols live in `common/` and which live\n * in a service directory.\n */\nexport interface SchemaPlacement {\n  /** Model -> service. Models in common/ are absent. */\n  modelToService: Map<string, string>;\n  /** Enum -> service. Enums in common/ are absent. */\n  enumToService: Map<string, string>;\n  /** Pre-relocation model -> service. Used to attach BC re-exports to the natural service barrel. */\n  originalModelToService: Map<string, string>;\n  /** Pre-relocation enum -> service. */\n  originalEnumToService: Map<string, string>;\n  /** Models relocated to common/ (the union of initial sharing + closure expansion). */\n  relocatedModels: Set<string>;\n  /** Enums relocated to common/. */\n  relocatedEnums: Set<string>;\n  /** Model alias name -> canonical model name (Python-only structural dedup). */\n  modelAliases: Map<string, string>;\n  /** Enum alias name -> canonical enum name. */\n  enumAliases: Map<string, string>;\n}\n\nexport function computeSchemaPlacement(spec: ApiSpec, ctx: EmitterContext): SchemaPlacement {\n  // Annotate models with implicit discriminators so the closure can follow\n  // dispatcher → variant edges. detectDiscriminators is idempotent.\n  const annotatedModels = detectDiscriminators(spec.models);\n  if (annotatedModels !== spec.models) {\n    spec = { ...spec, models: annotatedModels };\n  }\n  const modelsByName = new Map(spec.models.map((m) => [m.name, m]));\n  const hintedModels = new Set(Object.keys(ctx.modelHints ?? {}));\n\n  const originalModelToService = assignModelsToServices(spec.models, spec.services, ctx.modelHints);\n  const originalEnumToService = assignEnumsToServicesNatural(spec.enums, spec.services);\n\n  // Precompute Python-specific structural alias maps so the closure can\n  // promote a canonical when its alias is shared.\n  const modelAliases = computeModelAliases(spec);\n  const enumAliases = computeEnumAliases(spec.enums);\n\n  const initial = findSharedSchemas(spec);\n\n  // Ensure aliases imply their canonical: if the alias is shared, the canonical\n  // must follow it into common/, otherwise the alias file would import from a\n  // service directory.\n  for (const [aliasName, canonicalName] of modelAliases) {\n    if (initial.models.has(aliasName)) initial.models.add(canonicalName);\n  }\n  for (const [aliasName, canonicalName] of enumAliases) {\n    if (initial.enums.has(aliasName)) initial.enums.add(canonicalName);\n  }\n\n  // Initial common/-bound set: everything findSharedSchemas flagged (minus\n  // hinted models — direct shares respect explicit pins) plus everything that\n  // is unassigned from the natural placement and not pinned.\n  const sharedModels = new Set<string>();\n  for (const name of initial.models) {\n    if (!hintedModels.has(name)) sharedModels.add(name);\n  }\n  for (const model of spec.models) {\n    if (!originalModelToService.has(model.name) && !hintedModels.has(model.name)) {\n      sharedModels.add(model.name);\n    }\n  }\n  const sharedEnums = new Set(initial.enums);\n  for (const enumDef of spec.enums) {\n    if (!originalEnumToService.has(enumDef.name)) sharedEnums.add(enumDef.name);\n  }\n\n  // Closure: any model/enum referenced by a model that ends up in common/\n  // must also be in common/, otherwise the emitted common/ file would reach\n  // back into a service package and create a circular-import hazard. Hints\n  // are *not* a stop signal here — the closure is structural. If a hinted\n  // model is reachable from common/, leaving it pinned to a service would\n  // re-introduce the back-edge. BC for the pinned import path is preserved\n  // via re-exports from the natural service barrel.\n  let changed = true;\n  while (changed) {\n    changed = false;\n    for (const name of sharedModels) {\n      const model = modelsByName.get(name);\n      if (!model) continue;\n      const deps = collectEmittedDependencies(model, modelAliases);\n      for (const dep of deps.models) {\n        if (sharedModels.has(dep)) continue;\n        if (!modelsByName.has(dep)) continue;\n        sharedModels.add(dep);\n        changed = true;\n      }\n      for (const dep of deps.enums) {\n        if (sharedEnums.has(dep)) continue;\n        sharedEnums.add(dep);\n        changed = true;\n      }\n    }\n  }\n\n  // Build final assignment maps by relocating shared symbols to common/\n  // (i.e. removing them from the per-service assignment).\n  const modelToService = new Map(originalModelToService);\n  for (const name of sharedModels) {\n    modelToService.delete(name);\n  }\n  const enumToService = new Map(originalEnumToService);\n  for (const name of sharedEnums) {\n    enumToService.delete(name);\n  }\n\n  // relocatedModels = models with a natural service that ended up in common/.\n  // Models without a natural service were never in a service barrel, so they\n  // don't need a BC re-export. Hinted models DO get re-exported from the\n  // hinted service so existing imports keep resolving.\n  const relocatedModels = new Set<string>();\n  for (const name of sharedModels) {\n    if (!originalModelToService.has(name)) continue;\n    relocatedModels.add(name);\n  }\n  const relocatedEnums = new Set<string>();\n  for (const name of sharedEnums) {\n    if (!originalEnumToService.has(name)) continue;\n    relocatedEnums.add(name);\n  }\n\n  return {\n    modelToService,\n    enumToService,\n    originalModelToService,\n    originalEnumToService,\n    relocatedModels,\n    relocatedEnums,\n    modelAliases,\n    enumAliases,\n  };\n}\n\n/**\n * Dependencies the emitter will materialize for a model's generated file.\n * Captures alias canonicals, discriminator variants, and field-level model+enum\n * references so the placement closure can decide whether the dependency must\n * also live in `common/`.\n */\nfunction collectEmittedDependencies(\n  model: Model,\n  modelAliases: Map<string, string>,\n): { models: Set<string>; enums: Set<string> } {\n  const models = new Set<string>();\n  const enums = new Set<string>();\n\n  const canonical = modelAliases.get(model.name);\n  if (canonical) {\n    models.add(canonical);\n    return { models, enums };\n  }\n\n  const disc = (model as { discriminator?: { property: string; mapping: Record<string, string> } }).discriminator;\n  if (disc?.mapping) {\n    for (const variant of Object.values(disc.mapping)) models.add(variant);\n  }\n\n  const fieldDeps = collectFieldDependencies(model);\n  for (const m of fieldDeps.models) models.add(m);\n  for (const e of fieldDeps.enums) enums.add(e);\n\n  return { models, enums };\n}\n\ninterface ModelUsage {\n  requestOnly: Set<string>;\n  response: Set<string>;\n  mixed: Set<string>;\n}\n\nfunction collectModelUsage(spec: ApiSpec): ModelUsage {\n  const request = new Set<string>();\n  const response = new Set<string>();\n\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      const plan = planOperation(op);\n      if (plan.responseModelName) response.add(plan.responseModelName);\n      if (op.pagination?.itemType.kind === 'model') response.add(op.pagination.itemType.name);\n      if (op.requestBody?.kind === 'model') request.add(op.requestBody.name);\n      if (op.requestBody?.kind === 'union') {\n        for (const variant of op.requestBody.variants ?? []) {\n          if (variant.kind === 'model') request.add(variant.name);\n        }\n      }\n    }\n  }\n\n  const mixed = new Set<string>();\n  for (const name of request) if (response.has(name)) mixed.add(name);\n  const requestOnly = new Set([...request].filter((name) => !mixed.has(name)));\n  const responseOnly = new Set([...response].filter((name) => !mixed.has(name)));\n\n  return { requestOnly, response: responseOnly, mixed };\n}\n\nfunction compareAliasPriority(left: string, right: string, usage: ModelUsage): number {\n  const score = (name: string): number => {\n    if (usage.response.has(name)) return 0;\n    if (usage.mixed.has(name)) return 1;\n    if (usage.requestOnly.has(name)) return 2;\n    return 3;\n  };\n\n  const diff = score(left) - score(right);\n  if (diff !== 0) return diff;\n  return left.localeCompare(right);\n}\n\nfunction canAliasModels(canonical: string, alias: string, usage: ModelUsage): boolean {\n  // Aliases that snake_case-collide with their canonical would self-import.\n  if (fileName(canonical) === fileName(alias)) return false;\n  // Don't alias across the request/response boundary — they may evolve apart.\n  if (\n    (usage.response.has(canonical) && usage.requestOnly.has(alias)) ||\n    (usage.response.has(alias) && usage.requestOnly.has(canonical))\n  ) {\n    return false;\n  }\n  return true;\n}\n\n/**\n * Compute the Python emitter's structural model dedup map: alias -> canonical.\n * Mirrors the logic in models.ts so the placement closure can promote\n * canonicals when their aliases are shared.\n */\nexport function computeModelAliases(spec: ApiSpec): Map<string, string> {\n  const recursiveHashes = buildRecursiveHashMap(spec.models, spec.enums);\n  const usage = collectModelUsage(spec);\n\n  const hashGroups = new Map<string, string[]>();\n  for (const model of spec.models) {\n    if (model.fields.length === 0 && !(model as { discriminator?: unknown }).discriminator) {\n      // skipped by emit anyway when listmeta/wrapper, but we rely on emit-side filter.\n    }\n    const hash = recursiveHashes.get(model.name) ?? '';\n    if (!hashGroups.has(hash)) hashGroups.set(hash, []);\n    hashGroups.get(hash)!.push(model.name);\n  }\n\n  const aliasOf = new Map<string, string>();\n  for (const [, names] of hashGroups) {\n    if (names.length <= 1) continue;\n    const sorted = [...names].sort((a, b) => compareAliasPriority(a, b, usage));\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      if (canAliasModels(canonical, sorted[i], usage)) {\n        aliasOf.set(sorted[i], canonical);\n      }\n    }\n  }\n  return aliasOf;\n}\n\n/**\n * Compute the Python emitter's structural enum dedup map: alias -> canonical.\n * Mirrors the logic in enums.ts.\n */\nexport function computeEnumAliases(enums: Enum[]): Map<string, string> {\n  const hashGroups = new Map<string, string[]>();\n  for (const enumDef of enums) {\n    const hash = [...enumDef.values]\n      .map((v) => String(v.value))\n      .sort()\n      .join('|');\n    if (!hashGroups.has(hash)) hashGroups.set(hash, []);\n    hashGroups.get(hash)!.push(enumDef.name);\n  }\n\n  const aliasOf = new Map<string, string>();\n  for (const [, names] of hashGroups) {\n    if (names.length <= 1) continue;\n    const sorted = [...names].sort();\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      aliasOf.set(sorted[i], canonical);\n    }\n  }\n  return aliasOf;\n}\n\n/**\n * Recursive structural hashing for models so dedup runs against deeply-equal\n * shapes, not just same-named ones. Cycles fall back to the model name.\n */\nfunction buildRecursiveHashMap(models: Model[], enums: Enum[]): Map<string, string> {\n  const modelByName = new Map(models.map((m) => [m.name, m]));\n  const hashCache = new Map<string, string>();\n  const visiting = new Set<string>();\n\n  const enumVH = new Map<string, string>();\n  for (const e of enums) {\n    enumVH.set(\n      e.name,\n      [...e.values]\n        .map((v) => String(v.value))\n        .sort()\n        .join('|'),\n    );\n  }\n\n  function modelHash(name: string): string {\n    const cached = hashCache.get(name);\n    if (cached != null) return cached;\n    if (visiting.has(name)) return `m:${name}`;\n    visiting.add(name);\n\n    const model = modelByName.get(name);\n    if (!model) {\n      visiting.delete(name);\n      return `m:${name}`;\n    }\n\n    const hash = [...model.fields]\n      .sort((a, b) => a.name.localeCompare(b.name))\n      .map((f) => `${f.name}:${deepTypeHash(f.type)}:${f.required}`)\n      .join('|');\n\n    visiting.delete(name);\n    hashCache.set(name, hash);\n    return hash;\n  }\n\n  function deepTypeHash(ref: any): string {\n    switch (ref.kind) {\n      case 'primitive':\n        return `p:${ref.type}${ref.format ? `:${ref.format}` : ''}`;\n      case 'model':\n        return `m:{${modelHash(ref.name)}}`;\n      case 'enum': {\n        const vh = enumVH.get(ref.name);\n        return vh != null ? `e:{${vh}}` : `e:${ref.name}`;\n      }\n      case 'array':\n        return `a:${deepTypeHash(ref.items)}`;\n      case 'nullable':\n        return `n:${deepTypeHash(ref.inner)}`;\n      case 'union':\n        return `u:${(ref.variants ?? [])\n          .map((v: any) => deepTypeHash(v))\n          .sort()\n          .join(',')}`;\n      case 'map':\n        return `d:${deepTypeHash(ref.valueType)}`;\n      case 'literal':\n        return `l:${String(ref.value)}`;\n      default:\n        return 'unknown';\n    }\n  }\n\n  for (const model of models) modelHash(model.name);\n  return hashCache;\n}\n\n/**\n * Natural enum-to-service assignment without sharing logic — the first service\n * (alphabetically by spec order) to reference an enum wins.\n */\nfunction assignEnumsToServicesNatural(enums: Enum[], services: Service[]): Map<string, string> {\n  const enumNames = new Set(enums.map((e) => e.name));\n  const enumToService = new Map<string, string>();\n\n  for (const service of services) {\n    const refs = new Set<string>();\n    const collect = (ref: any): void => {\n      walkTypeRef(ref, { enum: (r: any) => refs.add(r.name) });\n    };\n    for (const op of service.operations) {\n      if (op.requestBody) collect(op.requestBody);\n      collect(op.response);\n      for (const p of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n        collect(p.type);\n      }\n    }\n    for (const name of refs) {\n      if (!enumNames.has(name)) continue;\n      if (!enumToService.has(name)) enumToService.set(name, service.name);\n    }\n  }\n\n  return enumToService;\n}\n","import type { Enum, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { toUpperSnakeCase } from '@workos/oagen';\nimport { className, fileName, buildMountDirMap, dirToModule } from './naming.js';\nimport { computeSchemaPlacement } from './shared-schemas.js';\nimport { isEnumInScope } from '../shared/resolved-ops.js';\n\n/**\n * Convert a PascalCase class name to a human-readable lowercase string,\n * preserving known acronyms instead of splitting them character-by-character.\n */\nfunction humanizeClassName(name: string): string {\n  // Insert spaces before uppercase runs, but keep acronyms together\n  let result = name.replace(/([a-z])([A-Z])/g, '$1 $2');\n  // Split consecutive uppercase letters from following lowercase: \"SSOProvider\" -> \"SSO Provider\"\n  result = result.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');\n  return result.toLowerCase();\n}\n\n/**\n * Generate Python enum class files from IR Enum definitions.\n * Uses `(str, Enum)` for type-safe enum values (Python 3.10+).\n */\nexport function generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n  if (enums.length === 0) return [];\n\n  // Tests sometimes pass enums that aren't in ctx.spec.enums, so synthesize a\n  // spec view with the passed-in enums to keep the placement logic accurate.\n  const placementSpec = enums === ctx.spec.enums ? ctx.spec : { ...ctx.spec, enums };\n  const placement = computeSchemaPlacement(placementSpec, ctx);\n  const enumToService = placement.enumToService;\n  const mountDirMap = buildMountDirMap(ctx);\n  const resolveDir = (irService: string | undefined) =>\n    irService ? (mountDirMap.get(irService) ?? 'common') : 'common';\n  const files: GeneratedFile[] = [];\n  const compatAliases = collectCompatEnumAliases(enums, ctx);\n\n  const aliasOf = placement.enumAliases;\n\n  for (const enumDef of enums) {\n    const service = enumToService.get(enumDef.name);\n    const dirName = resolveDir(service);\n    // FR-1.4: write per-enum FILES only when in scope; the enum barrel is built\n    // separately (collectGeneratedEnumSymbolsByDir over the full set), so an\n    // out-of-scope enum left on disk stays exported and importable.\n    const enumInScope = isEnumInScope(enumDef.name, ctx);\n\n    // If this enum is an alias for a canonical enum, generate a type alias file\n    const canonicalName = aliasOf.get(enumDef.name);\n    if (canonicalName) {\n      // Skip when alias and canonical produce the same file name (self-import)\n      if (fileName(enumDef.name) === fileName(canonicalName)) continue;\n      const canonicalService = enumToService.get(canonicalName);\n      const canonicalDir = resolveDir(canonicalService);\n      const canonicalCls = className(canonicalName);\n      const aliasCls = className(enumDef.name);\n      const lines: string[] = [];\n      // Use explicit __all__ to prevent ruff F401 from stripping the re-export\n      // Always use direct file import to avoid barrel dependency on the canonical\n      if (canonicalDir === dirName) {\n        lines.push('from typing import TypeAlias');\n        lines.push(`from .${fileName(canonicalName)} import ${canonicalCls}`);\n        lines.push('');\n        lines.push(`${aliasCls}: TypeAlias = ${canonicalCls}`);\n      } else {\n        // Cross-service enum aliases use TYPE_CHECKING + __getattr__ to avoid\n        // circular imports caused by service __init__.py eagerly re-exporting\n        // all models (e.g. common → radar → common cycle).\n        const modPath = `${ctx.namespace}.${dirToModule(canonicalDir)}.models.${fileName(canonicalName)}`;\n        lines.push('from typing import TYPE_CHECKING');\n        lines.push('');\n        lines.push('if TYPE_CHECKING:');\n        lines.push(`    from ${modPath} import ${canonicalCls} as ${aliasCls}`);\n        lines.push('else:');\n        lines.push('    def __getattr__(name: str):');\n        lines.push(`        if name == \"${aliasCls}\":`);\n        lines.push(`            from ${modPath} import ${canonicalCls}`);\n        lines.push(`            return ${canonicalCls}`);\n        lines.push('        raise AttributeError(f\"module {__name__!r} has no attribute {name!r}\")');\n      }\n      lines.push(`__all__ = [\"${aliasCls}\"]`);\n      if (enumInScope) {\n        files.push({\n          path: `src/${ctx.namespace}/${dirName}/models/${fileName(enumDef.name)}.py`,\n          content: lines.join('\\n'),\n          integrateTarget: true,\n          overwriteExisting: true,\n        });\n      }\n\n      // Also generate compat alias files for dedup aliases (they may have compat aliases too)\n      for (const aliasName of compatAliases.get(enumDef.name) ?? []) {\n        let compatContent: string;\n        if (canonicalDir === dirName) {\n          compatContent = [\n            'from typing import TypeAlias',\n            `from .${fileName(canonicalName)} import ${canonicalCls}`,\n            '',\n            `${aliasName}: TypeAlias = ${canonicalCls}`,\n            `__all__ = [\"${aliasName}\"]`,\n          ].join('\\n');\n        } else {\n          const modPath = `${ctx.namespace}.${dirToModule(canonicalDir)}.models.${fileName(canonicalName)}`;\n          compatContent = [\n            'from typing import TYPE_CHECKING',\n            '',\n            'if TYPE_CHECKING:',\n            `    from ${modPath} import ${canonicalCls} as ${aliasName}`,\n            'else:',\n            '    def __getattr__(name: str):',\n            `        if name == \"${aliasName}\":`,\n            `            from ${modPath} import ${canonicalCls}`,\n            `            return ${canonicalCls}`,\n            '        raise AttributeError(f\"module {__name__!r} has no attribute {name!r}\")',\n            `__all__ = [\"${aliasName}\"]`,\n          ].join('\\n');\n        }\n        if (enumInScope) {\n          files.push({\n            path: `src/${ctx.namespace}/${dirName}/models/${fileName(aliasName)}.py`,\n            content: compatContent,\n            integrateTarget: true,\n            overwriteExisting: true,\n          });\n        }\n      }\n\n      continue;\n    }\n\n    const cls = className(enumDef.name);\n    const lines: string[] = [];\n\n    const readable = humanizeClassName(enumDef.name);\n    lines.push(`\"\"\"Enumeration of ${readable} values.\"\"\"`);\n    lines.push('');\n    lines.push('from __future__ import annotations');\n    lines.push('');\n\n    if (enumDef.values.length === 0) {\n      lines.push('from typing import Union');\n      lines.push('from typing import TypeAlias');\n      lines.push('');\n      lines.push(`${cls}: TypeAlias = str`);\n    } else {\n      // Deduplicate values that produce the same string\n      const seenValues = new Set<string>();\n      const uniqueValues: typeof enumDef.values = [];\n      for (const value of enumDef.values) {\n        const valueStr = String(value.value);\n        if (!seenValues.has(valueStr)) {\n          seenValues.add(valueStr);\n          uniqueValues.push({ ...value, value: valueStr });\n        }\n      }\n\n      // Determine if all values are strings or all integers\n      const allStrings = uniqueValues.every((v) => typeof v.value === 'string');\n      const allIntegers = uniqueValues.every((v) => typeof v.value === 'number' && Number.isInteger(v.value));\n\n      if (allStrings) {\n        lines.push('from enum import Enum');\n        lines.push('from typing import Optional');\n        lines.push('from typing import Literal, TypeAlias');\n        lines.push('');\n        lines.push('');\n        lines.push(`class ${cls}(str, Enum):`);\n        lines.push(`    \"\"\"Known values for ${cls}.\"\"\"`);\n        lines.push('');\n      } else if (allIntegers) {\n        lines.push('from enum import IntEnum');\n        lines.push('from typing import Literal, TypeAlias');\n        lines.push('');\n        lines.push('');\n        lines.push(`class ${cls}(IntEnum):`);\n        lines.push(`    \"\"\"Known values for ${cls}.\"\"\"`);\n        lines.push('');\n      } else {\n        // Mixed types — fall back to Union[Literal[...], str]\n        lines.push('from typing import Union');\n        lines.push('from typing import Literal, TypeAlias');\n        lines.push('');\n        const literals = uniqueValues.map((v) =>\n          typeof v.value === 'string'\n            ? `\"${v.value}\"`\n            : typeof v.value === 'boolean'\n              ? v.value\n                ? 'True'\n                : 'False'\n              : String(v.value),\n        );\n        lines.push(`${cls}: TypeAlias = Union[Literal[${literals.join(', ')}], str]`);\n        files.push({\n          path: `src/${ctx.namespace}/${dirName}/models/${fileName(enumDef.name)}.py`,\n          content: lines.join('\\n'),\n          integrateTarget: true,\n          overwriteExisting: true,\n        });\n        continue;\n      }\n\n      const usedNames = new Set<string>();\n      for (const v of uniqueValues) {\n        let memberName = toUpperSnakeCase(String(v.value));\n        if (usedNames.has(memberName)) {\n          let suffix = 2;\n          while (usedNames.has(`${memberName}_${suffix}`)) suffix++;\n          memberName = `${memberName}_${suffix}`;\n        }\n        usedNames.add(memberName);\n        const valueStr =\n          typeof v.value === 'string'\n            ? `\"${v.value}\"`\n            : typeof v.value === 'boolean'\n              ? v.value\n                ? 'True'\n                : 'False'\n              : String(v.value);\n        lines.push(`    ${memberName} = ${valueStr}`);\n        if (v.description || v.deprecated) {\n          const parts: string[] = [];\n          if (v.description) parts.push(v.description);\n          if (v.deprecated) parts.push('.. deprecated::');\n          lines.push(`    \"\"\"${parts.join('\\n\\n    ')}\"\"\"`);\n        }\n      }\n      if (allStrings) {\n        lines.push('');\n        lines.push('    @classmethod');\n        lines.push(`    def _missing_(cls, value: object) -> Optional[\"${cls}\"]:`);\n        lines.push('        if not isinstance(value, str):');\n        lines.push('            return None');\n        lines.push('        unknown = str.__new__(cls, value)');\n        lines.push('        unknown._name_ = value.upper()');\n        lines.push('        unknown._value_ = value');\n        lines.push('        return unknown');\n      }\n      lines.push('');\n      lines.push(\n        `${cls}Literal: TypeAlias = Literal[${uniqueValues\n          .map((v) =>\n            typeof v.value === 'string'\n              ? `\"${v.value}\"`\n              : typeof v.value === 'boolean'\n                ? v.value\n                  ? 'True'\n                  : 'False'\n                : String(v.value),\n          )\n          .join(', ')}]`,\n      );\n    }\n\n    if (enumInScope) {\n      files.push({\n        path: `src/${ctx.namespace}/${dirName}/models/${fileName(enumDef.name)}.py`,\n        content: lines.join('\\n'),\n        integrateTarget: true,\n        overwriteExisting: true,\n      });\n\n      for (const aliasName of compatAliases.get(enumDef.name) ?? []) {\n        files.push({\n          path: `src/${ctx.namespace}/${dirName}/models/${fileName(aliasName)}.py`,\n          content: [\n            'from typing import TypeAlias',\n            `from .${fileName(enumDef.name)} import ${cls}`,\n            '',\n            `${aliasName}: TypeAlias = ${cls}`,\n            `__all__ = [\"${aliasName}\"]`,\n          ].join('\\n'),\n          integrateTarget: true,\n          overwriteExisting: true,\n        });\n      }\n    }\n  }\n\n  return files;\n}\n\nexport function collectCompatEnumAliases(enums: Enum[], ctx: EmitterContext): Map<string, string[]> {\n  const aliases = new Map<string, string[]>();\n  const irEnumNames = new Set(enums.map((enumDef) => enumDef.name));\n  const normalizedHashToEnum = new Map<string, string>();\n\n  for (const enumDef of enums) {\n    normalizedHashToEnum.set(enumValueHash(enumDef), enumDef.name);\n  }\n\n  for (const baselineEnum of Object.values(ctx.apiSurface?.enums ?? {})) {\n    if (irEnumNames.has(baselineEnum.name)) continue;\n    const hash = Object.values(baselineEnum.members)\n      .map((value) => String(value))\n      .sort()\n      .join('|');\n    const target = normalizedHashToEnum.get(hash);\n    if (!target) continue;\n    if (!aliases.has(target)) aliases.set(target, []);\n    aliases.get(target)!.push(baselineEnum.name);\n  }\n\n  return aliases;\n}\n\nexport function collectGeneratedEnumSymbolsByDir(enums: Enum[], ctx: EmitterContext): Map<string, string[]> {\n  const placementSpec = enums === ctx.spec.enums ? ctx.spec : { ...ctx.spec, enums };\n  const enumToService = computeSchemaPlacement(placementSpec, ctx).enumToService;\n  const mountDirMap = buildMountDirMap(ctx);\n  const resolveDir = (irService: string | undefined) =>\n    irService ? (mountDirMap.get(irService) ?? 'common') : 'common';\n  const compatAliases = collectCompatEnumAliases(enums, ctx);\n  const symbolsByDir = new Map<string, string[]>();\n\n  for (const enumDef of enums) {\n    const service = enumToService.get(enumDef.name);\n    const dirName = resolveDir(service);\n    if (!symbolsByDir.has(dirName)) symbolsByDir.set(dirName, []);\n    symbolsByDir.get(dirName)!.push(enumDef.name);\n    for (const aliasName of compatAliases.get(enumDef.name) ?? []) {\n      symbolsByDir.get(dirName)!.push(aliasName);\n    }\n  }\n\n  return symbolsByDir;\n}\n\nfunction enumValueHash(enumDef: Enum): string {\n  return [...enumDef.values]\n    .map((value) => String(value.value))\n    .sort()\n    .join('|');\n}\n","import type { Model, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { collectFieldDependencies, walkTypeRef } from '@workos/oagen';\nimport { mapTypeRef } from './type-map.js';\nimport { className, domainFieldName, fileName, buildMountDirMap, dirToModule } from './naming.js';\nimport { collectGeneratedEnumSymbolsByDir, collectCompatEnumAliases } from './enums.js';\nimport { computeSchemaPlacement } from './shared-schemas.js';\nimport {\n  isModelInScope,\n  isEnumInScope,\n  fileExistsAfterRun,\n  priorManifestBasenames,\n  isMountInScope,\n  getMountTarget,\n} from '../shared/resolved-ops.js';\n\n/**\n * Generate Python dataclass model files from IR Model definitions.\n * Each model becomes a single .py file with a dataclass, from_dict, and to_dict.\n */\nexport function generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n  if (models.length === 0) return [];\n\n  // Tests sometimes pass models that aren't in ctx.spec.models, so synthesize\n  // a spec view with the passed-in models to keep the placement logic accurate.\n  const placementSpec = models === ctx.spec.models ? ctx.spec : { ...ctx.spec, models };\n  const placement = computeSchemaPlacement(placementSpec, ctx);\n  const {\n    modelToService,\n    enumToService,\n    originalModelToService,\n    originalEnumToService,\n    relocatedModels,\n    relocatedEnums,\n    modelAliases: aliasOf,\n  } = placement;\n  const mountDirMap = buildMountDirMap(ctx);\n  const resolveDir = (irService: string | undefined) =>\n    irService ? (mountDirMap.get(irService) ?? 'common') : 'common';\n  const files: GeneratedFile[] = [];\n  const emittedModelSymbolsByDir = new Map<string, string[]>();\n  // Overrides fileName() for symbols that live in a differently-named file.\n  // Used for variant type aliases (e.g. EventSchemaVariant → event_schema).\n  const symbolToFile = new Map<string, string>();\n  // Track each emitted symbol's natural (pre-relocation) service so we can\n  // re-export relocated symbols from their original service barrel for BC.\n  const symbolToOriginalService = new Map<string, string>();\n\n  // Track emitted file paths to prevent duplicates when synthetic models from\n  // oneOf enrichment collide with existing IR models in snake_case.\n  const emittedFilePaths = new Set<string>();\n\n  // Wrappers referenced as a non-paginated operation response (e.g.\n  // `VersionListResponse` for `GET /vault/v1/kv/{id}/versions`) must still be\n  // emitted — the resource code references them by name and SyncPage doesn't\n  // wrap them.\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(ctx.spec.services);\n  // ListMetadata-shape models referenced by a surviving non-paginated wrapper\n  // (e.g. vault's `VersionListResponse`) must still emit a dataclass —\n  // otherwise the wrapper's module imports a class that was never written.\n  const listMetadataNeeded = collectReferencedListMetadataModels(models, nonPaginatedRefs);\n\n  // Discriminator model names — fields referencing these should use the Variant union type\n  const discriminatorNames = new Set<string>();\n  for (const m of models) {\n    if ((m as any).discriminator) discriminatorNames.add(m.name);\n  }\n\n  for (const model of models) {\n    // Skip list wrapper models (e.g., OrganizationList) — SyncPage handles envelopes\n    if (isListWrapperModel(model) && !nonPaginatedRefs.has(model.name)) continue;\n    // Skip all list metadata models (e.g., ListMetadata, FooListListMetadata)\n    if (isListMetadataModel(model) && !listMetadataNeeded.has(model.name)) continue;\n\n    const service = modelToService.get(model.name);\n    const dirName = resolveDir(service);\n    const modelClassName = className(model.name);\n\n    // Skip models whose file path was already emitted (name collision after snake_case)\n    const modelFilePath = `src/${ctx.namespace}/${dirName}/models/${fileName(model.name)}.py`;\n    if (emittedFilePaths.has(modelFilePath)) continue;\n    emittedFilePaths.add(modelFilePath);\n\n    // If this model is a discriminated union dispatcher, generate a factory class\n    // instead of a regular dataclass (e.g. EventSchema where each variant has\n    // event: const: \"...\"). The dispatcher owns a Union type alias and a from_dict\n    // method that routes to the correct concrete variant at runtime.\n    if ((model as any).discriminator) {\n      const disc = (model as any).discriminator as { property: string; mapping: Record<string, string> };\n      const variantNames = Object.values(disc.mapping); // model names, e.g. [\"ActionAuthenticationDenied\", ...]\n      const variantTypeName = `${modelClassName}Variant`; // e.g. \"EventSchemaVariant\"\n\n      const dispLines: string[] = [];\n      dispLines.push('from __future__ import annotations');\n      dispLines.push('');\n      dispLines.push('from dataclasses import dataclass');\n      dispLines.push('from typing import Any, ClassVar, Dict, Union, cast');\n      dispLines.push(`from ${ctx.namespace}._types import _raise_deserialize_error`);\n      dispLines.push('');\n\n      // Import each variant model from its resolved location\n      const sortedVariants = [...new Set(variantNames)].sort();\n      for (const variantModelName of sortedVariants) {\n        const variantService = modelToService.get(variantModelName);\n        const variantDir = resolveDir(variantService);\n        if (variantDir === dirName) {\n          dispLines.push(`from .${fileName(variantModelName)} import ${className(variantModelName)}`);\n        } else {\n          dispLines.push(\n            `from ${ctx.namespace}.${dirToModule(variantDir)}.models.${fileName(variantModelName)} import ${className(variantModelName)}`,\n          );\n        }\n      }\n\n      // Unknown variant for forward-compatible unknown discriminator values\n      const unknownClassName = `${modelClassName}Unknown`;\n      dispLines.push('');\n      dispLines.push('');\n      dispLines.push('@dataclass(slots=True)');\n      dispLines.push(`class ${unknownClassName}:`);\n      dispLines.push(`    \"\"\"Unknown variant of ${modelClassName} not yet recognized by this SDK version.\"\"\"`);\n      dispLines.push('');\n      dispLines.push('    raw_data: Dict[str, Any]');\n      dispLines.push('    \"\"\"The raw payload, preserved so callers can still inspect the data.\"\"\"');\n      dispLines.push('');\n      dispLines.push('    @classmethod');\n      dispLines.push(`    def from_dict(cls, data: Dict[str, Any]) -> \"${unknownClassName}\":`);\n      dispLines.push('        \"\"\"Wrap raw data in an unknown variant.\"\"\"');\n      dispLines.push('        return cls(raw_data=data)');\n      dispLines.push('');\n      dispLines.push('    def to_dict(self) -> Dict[str, Any]:');\n      dispLines.push('        \"\"\"Return the original raw data.\"\"\"');\n      dispLines.push('        return dict(self.raw_data)');\n\n      dispLines.push('');\n      dispLines.push('');\n\n      // Union type alias — includes unknown variant for forward compatibility\n      dispLines.push(`${variantTypeName} = Union[`);\n      for (const variantModelName of sortedVariants) {\n        dispLines.push(`    ${className(variantModelName)},`);\n      }\n      dispLines.push(`    ${unknownClassName},`);\n      dispLines.push(']');\n\n      dispLines.push('');\n      dispLines.push('');\n\n      // Dispatcher class\n      if (model.description) {\n        dispLines.push(`class ${modelClassName}:`);\n        dispLines.push(`    \"\"\"${model.description}\"\"\"`);\n      } else {\n        dispLines.push(`class ${modelClassName}:`);\n        dispLines.push(`    \"\"\"Discriminated union dispatcher (discriminated by '${disc.property}').\"\"\"`);\n      }\n      dispLines.push('');\n      dispLines.push(`    _DISPATCH: ClassVar[Dict[str, type]] = {`);\n      for (const [value, variantModelName] of Object.entries(disc.mapping).sort(([a], [b]) => a.localeCompare(b))) {\n        dispLines.push(`        \"${value}\": ${className(variantModelName)},`);\n      }\n      dispLines.push('    }');\n      dispLines.push('');\n      dispLines.push('    @classmethod');\n      dispLines.push(`    def from_dict(cls, data: Dict[str, Any]) -> \"${variantTypeName}\":`);\n      dispLines.push('        \"\"\"Deserialize from a dictionary, dispatching to the correct variant.\"\"\"');\n      dispLines.push(`        if \"${disc.property}\" not in data:`);\n      dispLines.push(\n        `            _raise_deserialize_error(\"${modelClassName}\", ValueError(\"Missing required field '${disc.property}'\"))`,\n      );\n      dispLines.push(`        disc_value = data[\"${disc.property}\"]`);\n      dispLines.push('        if disc_value is None:');\n      dispLines.push(\n        `            _raise_deserialize_error(\"${modelClassName}\", ValueError(\"${disc.property} must not be None\"))`,\n      );\n      dispLines.push('        dispatch_cls = cls._DISPATCH.get(disc_value)');\n      dispLines.push('        if dispatch_cls is not None:');\n      dispLines.push(`            return cast(\"${variantTypeName}\", dispatch_cls.from_dict(data))`);\n      dispLines.push(`        return ${unknownClassName}.from_dict(data)`);\n\n      // FR-1.4: write the file only when in scope; the barrel tracking below is\n      // gated on the file existing after the run so out-of-scope models that\n      // are already on disk stay exported, but brand-new out-of-scope models\n      // (whose file is never emitted) are NOT referenced by the barrel.\n      const dispInScope = isModelInScope(model.name, ctx);\n      if (dispInScope) {\n        files.push({\n          path: `src/${ctx.namespace}/${dirName}/models/${fileName(model.name)}.py`,\n          content: dispLines.join('\\n'),\n          integrateTarget: true,\n          overwriteExisting: true,\n        });\n      }\n\n      // Only reference this dispatcher (and its variant/unknown symbols, which\n      // live in the same file) from the barrel when that file exists on disk\n      // after the run.\n      if (fileExistsAfterRun(`src/${ctx.namespace}/${dirName}/models/${fileName(model.name)}.py`, dispInScope, ctx)) {\n        if (!emittedModelSymbolsByDir.has(dirName)) emittedModelSymbolsByDir.set(dirName, []);\n        emittedModelSymbolsByDir.get(dirName)!.push(model.name);\n        // Also register the variant type alias and unknown variant in the barrel,\n        // pointing to the same file as the dispatcher.\n        emittedModelSymbolsByDir.get(dirName)!.push(variantTypeName);\n        symbolToFile.set(variantTypeName, fileName(model.name));\n        emittedModelSymbolsByDir.get(dirName)!.push(unknownClassName);\n        symbolToFile.set(unknownClassName, fileName(model.name));\n        const dispatcherNatural = originalModelToService.get(model.name);\n        if (dispatcherNatural) {\n          symbolToOriginalService.set(model.name, dispatcherNatural);\n          symbolToOriginalService.set(variantTypeName, dispatcherNatural);\n          symbolToOriginalService.set(unknownClassName, dispatcherNatural);\n        }\n      }\n      continue;\n    }\n\n    // If this model is an alias for a canonical model, generate a type alias file\n    const canonicalName = aliasOf.get(model.name);\n    if (canonicalName) {\n      // Skip when alias and canonical produce the same file name (self-import).\n      // This happens when synthetic models from oneOf enrichment collide with\n      // existing IR models in snake_case (e.g., Foo_bar vs FooBar).\n      if (fileName(model.name) === fileName(canonicalName)) {\n        continue;\n      }\n      const canonicalService = modelToService.get(canonicalName);\n      const canonicalDir = resolveDir(canonicalService);\n      const canonicalClassName = className(canonicalName);\n      const lines: string[] = [];\n      lines.push('from typing import TypeAlias');\n      if (canonicalDir === dirName) {\n        lines.push(`from .${fileName(canonicalName)} import ${canonicalClassName}`);\n      } else {\n        lines.push(\n          `from ${ctx.namespace}.${dirToModule(canonicalDir)}.models.${fileName(canonicalName)} import ${canonicalClassName}`,\n        );\n      }\n      lines.push('');\n      lines.push(`${modelClassName}: TypeAlias = ${canonicalClassName}`);\n      const aliasInScope = isModelInScope(model.name, ctx);\n      const aliasPath = `src/${ctx.namespace}/${dirName}/models/${fileName(model.name)}.py`;\n      if (aliasInScope) {\n        files.push({\n          path: aliasPath,\n          content: lines.join('\\n'),\n          integrateTarget: true,\n          overwriteExisting: true,\n        });\n      }\n      // Reference the alias from the barrel only when its file exists on disk\n      // after the run (in-scope, or already present from a prior run).\n      if (fileExistsAfterRun(aliasPath, aliasInScope, ctx)) {\n        if (!emittedModelSymbolsByDir.has(dirName)) emittedModelSymbolsByDir.set(dirName, []);\n        emittedModelSymbolsByDir.get(dirName)!.push(model.name);\n        const aliasNatural = originalModelToService.get(model.name);\n        if (aliasNatural) symbolToOriginalService.set(model.name, aliasNatural);\n      }\n      continue;\n    }\n\n    // Deduplicate fields that map to the same snake_case name\n    const seenFieldNames = new Set<string>();\n    const deduplicatedFields = model.fields.filter((f) => {\n      // Dedup on the DOMAIN identifier (the dataclass attribute name), which\n      // honors a `domainName` override; the wire key stays `field.name`.\n      const pyName = domainFieldName(f);\n      if (seenFieldNames.has(pyName)) return false;\n      seenFieldNames.add(pyName);\n      return true;\n    });\n    const dedupModel = { ...model, fields: deduplicatedFields };\n    const deps = collectFieldDependencies(dedupModel);\n\n    const lines: string[] = [];\n\n    // Collect typing imports\n    const typingImports = new Set<string>();\n    typingImports.add('Any');\n    typingImports.add('Dict');\n    for (const field of deduplicatedFields) {\n      collectTypingImports(field.type, typingImports);\n    }\n    const hasOptional = deduplicatedFields.some((f) => isOptionalField(model.name, f, ctx));\n    if (hasOptional) typingImports.add('Optional');\n    const usesDateTime = deduplicatedFields.some((f) => isDateTimeType(f.type));\n    const usesEnum = deps.enums.size > 0;\n\n    lines.push('from __future__ import annotations');\n    lines.push('');\n    lines.push('from dataclasses import dataclass');\n    if (usesDateTime) {\n      lines.push('from datetime import datetime');\n    }\n    if (usesEnum) {\n      lines.push('from enum import Enum');\n    }\n    lines.push('from typing import cast');\n    lines.push(`from typing import ${[...typingImports].sort().join(', ')}`);\n    lines.push(`from ${ctx.namespace}._types import _raise_deserialize_error`);\n    if (usesDateTime) {\n      lines.push(`from ${ctx.namespace}._types import _format_datetime, _parse_datetime`);\n    }\n\n    // Import referenced models from their service's models package.\n    // Always use direct file imports (not barrel __init__.py) to avoid\n    // circular-import chains when common/ models reference service modules.\n    if (deps.models.size > 0) {\n      lines.push('');\n      for (const modelName of [...deps.models].sort()) {\n        if (modelName === model.name) continue; // skip self\n        const modelService = modelToService.get(modelName);\n        const modelDir = resolveDir(modelService);\n        // For discriminator models, also import the Variant type alias (lives in same file)\n        const importNames = discriminatorNames.has(modelName)\n          ? `${className(modelName)}, ${className(modelName)}Variant`\n          : className(modelName);\n        if (modelDir === dirName) {\n          lines.push(`from .${fileName(modelName)} import ${importNames}`);\n        } else {\n          lines.push(\n            `from ${ctx.namespace}.${dirToModule(modelDir)}.models.${fileName(modelName)} import ${importNames}`,\n          );\n        }\n      }\n    }\n\n    // Import referenced enums — same direct-file strategy.\n    if (deps.enums.size > 0) {\n      for (const enumName of [...deps.enums].sort()) {\n        const enumService = enumToService.get(enumName);\n        const enumDir = resolveDir(enumService);\n        if (enumDir === dirName) {\n          lines.push(`from .${fileName(enumName)} import ${className(enumName)}`);\n        } else {\n          lines.push(\n            `from ${ctx.namespace}.${dirToModule(enumDir)}.models.${fileName(enumName)} import ${className(enumName)}`,\n          );\n        }\n      }\n    }\n\n    lines.push('');\n    lines.push('');\n\n    // Dataclass definition\n    lines.push('@dataclass(slots=True)');\n    lines.push(`class ${modelClassName}:`);\n    if (model.description) {\n      lines.push(`    \"\"\"${model.description}\"\"\"`);\n    } else {\n      // Generate a default docstring from the class name when the spec\n      // doesn't provide a description.\n      let readable = modelClassName.replace(/([a-z])([A-Z])/g, '$1 $2');\n      readable = readable.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');\n      lines.push(`    \"\"\"${readable} model.\"\"\"`);\n    }\n\n    lines.push('');\n\n    // Sort fields: required first, then optional\n    const requiredFields = deduplicatedFields.filter((f) => !isOptionalField(model.name, f, ctx));\n    const optionalFields = deduplicatedFields.filter((f) => isOptionalField(model.name, f, ctx));\n\n    // Rewrite discriminator model references to their Variant union type.\n    // E.g. `\"ConnectApplication\"` → `\"ConnectApplicationVariant\"`\n    const rewriteDiscriminatorType = (typeStr: string): string => {\n      for (const discName of discriminatorNames) {\n        const quoted = `\"${className(discName)}\"`;\n        if (typeStr.includes(quoted)) {\n          typeStr = typeStr.replace(quoted, `\"${className(discName)}Variant\"`);\n        }\n      }\n      return typeStr;\n    };\n\n    for (const field of requiredFields) {\n      // DOMAIN identifier: the dataclass attribute name (honors `domainName`).\n      const pyFieldName = domainFieldName(field);\n      const pyType = rewriteDiscriminatorType(resolveModelFieldType(field.type));\n      if (field.description || field.deprecated) {\n        const parts: string[] = [];\n        if (field.description) parts.push(field.description);\n        if (field.deprecated) parts.push('.. deprecated:: This field is deprecated.');\n        lines.push(`    ${pyFieldName}: ${pyType}`);\n        lines.push(`    \"\"\"${parts.join('\\n\\n    ')}\"\"\"`);\n      } else {\n        lines.push(`    ${pyFieldName}: ${pyType}`);\n      }\n    }\n\n    for (const field of optionalFields) {\n      // DOMAIN identifier: the dataclass attribute name (honors `domainName`).\n      const pyFieldName = domainFieldName(field);\n      const innerType =\n        field.type.kind === 'nullable' ? resolveModelFieldType(field.type.inner) : resolveModelFieldType(field.type);\n      const pyType = `Optional[${rewriteDiscriminatorType(innerType)}]`;\n      if (field.description || field.deprecated) {\n        const parts: string[] = [];\n        if (field.description) parts.push(field.description);\n        if (field.deprecated) parts.push('.. deprecated:: This field is deprecated.');\n        lines.push(`    ${pyFieldName}: ${pyType} = None`);\n        lines.push(`    \"\"\"${parts.join('\\n\\n    ')}\"\"\"`);\n      } else {\n        lines.push(`    ${pyFieldName}: ${pyType} = None`);\n      }\n    }\n\n    // from_dict class method\n    lines.push('');\n    lines.push('    @classmethod');\n    lines.push(`    def from_dict(cls, data: Dict[str, Any]) -> \"${modelClassName}\":`);\n    lines.push(`        \"\"\"Deserialize from a dictionary.\"\"\"`);\n    lines.push('        try:');\n\n    const preludeLines: string[] = [];\n    const fieldAssignmentLines: string[] = [];\n\n    for (const field of [...requiredFields, ...optionalFields]) {\n      // DOMAIN identifier (LHS of `cls(...)`); the wire key below stays `field.name`.\n      const pyFieldName = domainFieldName(field);\n      const wireKey = field.name; // Wire keys are snake_case from the spec\n      const isRequired = !isOptionalField(model.name, field, ctx);\n\n      const discPrelude = renderDiscriminatedUnionPrelude(field, pyFieldName, wireKey, modelClassName, isRequired);\n      if (discPrelude) {\n        preludeLines.push(...discPrelude.prelude);\n        fieldAssignmentLines.push(`                ${pyFieldName}=${discPrelude.expr},`);\n        continue;\n      }\n\n      let accessor: string;\n      if (field.type.kind === 'literal' && isRequired) {\n        // Required literal fields have a statically known value; use .get() with a default\n        // so deserialization is resilient when the API omits the key.\n        accessor = `data.get(\"${wireKey}\", ${pythonLiteralDefault(field.type.value)})`;\n      } else {\n        accessor = isRequired ? `data[\"${wireKey}\"]` : `data.get(\"${wireKey}\")`;\n      }\n      // For deserialization expressions, nullable types must always handle None\n      // even when the field itself is required (the key must be present, but value can be null).\n      const deserRequired = isRequired && field.type.kind !== 'nullable';\n      const walrusVar = `_v_${pyFieldName}`;\n      const deserExpr = deserializeField(field.type, accessor, deserRequired, walrusVar);\n      fieldAssignmentLines.push(`                ${pyFieldName}=${deserExpr},`);\n    }\n\n    for (const preludeLine of preludeLines) lines.push(preludeLine);\n    lines.push('            return cls(');\n    for (const assignment of fieldAssignmentLines) lines.push(assignment);\n    lines.push('            )');\n    lines.push('        except (KeyError, ValueError) as e:');\n    lines.push(`            _raise_deserialize_error(\"${modelClassName}\", e)`);\n\n    // to_dict instance method\n    lines.push('');\n    lines.push('    def to_dict(self) -> Dict[str, Any]:');\n    lines.push('        \"\"\"Serialize to a dictionary.\"\"\"');\n    lines.push('        result: Dict[str, Any] = {}');\n\n    for (const field of [...requiredFields, ...optionalFields]) {\n      // DOMAIN identifier (`self.<attr>`); the wire key below stays `field.name`.\n      const pyFieldName = domainFieldName(field);\n      const wireKey = field.name;\n      const isRequired = !isOptionalField(model.name, field, ctx);\n\n      const isNullable = field.type.kind === 'nullable';\n      if (isRequired && !isNullable) {\n        // Required non-nullable: always serialize directly\n        const serExpr = serializeField(field.type, `self.${pyFieldName}`);\n        lines.push(`        result[\"${wireKey}\"] = ${serExpr}`);\n      } else if (isNullable) {\n        // Nullable fields should round-trip explicit None as null, even when optional\n        const innerType = (field.type as any).inner;\n        const serExpr = serializeField(innerType, `self.${pyFieldName}`);\n        lines.push(`        if self.${pyFieldName} is not None:`);\n        lines.push(`            result[\"${wireKey}\"] = ${serExpr}`);\n        lines.push(`        else:`);\n        lines.push(`            result[\"${wireKey}\"] = None`);\n      } else {\n        // Optional non-nullable fields should be omitted when unset\n        const serExpr = serializeField(field.type, `self.${pyFieldName}`);\n        lines.push(`        if self.${pyFieldName} is not None:`);\n        lines.push(`            result[\"${wireKey}\"] = ${serExpr}`);\n      }\n    }\n\n    lines.push('        return result');\n\n    const regularInScope = isModelInScope(model.name, ctx);\n    if (regularInScope) {\n      files.push({\n        path: modelFilePath,\n        content: lines.join('\\n'),\n        integrateTarget: true,\n        overwriteExisting: true,\n      });\n    }\n    // Reference the model from the barrel only when its file exists on disk\n    // after the run (in-scope, or already present from a prior run). A\n    // brand-new out-of-scope model whose file is never emitted must NOT be\n    // referenced, or the `from .x import X` line dangles and the import fails.\n    if (fileExistsAfterRun(modelFilePath, regularInScope, ctx)) {\n      if (!emittedModelSymbolsByDir.has(dirName)) emittedModelSymbolsByDir.set(dirName, []);\n      emittedModelSymbolsByDir.get(dirName)!.push(model.name);\n      const regularNatural = originalModelToService.get(model.name);\n      if (regularNatural) symbolToOriginalService.set(model.name, regularNatural);\n    }\n  }\n\n  // Generate __init__.py barrel files for each models/ directory\n  // Include both models and enums.\n  // A direct symbol lives in the file at `dirPath/<file>.py`. A re-exported\n  // symbol was relocated to common/ but is being mirrored from its natural\n  // service barrel for backwards compatibility.\n  // A `retainBasename` symbol has no known IR name — it is a per-item file\n  // recorded in the PRIOR manifest (renamed/removed from the current spec but\n  // still on disk) that we re-export wholesale via `from .<base> import *` so\n  // out-of-scope code the scoped run did not regenerate keeps resolving.\n  type BarrelSymbol = { name: string; reExport?: { fromDir: string; file: string }; retainBasename?: string };\n  const symbolsByDir = new Map<string, BarrelSymbol[]>();\n  for (const [dirName, names] of emittedModelSymbolsByDir) {\n    const key = `src/${ctx.namespace}/${dirName}/models`;\n    if (!symbolsByDir.has(key)) symbolsByDir.set(key, []);\n    for (const name of names) symbolsByDir.get(key)!.push({ name });\n  }\n\n  // Also include enums in the barrels using the enum emitter's actual output placement.\n  const reachableEnumNames = collectReachableEnumNames(ctx);\n  const emittedEnums = ctx.spec.enums.filter((enumDef) => reachableEnumNames.has(enumDef.name));\n  const enumSymbolsByDir = collectGeneratedEnumSymbolsByDir(emittedEnums, ctx);\n  // Map each compat-alias symbol back to its canonical enum so we can gate it by\n  // the canonical enum's scope (the alias file is only written when the\n  // canonical enum is in scope; see enums.ts).\n  const aliasToCanonicalEnum = new Map<string, string>();\n  for (const [canonical, aliasNames] of collectCompatEnumAliases(emittedEnums, ctx)) {\n    for (const aliasName of aliasNames) aliasToCanonicalEnum.set(aliasName, canonical);\n  }\n  for (const [dirName, names] of enumSymbolsByDir) {\n    const key = `src/${ctx.namespace}/${dirName}/models`;\n    if (!symbolsByDir.has(key)) symbolsByDir.set(key, []);\n    for (const name of names) {\n      // Reference an enum (or its compat alias) from the barrel only when its\n      // per-enum file exists on disk after the run. A brand-new out-of-scope\n      // enum whose file is never emitted must NOT be referenced.\n      const enumFilePath = `${key}/${fileName(name)}.py`;\n      const scopeName = aliasToCanonicalEnum.get(name) ?? name;\n      if (fileExistsAfterRun(enumFilePath, isEnumInScope(scopeName, ctx), ctx)) {\n        symbolsByDir.get(key)!.push({ name });\n      }\n    }\n  }\n\n  // Scoped runs: retain barrel entries for per-item files still on disk (prior\n  // manifest) that the current spec no longer produces — e.g. a model/enum\n  // renamed or removed for an out-of-scope service. Out-of-scope code we did\n  // not regenerate may still `from .<base> import X`, so dropping it would\n  // break the import. We can't recover the original class name from the\n  // basename, so re-export the module wholesale with `import *`. A full run\n  // (priorManifestBasenames returns []) yields nothing here. De-duped against\n  // files already referenced by an emitted/enum symbol in the same dir.\n  //\n  // Candidate dirs are every `src/<ns>/<dir>/models` that appears in the prior\n  // manifest (a dir may have no in-scope items yet still hold on-disk files\n  // referenced by stale out-of-scope code).\n  const manifestModelDirs = new Set<string>();\n  for (const p of ctx.priorTargetManifestPaths ?? []) {\n    const m = p.match(new RegExp(`^(src/${ctx.namespace}/[^/]+/models)/[^/]+\\\\.py$`));\n    if (m) manifestModelDirs.add(m[1]);\n  }\n  for (const dirPath of manifestModelDirs) {\n    if (!symbolsByDir.has(dirPath)) symbolsByDir.set(dirPath, []);\n    const referencedBasenames = new Set<string>();\n    for (const sym of symbolsByDir.get(dirPath)!) {\n      if (sym.reExport || sym.retainBasename) continue;\n      referencedBasenames.add(symbolToFile.get(sym.name) ?? fileName(sym.name));\n    }\n    for (const base of priorManifestBasenames(ctx, dirPath, '.py', new Set(['__init__']))) {\n      if (referencedBasenames.has(base)) continue;\n      referencedBasenames.add(base);\n      symbolsByDir.get(dirPath)!.push({ name: base, retainBasename: base });\n    }\n  }\n\n  // Backwards-compat re-exports: every relocated model is also re-exported\n  // from its pre-relocation service barrel so existing\n  // `from workos.<service>.models import X` imports keep working.\n  const commonDirName = 'common';\n  const addReExport = (naturalService: string | undefined, name: string, sourceFile: string): void => {\n    if (!naturalService) return;\n    const naturalDir = mountDirMap.get(naturalService) ?? naturalService;\n    if (naturalDir === commonDirName) return;\n    const key = `src/${ctx.namespace}/${naturalDir}/models`;\n    if (!symbolsByDir.has(key)) symbolsByDir.set(key, []);\n    symbolsByDir.get(key)!.push({ name, reExport: { fromDir: commonDirName, file: sourceFile } });\n  };\n\n  for (const symbol of symbolToOriginalService.keys()) {\n    // Only re-export symbols that ended up relocated (i.e. their owning model is in relocatedModels)\n    // or whose dispatcher parent is relocated.\n    const naturalService = symbolToOriginalService.get(symbol)!;\n    // Find what file the symbol lives in (in common/)\n    const file = symbolToFile.get(symbol) ?? fileName(symbol);\n    // Only re-export if it actually got relocated — that is, if its primary\n    // model name (or the parent it shares a file with) is in relocatedModels.\n    const primaryName = file === fileName(symbol) ? symbol : reverseLookupModelByFile(file, ctx);\n    if (primaryName && !relocatedModels.has(primaryName)) continue;\n    addReExport(naturalService, symbol, file);\n  }\n  for (const enumName of relocatedEnums) {\n    const naturalService = originalEnumToService.get(enumName);\n    addReExport(naturalService, enumName, fileName(enumName));\n  }\n\n  // Build set of service directory model paths — these get their parent __init__.py\n  // from generateServiceInits in client.ts, so we must not create a competing one here.\n  // `inScopeServiceDirModelPaths` is the subset the current run is generating: in a\n  // scoped (`--services`) run it excludes services not selected, so a brand-new\n  // out-of-scope service the spec just added does not get a stray empty barrel.\n  // (Inactive scoping ⇒ isMountInScope is always true ⇒ the two sets match.)\n  const serviceDirModelPaths = new Set<string>();\n  const inScopeServiceDirModelPaths = new Set<string>();\n  for (const service of ctx.spec.services) {\n    const dirName = mountDirMap.get(service.name) ?? resolveDir(service.name);\n    const modelsPath = `src/${ctx.namespace}/${dirName}/models`;\n    serviceDirModelPaths.add(modelsPath);\n    if (isMountInScope(getMountTarget(service, ctx), ctx)) {\n      inScopeServiceDirModelPaths.add(modelsPath);\n    }\n  }\n\n  // Emit an empty barrel for every service-models dir that has no symbols of\n  // its own (e.g. a service whose models live in another package via\n  // cross-domain aliases). Otherwise the live SDK can keep a stale\n  // `__init__.py` from a previous spec revision — when the underlying module\n  // gets pruned the dangling re-export survives and breaks pyright. Done here\n  // (not in client.ts) so a subsequent emission for the same path with real\n  // content always wins last-write-wins. Skipped for services outside a scoped\n  // run's selection — we don't manage their tree this run.\n  for (const dirPath of inScopeServiceDirModelPaths) {\n    if (!symbolsByDir.has(dirPath)) {\n      files.push({\n        path: `${dirPath}/__init__.py`,\n        content: '',\n        integrateTarget: true,\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  for (const [dirPath, symbols] of symbolsByDir) {\n    // Deduplicate by symbol name (a direct emission always wins over a stale\n    // re-export with the same name).\n    const seen = new Map<string, BarrelSymbol>();\n    for (const sym of symbols) {\n      const existing = seen.get(sym.name);\n      if (!existing || (existing.reExport && !sym.reExport)) seen.set(sym.name, sym);\n    }\n    const uniqueSymbols = [...seen.values()].sort((a, b) => a.name.localeCompare(b.name));\n\n    // Use `import X as X` syntax for explicit re-exports (required by pyright strict)\n    const importLines: string[] = [];\n    for (const sym of uniqueSymbols) {\n      if (sym.retainBasename) {\n        // On-disk module renamed/removed from the spec: re-export it wholesale\n        // since its concrete symbol names are unknown from the manifest alone.\n        importLines.push(`from .${sym.retainBasename} import *  # noqa: F401,F403`);\n        continue;\n      }\n      const cls = className(sym.name);\n      if (sym.reExport) {\n        importLines.push(\n          `from ${ctx.namespace}.${dirToModule(sym.reExport.fromDir)}.models.${sym.reExport.file} import ${cls} as ${cls}`,\n        );\n      } else {\n        const fileNameForSymbol = symbolToFile.get(sym.name) ?? fileName(sym.name);\n        importLines.push(`from .${fileNameForSymbol} import ${cls} as ${cls}`);\n      }\n    }\n    const imports = importLines.join('\\n');\n    files.push({\n      path: `${dirPath}/__init__.py`,\n      content: imports,\n      integrateTarget: true,\n      overwriteExisting: true,\n    });\n\n    // Only generate parent __init__.py for non-service dirs (e.g., common/).\n    // Service dirs get their __init__.py from generateServiceInits in client.ts\n    // which includes both the resource class re-export and model star import.\n    if (!serviceDirModelPaths.has(dirPath)) {\n      const parentDir = dirPath.replace(/\\/models$/, '');\n      const reExports = [\n        ...new Set(\n          uniqueSymbols.map((sym) =>\n            sym.retainBasename\n              ? 'from .models import *  # noqa: F401,F403'\n              : `from .models import ${className(sym.name)} as ${className(sym.name)}`,\n          ),\n        ),\n      ].join('\\n');\n      files.push({\n        path: `${parentDir}/__init__.py`,\n        content: reExports,\n        integrateTarget: true,\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n\n/**\n * Given a snake_case file name, return the IR model name that owns it.\n * Used to attribute dispatcher children (FooVariant, FooUnknown) to their\n * parent model when computing relocation re-exports.\n */\nfunction reverseLookupModelByFile(file: string, ctx: EmitterContext): string | undefined {\n  for (const m of ctx.spec.models) {\n    if (fileName(m.name) === file) return m.name;\n  }\n  return undefined;\n}\n\nfunction collectTypingImports(ref: any, imports: Set<string>): void {\n  switch (ref.kind) {\n    case 'array':\n      imports.add('List');\n      collectTypingImports(ref.items, imports);\n      break;\n    case 'nullable':\n      imports.add('Optional');\n      collectTypingImports(ref.inner, imports);\n      break;\n    case 'union':\n      imports.add('Union');\n      for (const v of ref.variants) collectTypingImports(v, imports);\n      break;\n    case 'map':\n      imports.add('Dict');\n      collectTypingImports(ref.valueType, imports);\n      break;\n    case 'literal':\n      imports.add('Literal');\n      break;\n    case 'primitive':\n      if (ref.type === 'unknown') imports.add('Any');\n      break;\n  }\n}\n\nfunction collectReachableEnumNames(ctx: EmitterContext): Set<string> {\n  const referencedModels = new Set<string>();\n  const referencedEnums = new Set<string>();\n\n  const collectFromTypeRef = (ref: any): void => {\n    walkTypeRef(ref, {\n      model: (r) => referencedModels.add(r.name),\n      enum: (r) => referencedEnums.add(r.name),\n    });\n  };\n\n  for (const service of ctx.spec.services) {\n    for (const op of service.operations) {\n      for (const p of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n        collectFromTypeRef(p.type);\n      }\n      if (op.requestBody) collectFromTypeRef(op.requestBody);\n      collectFromTypeRef(op.response);\n      if (op.pagination) collectFromTypeRef(op.pagination.itemType);\n      for (const err of op.errors) {\n        if (err.type) collectFromTypeRef(err.type);\n      }\n      if (op.successResponses) {\n        for (const sr of op.successResponses) {\n          collectFromTypeRef(sr.type);\n        }\n      }\n    }\n  }\n\n  const modelsByName = new Map(ctx.spec.models.map((m) => [m.name, m]));\n  const visited = new Set<string>();\n  const queue = [...referencedModels];\n  while (queue.length > 0) {\n    const name = queue.pop()!;\n    if (visited.has(name)) continue;\n    visited.add(name);\n    const model = modelsByName.get(name);\n    if (!model) continue;\n    for (const field of model.fields) {\n      collectFromTypeRef(field.type);\n      for (const modelName of referencedModels) {\n        if (!visited.has(modelName)) queue.push(modelName);\n      }\n    }\n  }\n\n  return referencedEnums;\n}\n\nfunction isOptionalField(modelName: string, field: Model['fields'][number], ctx: EmitterContext): boolean {\n  void modelName;\n  void ctx;\n  // A field is optional (gets = None default) only if it's not required or deprecated.\n  // Nullable-required fields (required: true, type: nullable) are NOT optional —\n  // they must appear in the API response (value can be null, but key must be present).\n  // The spec's required status always takes precedence over the old SDK's API surface.\n  if (!field.required || field.deprecated) return true;\n  return false;\n}\n\n/** Convert a LiteralType value to a Python default expression for use in data.get(). */\nfunction pythonLiteralDefault(value: string | number | boolean | null): string {\n  if (value === null) return 'None';\n  if (typeof value === 'boolean') return value ? 'True' : 'False';\n  if (typeof value === 'string') return `\"${value}\"`;\n  return String(value);\n}\n\nfunction resolveModelFieldType(ref: any): string {\n  // Handle nullable datetime: return Optional[datetime] to preserve nullable wrapper\n  if (ref.kind === 'nullable' && isDateTimeType(ref.inner)) {\n    return 'Optional[datetime]';\n  }\n  if (isDateTimeType(ref)) {\n    return 'datetime';\n  }\n  return mapTypeRef(ref);\n}\n\nfunction isDateTimeType(ref: any): boolean {\n  if (ref.kind === 'nullable') {\n    return isDateTimeType(ref.inner);\n  }\n  return ref.kind === 'primitive' && ref.type === 'string' && ref.format === 'date-time';\n}\n\n/**\n * If `field` is a discriminated-union (or nullable-wrapped discriminated-union)\n * field, return prelude statements that perform strict dispatch and an\n * expression for the `cls(...)` call. Returns null otherwise.\n *\n * Strict dispatch means: an unknown discriminator value raises ValueError\n * naming the parent class, field, observed value, and valid options. The\n * caller's `try/except` block converts that into `_raise_deserialize_error`.\n */\nfunction renderDiscriminatedUnionPrelude(\n  field: any,\n  pyFieldName: string,\n  wireKey: string,\n  parentClassName: string,\n  isRequired: boolean,\n): { prelude: string[]; expr: string } | null {\n  let unionRef: any = null;\n  let nullable = false;\n  if (field.type.kind === 'union' && field.type.discriminator?.mapping) {\n    unionRef = field.type;\n  } else if (\n    field.type.kind === 'nullable' &&\n    field.type.inner.kind === 'union' &&\n    field.type.inner.discriminator?.mapping\n  ) {\n    unionRef = field.type.inner;\n    nullable = true;\n  }\n  if (!unionRef) return null;\n\n  const mapping = unionRef.discriminator.mapping as Record<string, string>;\n  const entries = Object.entries(mapping);\n  if (entries.length === 0) return null;\n\n  const discProp = unionRef.discriminator.property as string;\n  const rawVar = `_${pyFieldName}_raw`;\n  const dataVar = `_${pyFieldName}_data`;\n  const typeVar = `_${pyFieldName}_disc`;\n  const mapVar = `_${pyFieldName}_disc_map`;\n  const clsVar = `_${pyFieldName}_cls`;\n  const valueVar = `_${pyFieldName}_value`;\n  const indent = '            ';\n\n  const dispatchBlock = (innerIndent: string): string[] => {\n    const lines: string[] = [];\n    lines.push(`${innerIndent}${dataVar} = cast(Dict[str, Any], ${rawVar})`);\n    lines.push(`${innerIndent}${typeVar} = cast(str, ${dataVar}.get(\"${discProp}\"))`);\n    lines.push(`${innerIndent}${mapVar}: Dict[str, Any] = {`);\n    for (const [value, variantModelName] of entries) {\n      lines.push(`${innerIndent}    \"${value}\": ${className(variantModelName)},`);\n    }\n    lines.push(`${innerIndent}}`);\n    lines.push(`${innerIndent}${clsVar} = ${mapVar}.get(${typeVar})`);\n    lines.push(`${innerIndent}if ${clsVar} is None:`);\n    lines.push(`${innerIndent}    raise ValueError(`);\n    lines.push(\n      `${innerIndent}        f\"Unknown discriminator '${discProp}' for ${parentClassName}.${pyFieldName}: {${typeVar}!r}. \"`,\n    );\n    lines.push(`${innerIndent}        f\"Expected one of {sorted(${mapVar})}.\"`);\n    lines.push(`${innerIndent}    )`);\n    return lines;\n  };\n\n  const prelude: string[] = [];\n  if (isRequired && !nullable) {\n    prelude.push(`${indent}${rawVar} = data[\"${wireKey}\"]`);\n    prelude.push(...dispatchBlock(indent));\n    return { prelude, expr: `${clsVar}.from_dict(${dataVar})` };\n  }\n\n  // Optional or nullable: handle missing/None explicitly.\n  const accessor = isRequired ? `data[\"${wireKey}\"]` : `data.get(\"${wireKey}\")`;\n  prelude.push(`${indent}${rawVar} = ${accessor}`);\n  prelude.push(`${indent}if ${rawVar} is None:`);\n  prelude.push(`${indent}    ${valueVar} = None`);\n  prelude.push(`${indent}else:`);\n  prelude.push(...dispatchBlock(indent + '    '));\n  prelude.push(`${indent}    ${valueVar} = ${clsVar}.from_dict(${dataVar})`);\n  return { prelude, expr: valueVar };\n}\n\nfunction deserializeField(ref: any, accessor: string, isRequired: boolean, walrusVar: string = '_v'): string {\n  if (isDateTimeType(ref)) {\n    if (isRequired) {\n      return `_parse_datetime(${accessor})`;\n    }\n    return `_parse_datetime(${walrusVar}) if (${walrusVar} := ${accessor}) is not None else None`;\n  }\n  switch (ref.kind) {\n    case 'model': {\n      if (isRequired) {\n        return `${className(ref.name)}.from_dict(cast(Dict[str, Any], ${accessor}))`;\n      }\n      return `${className(ref.name)}.from_dict(cast(Dict[str, Any], ${walrusVar})) if (${walrusVar} := ${accessor}) is not None else None`;\n    }\n    case 'array': {\n      if (ref.items.kind === 'model') {\n        const listExpr = `[${className(ref.items.name)}.from_dict(cast(Dict[str, Any], item)) for item in cast(list[Any], ${isRequired ? accessor : walrusVar})]`;\n        if (isRequired) {\n          return listExpr;\n        }\n        // For optional arrays, preserve None instead of converting to []\n        return `${listExpr} if (${walrusVar} := ${accessor}) is not None else None`;\n      }\n      if (ref.items.kind === 'enum') {\n        const enumClass = className(ref.items.name);\n        const listExpr = `[${enumClass}(item) for item in cast(list[Any], ${isRequired ? accessor : walrusVar})]`;\n        if (isRequired) {\n          return listExpr;\n        }\n        return `${listExpr} if (${walrusVar} := ${accessor}) is not None else None`;\n      }\n      return accessor;\n    }\n    case 'enum': {\n      const enumClass = className(ref.name);\n      if (isRequired) {\n        return `${enumClass}(${accessor})`;\n      }\n      return `${enumClass}(${walrusVar}) if (${walrusVar} := ${accessor}) is not None else None`;\n    }\n    case 'nullable':\n      return deserializeField(ref.inner, accessor, false, walrusVar);\n    case 'union': {\n      // Discriminated unions are handled by `renderDiscriminatedUnionPrelude`\n      // before deserializeField is called, so they never reach this branch.\n      const modelVariants = (ref.variants ?? []).filter((v: any) => v.kind === 'model');\n      const uniqueModels = [...new Set(modelVariants.map((v: any) => v.name))] as string[];\n      if (uniqueModels.length === 1) {\n        return deserializeField({ kind: 'model', name: uniqueModels[0] }, accessor, isRequired, walrusVar);\n      }\n      // Mixed unions — pass through (would need runtime discriminant logic)\n      return accessor;\n    }\n    default:\n      return accessor;\n  }\n}\n\nfunction serializeField(ref: any, accessor: string): string {\n  if (isDateTimeType(ref)) {\n    return `_format_datetime(${accessor})`;\n  }\n  switch (ref.kind) {\n    case 'model':\n      return `${accessor}.to_dict()`;\n    case 'enum':\n      return `${accessor}.value if isinstance(${accessor}, Enum) else ${accessor}`;\n    case 'array': {\n      if (ref.items.kind === 'model') {\n        return `[item.to_dict() for item in ${accessor}]`;\n      }\n      if (ref.items.kind === 'enum') {\n        return `[item.value if isinstance(item, Enum) else item for item in ${accessor}]`;\n      }\n      return accessor;\n    }\n    case 'union': {\n      const modelVariants = (ref.variants ?? []).filter((v: any) => v.kind === 'model');\n      const uniqueModels = [...new Set(modelVariants.map((v: any) => v.name))];\n      if (uniqueModels.length === 1) {\n        return `${accessor}.to_dict()`;\n      }\n      // Discriminated union: from_dict always produces a concrete dataclass\n      // instance (unknown discriminators raise instead of falling back to a\n      // raw dict), so the serialized field is unconditionally `.to_dict()`-able.\n      if (ref.discriminator && ref.discriminator.mapping && modelVariants.length > 0) {\n        return `${accessor}.to_dict()`;\n      }\n      return accessor;\n    }\n    default:\n      return accessor;\n  }\n}\n\n// Import and re-export shared model detection utilities\nimport {\n  isListMetadataModel,\n  isListWrapperModel,\n  collectNonPaginatedResponseModelNames,\n  collectReferencedListMetadataModels,\n} from '../shared/model-utils.js';\nexport { isListMetadataModel, isListWrapperModel };\n","import { parsePathTemplate, type PathSegment } from '../shared/path-template.js';\nimport { fieldName } from './naming.js';\n\nexport interface PythonPathOptions {\n  /** Raw OpenAPI param names whose runtime value is enum-typed. */\n  enumParams?: ReadonlySet<string>;\n}\n\n/**\n * Build the Python tuple expression that the SDK passes to the request layer.\n *\n * The returned expression is a tuple of per-segment values. The request layer\n * (`_BaseWorkOSClient._encode_path`) URL-encodes each element with `safe=\"\"`\n * before joining with \"/\", so a caller-supplied id containing \"/\" or \"../\"\n * cannot escape its intended segment. This is the structural fix that lets\n * the request layer make a real guarantee instead of inspecting an already-\n * concatenated path string.\n *\n *   \"/orgs\"                        → `(\"orgs\",)`\n *   \"/orgs/{id}\"                   → `(\"orgs\", str(id))`\n *   \"/orgs/{id}/users/{uid}\"       → `(\"orgs\", str(id), \"users\", str(uid))`\n *   \"/orgs/{id}\" with id ∈ enums   → `(\"orgs\", str(enum_value(id)))`\n *\n * Mixed segments (e.g. literal text adjacent to a placeholder within a single\n * path component) are emitted as a Python f-string element. Per-segment\n * encoding is still applied to the whole element by the request layer; this\n * is rare in WorkOS specs but is handled deterministically.\n */\nexport function buildPythonPathExpression(rawPath: string, options: PythonPathOptions = {}): string {\n  const segments = parsePathTemplate(rawPath, { stripLeadingSlash: true });\n  if (segments.length === 0) return '()';\n\n  const components = splitIntoComponents(segments);\n  const parts = components.map((c) => emitComponent(c, options.enumParams));\n  return parts.length === 1 ? `(${parts[0]!},)` : `(${parts.join(', ')})`;\n}\n\ntype Subpiece = { kind: 'literal'; value: string } | { kind: 'param'; name: string };\n\n/**\n * Split a parsed path template into one component per \"/\"-separated piece.\n * Each component is a list of literal / param subpieces; multi-subpiece\n * components occur only for mixed segments like `foo{id}bar`.\n */\nfunction splitIntoComponents(segments: PathSegment[]): Subpiece[][] {\n  const components: Subpiece[][] = [[]];\n  for (const seg of segments) {\n    if (seg.kind === 'literal') {\n      const parts = seg.value.split('/');\n      const first = parts[0];\n      if (first !== undefined && first !== '') {\n        components[components.length - 1]!.push({ kind: 'literal', value: first });\n      }\n      for (let i = 1; i < parts.length; i++) {\n        components.push([]);\n        const part = parts[i];\n        if (part !== undefined && part !== '') {\n          components[components.length - 1]!.push({ kind: 'literal', value: part });\n        }\n      }\n    } else {\n      components[components.length - 1]!.push({ kind: 'param', name: seg.name });\n    }\n  }\n  // Drop a trailing empty component if the path ended with a separator.\n  while (components.length > 1 && components[components.length - 1]!.length === 0) {\n    components.pop();\n  }\n  return components;\n}\n\nfunction emitComponent(component: Subpiece[], enumParams?: ReadonlySet<string>): string {\n  if (component.length === 1) {\n    const only = component[0]!;\n    if (only.kind === 'literal') return `\"${escapePyDoubleQuoted(only.value)}\"`;\n    const varName = fieldName(only.name);\n    const inner = enumParams?.has(only.name) ? `enum_value(${varName})` : varName;\n    return `str(${inner})`;\n  }\n  // Mixed component — fall back to an f-string. The request layer still\n  // URL-encodes the resulting element as a single segment.\n  let body = '';\n  for (const piece of component) {\n    if (piece.kind === 'literal') {\n      body += escapeFStringLiteral(piece.value);\n    } else {\n      const varName = fieldName(piece.name);\n      const inner = enumParams?.has(piece.name) ? `enum_value(${varName})` : varName;\n      body += `{${inner}}`;\n    }\n  }\n  return `f\"${body}\"`;\n}\n\nfunction escapePyDoubleQuoted(literal: string): string {\n  return literal.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\nfunction escapeFStringLiteral(literal: string): string {\n  return literal.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\{/g, '{{').replace(/\\}/g, '}}');\n}\n","import type { EmitterContext, ResolvedOperation, ResolvedWrapper, Model } from '@workos/oagen';\nimport { toSnakeCase } from '@workos/oagen';\nimport { className, fieldName } from './naming.js';\nimport { resolveWrapperParams, formatWrapperDescription } from '../shared/wrapper-utils.js';\nimport { buildPythonPathExpression } from './path-expression.js';\n\n/**\n * Generate Python wrapper method lines for split operations.\n *\n * Each wrapper is a typed convenience method that:\n * - Accepts only the exposed params (not the full union body)\n * - Injects constant defaults (e.g., grant_type)\n * - Reads inferred fields from client config (e.g., client_id)\n * - Delegates to the HTTP client with the constructed body\n *\n * Generates both sync and async versions.\n */\nexport function generateSyncWrapperMethods(resolvedOp: ResolvedOperation, ctx: EmitterContext): string[] {\n  return generateWrapperMethodsInner(resolvedOp, ctx, false);\n}\n\nexport function generateAsyncWrapperMethods(resolvedOp: ResolvedOperation, ctx: EmitterContext): string[] {\n  return generateWrapperMethodsInner(resolvedOp, ctx, true);\n}\n\nfunction generateWrapperMethodsInner(resolvedOp: ResolvedOperation, ctx: EmitterContext, isAsync: boolean): string[] {\n  if (!resolvedOp.wrappers || resolvedOp.wrappers.length === 0) return [];\n\n  const lines: string[] = [];\n\n  for (const wrapper of resolvedOp.wrappers) {\n    lines.push('');\n    emitWrapperMethod(lines, resolvedOp, wrapper, ctx, isAsync);\n  }\n\n  return lines;\n}\n\nfunction emitWrapperMethod(\n  lines: string[],\n  resolvedOp: ResolvedOperation,\n  wrapper: ResolvedWrapper,\n  ctx: EmitterContext,\n  isAsync: boolean,\n): void {\n  const op = resolvedOp.operation;\n  const method = wrapper.name; // already snake_case\n  const wrapperParams = resolveWrapperParams(wrapper, ctx);\n\n  // Build signature\n  const defKeyword = isAsync ? 'async def' : 'def';\n  lines.push(`    ${defKeyword} ${method}(`);\n  lines.push('        self,');\n\n  // Path params as positional args\n  for (const param of op.pathParams) {\n    const paramName = fieldName(param.name);\n    const paramType = resolveSimpleType(param.type);\n    lines.push(`        ${paramName}: ${paramType},`);\n  }\n\n  lines.push('        *,');\n\n  // Exposed params as keyword args\n  for (const { paramName, field, isOptional } of wrapperParams) {\n    const pyName = fieldName(paramName);\n    const pyType = field ? resolveSimpleType(field.type) : 'str';\n\n    if (isOptional) {\n      lines.push(`        ${pyName}: Optional[${pyType}] = None,`);\n    } else {\n      lines.push(`        ${pyName}: ${pyType},`);\n    }\n  }\n\n  lines.push('        request_options: Optional[RequestOptions] = None,');\n\n  // Return type — use Variant type for discriminated union responses\n  const isDiscriminatorResponse = wrapper.responseModelName\n    ? !!(ctx.spec.models.find((m: Model) => m.name === wrapper.responseModelName) as any)?.discriminator\n    : false;\n  const responseType = wrapper.responseModelName\n    ? isDiscriminatorResponse\n      ? className(wrapper.responseModelName) + 'Variant'\n      : className(wrapper.responseModelName)\n    : 'None';\n\n  lines.push(`    ) -> ${responseType}:`);\n\n  // Docstring\n  lines.push(`        \"\"\"${formatWrapperDescription(wrapper.name)}.\"\"\"`);\n\n  // Build body dict\n  lines.push('        body: Dict[str, Any] = {');\n\n  // Constant defaults\n  for (const [key, value] of Object.entries(wrapper.defaults)) {\n    lines.push(`            \"${key}\": ${pythonLiteral(value)},`);\n  }\n\n  // Exposed params (required ones go directly)\n  for (const { paramName, isOptional } of wrapperParams) {\n    if (isOptional) continue;\n    const pyName = fieldName(paramName);\n    lines.push(`            \"${paramName}\": ${pyName},`);\n  }\n\n  lines.push('        }');\n\n  // Inferred fields from client config\n  for (const field of wrapper.inferFromClient) {\n    const expr = clientFieldExpression(field);\n    lines.push(`        if ${expr} is not None:`);\n    lines.push(`            body[\"${field}\"] = ${expr}`);\n  }\n\n  // Optional exposed params\n  for (const { paramName, isOptional } of wrapperParams) {\n    if (!isOptional) continue;\n    const pyName = fieldName(paramName);\n    lines.push(`        if ${pyName} is not None:`);\n    lines.push(`            body[\"${paramName}\"] = ${pyName}`);\n  }\n\n  // Build path expression\n  const pathExpr = buildPythonPathExpression(op.path);\n\n  // Make the request\n  const awaitPrefix = isAsync ? 'await ' : '';\n  lines.push('');\n\n  if (wrapper.responseModelName && isDiscriminatorResponse) {\n    const variantType = className(wrapper.responseModelName) + 'Variant';\n    lines.push(`        return cast(`);\n    lines.push(`            ${variantType},`);\n    lines.push(`            ${awaitPrefix}self._client.request(`);\n    lines.push(`                method=\"${op.httpMethod.toUpperCase()}\",`);\n    lines.push(`                path=${pathExpr},`);\n    lines.push('                body=body,');\n    lines.push(\n      `                model=${className(wrapper.responseModelName)},  # type: ignore[arg-type]  # dispatcher; request only calls from_dict`,\n    );\n    lines.push('                request_options=request_options,');\n    lines.push('            )');\n    lines.push('        )');\n  } else if (wrapper.responseModelName) {\n    lines.push(`        return ${awaitPrefix}self._client.request(`);\n    lines.push(`            method=\"${op.httpMethod.toUpperCase()}\",`);\n    lines.push(`            path=${pathExpr},`);\n    lines.push('            body=body,');\n    lines.push(`            model=${className(wrapper.responseModelName)},`);\n    lines.push('            request_options=request_options,');\n    lines.push('        )');\n  } else {\n    lines.push(`        ${awaitPrefix}self._client.request(`);\n    lines.push(`            method=\"${op.httpMethod.toUpperCase()}\",`);\n    lines.push(`            path=${pathExpr},`);\n    lines.push('            body=body,');\n    lines.push('            request_options=request_options,');\n    lines.push('        )');\n  }\n}\n\n/** Convert a value to a Python literal. */\nexport function pythonLiteral(value: string | number | boolean): string {\n  if (typeof value === 'string') return `\"${value.replace(/\"/g, '\\\\\"')}\"`;\n  if (typeof value === 'boolean') return value ? 'True' : 'False';\n  return String(value);\n}\n\n/** Get the Python expression for reading a client config field. */\nexport function clientFieldExpression(field: string): string {\n  switch (field) {\n    case 'client_id':\n      return 'self._client.client_id';\n    case 'client_secret':\n      return 'self._client._api_key';\n    default:\n      return `self._client.${toSnakeCase(field)}`;\n  }\n}\n\n/** Resolve a TypeRef to a simple Python type string. */\nfunction resolveSimpleType(ref: any): string {\n  if (ref.kind === 'primitive') {\n    switch (ref.type) {\n      case 'string':\n        return 'str';\n      case 'integer':\n        return 'int';\n      case 'number':\n        return 'float';\n      case 'boolean':\n        return 'bool';\n      default:\n        return 'Any';\n    }\n  }\n  if (ref.kind === 'nullable') return resolveSimpleType(ref.inner);\n  if (ref.kind === 'array') return `List[${resolveSimpleType(ref.items)}]`;\n  if (ref.kind === 'model') return className(ref.name);\n  if (ref.kind === 'enum') return className(ref.name);\n  return 'Any';\n}\n","import type {\n  Service,\n  Operation,\n  OperationPlan,\n  EmitterContext,\n  GeneratedFile,\n  TypeRef,\n  ResolvedOperation,\n  Parameter,\n  Model,\n} from '@workos/oagen';\n\n/** Extend Parameter with `explode` until @workos/oagen publishes the field. */\ntype ParameterExt = Parameter & { explode?: boolean };\nimport { planOperation, toPascalCase, toSnakeCase, collectModelRefs, collectEnumRefs } from '@workos/oagen';\nimport { mapTypeRefUnquoted } from './type-map.js';\nimport {\n  className,\n  fieldName,\n  fileName,\n  moduleName,\n  resolveClassName,\n  buildMountDirMap,\n  dirToModule,\n  relativeImportPrefix,\n  buildExportedClassNameSet,\n  resolveServiceTarget,\n} from './naming.js';\nimport {\n  buildResolvedLookup,\n  lookupMethodName,\n  lookupResolved,\n  scopedMountGroups,\n  getOpDefaults,\n  getOpInferFromClient,\n  buildHiddenParams as buildHiddenParamsShared,\n  collectGroupedParamNames,\n  collectBodyFieldTypes,\n} from '../shared/resolved-ops.js';\nimport {\n  generateSyncWrapperMethods,\n  generateAsyncWrapperMethods,\n  pythonLiteral,\n  clientFieldExpression,\n} from './wrappers.js';\nimport { buildPythonPathExpression } from './path-expression.js';\nimport { computeSchemaPlacement } from './shared-schemas.js';\n\n/**\n * Compute the Python parameter name for a body field, prefixing with `body_` if it\n * collides with a path parameter name.\n */\nexport function bodyParamName(field: { name: string }, pathParamNames: Set<string>): string {\n  const name = fieldName(field.name);\n  return pathParamNames.has(name) ? `body_${name}` : name;\n}\n\n/**\n * Resolve the resource class name for a service.\n */\nexport function resolveResourceClassName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n// buildHiddenParams is imported from ../shared/resolved-ops.js as buildHiddenParamsShared\nconst buildHiddenParams = buildHiddenParamsShared;\n\n// ─── Parameter group support ─────────────────────────────────────────\n\n/**\n * PascalCase variant class name for a parameter group variant.\n * E.g., group \"parent_resource\", variant \"by_id\" -> \"ParentResourceById\".\n */\nfunction groupVariantClassName(groupName: string, variantName: string): string {\n  return className(`${groupName}_${variantName}`);\n}\n\n/**\n * Generate Python dataclass definitions for all parameter group variants\n * across a set of operations. Returns lines to insert near the top of the\n * resource file (after imports, before class definitions).\n */\nfunction generateParameterGroupDataclasses(\n  operations: Operation[],\n  specEnumNames: Set<string>,\n  models: Model[],\n): string[] {\n  const lines: string[] = [];\n  const emitted = new Set<string>();\n\n  for (const op of operations) {\n    const bodyFieldTypes = collectBodyFieldTypes(op, models);\n    for (const group of op.parameterGroups ?? []) {\n      for (const variant of group.variants) {\n        const variantClass = groupVariantClassName(group.name, variant.name);\n        if (emitted.has(variantClass)) continue;\n        emitted.add(variantClass);\n\n        lines.push('');\n        lines.push('@dataclass');\n        lines.push(`class ${variantClass}:`);\n        const readableGroup = group.name.replace(/_/g, ' ');\n        const readableVariant = variant.name.replace(/_/g, ' ');\n        lines.push(`    \"\"\"Identify ${readableGroup} ${readableVariant}.\"\"\"`);\n        for (const param of variant.parameters) {\n          const pyField = fieldName(param.name);\n          const effectiveType = bodyFieldTypes.get(param.name) ?? param.type;\n          const pyType = mapTypeRefUnquoted(effectiveType, specEnumNames, true);\n          lines.push(`    ${pyField}: ${pyType}`);\n        }\n      }\n    }\n  }\n\n  return lines;\n}\n\n/**\n * Check whether any operation has parameter groups.\n */\nfunction hasParameterGroups(operations: Operation[]): boolean {\n  return operations.some((op) => (op.parameterGroups?.length ?? 0) > 0);\n}\n\n/**\n * Collect the PascalCase class names of all parameter group variants\n * across a set of operations.  Used by client.ts to re-export these\n * dataclasses from the service __init__.py.\n */\nexport function collectParameterGroupClassNames(operations: Operation[]): string[] {\n  const names: string[] = [];\n  const seen = new Set<string>();\n  for (const op of operations) {\n    for (const group of op.parameterGroups ?? []) {\n      for (const variant of group.variants) {\n        const cls = groupVariantClassName(group.name, variant.name);\n        if (!seen.has(cls)) {\n          seen.add(cls);\n          names.push(cls);\n        }\n      }\n    }\n  }\n  return names;\n}\n\n// ─── Shared method-emission helpers ──────────────────────────────────\n\n/** Metadata returned by emitMethodSignature, consumed by docstring & body emitters. */\ninterface SignatureMetadata {\n  returnType: string;\n  pathParamNames: Set<string>;\n  isArrayResponse: boolean;\n  isRedirect: boolean;\n  hasBearerOverride: boolean;\n}\n\nfunction emitDocArg(lines: string[], name: string, desc?: string): void {\n  const fallback = `The ${name.replace(/_/g, ' ')}.`;\n  const description = desc ?? fallback;\n  const descLines = description\n    .split('\\n')\n    .map((line) => line.trim())\n    .filter((line) => line.length > 0);\n\n  if (descLines.length === 0) {\n    lines.push(`            ${name}: ${fallback}`);\n    return;\n  }\n\n  lines.push(`            ${name}: ${descLines[0]}`);\n  for (const line of descLines.slice(1)) {\n    lines.push(`                ${line}`);\n  }\n}\n\n/**\n * Emit a Python method signature (def / async def, parameters, return type).\n */\nfunction emitMethodSignature(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  isAsync: boolean,\n  specEnumNames: Set<string>,\n  modelImports: Set<string>,\n  listWrapperNames: Set<string>,\n  ctx: EmitterContext,\n  resolvedOp?: ResolvedOperation,\n): SignatureMetadata {\n  const hiddenParams = buildHiddenParams(resolvedOp);\n  const isPaginated = plan.isPaginated;\n  const isDelete = plan.isDelete;\n  // Redirect endpoints never await, so emit as plain def even in async class\n  const isRedirectOp = isRedirectEndpoint(op);\n  const defKeyword = isAsync && !isRedirectOp ? 'async def' : 'def';\n  const usesClientCredentialDefaults = false;\n\n  lines.push(`    ${defKeyword} ${method}(`);\n  lines.push('        self,');\n\n  // Path params as positional args\n  for (const param of op.pathParams) {\n    const paramName = fieldName(param.name);\n    const paramType = mapTypeRefUnquoted(param.type, specEnumNames, true);\n    lines.push(`        ${paramName}: ${paramType},`);\n  }\n\n  lines.push('        *,');\n\n  const pathParamNames = new Set(op.pathParams.map((p) => fieldName(p.name)));\n\n  // Request body fields as keyword args (rename fields that clash with path params)\n  const groupedBodyParamNames = collectGroupedParamNames(op);\n  if (plan.hasBody && op.requestBody) {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) {\n      const reqFields = bodyModel.fields.filter(\n        (f) => f.required && !hiddenParams.has(f.name) && !groupedBodyParamNames.has(f.name),\n      );\n      const optFields = bodyModel.fields.filter(\n        (f) => !f.required && !hiddenParams.has(f.name) && !groupedBodyParamNames.has(f.name),\n      );\n      for (const f of reqFields) {\n        const fieldType = mapTypeRefUnquoted(f.type, specEnumNames, true);\n        if (usesClientCredentialDefaults && (f.name === 'client_id' || f.name === 'client_secret')) {\n          lines.push(`        ${bodyParamName(f, pathParamNames)}: Optional[${fieldType}] = None,`);\n        } else {\n          lines.push(`        ${bodyParamName(f, pathParamNames)}: ${fieldType},`);\n        }\n      }\n      for (const f of optFields) {\n        const innerType =\n          f.type.kind === 'nullable'\n            ? mapTypeRefUnquoted(f.type.inner, specEnumNames, true)\n            : mapTypeRefUnquoted(f.type, specEnumNames, true);\n        lines.push(`        ${bodyParamName(f, pathParamNames)}: Optional[${innerType}] = None,`);\n      }\n    } else if (op.requestBody.kind === 'union') {\n      // Union body — accept any of the variant models or a plain dict\n      const variantModels = (op.requestBody.variants ?? [])\n        .filter((v: any) => v.kind === 'model')\n        .map((v: any) => className(v.name));\n      // Add variant models to imports\n      for (const vm of variantModels) {\n        modelImports.add(vm);\n      }\n      if (variantModels.length > 0) {\n        const unionType = `Union[${[...variantModels, 'Dict[str, Any]'].join(', ')}]`;\n        lines.push(`        body: ${unionType},`);\n      } else {\n        lines.push('        body: Dict[str, Any],');\n      }\n    } else {\n      // Non-model body — use generic dict\n      lines.push('        body: Optional[Dict[str, Any]] = None,');\n    }\n  }\n\n  // Query params for non-paginated methods\n  const groupedParamNames = collectGroupedParamNames(op);\n  if (plan.hasQueryParams && !isPaginated) {\n    for (const param of op.queryParams) {\n      if (hiddenParams.has(param.name)) continue;\n      if (groupedParamNames.has(param.name)) continue;\n      const paramName = fieldName(param.name);\n      if (pathParamNames.has(paramName)) continue;\n      // Skip query params that collide with body field names (using possibly-renamed names)\n      if (plan.hasBody && op.requestBody?.kind === 'model') {\n        const bodyModel = ctx.spec.models.find(\n          (m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name,\n        );\n        if (bodyModel?.fields.some((f) => bodyParamName(f, pathParamNames) === paramName)) continue;\n      }\n      const paramType = mapTypeRefUnquoted(param.type, specEnumNames, true);\n      if (usesClientCredentialDefaults && (param.name === 'client_id' || param.name === 'client_secret')) {\n        lines.push(`        ${paramName}: Optional[${paramType}] = None,`);\n      } else if (param.required) {\n        lines.push(`        ${paramName}: ${paramType},`);\n      } else {\n        lines.push(`        ${paramName}: Optional[${paramType}] = None,`);\n      }\n    }\n  }\n\n  // Pagination params\n  if (isPaginated) {\n    lines.push('        limit: Optional[int] = None,');\n    lines.push('        before: Optional[str] = None,');\n    lines.push('        after: Optional[str] = None,');\n    // Use typed enum for order param if the spec provides one, otherwise fall\n    // back to str. The default value comes from the spec's `default:` field;\n    // when the spec drops the default, we surface that as `None` rather than\n    // silently restoring \"desc\" client-side (which would mask a server-side\n    // behavior change from the caller).\n    const orderParam = op.queryParams.find((p) => p.name === 'order');\n    const orderType =\n      orderParam && orderParam.type.kind === 'enum' ? mapTypeRefUnquoted(orderParam.type, specEnumNames, true) : 'str';\n    const orderDefaultRaw = orderParam?.default;\n    const orderDefault =\n      typeof orderDefaultRaw === 'string' || typeof orderDefaultRaw === 'number' || typeof orderDefaultRaw === 'boolean'\n        ? pythonLiteral(orderDefaultRaw)\n        : 'None';\n    lines.push(`        order: Optional[${orderType}] = ${orderDefault},`);\n    // Additional non-pagination query params\n    for (const param of op.queryParams) {\n      if (['limit', 'before', 'after', 'order'].includes(param.name)) continue;\n      if (hiddenParams.has(param.name)) continue;\n      if (groupedParamNames.has(param.name)) continue;\n      const paramName = fieldName(param.name);\n      const paramType = mapTypeRefUnquoted(param.type, specEnumNames, true);\n      if (param.required) {\n        lines.push(`        ${paramName}: ${paramType},`);\n      } else {\n        lines.push(`        ${paramName}: Optional[${paramType}] = None,`);\n      }\n    }\n  }\n\n  // Parameter group union kwargs\n  for (const group of op.parameterGroups ?? []) {\n    const variantClasses = group.variants.map((v) => groupVariantClassName(group.name, v.name));\n    const unionType = `Union[${variantClasses.join(', ')}]`;\n    const paramName = fieldName(group.name);\n    if (group.optional) {\n      lines.push(`        ${paramName}: Optional[${unionType}] = None,`);\n    } else {\n      lines.push(`        ${paramName}: ${unionType},`);\n    }\n  }\n\n  // Idempotency key for idempotent POSTs\n  if (plan.isIdempotentPost) {\n    lines.push('        idempotency_key: Optional[str] = None,');\n  }\n\n  // Per-operation Bearer token auth (e.g., SSO.get_profile uses access_token instead of API key)\n  const hasBearerOverride = op.security?.some((s) => s.schemeName !== 'bearerAuth') ?? false;\n  if (hasBearerOverride) {\n    const tokenParamName = op.security!.find((s) => s.schemeName !== 'bearerAuth')!.schemeName;\n    lines.push(`        ${fieldName(tokenParamName)}: str,`);\n  }\n\n  lines.push('        request_options: Optional[RequestOptions] = None,');\n\n  // Detect array response type\n  const isArrayResponse = op.response.kind === 'array' && op.response.items.kind === 'model';\n  const isRedirect = isRedirectEndpoint(op);\n\n  // Return type\n  const pageType = isAsync ? 'AsyncPage' : 'SyncPage';\n  let returnType: string;\n  if (isDelete) {\n    returnType = 'None';\n  } else if (isRedirect) {\n    returnType = 'str';\n  } else if (isPaginated) {\n    const resolvedItem = resolvePageItemName(op.pagination!.itemType, listWrapperNames, ctx);\n    const resolvedItemModel = ctx.spec.models.find((m) => m.name === resolvedItem);\n    const itemTypeName = (resolvedItemModel as any)?.discriminator\n      ? className(resolvedItem) + 'Variant'\n      : className(resolvedItem);\n    returnType = `${pageType}[${itemTypeName}]`;\n  } else if (isArrayResponse) {\n    const arrayItemModel = ctx.spec.models.find((m) => m.name === plan.responseModelName);\n    const arrayItemTypeName = (arrayItemModel as any)?.discriminator\n      ? className(plan.responseModelName!) + 'Variant'\n      : className(plan.responseModelName!);\n    returnType = `List[${arrayItemTypeName}]`;\n  } else if (plan.responseModelName) {\n    const singleResponseModel = ctx.spec.models.find((m) => m.name === plan.responseModelName);\n    returnType = (singleResponseModel as any)?.discriminator\n      ? className(plan.responseModelName) + 'Variant'\n      : className(plan.responseModelName);\n  } else {\n    returnType = 'None';\n  }\n\n  lines.push(`    ) -> ${returnType}:`);\n\n  return { returnType, pathParamNames, isArrayResponse, isRedirect, hasBearerOverride };\n}\n\n/**\n * Emit a Python method docstring (description, Args, Returns, Raises).\n * Identical for sync and async — no isAsync parameter needed.\n */\nfunction emitMethodDocstring(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  method: string,\n  meta: SignatureMetadata,\n  specEnumNames: Set<string>,\n  ctx: EmitterContext,\n  resolvedOp?: ResolvedOperation,\n): void {\n  const { returnType, pathParamNames, hasBearerOverride } = meta;\n  const isPaginated = plan.isPaginated;\n  const hiddenParams = buildHiddenParams(resolvedOp);\n\n  // Description — indent continuation lines to align with the opening `\"\"\"`\n  if (op.description) {\n    const descLines = op.description.split('\\n');\n    const indentedDesc = descLines\n      .map((line, i) => (i === 0 ? line : line.trim() === '' ? '' : `        ${line}`))\n      .join('\\n');\n    lines.push(`        \"\"\"${indentedDesc}`);\n  } else {\n    lines.push(`        \"\"\"${toPascalCase(method.replace(/_/g, ' '))} operation.`);\n  }\n\n  // Args section\n  const allParams: { name: string; desc?: string }[] = op.pathParams.map((p) => ({\n    name: fieldName(p.name),\n    desc: p.deprecated ? (p.description ? `(deprecated) ${p.description}` : '(deprecated)') : p.description,\n  }));\n\n  // Add body model fields to docs\n  const groupedDocBodyParams = collectGroupedParamNames(op);\n  if (plan.hasBody && op.requestBody) {\n    if (op.requestBody.kind === 'model') {\n      const requestBodyName = op.requestBody.name;\n      const bodyModel = ctx.spec.models.find((m) => m.name === requestBodyName);\n      if (bodyModel) {\n        for (const f of bodyModel.fields) {\n          if (hiddenParams.has(f.name)) continue;\n          if (groupedDocBodyParams.has(f.name)) continue;\n          allParams.push({\n            name: bodyParamName(f, pathParamNames),\n            desc: f.deprecated ? (f.description ? `(deprecated) ${f.description}` : '(deprecated)') : f.description,\n          });\n        }\n      }\n    } else if (op.requestBody.kind === 'union') {\n      // Union body — document the body parameter with the accepted variant types\n      const variantModels = (op.requestBody.variants ?? [])\n        .filter((v: any) => v.kind === 'model')\n        .map((v: any) => className(v.name));\n      const desc =\n        variantModels.length > 0\n          ? `The request body. Accepts: ${variantModels.join(', ')}, or a plain dict.`\n          : 'The request body.';\n      allParams.push({ name: 'body', desc });\n    }\n  }\n\n  // Add query params for non-paginated methods\n  const groupedDocParams = collectGroupedParamNames(op);\n  if (plan.hasQueryParams && !isPaginated) {\n    for (const param of op.queryParams) {\n      if (hiddenParams.has(param.name)) continue;\n      if (groupedDocParams.has(param.name)) continue;\n      const pn = fieldName(param.name);\n      if (pathParamNames.has(pn)) continue;\n      // Skip params already documented from body fields\n      if (allParams.some((p) => p.name === pn)) continue;\n      let desc = param.deprecated\n        ? param.description\n          ? `(deprecated) ${param.description}`\n          : '(deprecated)'\n        : param.description;\n      if (param.default != null) {\n        const defaultStr = `Defaults to \\`${param.default}\\`.`;\n        desc = desc ? `${desc} ${defaultStr}` : defaultStr;\n      }\n      allParams.push({ name: pn, desc });\n    }\n  }\n\n  // Add extra non-standard pagination query params\n  if (isPaginated) {\n    for (const paramName of ['limit', 'before', 'after', 'order']) {\n      const param = op.queryParams.find((p) => p.name === paramName);\n      let desc = param?.description;\n      if (param?.default != null) {\n        const defaultStr = `Defaults to \\`${param.default}\\`.`;\n        desc = desc ? `${desc} ${defaultStr}` : defaultStr;\n      }\n      allParams.push({\n        name: fieldName(paramName),\n        desc,\n      });\n    }\n    for (const param of op.queryParams) {\n      if (['limit', 'before', 'after', 'order'].includes(param.name)) continue;\n      if (groupedDocParams.has(param.name)) continue;\n      let desc = param.deprecated\n        ? param.description\n          ? `(deprecated) ${param.description}`\n          : '(deprecated)'\n        : param.description;\n      if (param.default != null) {\n        const defaultStr = `Defaults to \\`${param.default}\\`.`;\n        desc = desc ? `${desc} ${defaultStr}` : defaultStr;\n      }\n      allParams.push({ name: fieldName(param.name), desc });\n    }\n  }\n\n  // Add parameter group docs\n  for (const group of op.parameterGroups ?? []) {\n    const variantClasses = group.variants.map((v) => groupVariantClassName(group.name, v.name));\n    const readableGroup = group.name.replace(/_/g, ' ');\n    const desc = `Identifies the ${readableGroup}. One of: ${variantClasses.join(', ')}.`;\n    allParams.push({ name: fieldName(group.name), desc });\n  }\n\n  // Add idempotency key parameter to docs\n  if (plan.isIdempotentPost) {\n    allParams.push({ name: 'idempotency_key', desc: 'Optional idempotency key for safe retries.' });\n  }\n\n  // Add bearer override parameter to docs (e.g., access_token for SSO)\n  if (hasBearerOverride) {\n    const tokenParamName = fieldName(op.security!.find((s) => s.schemeName !== 'bearerAuth')!.schemeName);\n    allParams.push({ name: tokenParamName, desc: 'The bearer token for authentication.' });\n  }\n\n  if (allParams.length > 0 || isPaginated) {\n    lines.push('');\n    lines.push('        Args:');\n    for (const p of allParams) {\n      emitDocArg(lines, p.name, p.desc);\n    }\n    lines.push(\n      '            request_options: Per-request options. Supports extra_headers, timeout, max_retries, and base_url override.',\n    );\n  }\n\n  if (returnType !== 'None') {\n    lines.push('');\n    lines.push('        Returns:');\n    lines.push(`            ${returnType}`);\n  }\n\n  // Per-operation error documentation from spec error responses\n  const errorRaises = buildErrorRaisesBlock(op);\n  lines.push('');\n  lines.push('        Raises:');\n  for (const line of errorRaises) {\n    lines.push(`            ${line}`);\n  }\n  if (op.deprecated) {\n    lines.push('');\n    lines.push('        .. deprecated::');\n    lines.push('            This operation is deprecated. See the migration guide for alternatives.');\n  }\n  lines.push('        \"\"\"');\n}\n\n/**\n * Emit the Python method body (auth override, path building, request call).\n */\nfunction emitMethodBody(\n  lines: string[],\n  op: Operation,\n  plan: OperationPlan,\n  meta: SignatureMetadata,\n  isAsync: boolean,\n  modelImports: Set<string>,\n  listWrapperNames: Set<string>,\n  ctx: EmitterContext,\n  resolvedOp?: ResolvedOperation,\n): void {\n  const { pathParamNames, isArrayResponse, isRedirect, hasBearerOverride } = meta;\n  const isPaginated = plan.isPaginated;\n  const awaitPrefix = isAsync ? 'await ' : '';\n  const usesClientCredentialDefaults = false;\n  const hiddenParams = buildHiddenParams(resolvedOp);\n  const opDefaults = getOpDefaults(resolvedOp);\n  const opInferFromClient = getOpInferFromClient(resolvedOp);\n\n  if (op.deprecated) {\n    const method = toSnakeCase(op.name);\n    lines.push(`        warnings.warn(\"${method} is deprecated\", DeprecationWarning, stacklevel=2)`);\n  }\n\n  // Method body — build path\n  const pathStr = buildPathString(op);\n  const httpMethod = op.httpMethod;\n\n  // Emit auth override for per-operation Bearer token security\n  if (hasBearerOverride) {\n    const tokenParamName = fieldName(op.security!.find((s) => s.schemeName !== 'bearerAuth')!.schemeName);\n    lines.push(`        request_options = request_options or {}`);\n    lines.push(\n      `        request_options = {**request_options, \"extra_headers\": {**(request_options.get(\"extra_headers\") or {}), \"Authorization\": f\"Bearer {${tokenParamName}}\"}}`,\n    );\n  }\n\n  if (isRedirect) {\n    // Redirect endpoint: construct URL client-side instead of making HTTP request\n    const bodyModel =\n      plan.hasBody && op.requestBody?.kind === 'model'\n        ? ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name)\n        : undefined;\n    const redirectParamEntries: { key: string; varName: string }[] = [];\n    if (bodyModel) {\n      for (const f of bodyModel.fields) {\n        if (hiddenParams.has(f.name)) continue;\n        redirectParamEntries.push({ key: f.name, varName: bodyParamName(f, pathParamNames) });\n      }\n    }\n    for (const param of op.queryParams) {\n      if (hiddenParams.has(param.name)) continue;\n      const pn = fieldName(param.name);\n      if (!redirectParamEntries.some((e) => e.varName === pn)) {\n        redirectParamEntries.push({ key: param.name, varName: pn });\n      }\n    }\n    const hasHiddenInjections =\n      (opDefaults && Object.keys(opDefaults).length > 0) || (opInferFromClient && opInferFromClient.length > 0);\n    if (redirectParamEntries.length > 0 || hasHiddenInjections) {\n      lines.push('        params = {k: v for k, v in {');\n      for (const entry of redirectParamEntries) {\n        const param = op.queryParams.find((p) => p.name === entry.key);\n        const value = param\n          ? serializeParameterValue(param.type, entry.varName, false, (param as ParameterExt).explode)\n          : entry.varName;\n        lines.push(`            \"${entry.key}\": ${value},`);\n      }\n      lines.push('        }.items() if v is not None}');\n      // Inject constant defaults\n      if (Object.keys(opDefaults).length > 0) {\n        for (const [key, value] of Object.entries(opDefaults)) {\n          lines.push(`        params[\"${key}\"] = ${pythonLiteral(value)}`);\n        }\n      }\n      // Inject fields from client config\n      if (opInferFromClient.length > 0) {\n        for (const field of opInferFromClient) {\n          const expr = clientFieldExpression(field);\n          lines.push(`        if ${expr} is not None:`);\n          lines.push(`            params[\"${field}\"] = ${expr}`);\n        }\n      }\n      if (usesClientCredentialDefaults) {\n        if (op.queryParams.some((param) => param.name === 'client_id')) {\n          lines.push('        params[\"client_id\"] = params.get(\"client_id\") or self._client._require_client_id()');\n        }\n        if (op.queryParams.some((param) => param.name === 'client_secret')) {\n          lines.push(\n            '        params[\"client_secret\"] = params.get(\"client_secret\") or self._client._require_api_key()',\n          );\n        }\n      }\n      lines.push(`        return self._client.build_url(${pathStr}, params)`);\n    } else {\n      lines.push(`        return self._client.build_url(${pathStr})`);\n    }\n  } else if (isPaginated) {\n    const resolvedItemName = resolvePageItemName(op.pagination!.itemType, listWrapperNames, ctx);\n    const itemTypeClass = className(resolvedItemName);\n    const resolvedItemModel = ctx.spec.models.find((m) => m.name === resolvedItemName);\n    const isDiscriminatorModel = !!(resolvedItemModel as any)?.discriminator;\n    const variantTypeName = isDiscriminatorModel ? itemTypeClass + 'Variant' : null;\n    const pageType = isAsync ? 'AsyncPage' : 'SyncPage';\n    const orderParam = op.queryParams.find((p) => p.name === 'order');\n    // Build query params dict\n    lines.push('        params = {k: v for k, v in {');\n    lines.push('            \"limit\": limit,');\n    lines.push('            \"before\": before,');\n    lines.push('            \"after\": after,');\n    lines.push(\n      `            \"order\": ${serializeParameterValue(orderParam?.type, 'order', false, (orderParam as ParameterExt | undefined)?.explode)},`,\n    );\n    const paginatedGroupedParams = collectGroupedParamNames(op);\n    for (const param of op.queryParams) {\n      if (['limit', 'before', 'after', 'order'].includes(param.name)) continue;\n      if (hiddenParams.has(param.name)) continue;\n      if (paginatedGroupedParams.has(param.name)) continue;\n      const pn = fieldName(param.name);\n      const value = serializeParameterValue(param.type, pn, param.required, (param as ParameterExt).explode);\n      lines.push(`            \"${param.name}\": ${value},`);\n    }\n    lines.push('        }.items() if v is not None}');\n    // Inject constant defaults\n    if (Object.keys(opDefaults).length > 0) {\n      for (const [key, value] of Object.entries(opDefaults)) {\n        lines.push(`        params[\"${key}\"] = ${pythonLiteral(value)}`);\n      }\n    }\n    // Inject fields from client config\n    if (opInferFromClient.length > 0) {\n      for (const field of opInferFromClient) {\n        const expr = clientFieldExpression(field);\n        lines.push(`        if ${expr} is not None:`);\n        lines.push(`            params[\"${field}\"] = ${expr}`);\n      }\n    }\n    // isinstance dispatch for parameter groups\n    emitGroupDispatch(lines, op);\n    if (isDiscriminatorModel && variantTypeName) {\n      // Dispatcher model: cast the page to the variant union type so callers get\n      // rich type information when iterating events.\n      lines.push(`        return cast(`);\n      lines.push(`            ${pageType}[${variantTypeName}],`);\n      lines.push(`            ${awaitPrefix}self._client.request_page(`);\n      lines.push(`                method=\"${httpMethod}\",`);\n      lines.push(`                path=${pathStr},`);\n      lines.push(\n        `                model=${itemTypeClass},  # type: ignore[arg-type]  # dispatcher; pagination only calls from_dict`,\n      );\n      lines.push('                params=params,');\n      lines.push('                request_options=request_options,');\n      lines.push('            )');\n      lines.push('        )');\n    } else {\n      lines.push(`        return ${awaitPrefix}self._client.request_page(`);\n      lines.push(`            method=\"${httpMethod}\",`);\n      lines.push(`            path=${pathStr},`);\n      lines.push(`            model=${itemTypeClass},`);\n      lines.push('            params=params,');\n      lines.push('            request_options=request_options,');\n      lines.push('        )');\n    }\n  } else if (plan.isDelete) {\n    // Build body dict if the DELETE has a request body\n    const deleteGroupedParams = collectGroupedParamNames(op);\n    const deleteBodyFieldNames = new Set<string>();\n    if (plan.hasBody && op.requestBody) {\n      const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n      if (bodyModel) {\n        const bodyFields = bodyModel.fields.filter(\n          (f) => !hiddenParams.has(f.name) && !deleteGroupedParams.has(f.name),\n        );\n        for (const f of bodyFields) deleteBodyFieldNames.add(bodyParamName(f, pathParamNames));\n        const hasOptionalBodyFields = bodyFields.some((f) => !f.required);\n        if (bodyFields.length > 0 && hasOptionalBodyFields) {\n          lines.push('        body: Dict[str, Any] = {k: v for k, v in {');\n          for (const f of bodyFields) {\n            lines.push(\n              `            \"${f.name}\": ${serializeBodyFieldValue(f.type, bodyParamName(f, pathParamNames), f.required)},`,\n            );\n          }\n          lines.push('        }.items() if v is not None}');\n        } else if (bodyFields.length > 0) {\n          lines.push('        body: Dict[str, Any] = {');\n          for (const f of bodyFields) {\n            lines.push(\n              `            \"${f.name}\": ${serializeBodyFieldValue(f.type, bodyParamName(f, pathParamNames), f.required)},`,\n            );\n          }\n          lines.push('        }');\n        }\n        // Inject constant defaults into body\n        if (Object.keys(opDefaults).length > 0) {\n          for (const [key, value] of Object.entries(opDefaults)) {\n            lines.push(`        body[\"${key}\"] = ${pythonLiteral(value)}`);\n          }\n        }\n        // Inject fields from client config into body\n        if (opInferFromClient.length > 0) {\n          for (const field of opInferFromClient) {\n            const expr = clientFieldExpression(field);\n            lines.push(`        if ${expr} is not None:`);\n            lines.push(`            body[\"${field}\"] = ${expr}`);\n          }\n        }\n        // isinstance dispatch for parameter groups into body\n        emitGroupDispatch(lines, op, 'body', collectBodyFieldTypes(op, ctx.spec.models));\n      }\n    }\n    // Build query params dict if any exist alongside the body/path\n    const deleteHasParams =\n      plan.hasQueryParams && emitQueryParamsDict(lines, op, pathParamNames, deleteBodyFieldNames, hiddenParams);\n    lines.push(`        ${awaitPrefix}self._client.request(`);\n    lines.push(`            method=\"${httpMethod}\",`);\n    lines.push(`            path=${pathStr},`);\n    if (plan.hasBody && op.requestBody) {\n      lines.push('            body=body,');\n    }\n    if (deleteHasParams) {\n      lines.push('            params=params,');\n    }\n    lines.push('            request_options=request_options,');\n    lines.push('        )');\n  } else if (plan.hasBody && op.requestBody) {\n    const responseModel = plan.responseModelName ? className(plan.responseModelName) : 'None';\n    const bodyResponseModelObj = plan.responseModelName\n      ? ctx.spec.models.find((m) => m.name === plan.responseModelName)\n      : null;\n    const isBodyResponseDiscriminator = !!(bodyResponseModelObj as any)?.discriminator;\n    // Build body dict\n    const bodyGroupedParams = collectGroupedParamNames(op);\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    const bodyFieldNamesSet = new Set<string>();\n    if (bodyModel) {\n      const bodyFields = bodyModel.fields.filter((f) => !hiddenParams.has(f.name) && !bodyGroupedParams.has(f.name));\n      for (const f of bodyFields) bodyFieldNamesSet.add(bodyParamName(f, pathParamNames));\n      const hasOptionalBodyFields = bodyFields.some((f) => !f.required);\n      if (bodyFields.length > 0 && hasOptionalBodyFields) {\n        lines.push('        body: Dict[str, Any] = {k: v for k, v in {');\n        for (const f of bodyFields) {\n          lines.push(\n            `            \"${f.name}\": ${serializeBodyFieldValue(f.type, bodyParamName(f, pathParamNames), f.required)},`,\n          );\n        }\n        lines.push('        }.items() if v is not None}');\n      } else if (bodyFields.length > 0) {\n        lines.push('        body: Dict[str, Any] = {');\n        for (const f of bodyFields) {\n          lines.push(\n            `            \"${f.name}\": ${serializeBodyFieldValue(f.type, bodyParamName(f, pathParamNames), f.required)},`,\n          );\n        }\n        lines.push('        }');\n      } else {\n        lines.push('        body: Dict[str, Any] = {}');\n      }\n      // Inject constant defaults into body\n      if (Object.keys(opDefaults).length > 0) {\n        for (const [key, value] of Object.entries(opDefaults)) {\n          lines.push(`        body[\"${key}\"] = ${pythonLiteral(value)}`);\n        }\n      }\n      // Inject fields from client config into body\n      if (opInferFromClient.length > 0) {\n        for (const field of opInferFromClient) {\n          const expr = clientFieldExpression(field);\n          lines.push(`        if ${expr} is not None:`);\n          lines.push(`            body[\"${field}\"] = ${expr}`);\n        }\n      }\n      // isinstance dispatch for parameter groups into body\n      emitGroupDispatch(lines, op, 'body', collectBodyFieldTypes(op, ctx.spec.models));\n    } else {\n      // Union or non-model body — convert model instances to dicts\n      lines.push('        _body: Dict[str, Any] = body if isinstance(body, dict) else body.to_dict()');\n    }\n    // Build query params dict if any exist alongside the body\n    const bodyHasParams =\n      plan.hasQueryParams && emitQueryParamsDict(lines, op, pathParamNames, bodyFieldNamesSet, hiddenParams);\n    const bodyVarName = bodyModel ? 'body' : '_body';\n    if (bodyModel && usesClientCredentialDefaults) {\n      if (bodyModel.fields.some((f) => f.name === 'client_id')) {\n        lines.push('        body[\"client_id\"] = body.get(\"client_id\") or self._client._require_client_id()');\n      }\n      if (bodyModel.fields.some((f) => f.name === 'client_secret')) {\n        lines.push('        body[\"client_secret\"] = body.get(\"client_secret\") or self._client._require_api_key()');\n      }\n    }\n    if (isArrayResponse) {\n      // Array response with body: request_list returns List[Dict], then deserialize each item\n      const itemModel = className(plan.responseModelName!);\n      lines.push(`        raw = ${awaitPrefix}self._client.request_list(`);\n      lines.push(`            method=\"${httpMethod}\",`);\n      lines.push(`            path=${pathStr},`);\n      lines.push(`            body=${bodyVarName},`);\n      if (bodyHasParams) {\n        lines.push('            params=params,');\n      }\n      if (plan.isIdempotentPost) {\n        lines.push('            idempotency_key=idempotency_key,');\n      }\n      lines.push('            request_options=request_options,');\n      lines.push('        )');\n      lines.push(`        return [${itemModel}.from_dict(cast(Dict[str, Any], item)) for item in raw]`);\n    } else if (isBodyResponseDiscriminator && responseModel !== 'None') {\n      const variantType = responseModel + 'Variant';\n      lines.push(`        return cast(`);\n      lines.push(`            ${variantType},`);\n      lines.push(`            ${awaitPrefix}self._client.request(`);\n      lines.push(`                method=\"${httpMethod}\",`);\n      lines.push(`                path=${pathStr},`);\n      lines.push(`                body=${bodyVarName},`);\n      if (bodyHasParams) {\n        lines.push('                params=params,');\n      }\n      lines.push(\n        `                model=${responseModel},  # type: ignore[arg-type]  # dispatcher; request only calls from_dict`,\n      );\n      if (plan.isIdempotentPost) {\n        lines.push('                idempotency_key=idempotency_key,');\n      }\n      lines.push('                request_options=request_options,');\n      lines.push('            )');\n      lines.push('        )');\n    } else {\n      const bodyReturnPrefix = responseModel !== 'None' ? 'return ' : '';\n      lines.push(`        ${bodyReturnPrefix}${awaitPrefix}self._client.request(`);\n      lines.push(`            method=\"${httpMethod}\",`);\n      lines.push(`            path=${pathStr},`);\n      lines.push(`            body=${bodyVarName},`);\n      if (bodyHasParams) {\n        lines.push('            params=params,');\n      }\n      if (responseModel !== 'None') {\n        lines.push(`            model=${responseModel},`);\n      }\n      if (plan.isIdempotentPost) {\n        lines.push('            idempotency_key=idempotency_key,');\n      }\n      lines.push('            request_options=request_options,');\n      lines.push('        )');\n    }\n  } else {\n    // GET or similar with query params\n    const responseModel = plan.responseModelName ? className(plan.responseModelName) : 'None';\n    const getResponseModelObj = plan.responseModelName\n      ? ctx.spec.models.find((m) => m.name === plan.responseModelName)\n      : null;\n    const isGetResponseDiscriminator = !!(getResponseModelObj as any)?.discriminator;\n    const getGroupedParams = collectGroupedParamNames(op);\n    const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n    const visibleQueryParams = op.queryParams.filter((p) => !hiddenParams.has(p.name) && !getGroupedParams.has(p.name));\n    const hasVisibleQueryParams = plan.hasQueryParams && visibleQueryParams.length > 0;\n    const hasInjections =\n      (opDefaults && Object.keys(opDefaults).length > 0) || (opInferFromClient && opInferFromClient.length > 0);\n    const needsParamsDict = hasVisibleQueryParams || hasInjections || hasGroups;\n    if (needsParamsDict) {\n      const hasOptionalQueryParams = visibleQueryParams.some((p) => !p.required);\n      if (hasOptionalQueryParams) {\n        lines.push('        params: Dict[str, Any] = {k: v for k, v in {');\n        for (const param of visibleQueryParams) {\n          const pn = fieldName(param.name);\n          const value = serializeParameterValue(param.type, pn, param.required, (param as ParameterExt).explode);\n          lines.push(`            \"${param.name}\": ${value},`);\n        }\n        lines.push('        }.items() if v is not None}');\n      } else if (visibleQueryParams.length > 0) {\n        lines.push('        params: Dict[str, Any] = {');\n        for (const param of visibleQueryParams) {\n          const pn = fieldName(param.name);\n          const value = serializeParameterValue(param.type, pn, param.required, (param as ParameterExt).explode);\n          lines.push(`            \"${param.name}\": ${value},`);\n        }\n        lines.push('        }');\n      } else {\n        // No visible query params but we have injections or groups — start with empty dict\n        lines.push('        params: Dict[str, Any] = {}');\n      }\n      // Inject constant defaults\n      if (Object.keys(opDefaults).length > 0) {\n        for (const [key, value] of Object.entries(opDefaults)) {\n          lines.push(`        params[\"${key}\"] = ${pythonLiteral(value)}`);\n        }\n      }\n      // Inject fields from client config\n      if (opInferFromClient.length > 0) {\n        for (const field of opInferFromClient) {\n          const expr = clientFieldExpression(field);\n          lines.push(`        if ${expr} is not None:`);\n          lines.push(`            params[\"${field}\"] = ${expr}`);\n        }\n      }\n      if (usesClientCredentialDefaults) {\n        if (op.queryParams.some((param) => param.name === 'client_id')) {\n          lines.push('        params[\"client_id\"] = params.get(\"client_id\") or self._client._require_client_id()');\n        }\n        if (op.queryParams.some((param) => param.name === 'client_secret')) {\n          lines.push(\n            '        params[\"client_secret\"] = params.get(\"client_secret\") or self._client._require_api_key()',\n          );\n        }\n      }\n      // isinstance dispatch for parameter groups\n      emitGroupDispatch(lines, op);\n    }\n    const emittedParams = needsParamsDict;\n    if (isArrayResponse) {\n      // Array response: request_list returns List[Dict], then deserialize each item\n      const itemModel = className(plan.responseModelName!);\n      lines.push(`        raw = ${awaitPrefix}self._client.request_list(`);\n      lines.push(`            method=\"${httpMethod}\",`);\n      lines.push(`            path=${pathStr},`);\n      if (emittedParams) {\n        lines.push('            params=params,');\n      }\n      lines.push('            request_options=request_options,');\n      lines.push('        )');\n      lines.push(`        return [${itemModel}.from_dict(cast(Dict[str, Any], item)) for item in raw]`);\n    } else if (isGetResponseDiscriminator && responseModel !== 'None') {\n      const variantType = responseModel + 'Variant';\n      lines.push(`        return cast(`);\n      lines.push(`            ${variantType},`);\n      lines.push(`            ${awaitPrefix}self._client.request(`);\n      lines.push(`                method=\"${httpMethod}\",`);\n      lines.push(`                path=${pathStr},`);\n      if (emittedParams) {\n        lines.push('                params=params,');\n      }\n      lines.push(\n        `                model=${responseModel},  # type: ignore[arg-type]  # dispatcher; request only calls from_dict`,\n      );\n      lines.push('                request_options=request_options,');\n      lines.push('            )');\n      lines.push('        )');\n    } else {\n      const returnPrefix = responseModel !== 'None' ? 'return ' : '';\n      lines.push(`        ${returnPrefix}${awaitPrefix}self._client.request(`);\n      lines.push(`            method=\"${httpMethod}\",`);\n      lines.push(`            path=${pathStr},`);\n      if (emittedParams) {\n        lines.push('            params=params,');\n      }\n      if (responseModel !== 'None') {\n        lines.push(`            model=${responseModel},`);\n      }\n      lines.push('            request_options=request_options,');\n      lines.push('        )');\n    }\n  }\n}\n\n/**\n * Emit isinstance dispatch blocks for all parameter groups on an operation.\n * Each group produces a chain of if/elif branches that test the group kwarg\n * against each variant dataclass and serializes the variant's parameters\n * into the target dict using their wire names.\n *\n * @param target - The Python dict variable to write into (e.g., \"params\" or \"body\").\n */\nfunction emitGroupDispatch(\n  lines: string[],\n  op: Operation,\n  target = 'params',\n  bodyFieldTypes?: Map<string, TypeRef>,\n): void {\n  for (const group of op.parameterGroups ?? []) {\n    const groupParam = fieldName(group.name);\n    if (group.optional) {\n      lines.push(`        if ${groupParam} is not None:`);\n    }\n    const indent = group.optional ? '    ' : '';\n    let first = true;\n    for (const variant of group.variants) {\n      const variantClass = groupVariantClassName(group.name, variant.name);\n      const keyword = first ? 'if' : 'elif';\n      first = false;\n      lines.push(`        ${indent}${keyword} isinstance(${groupParam}, ${variantClass}):`);\n      for (const param of variant.parameters) {\n        const pyField = fieldName(param.name);\n        const resolvedType = bodyFieldTypes?.get(param.name) ?? param.type;\n        const effectiveType = resolvedType.kind === 'nullable' ? resolvedType.inner : resolvedType;\n        const isEnum = effectiveType.kind === 'enum';\n        const value = isEnum ? `enum_value(${groupParam}.${pyField})` : `${groupParam}.${pyField}`;\n        lines.push(`            ${indent}${target}[\"${param.name}\"] = ${value}`);\n      }\n    }\n  }\n}\n\n// ─── Main generator ──────────────────────────────────────────────────\n\n/**\n * Generate Python resource class files from IR Service definitions.\n * Uses mount-based grouping: one resource file per mount target with all\n * co-mounted operations merged (flat pattern matching PHP).\n */\nexport function generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n  if (services.length === 0) return [];\n\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const files: GeneratedFile[] = [];\n  const mountDirMap = buildMountDirMap(ctx);\n  const mountGroups = scopedMountGroups(ctx);\n\n  // Build mount group entries. When resolved operations are available, group by\n  // mount target. Otherwise fall back to one group per service (for tests).\n  const entries: Array<{ name: string; operations: Operation[] }> =\n    mountGroups.size > 0 || ctx.scopedServices?.size\n      ? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations }))\n      : services.map((s) => ({ name: resolveClassName(s, ctx), operations: s.operations }));\n\n  const exportedClasses = buildExportedClassNameSet(ctx);\n  for (const { name: mountName, operations: allOperations } of entries) {\n    if (allOperations.length === 0) continue;\n    const dirName = moduleName(mountName);\n    const resourceClassName = className(resolveServiceTarget(mountName, exportedClasses));\n    const importPrefix = relativeImportPrefix(dirName);\n\n    const lines: string[] = [];\n    lines.push('from __future__ import annotations');\n    lines.push('');\n    lines.push('from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type, Union, cast');\n\n    lines.push('');\n    lines.push('if TYPE_CHECKING:');\n    lines.push(`    from ${importPrefix}_client import AsyncWorkOSClient, WorkOSClient`);\n    lines.push('');\n\n    const hasDeprecatedOps = allOperations.some((op) => op.deprecated);\n    if (hasDeprecatedOps) {\n      lines.push('import warnings');\n      lines.push('');\n    }\n\n    // Collect all model and enum imports needed\n    const modelImports = new Set<string>();\n    const enumImports = new Set<string>();\n\n    // Build a set of list wrapper model names to skip\n    const listWrapperNames = new Set<string>();\n    for (const m of ctx.spec.models) {\n      const dataField = m.fields.find((f) => f.name === 'data');\n      const hasListMeta = m.fields.some((f) => f.name === 'list_metadata' || f.name === 'listMetadata');\n      if (dataField && hasListMeta && dataField.type.kind === 'array') {\n        listWrapperNames.add(m.name);\n      }\n    }\n\n    for (const op of allOperations) {\n      const plan = planOperation(op);\n      if (plan.responseModelName) {\n        // List-wrapper responses are normally replaced by SyncPage on paginated\n        // ops, so the wrapper itself is never referenced. On non-paginated ops\n        // (e.g. `GET /vault/v1/kv/{id}/versions` → `VersionListResponse`) the\n        // resource method still returns the wrapper by name and must import it.\n        if (!listWrapperNames.has(plan.responseModelName) || !plan.isPaginated) {\n          modelImports.add(plan.responseModelName);\n        }\n        // For discriminator (dispatcher) models also import the variant union type alias\n        if (!plan.isPaginated) {\n          const responseModelObj = ctx.spec.models.find((m) => m.name === plan.responseModelName);\n          if ((responseModelObj as any)?.discriminator) {\n            modelImports.add(plan.responseModelName + 'Variant');\n          }\n        }\n      }\n      if (op.requestBody?.kind === 'model') {\n        const requestBodyRef = op.requestBody;\n        modelImports.add(requestBodyRef.name);\n        // Also collect types from body model fields (expanded as keyword params)\n        const bodyModel = ctx.spec.models.find((m) => m.name === requestBodyRef.name);\n        if (bodyModel) {\n          const importGroupedParams = collectGroupedParamNames(op);\n          for (const f of bodyModel.fields) {\n            if (importGroupedParams.has(f.name)) continue;\n            for (const ref of collectModelRefs(f.type)) modelImports.add(ref);\n            for (const ref of collectEnumRefs(f.type)) enumImports.add(ref);\n          }\n        }\n      }\n      // Collect from params\n      for (const p of [...op.pathParams, ...op.queryParams]) {\n        for (const ref of collectEnumRefs(p.type)) {\n          enumImports.add(ref);\n        }\n      }\n      if (op.requestBody) {\n        for (const ref of collectModelRefs(op.requestBody)) {\n          modelImports.add(ref);\n        }\n        for (const ref of collectEnumRefs(op.requestBody)) {\n          enumImports.add(ref);\n        }\n      }\n      if (op.pagination?.itemType.kind === 'model') {\n        let paginationItemName = op.pagination.itemType.name;\n        // Unwrap list wrapper models to their inner item type for imports\n        if (listWrapperNames.has(paginationItemName)) {\n          const wrapperModel = ctx.spec.models.find((m) => m.name === paginationItemName);\n          const dataField = wrapperModel?.fields.find((f) => f.name === 'data');\n          if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n            paginationItemName = dataField.type.items.name;\n          }\n        }\n        modelImports.add(paginationItemName);\n        // For discriminator (dispatcher) models also import the variant union type alias\n        const paginationItemModel = ctx.spec.models.find((m) => m.name === paginationItemName);\n        if ((paginationItemModel as any)?.discriminator) {\n          modelImports.add(paginationItemName + 'Variant');\n        }\n      }\n      // Collect model imports for union split wrapper response types\n      const resolved = lookupResolved(op, resolvedLookup);\n      if (resolved?.wrappers) {\n        for (const w of resolved.wrappers) {\n          if (w.responseModelName) modelImports.add(w.responseModelName);\n        }\n      }\n    }\n\n    // Filter enum imports to only those that actually exist in the spec\n    const specEnumNames = new Set(ctx.spec.enums.map((e) => e.name));\n    for (const name of enumImports) {\n      if (!specEnumNames.has(name)) enumImports.delete(name);\n    }\n\n    if (enumImports.size > 0) {\n      lines.push(`from ${importPrefix}_types import RequestOptions, enum_value`);\n    } else {\n      lines.push(`from ${importPrefix}_types import RequestOptions`);\n    }\n    const actualModelImports = [...modelImports];\n\n    // Split imports into same-service and cross-service (using mount-based dirs)\n    const placement = computeSchemaPlacement(ctx.spec, ctx);\n    const modelToServiceMap = new Map(placement.modelToService);\n    // Discriminator variant type aliases (e.g. EventSchemaVariant) live in the same\n    // service as their dispatcher model, so ensure they resolve to the same directory.\n    for (const model of ctx.spec.models) {\n      if ((model as any).discriminator) {\n        const svc = modelToServiceMap.get(model.name);\n        if (svc) modelToServiceMap.set(model.name + 'Variant', svc);\n      }\n    }\n    const resolveModelDir = (modelName: string) => {\n      const svc = modelToServiceMap.get(modelName);\n      return svc ? (mountDirMap.get(svc) ?? 'common') : 'common';\n    };\n\n    const localModels: string[] = [];\n    const crossServiceModels = new Map<string, string[]>(); // dir -> names\n\n    for (const name of actualModelImports.sort()) {\n      const modelDir = resolveModelDir(name);\n      if (modelDir === dirName) {\n        localModels.push(name);\n      } else {\n        if (!crossServiceModels.has(modelDir)) crossServiceModels.set(modelDir, []);\n        crossServiceModels.get(modelDir)!.push(name);\n      }\n    }\n\n    // Deduplicate: skip cross-service imports for models already available locally\n    const localSet = new Set(localModels);\n\n    // Build a mapping from variant type aliases to their dispatcher's file name\n    // (e.g. ConnectApplicationVariant -> connect_application, not connect_application_variant)\n    const variantToFile = new Map<string, string>();\n    for (const model of ctx.spec.models) {\n      if ((model as any).discriminator) {\n        variantToFile.set(model.name + 'Variant', fileName(model.name));\n      }\n    }\n\n    if (localModels.length > 0) {\n      lines.push(`from .models import ${localModels.map((n) => className(n)).join(', ')}`);\n    }\n    for (const [csDir, names] of [...crossServiceModels].sort()) {\n      const unique = names.filter((n) => !localSet.has(n));\n      for (const n of unique) {\n        const filePath = variantToFile.get(n) ?? fileName(n);\n        lines.push(`from ${ctx.namespace}.${dirToModule(csDir)}.models.${filePath} import ${className(n)}`);\n      }\n    }\n\n    // Enum imports — same-service vs cross-service. Shared enums (referenced\n    // by 2+ services) are intentionally absent from this map so they resolve\n    // to common/ via the resolveDir() fallback below.\n    const enumToServiceMap = placement.enumToService;\n\n    const localEnums: string[] = [];\n    const crossServiceEnums = new Map<string, string[]>();\n    for (const name of [...enumImports].sort()) {\n      const enumSvc = enumToServiceMap.get(name);\n      const enumDir = enumSvc ? (mountDirMap.get(enumSvc) ?? 'common') : 'common';\n      if (enumDir === dirName) {\n        localEnums.push(name);\n      } else {\n        if (!crossServiceEnums.has(enumDir)) crossServiceEnums.set(enumDir, []);\n        crossServiceEnums.get(enumDir)!.push(name);\n      }\n    }\n\n    if (localEnums.length > 0) {\n      lines.push(`from .models import ${localEnums.map((n) => className(n)).join(', ')}`);\n    }\n    for (const [csDir, names] of [...crossServiceEnums].sort()) {\n      for (const n of names) {\n        lines.push(`from ${ctx.namespace}.${dirToModule(csDir)}.models.${fileName(n)} import ${className(n)}`);\n      }\n    }\n\n    const hasPaginated = allOperations.some((op) => op.pagination);\n    if (hasPaginated) {\n      lines.push(`from ${importPrefix}_pagination import AsyncPage, SyncPage`);\n    }\n    // dataclass import + group variant definitions\n    const hasGroups = hasParameterGroups(allOperations);\n    if (hasGroups) {\n      lines.push('from dataclasses import dataclass');\n      const dataclassLines = generateParameterGroupDataclasses(allOperations, specEnumNames, ctx.spec.models);\n      lines.push(...dataclassLines);\n    }\n    // --- Generate sync class ---\n    lines.push('');\n    lines.push(`class ${resourceClassName}:`);\n    {\n      let readable = resourceClassName.replace(/([a-z])([A-Z])/g, '$1 $2');\n      readable = readable.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');\n      lines.push(`    \"\"\"${readable} API resources.\"\"\"`);\n    }\n    lines.push('');\n    lines.push('    def __init__(self, client: \"WorkOSClient\") -> None:');\n    lines.push('        self._client = client');\n\n    const emittedMethods = new Set<string>();\n    for (const op of allOperations) {\n      const plan = planOperation(op);\n      let method = lookupMethodName(op, resolvedLookup) ?? toSnakeCase(op.name);\n      // On name collision, fall back to the full snake_case operation name\n      if (emittedMethods.has(method)) {\n        const fallback = toSnakeCase(op.name);\n        if (fallback !== method && !emittedMethods.has(fallback)) {\n          method = fallback;\n        } else {\n          continue;\n        }\n      }\n      emittedMethods.add(method);\n\n      // Look up the resolved operation for defaults/inferFromClient support\n      const resolvedSync = lookupResolved(op, resolvedLookup);\n\n      lines.push('');\n      const meta = emitMethodSignature(\n        lines,\n        op,\n        plan,\n        method,\n        false,\n        specEnumNames,\n        modelImports,\n        listWrapperNames,\n        ctx,\n        resolvedSync,\n      );\n      emitMethodDocstring(lines, op, plan, method, meta, specEnumNames, ctx, resolvedSync);\n      emitMethodBody(lines, op, plan, meta, false, modelImports, listWrapperNames, ctx, resolvedSync);\n\n      // Emit union split wrapper methods (e.g., authenticate_with_password)\n      if (resolvedSync?.wrappers && resolvedSync.wrappers.length > 0) {\n        lines.push(...generateSyncWrapperMethods(resolvedSync, ctx));\n        for (const w of resolvedSync.wrappers) emittedMethods.add(w.name);\n      }\n    }\n\n    // --- Generate async class ---\n    const asyncClassName = `Async${resourceClassName}`;\n    lines.push('');\n    lines.push('');\n    lines.push(`class ${asyncClassName}:`);\n    {\n      let readable = resourceClassName.replace(/([a-z])([A-Z])/g, '$1 $2');\n      readable = readable.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');\n      lines.push(`    \"\"\"${readable} API resources (async).\"\"\"`);\n    }\n    lines.push('');\n    lines.push('    def __init__(self, client: \"AsyncWorkOSClient\") -> None:');\n    lines.push('        self._client = client');\n\n    const asyncEmittedMethods = new Set<string>();\n    for (const op of allOperations) {\n      const plan = planOperation(op);\n      let method = lookupMethodName(op, resolvedLookup) ?? toSnakeCase(op.name);\n      if (asyncEmittedMethods.has(method)) {\n        const fallback = toSnakeCase(op.name);\n        if (fallback !== method && !asyncEmittedMethods.has(fallback)) {\n          method = fallback;\n        } else {\n          continue;\n        }\n      }\n      asyncEmittedMethods.add(method);\n\n      // Look up the resolved operation for defaults/inferFromClient support\n      const resolvedAsync = lookupResolved(op, resolvedLookup);\n\n      lines.push('');\n      const meta = emitMethodSignature(\n        lines,\n        op,\n        plan,\n        method,\n        true,\n        specEnumNames,\n        modelImports,\n        listWrapperNames,\n        ctx,\n        resolvedAsync,\n      );\n      emitMethodDocstring(lines, op, plan, method, meta, specEnumNames, ctx, resolvedAsync);\n      emitMethodBody(lines, op, plan, meta, true, modelImports, listWrapperNames, ctx, resolvedAsync);\n\n      // Emit union split wrapper methods (e.g., authenticate_with_password)\n      if (resolvedAsync?.wrappers && resolvedAsync.wrappers.length > 0) {\n        lines.push(...generateAsyncWrapperMethods(resolvedAsync, ctx));\n        for (const w of resolvedAsync.wrappers) asyncEmittedMethods.add(w.name);\n      }\n    }\n\n    files.push({\n      path: `src/${ctx.namespace}/${dirName}/_resource.py`,\n      content: lines.join('\\n'),\n      integrateTarget: true,\n      overwriteExisting: true,\n    });\n  }\n\n  return files;\n}\n\n// ─── Existing shared helpers ─────────────────────────────────────────\n\n/**\n * Emit a `params` dict from query params (for methods that also have a body or DELETE).\n * Returns true if params were emitted, false if no query params exist.\n */\nfunction emitQueryParamsDict(\n  lines: string[],\n  op: Operation,\n  pathParamNames: Set<string>,\n  bodyFieldNames: Set<string>,\n  hiddenParams?: Set<string>,\n): boolean {\n  // Filter to query params that aren't already path params, body fields, or hidden\n  const queryParams = op.queryParams.filter((p) => {\n    if (hiddenParams?.has(p.name)) return false;\n    const pn = fieldName(p.name);\n    return !pathParamNames.has(pn) && !bodyFieldNames.has(pn);\n  });\n  if (queryParams.length === 0) return false;\n\n  const hasOptional = queryParams.some((p) => !p.required);\n  if (hasOptional) {\n    lines.push('        params: Dict[str, Any] = {k: v for k, v in {');\n    for (const param of queryParams) {\n      lines.push(\n        `            \"${param.name}\": ${serializeParameterValue(param.type, fieldName(param.name), param.required, (param as ParameterExt).explode)},`,\n      );\n    }\n    lines.push('        }.items() if v is not None}');\n  } else {\n    lines.push('        params: Dict[str, Any] = {');\n    for (const param of queryParams) {\n      lines.push(\n        `            \"${param.name}\": ${serializeParameterValue(param.type, fieldName(param.name), param.required, (param as ParameterExt).explode)},`,\n      );\n    }\n    lines.push('        }');\n  }\n  return true;\n}\n\n/**\n * Serialize a body field value for inclusion in a request body dict.\n * Calls .to_dict() directly on model fields since types are known at generation time.\n * For arrays of models, maps each item through .to_dict().\n */\nfunction serializeBodyFieldValue(fieldType: any, varName: string, isRequired: boolean): string {\n  const effectiveType = fieldType.kind === 'nullable' ? fieldType.inner : fieldType;\n  if (effectiveType.kind === 'enum') {\n    return serializeParameterValue(effectiveType, varName, isRequired);\n  }\n  if (effectiveType.kind === 'model') {\n    if (!isRequired) {\n      return `${varName}.to_dict() if ${varName} is not None else None`;\n    }\n    return `${varName}.to_dict()`;\n  }\n  if (effectiveType.kind === 'array' && effectiveType.items?.kind === 'model') {\n    if (!isRequired) {\n      return `[item.to_dict() for item in ${varName}] if ${varName} is not None else None`;\n    }\n    return `[item.to_dict() for item in ${varName}]`;\n  }\n  return varName;\n}\n\nfunction serializeParameterValue(\n  type: TypeRef | undefined,\n  varName: string,\n  isRequired: boolean,\n  explode?: boolean,\n): string {\n  if (type?.kind === 'nullable') {\n    return serializeParameterValue(type.inner, varName, false, explode);\n  }\n  if (type?.kind === 'enum') {\n    const expr = `enum_value(${varName})`;\n    return isRequired ? expr : `${expr} if ${varName} is not None else None`;\n  }\n  // For explode=false array params, emit comma-joined string\n  if (explode === false && type?.kind === 'array') {\n    const joinExpr = `\",\".join(str(v) for v in ${varName})`;\n    return isRequired ? joinExpr : `${joinExpr} if ${varName} is not None else None`;\n  }\n  return varName;\n}\n\n/**\n * Resolve the item type name for a paginated operation, unwrapping list wrappers.\n */\nexport function resolvePageItemName(itemType: TypeRef, listWrapperNames: Set<string>, ctx: EmitterContext): string {\n  if (itemType.kind === 'model') {\n    if (listWrapperNames.has(itemType.name)) {\n      const wrapperModel = ctx.spec.models.find((m) => m.name === itemType.name);\n      const dataField = wrapperModel?.fields.find((f) => f.name === 'data');\n      if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n        return dataField.type.items.name;\n      }\n    }\n    return itemType.name;\n  }\n  return 'dict';\n}\n\n/**\n * Check if an operation is a redirect endpoint that should construct a URL\n * instead of making an HTTP request.\n *\n * Detection: GET endpoints with no response body (primitive unknown) are redirect\n * endpoints — e.g., SSO/OAuth authorize and logout flows that redirect the browser.\n * Also catches endpoints with 302 success responses when the parser includes them.\n */\nfunction isRedirectEndpoint(op: Operation): boolean {\n  // Explicit 302 in success responses\n  if (op.successResponses?.some((r) => r.statusCode >= 300 && r.statusCode < 400)) {\n    return true;\n  }\n  // GET with no response body (primitive unknown) = browser redirect endpoint\n  if (\n    op.httpMethod === 'get' &&\n    op.response.kind === 'primitive' &&\n    op.response.type === 'unknown' &&\n    op.queryParams.length > 0\n  ) {\n    return true;\n  }\n  return false;\n}\n\n/**\n * Map HTTP status codes to Python error class names for per-operation Raises: documentation.\n * Falls back to a baseline set (401, 429, 5xx) when the operation has no explicit errors.\n */\nconst STATUS_TO_ERROR: Record<number, string> = {\n  400: 'BadRequestError',\n  401: 'AuthenticationError',\n  403: 'AuthorizationError',\n  404: 'NotFoundError',\n  409: 'ConflictError',\n  422: 'UnprocessableEntityError',\n  429: 'RateLimitExceededError',\n};\n\nconst STATUS_TO_DESC: Record<number, string> = {\n  400: 'If the request is malformed (400).',\n  401: 'If the API key is invalid (401).',\n  403: 'If the request is forbidden (403).',\n  404: 'If the resource is not found (404).',\n  409: 'If a conflict occurs (409).',\n  422: 'If the request data is unprocessable (422).',\n  429: 'If rate limited (429).',\n};\n\nfunction buildErrorRaisesBlock(op: Operation): string[] {\n  const lines: string[] = [];\n  const emittedCodes = new Set<number>();\n\n  if (op.errors.length > 0) {\n    // Use per-operation error responses from the spec\n    for (const err of op.errors) {\n      const errorClass = STATUS_TO_ERROR[err.statusCode];\n      const desc = STATUS_TO_DESC[err.statusCode];\n      if (errorClass && !emittedCodes.has(err.statusCode)) {\n        lines.push(`${errorClass}: ${desc}`);\n        emittedCodes.add(err.statusCode);\n      }\n    }\n  }\n\n  // Always include baseline errors for authenticated endpoints (401, 429, 5xx)\n  if (!emittedCodes.has(401)) {\n    lines.push('AuthenticationError: If the API key is invalid (401).');\n  }\n  if (!emittedCodes.has(429)) {\n    lines.push('RateLimitExceededError: If rate limited (429).');\n  }\n  if (!emittedCodes.has(500)) {\n    lines.push('ServerError: If the server returns a 5xx error.');\n  }\n\n  return lines;\n}\n\n/**\n * Build a Python f-string path expression from an operation path.\n * E.g., \"/organizations/{id}\" -> f\"organizations/{quote(str(id), safe='')}\"\n */\nfunction buildPathString(op: Operation): string {\n  const enumParams = new Set<string>();\n  for (const p of op.pathParams) {\n    if (p.type.kind === 'enum' || (p.type.kind === 'nullable' && (p.type as any).inner?.kind === 'enum')) {\n      enumParams.add(p.name);\n    }\n  }\n  return buildPythonPathExpression(op.path, { enumParams });\n}\n","/**\n * Non-spec services: hand-maintained modules that are wired into the\n * generated client class alongside the spec-driven service accessors.\n *\n * Each entry describes one hand-maintained module. Emitters translate these\n * to language-idiomatic class names, property names, and import paths.\n *\n * Adding a new non-spec service here is the *only* change needed in the\n * emitter repo — each language emitter reads this list and generates the\n * appropriate client accessor.\n */\nexport interface NonSpecService {\n  /** Logical identifier (snake_case). Used as the canonical key. */\n  id: string;\n\n  /**\n   * Human-readable description.  Not emitted anywhere — exists so that\n   * someone reading this file understands what the service does.\n   */\n  description: string;\n\n  /**\n   * When true, the generated Client struct includes a cached field for this\n   * service and a public accessor method — identical to spec-driven services.\n   * The hand-written file must export the service type (e.g. PasswordlessService)\n   * but should NOT define its own Client accessor (the generated code handles that).\n   *\n   * Defaults to false — most non-spec modules are standalone helpers, not\n   * Client-mounted services.\n   */\n  hasClientAccessor?: boolean;\n}\n\n/**\n * The canonical list of non-spec services that every SDK must expose.\n *\n * Order here determines emission order in the generated client.\n */\nexport const NON_SPEC_SERVICES: readonly NonSpecService[] = [\n  {\n    id: 'passwordless',\n    description: 'Passwordless (magic-link) session endpoints, not yet in the OpenAPI spec.',\n    hasClientAccessor: true,\n  },\n  {\n    id: 'webhook_verification',\n    description: 'Webhook signature verification and event deserialization (H01/H02).',\n  },\n  {\n    id: 'actions',\n    description: 'AuthKit Actions request verification and response signing (H03).',\n  },\n  {\n    id: 'session_manager',\n    description: 'Sealed session cookies, JWT validation, JWKS helpers (H04-H07, H13).',\n  },\n  {\n    id: 'pkce',\n    description:\n      'PKCE utilities, AuthKit/SSO PKCE URL builders, code exchange, public client factory (H08-H11, H15, H16, H19).',\n  },\n] as const;\n","import type { ApiSpec, EmitterContext, GeneratedFile, Service } from '@workos/oagen';\nimport { toPascalCase } from '@workos/oagen';\nimport {\n  className,\n  resolveServiceDir,\n  servicePropertyName,\n  buildMountDirMap,\n  dirToModule,\n  buildExportedClassNameSet,\n  resolveServiceTarget,\n} from './naming.js';\nimport { resolveResourceClassName, collectParameterGroupClassNames } from './resources.js';\nimport { getMountTarget, groupByMount } from '../shared/resolved-ops.js';\nimport { NON_SPEC_SERVICES } from '../shared/non-spec-services.js';\n\n/** Python-specific wiring for each non-spec service. */\ninterface PythonNonSpecWiring {\n  importLine: string;\n  prop: string;\n  syncClass: string;\n  asyncClass: string | null;\n  ctorArg: 'self' | '';\n  docstring?: string;\n}\n\nconst PYTHON_NON_SPEC_WIRING: Record<string, PythonNonSpecWiring> = {\n  passwordless: {\n    importLine: 'from .passwordless import AsyncPasswordless, Passwordless',\n    prop: 'passwordless',\n    syncClass: 'Passwordless',\n    asyncClass: 'AsyncPasswordless',\n    ctorArg: 'self',\n    docstring: 'Passwordless authentication sessions.',\n  },\n  actions: {\n    importLine: 'from .actions import Actions, AsyncActions',\n    prop: 'actions',\n    syncClass: 'Actions',\n    asyncClass: 'AsyncActions',\n    ctorArg: '',\n    docstring: 'Actions logging and audit trail.',\n  },\n  pkce: {\n    importLine: 'from .pkce import PKCE',\n    prop: 'pkce',\n    syncClass: 'PKCE',\n    asyncClass: null,\n    ctorArg: '',\n    docstring: 'PKCE (Proof Key for Code Exchange) utilities.',\n  },\n};\n\n/**\n * Generate the slim Python client class (service-wiring only),\n * service __init__.py files, and types barrels.\n *\n * Static HTTP infrastructure lives in _base_client.py (hand-maintained\n * in the target SDK, marked @oagen-ignore-file).\n */\nexport function generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  assertPublicClientReachability(spec, ctx);\n\n  const files: GeneratedFile[] = [];\n\n  files.push(...generateWorkOSClient(spec, ctx));\n  files.push(...generateServiceInits(spec, ctx));\n  files.push(...generateTypesBarrels(spec, ctx));\n\n  return files;\n}\n\n/**\n * Deduplicate services by mount target. Multiple IR services may mount to the\n * same target (e.g., Applications + ApplicationClientSecrets -> Connect).\n * Returns one representative service per unique mount target, using the service\n * whose PascalCase name matches the target (if any), or the first one found.\n */\nfunction deduplicateByMount(services: Service[], ctx: EmitterContext): Service[] {\n  const byTarget = new Map<string, Service>();\n  for (const s of services) {\n    const target = getMountTarget(s, ctx);\n    const existing = byTarget.get(target);\n    if (!existing || toPascalCase(s.name) === target) {\n      byTarget.set(target, s);\n    }\n  }\n  return [...byTarget.values()];\n}\n\nexport function buildServiceAccessPaths(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const topLevel = deduplicateByMount(services, ctx);\n  const paths = new Map<string, string>();\n\n  for (const service of topLevel) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const prop = servicePropertyName(resolvedName);\n    paths.set(service.name, prop);\n  }\n\n  // Build reverse map: mount target name -> access path\n  const targetPaths = new Map<string, string>();\n  for (const service of topLevel) {\n    const target = getMountTarget(service, ctx);\n    if (!targetPaths.has(target) && paths.has(service.name)) {\n      targetPaths.set(target, paths.get(service.name)!);\n    }\n  }\n\n  // Map mounted services to their mount target's access path\n  for (const service of services) {\n    if (paths.has(service.name)) continue;\n    const mountTarget = getMountTarget(service, ctx);\n    const targetPath = targetPaths.get(mountTarget) ?? paths.get(mountTarget);\n    if (targetPath) paths.set(service.name, targetPath);\n  }\n\n  return paths;\n}\n\nfunction assertPublicClientReachability(spec: ApiSpec, ctx: EmitterContext): void {\n  const topLevelServices = deduplicateByMount(spec.services, ctx);\n  const accessPaths = buildServiceAccessPaths(spec.services, ctx);\n  const unreachableServices = topLevelServices\n    .filter((service) => service.operations.length > 0 && !accessPaths.has(service.name))\n    .map((service) => service.name);\n\n  if (unreachableServices.length > 0) {\n    throw new Error(`Python emitter reachability audit failed for services: ${unreachableServices.join(', ')}`);\n  }\n}\n\n/**\n * Generate the slim _client.py that subclasses the static _base_client.py\n * and wires spec-driven service accessors.\n */\nfunction generateWorkOSClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const lines: string[] = [];\n  const topLevelServices = deduplicateByMount(spec.services, ctx);\n\n  // --- Imports ---\n  lines.push('from __future__ import annotations');\n  lines.push('');\n  lines.push('import functools');\n  lines.push('');\n  lines.push('from ._base_client import (');\n  lines.push('    WorkOSClient as _SyncBase,');\n  lines.push('    AsyncWorkOSClient as _AsyncBase,');\n  lines.push(')');\n\n  // Import resource classes (both sync and async)\n  const serviceDirMap = buildMountDirMap(ctx);\n  const exportedClasses = buildExportedClassNameSet(ctx);\n  for (const service of topLevelServices) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const clsName = className(resolveServiceTarget(resolvedName, exportedClasses));\n    const dirName = serviceDirMap.get(service.name) ?? resolveServiceDir(resolvedName);\n    const importLine = `from .${dirToModule(dirName)}._resource import ${clsName}, Async${clsName}`;\n    if (importLine.length > 88) {\n      lines.push(`from .${dirToModule(dirName)}._resource import (`);\n      lines.push(`    ${clsName},`);\n      lines.push(`    Async${clsName},`);\n      lines.push(')');\n    } else {\n      lines.push(importLine);\n    }\n  }\n  // Non-spec service imports — emitted as plain imports (not wrapped in\n  // ignore markers). The overwriteWithPreservedRegions() machinery in oagen\n  // relocates top-level ignore blocks to EOF because they have no containing\n  // class, stripping the markers from the imports while spliceExtraImports()\n  // preserves the bare import lines. Emitting them directly avoids the\n  // displacement entirely; spliceExtraImports() will preserve any additional\n  // hand-added imports from the existing file on subsequent regenerations.\n  for (const s of NON_SPEC_SERVICES) {\n    const w = PYTHON_NON_SPEC_WIRING[s.id];\n    if (w) lines.push(w.importLine);\n  }\n  lines.push('');\n  lines.push('');\n\n  // --- Sync client ---\n  lines.push('class WorkOSClient(_SyncBase):');\n  lines.push('    \"\"\"Synchronous WorkOS API client with service accessors.\"\"\"');\n\n  // Collect all generated property names\n  const generatedProps = new Set<string>();\n  for (const service of topLevelServices) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const clsName = className(resolveServiceTarget(resolvedName, exportedClasses));\n    const prop = servicePropertyName(resolvedName);\n    const readable = clsName.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');\n    lines.push('');\n    lines.push('    @functools.cached_property');\n    lines.push(`    def ${prop}(self) -> ${clsName}:`);\n    lines.push(`        \"\"\"${readable} API resources.\"\"\"`);\n    lines.push(`        return ${clsName}(self)`);\n    generatedProps.add(prop);\n  }\n  emitCompatClientPropertyAliases(lines, generatedProps, false);\n  emitNonSpecClientAccessors(lines, false);\n\n  lines.push('');\n  lines.push('');\n\n  // --- Async client ---\n  lines.push('class AsyncWorkOSClient(_AsyncBase):');\n  lines.push('    \"\"\"Asynchronous WorkOS API client with service accessors.\"\"\"');\n\n  const asyncGeneratedProps = new Set<string>();\n  for (const service of topLevelServices) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const clsName = className(resolveServiceTarget(resolvedName, exportedClasses));\n    const prop = servicePropertyName(resolvedName);\n    const readable = clsName.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');\n    lines.push('');\n    lines.push('    @functools.cached_property');\n    lines.push(`    def ${prop}(self) -> Async${clsName}:`);\n    lines.push(`        \"\"\"${readable} API resources.\"\"\"`);\n    lines.push(`        return Async${clsName}(self)`);\n    asyncGeneratedProps.add(prop);\n  }\n  emitCompatClientPropertyAliases(lines, asyncGeneratedProps, true);\n  emitNonSpecClientAccessors(lines, true);\n\n  return [\n    {\n      path: `src/${ctx.namespace}/_client.py`,\n      content: lines.join('\\n'),\n      overwriteExisting: true,\n    },\n  ];\n}\n\nfunction emitNonSpecClientAccessors(lines: string[], isAsync: boolean): void {\n  lines.push('');\n  lines.push('    # @oagen-ignore-start — non-spec service accessors (hand-maintained)');\n  for (const s of NON_SPEC_SERVICES) {\n    const w = PYTHON_NON_SPEC_WIRING[s.id];\n    if (!w) continue;\n    const typeName = isAsync ? (w.asyncClass ?? w.syncClass) : w.syncClass;\n    const arg = w.ctorArg === 'self' ? 'self' : '';\n\n    lines.push('');\n    lines.push('    @functools.cached_property');\n    lines.push(`    def ${w.prop}(self) -> ${typeName}:`);\n    if (w.docstring) {\n      lines.push(`        \"\"\"${w.docstring}\"\"\"`);\n    }\n    lines.push(`        return ${typeName}(${arg})`);\n  }\n  lines.push('');\n  lines.push('    # @oagen-ignore-end');\n}\n\nfunction generateServiceInits(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const topLevel = deduplicateByMount(spec.services, ctx);\n  const serviceDirMap = buildMountDirMap(ctx);\n  const exportedClasses = buildExportedClassNameSet(ctx);\n\n  // Build a map from mount target -> operations so we can discover parameter\n  // group dataclasses that need re-exporting from __init__.py.\n  const mountGroups = groupByMount(ctx);\n\n  for (const service of topLevel) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const clsName = className(resolveServiceTarget(resolvedName, exportedClasses));\n    const dirName = serviceDirMap.get(service.name) ?? resolveServiceDir(resolvedName);\n    const lines: string[] = [];\n\n    // Collect parameter group class names from all operations in this mount group\n    const mountTarget = getMountTarget(service, ctx);\n    const ops = mountGroups.get(mountTarget)?.operations ?? service.operations;\n    const groupClassNames = collectParameterGroupClassNames(ops);\n\n    // Use `X as X` re-export form (PEP 484) so pyright recognizes these as\n    // public re-exports. Otherwise consumers importing\n    // `from workos.user_management import RoleSingle` get a private-import\n    // warning under strict mode. Models barrel uses the same convention.\n    const resourceImports = [clsName, `Async${clsName}`, ...groupClassNames];\n    const aliasedImports = resourceImports.map((n) => `${n} as ${n}`);\n    lines.push(`from ._resource import ${aliasedImports.join(', ')}`);\n    lines.push('from .models import *');\n\n    files.push({\n      path: `src/${ctx.namespace}/${dirName}/__init__.py`,\n      content: lines.join('\\n'),\n      integrateTarget: true,\n      overwriteExisting: true,\n    });\n\n    // models/__init__.py is emitted unconditionally by `models.ts` — including\n    // an empty barrel for services with no models — so we don't need a safety\n    // net here. (A `skipIfExists` safety net previously caused stale imports\n    // to survive when the underlying module was pruned.)\n  }\n\n  return files;\n}\n\nfunction emitCompatClientPropertyAliases(lines: string[], generatedProps: Set<string>, isAsync: boolean): void {\n  const aliases: Array<{ alias: string; typeName: string; returnExpr: string; docstring: string }> = [];\n  if (generatedProps.has('multi_factor_auth') && !generatedProps.has('mfa')) {\n    const mfaType = isAsync ? 'AsyncMultiFactorAuth' : 'MultiFactorAuth';\n    aliases.push({\n      alias: 'mfa',\n      typeName: mfaType,\n      returnExpr: 'self.multi_factor_auth',\n      docstring: '\"\"\"Alias for multi_factor_auth.\"\"\"',\n    });\n  }\n  for (const alias of aliases) {\n    lines.push('');\n    lines.push('    @functools.cached_property');\n    lines.push(`    def ${alias.alias}(self) -> ${alias.typeName}:`);\n    lines.push(`        ${alias.docstring}`);\n    lines.push(`        return ${alias.returnExpr}`);\n  }\n}\n\n/**\n * Generate types/<service>/__init__.py re-export barrels so that\n * `from workos.types.<service> import Model` continues to work.\n */\nfunction generateTypesBarrels(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const serviceDirMap = buildMountDirMap(ctx);\n\n  // Collect (types dir name -> set of service dirs whose models should be re-exported)\n  const typesEntries = new Map<string, Set<string>>();\n\n  for (const service of spec.services) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const prop = servicePropertyName(resolvedName);\n    const dir = serviceDirMap.get(service.name) ?? prop;\n    const dirs = typesEntries.get(prop) ?? new Set();\n    dirs.add(dir);\n    typesEntries.set(prop, dirs);\n  }\n\n  for (const [typesDir, serviceDirs] of typesEntries) {\n    const imports = [...serviceDirs]\n      .sort()\n      .map((dir) => `from ${ctx.namespace}.${dirToModule(dir)}.models import *  # noqa: F401,F403`);\n\n    files.push({\n      path: `src/${ctx.namespace}/types/${typesDir}/__init__.py`,\n      content: imports.join('\\n'),\n      integrateTarget: true,\n      overwriteExisting: true,\n    });\n  }\n\n  // Root types/__init__.py\n  files.push({\n    path: `src/${ctx.namespace}/types/__init__.py`,\n    content: '',\n    integrateTarget: true,\n    overwriteExisting: true,\n  });\n\n  return files;\n}\n","import type { Model, TypeRef, Enum, EmitterContext } from '@workos/oagen';\n\nimport { fileName, domainFieldName } from './naming.js';\nimport { isListMetadataModel, isListWrapperModel } from './models.js';\nimport { collectNonPaginatedResponseModelNames, collectReferencedListMetadataModels } from '../shared/model-utils.js';\nimport { isModelInScope, fileExistsAfterRun } from '../shared/resolved-ops.js';\n\n/**\n * Prefix mapping for generating realistic ID fixture values.\n */\nexport const ID_PREFIXES: Record<string, string> = {\n  Connection: 'conn_',\n  Organization: 'org_',\n  OrganizationMembership: 'om_',\n  User: 'user_',\n  Directory: 'directory_',\n  DirectoryGroup: 'dir_grp_',\n  DirectoryUser: 'dir_usr_',\n  Invitation: 'inv_',\n  Session: 'session_',\n  AuthenticationFactor: 'auth_factor_',\n  EmailVerification: 'email_verification_',\n  MagicAuth: 'magic_auth_',\n  PasswordReset: 'password_reset_',\n};\n\n/**\n * Generate JSON fixture files for test data.\n *\n * `ctx` is optional so unit tests can call with a bare spec; when supplied, a\n * scoped (`--services`) run only emits a fixture for a model whose per-model\n * file will exist on disk after the run (in-scope, or already present from a\n * prior manifest). Brand-new out-of-scope models are skipped: the round-trip\n * test that consumes these fixtures is gated the same way, and the per-service\n * tests only reference fixtures for their (in-scope) models.\n */\nexport function generateFixtures(\n  spec: {\n    models: Model[];\n    enums: Enum[];\n    services: any[];\n  },\n  ctx?: EmitterContext,\n): { path: string; content: string }[] {\n  if (spec.models.length === 0) return [];\n\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n  const files: { path: string; content: string }[] = [];\n\n  // Gate a fixture by ITS OWN path (recorded verbatim in the prior manifest),\n  // scoped on the owning model. A base-model fixture and its `list_*` fixture\n  // are distinct files, so each must be checked against its own path — keying a\n  // list fixture off the base path would leak a brand-new `list_*` fixture for\n  // an out-of-scope model that merely already had its base fixture on disk.\n  // When ctx is absent (unit tests) every fixture is in scope.\n  const fixtureEmitted = (path: string, modelName: string): boolean => {\n    if (!ctx) return true;\n    return fileExistsAfterRun(path, isModelInScope(modelName, ctx), ctx);\n  };\n\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(spec.services);\n  const listMetadataNeeded = collectReferencedListMetadataModels(spec.models, nonPaginatedRefs);\n\n  for (const model of spec.models) {\n    if (isListMetadataModel(model) && !listMetadataNeeded.has(model.name)) continue;\n    if (isListWrapperModel(model) && !nonPaginatedRefs.has(model.name)) continue;\n    // Skip models with no fields — these are typically discriminated unions\n    // with hand-maintained @oagen-ignore overrides; generated empty fixtures\n    // would not match the override's required fields.\n    if (model.fields.length === 0) continue;\n    // Scoped run: skip a fixture for a brand-new out-of-scope model.\n    if (!fixtureEmitted(`tests/fixtures/${fileName(model.name)}.json`, model.name)) continue;\n\n    const fixture = generateModelFixture(model, modelMap, enumMap);\n\n    files.push({\n      path: `tests/fixtures/${fileName(model.name)}.json`,\n      content: JSON.stringify(fixture, null, 2),\n    });\n  }\n\n  // Generate list fixtures for paginated responses\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      if (op.pagination) {\n        let itemModel = op.pagination.itemType.kind === 'model' ? modelMap.get(op.pagination.itemType.name) : null;\n        if (itemModel) {\n          const unwrapped = unwrapListModel(itemModel, modelMap);\n          if (unwrapped) itemModel = unwrapped;\n          if (itemModel.fields.length === 0) continue;\n          // Scoped run: a list fixture for a brand-new out-of-scope item model\n          // would be referenced by no emitted test; gate it on the LIST\n          // fixture's own path (not the base model fixture's).\n          if (!fixtureEmitted(`tests/fixtures/list_${fileName(itemModel.name)}.json`, itemModel.name)) continue;\n          const fixture = generateModelFixture(itemModel, modelMap, enumMap);\n          const listFixture = {\n            data: [fixture],\n            list_metadata: {\n              before: null,\n              after: null,\n            },\n          };\n          files.push({\n            path: `tests/fixtures/list_${fileName(itemModel.name)}.json`,\n            content: JSON.stringify(listFixture, null, 2),\n          });\n        }\n      }\n    }\n  }\n\n  return files;\n}\n\nexport function unwrapListModel(model: Model, modelMap: Map<string, Model>): Model | null {\n  const dataField = model.fields.find((f) => f.name === 'data');\n  const hasListMetadata = model.fields.some((f) => f.name === 'list_metadata' || f.name === 'listMetadata');\n  if (dataField && hasListMetadata && dataField.type.kind === 'array') {\n    const itemType = dataField.type.items;\n    if (itemType.kind === 'model') {\n      return modelMap.get(itemType.name) ?? null;\n    }\n  }\n  return null;\n}\n\nexport function generateModelFixture(\n  model: Model,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): Record<string, any> {\n  const fixture: Record<string, any> = {};\n\n  // Deduplicate fields by DOMAIN identifier (matching model generation in\n  // models.ts, which honors `domainName`); the wire key below stays `field.name`.\n  const seenFieldNames = new Set<string>();\n  const deduplicatedFields = model.fields.filter((f) => {\n    const pyName = domainFieldName(f);\n    if (seenFieldNames.has(pyName)) return false;\n    seenFieldNames.add(pyName);\n    return true;\n  });\n\n  for (const field of deduplicatedFields) {\n    // Use the original field name as the wire key (matches from_dict access patterns)\n    const wireName = field.name;\n    if (field.example !== undefined) {\n      fixture[wireName] = normalizeDateTimeExample(field, field.example);\n    } else {\n      fixture[wireName] = generateFieldValue(field.type, field.name, model.name, modelMap, enumMap);\n    }\n  }\n\n  if (model.discriminator) {\n    const [firstValue, variantName] = Object.entries(model.discriminator.mapping)[0];\n    fixture[model.discriminator.property] = firstValue;\n    const variantModel = modelMap.get(variantName);\n    if (variantModel) {\n      for (const field of variantModel.fields) {\n        fixture[field.name] =\n          field.example !== undefined\n            ? normalizeDateTimeExample(field, field.example)\n            : generateFieldValue(field.type, field.name, variantName, modelMap, enumMap);\n      }\n    }\n  }\n\n  return fixture;\n}\n\nfunction generateFieldValue(\n  ref: TypeRef,\n  fieldName: string,\n  modelName: string,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): any {\n  switch (ref.kind) {\n    case 'primitive':\n      return generatePrimitiveValue(ref.type, ref.format, fieldName, modelName);\n    case 'literal':\n      return ref.value;\n    case 'enum': {\n      const e = enumMap.get(ref.name);\n      return e?.values[0]?.value ?? 'unknown';\n    }\n    case 'model': {\n      const nested = modelMap.get(ref.name);\n      if (nested) return generateModelFixture(nested, modelMap, enumMap);\n      return {};\n    }\n    case 'array': {\n      if (ref.items.kind === 'enum') {\n        const e = enumMap.get(ref.items.name);\n        if (e && e.values.length > 0) {\n          return e.values.map((v) => v.value);\n        }\n      }\n      const item = generateFieldValue(ref.items, fieldName, modelName, modelMap, enumMap);\n      return [item];\n    }\n    case 'nullable':\n      return generateFieldValue(ref.inner, fieldName, modelName, modelMap, enumMap);\n    case 'union':\n      if (ref.variants.length > 0) {\n        return generateFieldValue(ref.variants[0], fieldName, modelName, modelMap, enumMap);\n      }\n      return null;\n    case 'map':\n      return {\n        key: generateFieldValue(ref.valueType, 'value', modelName, modelMap, enumMap),\n      };\n  }\n}\n\n/**\n * Normalize date-time example values to millisecond precision so that\n * round-trip tests (from_dict → to_dict) produce identical output.\n * Python's _format_datetime always serializes with milliseconds.\n */\nfunction normalizeDateTimeExample(\n  field: { type: { kind: string; format?: string; type?: string; inner?: any } },\n  value: any,\n): any {\n  if (typeof value !== 'string') return value;\n  const ref = field.type.kind === 'nullable' ? field.type.inner : field.type;\n  if (ref?.kind !== 'primitive' || ref?.type !== 'string' || ref?.format !== 'date-time') return value;\n  const match = value.match(/^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/);\n  if (!match) return value;\n  const [, prefix, , suffix] = match;\n  return `${prefix}.000${suffix}`;\n}\n\nfunction generatePrimitiveValue(type: string, format: string | undefined, name: string, modelName: string): any {\n  switch (type) {\n    case 'string':\n      if (format === 'date-time') return '2023-01-01T00:00:00.000Z';\n      if (format === 'date') return '2023-01-01';\n      if (format === 'uuid') return '00000000-0000-0000-0000-000000000000';\n      if (name === 'id') {\n        const prefix = ID_PREFIXES[modelName] ?? '';\n        return `${prefix}01234`;\n      }\n      if (name.includes('id')) return `${name}_01234`;\n      if (name.includes('email')) return 'test@example.com';\n      if (name.includes('url') || name.includes('uri')) return 'https://example.com';\n      if (name.includes('name')) return 'Test';\n      return `test_${name}`;\n    case 'integer':\n      return 1;\n    case 'number':\n      return 1.0;\n    case 'boolean':\n      return true;\n    case 'unknown':\n      return {};\n    default:\n      return null;\n  }\n}\n","import type {\n  ApiSpec,\n  Service,\n  Operation,\n  EmitterContext,\n  GeneratedFile,\n  TypeRef,\n  Model,\n  ResolvedOperation,\n} from '@workos/oagen';\nimport { planOperation, toSnakeCase } from '@workos/oagen';\nimport {\n  className,\n  fileName,\n  fieldName,\n  domainFieldName,\n  moduleName,\n  resolveMethodName,\n  buildMountDirMap,\n  dirToModule,\n} from './naming.js';\nimport { resolveResourceClassName, bodyParamName } from './resources.js';\nimport { buildServiceAccessPaths } from './client.js';\nimport { generateFixtures, generateModelFixture } from './fixtures.js';\nimport { isListWrapperModel, isListMetadataModel } from './models.js';\nimport { collectNonPaginatedResponseModelNames, collectReferencedListMetadataModels } from '../shared/model-utils.js';\nimport {\n  scopedMountGroups,\n  buildResolvedLookup,\n  lookupResolved,\n  buildHiddenParams,\n  collectGroupedParamNames,\n  isModelInScope,\n  fileExistsAfterRun,\n} from '../shared/resolved-ops.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { pythonLiteral } from './wrappers.js';\nimport { computeSchemaPlacement } from './shared-schemas.js';\n\n/**\n * Resolve the Python class name to use for isinstance checks on paginated items.\n * For discriminated unions, generates the fixture and determines which variant\n * the discriminator value maps to. For regular models, returns the model class.\n */\nfunction resolvePaginatedItemClass(itemName: string | null, spec: ApiSpec): string | null {\n  if (!itemName) return null;\n  const itemModel = spec.models.find((m) => m.name === itemName);\n  if (!itemModel) return className(itemName);\n\n  const disc = (itemModel as any).discriminator as { property: string; mapping: Record<string, string> } | undefined;\n  if (!disc) return className(itemName);\n\n  // Generate the fixture to determine which discriminator value appears\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n  const fixture = generateModelFixture(itemModel, modelMap, enumMap);\n  const discValue = fixture[disc.property];\n\n  if (typeof discValue === 'string' && disc.mapping[discValue]) {\n    return className(disc.mapping[discValue]);\n  }\n\n  // Fallback: first variant alphabetically\n  const sortedEntries = Object.entries(disc.mapping).sort(([a], [b]) => a.localeCompare(b));\n  if (sortedEntries.length > 0) return className(sortedEntries[0][1]);\n\n  return className(itemName);\n}\n\n/** Check if an operation is a redirect endpoint (same logic as resources.ts). */\nfunction isRedirectEndpoint(op: Operation): boolean {\n  if (op.successResponses?.some((r) => r.statusCode >= 300 && r.statusCode < 400)) return true;\n  if (\n    op.httpMethod === 'get' &&\n    op.response.kind === 'primitive' &&\n    (op.response as any).type === 'unknown' &&\n    op.queryParams.length > 0\n  ) {\n    return true;\n  }\n  return false;\n}\n\n/** Push an async test method definition with @pytest.mark.asyncio decorator. */\nfunction pushAsyncTestDef(lines: string[], def: string): void {\n  lines.push('    @pytest.mark.asyncio');\n  lines.push(def);\n}\n\nfunction buildDeleteSuccessResponseSetup(op: Operation): string {\n  const statusCode = op.successResponses?.[0]?.statusCode ?? 204;\n  if (statusCode === 204) {\n    return 'httpx_mock.add_response(status_code=204)';\n  }\n  return `httpx_mock.add_response(status_code=${statusCode}, content=b\"\\\\n\")`;\n}\n\n/**\n * Generate pytest test files and JSON fixtures for the Python SDK.\n */\nexport function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  // Generate fixture JSON files\n  const fixtures = generateFixtures(spec, ctx);\n  for (const fixture of fixtures) {\n    files.push({\n      path: fixture.path,\n      content: fixture.content,\n      headerPlacement: 'skip',\n      integrateTarget: true,\n      overwriteExisting: true,\n    });\n  }\n\n  // conftest.py, generated_helpers.py, test_pagination.py, and test_generated_client.py\n  // are now hand-maintained in the target SDK (@oagen-ignore-file).\n\n  // Build access path map for all services\n  const accessPaths = buildServiceAccessPaths(spec.services, ctx);\n\n  // Generate per-mount-target test files (merges all sub-services into one file)\n  const mountGroups = scopedMountGroups(ctx);\n  const testEntries: Array<{ name: string; operations: Operation[]; resolvedOps?: ResolvedOperation[] }> =\n    mountGroups.size > 0 || ctx.scopedServices?.size\n      ? [...mountGroups].map(([name, group]) => ({\n          name,\n          operations: group.operations,\n          resolvedOps: group.resolvedOps,\n        }))\n      : spec.services.map((s) => ({ name: resolveResourceClassName(s, ctx), operations: s.operations }));\n\n  for (const { name: mountName, operations, resolvedOps } of testEntries) {\n    if (operations.length === 0) continue;\n    const mergedService: Service = { name: mountName, operations };\n    const testFile = generateServiceTest(mergedService, spec, ctx, accessPaths, resolvedOps);\n    if (testFile) files.push(testFile);\n  }\n\n  // Generate model round-trip tests (P3-7)\n  const modelTests = generateModelRoundTripTests(spec, ctx);\n  if (modelTests) files.push(modelTests);\n\n  return files;\n}\n\nfunction generateServiceTest(\n  service: Service,\n  spec: ApiSpec,\n  ctx: EmitterContext,\n  accessPaths: Map<string, string>,\n  resolvedOps?: ResolvedOperation[],\n): GeneratedFile | null {\n  if (service.operations.length === 0) return null;\n\n  const resolvedName = resolveResourceClassName(service, ctx);\n  const propName = accessPaths.get(service.name) ?? toSnakeCase(resolvedName);\n\n  const lines: string[] = [];\n\n  lines.push('import json');\n  lines.push('');\n  lines.push('import pytest');\n  lines.push(`from ${ctx.namespace} import WorkOSClient, AsyncWorkOSClient`);\n  lines.push('from tests.generated_helpers import load_fixture');\n  lines.push('');\n\n  // Collect model and enum imports needed (response models, body field models, and enum params)\n  const modelImports = new Set<string>();\n  const enumImports = new Set<string>();\n  for (const op of service.operations) {\n    const plan = planOperation(op);\n    if (plan.responseModelName) {\n      modelImports.add(plan.responseModelName);\n      // For non-paginated discriminated union responses, import the resolved variant class\n      if (!plan.isPaginated) {\n        const resolvedVariantClass = resolvePaginatedItemClass(plan.responseModelName, spec);\n        if (resolvedVariantClass && resolvedVariantClass !== className(plan.responseModelName)) {\n          const responseModel = spec.models.find((m) => m.name === plan.responseModelName);\n          const disc =\n            responseModel &&\n            ((responseModel as any).discriminator as { property: string; mapping: Record<string, string> } | undefined);\n          if (disc) {\n            for (const variantName of Object.values(disc.mapping)) {\n              if (className(variantName) === resolvedVariantClass) {\n                modelImports.add(variantName);\n                break;\n              }\n            }\n          }\n        }\n      }\n    }\n    if (op.pagination?.itemType.kind === 'model') {\n      modelImports.add(op.pagination.itemType.name);\n      // Unwrap list wrapper to find the inner item model (may be a discriminated union)\n      let paginationItemName = op.pagination.itemType.name;\n      const wrapperModel = spec.models.find((m) => m.name === paginationItemName);\n      if (wrapperModel && isListWrapperModel(wrapperModel)) {\n        const dataField = wrapperModel.fields.find((f) => f.name === 'data');\n        if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n          paginationItemName = dataField.type.items.name;\n          modelImports.add(paginationItemName);\n        }\n      }\n      // For discriminated union pagination items, import the variant that the fixture resolves to\n      const resolvedVariantClass = resolvePaginatedItemClass(paginationItemName, spec);\n      if (resolvedVariantClass && resolvedVariantClass !== className(paginationItemName)) {\n        // Find the model name from the class name — reverse-lookup through the discriminator mapping\n        const paginationModel = spec.models.find((m) => m.name === paginationItemName);\n        const disc =\n          paginationModel &&\n          ((paginationModel as any).discriminator as { property: string; mapping: Record<string, string> } | undefined);\n        if (disc) {\n          for (const variantName of Object.values(disc.mapping)) {\n            if (className(variantName) === resolvedVariantClass) {\n              modelImports.add(variantName);\n              break;\n            }\n          }\n        }\n      }\n    }\n    // Collect model-typed and enum-typed body fields (used as method arguments)\n    if (plan.hasBody && op.requestBody?.kind === 'model') {\n      const bodyModel = spec.models.find((m) => m.name === (op.requestBody as any).name);\n      if (bodyModel) {\n        const testGroupedParams = collectGroupedParamNames(op);\n        for (const f of bodyModel.fields) {\n          if (testGroupedParams.has(f.name)) continue;\n          if (f.type.kind === 'model') modelImports.add(f.type.name);\n          if (f.type.kind === 'nullable' && f.type.inner.kind === 'model') modelImports.add(f.type.inner.name);\n          if (f.type.kind === 'array' && f.type.items.kind === 'model') modelImports.add(f.type.items.name);\n          if (f.type.kind === 'enum') enumImports.add(f.type.name);\n          if (f.type.kind === 'nullable' && f.type.inner.kind === 'enum') enumImports.add(f.type.inner.name);\n        }\n      }\n    }\n    // Collect enum-typed query params\n    for (const param of op.queryParams) {\n      if (param.type.kind === 'enum') enumImports.add(param.type.name);\n      if (param.type.kind === 'nullable' && param.type.inner.kind === 'enum') enumImports.add(param.type.inner.name);\n    }\n  }\n\n  // Filter out list wrapper models, but keep non-paginated response wrappers\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(spec.services);\n  const actualImports = [...modelImports].filter((name) => {\n    const model = spec.models.find((m) => m.name === name);\n    if (!model) return true;\n    if (isListWrapperModel(model) && !nonPaginatedRefs.has(name)) return false;\n    return true;\n  });\n\n  // Group imports by their actual service directory (models may live in different services)\n  const placement = computeSchemaPlacement(spec, ctx);\n  const modelToServiceMap = placement.modelToService;\n  const enumToServiceMap = placement.enumToService;\n  const mountDirMap = buildMountDirMap(ctx);\n  const resolveModelDir = (modelName: string) => {\n    const svc = modelToServiceMap.get(modelName);\n    return svc ? (mountDirMap.get(svc) ?? 'common') : 'common';\n  };\n  const resolveEnumDir = (enumName: string) => {\n    const svc = enumToServiceMap.get(enumName);\n    return svc ? (mountDirMap.get(svc) ?? 'common') : 'common';\n  };\n\n  const importsByDir = new Map<string, string[]>();\n  for (const name of actualImports.sort()) {\n    const modelDir = resolveModelDir(name);\n    if (!importsByDir.has(modelDir)) importsByDir.set(modelDir, []);\n    importsByDir.get(modelDir)!.push(className(name));\n  }\n  for (const name of [...enumImports].sort()) {\n    const enumDir = resolveEnumDir(name);\n    if (!importsByDir.has(enumDir)) importsByDir.set(enumDir, []);\n    const existing = importsByDir.get(enumDir)!;\n    const cn = className(name);\n    if (!existing.includes(cn)) existing.push(cn);\n  }\n\n  for (const [modelDir, names] of [...importsByDir].sort()) {\n    lines.push(`from ${ctx.namespace}.${dirToModule(modelDir)}.models import ${names.join(', ')}`);\n  }\n\n  const hasPaginated = service.operations.some((op) => op.pagination);\n  if (hasPaginated) {\n    lines.push(`from ${ctx.namespace}._pagination import AsyncPage, SyncPage`);\n  }\n  lines.push(\n    `from ${ctx.namespace}._errors import AuthenticationError, BadRequestError, NotFoundError, RateLimitExceededError, ServerError, UnprocessableEntityError`,\n  );\n\n  // Import parameter group variant classes\n  const groupVariantImports = new Set<string>();\n  for (const op of service.operations) {\n    for (const group of op.parameterGroups ?? []) {\n      for (const variant of group.variants) {\n        groupVariantImports.add(className(`${group.name}_${variant.name}`));\n      }\n    }\n  }\n  if (groupVariantImports.size > 0) {\n    const mountDir = dirToModule(buildMountDirMap(ctx).get(service.name) ?? moduleName(service.name));\n    lines.push(`from ${ctx.namespace}.${mountDir}._resource import ${[...groupVariantImports].join(', ')}`);\n  }\n\n  lines.push('');\n  lines.push('');\n  lines.push(`class Test${resolvedName}:`);\n\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const emittedTestMethods = new Set<string>();\n  for (const op of service.operations) {\n    const plan = planOperation(op);\n    const resolvedOp = lookupResolved(op, resolvedLookup);\n    const hiddenParams = buildHiddenParams(resolvedOp);\n    let method = resolveMethodName(op, service, ctx);\n\n    // On name collision, fall back to the full snake_case operation name (match resource dedup)\n    if (emittedTestMethods.has(method)) {\n      const fallback = toSnakeCase(op.name);\n      if (fallback !== method && !emittedTestMethods.has(fallback)) {\n        method = fallback;\n      } else {\n        continue;\n      }\n    }\n    emittedTestMethods.add(method);\n\n    const isDelete = plan.isDelete;\n    const isPaginated = plan.isPaginated;\n    const isArrayResponse = op.response.kind === 'array' && op.response.items.kind === 'model';\n\n    lines.push('');\n\n    if (isPaginated) {\n      const itemType = op.pagination!.itemType;\n      let itemName = itemType.kind === 'model' ? itemType.name : null;\n      // Unwrap list wrapper models to their inner item type for fixture names\n      if (itemName) {\n        const wrapperModel = spec.models.find((m) => m.name === itemName);\n        if (wrapperModel && isListWrapperModel(wrapperModel)) {\n          const dataField = wrapperModel.fields.find((f) => f.name === 'data');\n          if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n            itemName = dataField.type.items.name;\n          }\n        }\n      }\n      // Skip fixture-based testing for models with no fields (discriminated unions)\n      // Save the unwrapped name before nulling — needed for discriminator check below\n      const unwrappedItemName = itemName;\n      if (itemName) {\n        const itemModel = spec.models.find((m) => m.name === itemName);\n        if (itemModel && itemModel.fields.length === 0) itemName = null;\n      }\n      const fixtureName = itemName ? `list_${fileName(itemName)}.json` : null;\n\n      // Determine the class name to use for isinstance checks on paginated items.\n      // If the item model is a discriminated union (has a discriminator), the fixture\n      // will deserialize to a concrete variant, so assert on that variant class.\n      const paginatedItemClass = resolvePaginatedItemClass(itemName, spec);\n\n      const paginatedArgs = buildTestArgs(op, spec, hiddenParams);\n      lines.push(`    def test_${method}(self, workos, httpx_mock):`);\n      if (fixtureName) {\n        lines.push(`        httpx_mock.add_response(`);\n        lines.push(`            json=load_fixture(\"${fixtureName}\"),`);\n        lines.push('        )');\n        lines.push(`        page = workos.${propName}.${method}(${paginatedArgs})`);\n        lines.push('        assert isinstance(page, SyncPage)');\n        lines.push('        assert len(page.data) == 1');\n        lines.push(`        assert isinstance(page.data[0], ${paginatedItemClass})`);\n\n        lines.push('');\n        lines.push(`    def test_${method}_empty_page(self, workos, httpx_mock):`);\n        lines.push('        httpx_mock.add_response(json={\"data\": [], \"list_metadata\": {}})');\n        lines.push(`        page = workos.${propName}.${method}(${paginatedArgs})`);\n\n        lines.push('        assert isinstance(page, SyncPage)');\n        lines.push('        assert page.data == []');\n      } else {\n        // Check if the unwrapped item is a discriminated union — test dispatch through pagination\n        const discModel = unwrappedItemName ? spec.models.find((m) => m.name === unwrappedItemName) : null;\n        const disc =\n          discModel && (discModel as any).discriminator\n            ? ((discModel as any).discriminator as { property: string; mapping: Record<string, string> })\n            : null;\n        const discEntries = disc ? Object.entries(disc.mapping).sort(([a], [b]) => a.localeCompare(b)) : [];\n        if (disc && discEntries.length > 0) {\n          const [, firstVariantName] = discEntries[0];\n          const variantFixture = `${fileName(firstVariantName)}.json`;\n          const variantClass = className(firstVariantName);\n          lines.push('        httpx_mock.add_response(');\n          lines.push(`            json={\"data\": [load_fixture(\"${variantFixture}\")], \"list_metadata\": {}},`);\n          lines.push('        )');\n          lines.push(`        page = workos.${propName}.${method}(${paginatedArgs})`);\n          lines.push('        assert isinstance(page, SyncPage)');\n          lines.push('        assert len(page.data) == 1');\n          lines.push(`        assert isinstance(page.data[0], ${variantClass})`);\n        } else {\n          lines.push('        httpx_mock.add_response(json={\"data\": [], \"list_metadata\": {}})');\n          lines.push(`        page = workos.${propName}.${method}(${paginatedArgs})`);\n          lines.push('        assert isinstance(page, SyncPage)');\n        }\n      }\n    } else if (isDelete) {\n      lines.push(`    def test_${method}(self, workos, httpx_mock):`);\n      lines.push(`        ${buildDeleteSuccessResponseSetup(op)}`);\n      const args = buildTestArgs(op, spec, hiddenParams);\n      lines.push(`        result = workos.${propName}.${method}(${args})`);\n      lines.push('        assert result is None');\n      // Request assertions for delete\n      const deletePath = buildExpectedPath(op);\n      lines.push('        request = httpx_mock.get_request()');\n      lines.push(`        assert request.method == \"DELETE\"`);\n      lines.push(`        assert request.url.path.endswith(\"/${deletePath}\")`);\n    } else if (isRedirectEndpoint(op)) {\n      // Redirect endpoint: returns a URL string, no HTTP request made\n      const args = buildTestArgs(op, spec, hiddenParams);\n      lines.push(`    def test_${method}(self, workos):`);\n      lines.push(`        result = workos.${propName}.${method}(${args})`);\n      lines.push('        assert isinstance(result, str)');\n      lines.push('        assert result.startswith(\"http\")');\n    } else if (isArrayResponse) {\n      // Array response: returns List[Model]\n      const modelClass = className(plan.responseModelName!);\n      const fixtureName = `${fileName(plan.responseModelName!)}.json`;\n      const args = buildTestArgs(op, spec, hiddenParams);\n      lines.push(`    def test_${method}(self, workos, httpx_mock):`);\n      lines.push(`        httpx_mock.add_response(json=[load_fixture(\"${fixtureName}\")])`);\n      lines.push(`        result = workos.${propName}.${method}(${args})`);\n      lines.push('        assert isinstance(result, list)');\n      lines.push(`        assert len(result) == 1`);\n      lines.push(`        assert isinstance(result[0], ${modelClass})`);\n    } else if (plan.responseModelName) {\n      const modelName = plan.responseModelName;\n      const fixtureName = `${fileName(modelName)}.json`;\n      const modelClass = className(modelName);\n\n      // For discriminated union responses, resolve to the concrete variant class\n      const resolvedClass = resolvePaginatedItemClass(modelName, spec) ?? modelClass;\n      // Pick assertable fields from the resolved variant, not the dispatcher\n      const resolvedModelName =\n        resolvedClass !== modelClass\n          ? (() => {\n              const responseModel = spec.models.find((m) => m.name === modelName);\n              const disc = (responseModel as any)?.discriminator as { mapping: Record<string, string> } | undefined;\n              if (disc) {\n                for (const variantName of Object.values(disc.mapping)) {\n                  if (className(variantName) === resolvedClass) return variantName;\n                }\n              }\n              return modelName;\n            })()\n          : modelName;\n\n      lines.push(`    def test_${method}(self, workos, httpx_mock):`);\n      lines.push(`        httpx_mock.add_response(`);\n      lines.push(`            json=load_fixture(\"${fixtureName}\"),`);\n      lines.push('        )');\n      const args = buildTestArgs(op, spec, hiddenParams);\n      lines.push(`        result = workos.${propName}.${method}(${args})`);\n      lines.push(`        assert isinstance(result, ${resolvedClass})`);\n\n      // Field-value assertions: verify at least 2 scalar fields from fixture\n      const assertFields = pickAssertableFields(resolvedModelName, spec);\n      for (const af of assertFields) {\n        const op_ = af.isBool ? 'is' : '==';\n        lines.push(`        assert result.${af.field} ${op_} ${af.value}`);\n      }\n\n      // Request assertions: verify HTTP method and URL path\n      const expectedPath = buildExpectedPath(op);\n      lines.push('        request = httpx_mock.get_request()');\n      lines.push(`        assert request.method == \"${op.httpMethod.toUpperCase()}\"`);\n      lines.push(`        assert request.url.path.endswith(\"/${expectedPath}\")`);\n      // For POST/PUT/PATCH with required body fields, verify specific field values\n      if (plan.hasBody && ['post', 'put', 'patch'].includes(op.httpMethod.toLowerCase())) {\n        const bodyModel = spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n        const reqFields = bodyModel?.fields.filter((f) => f.required && !hiddenParams?.has(f.name)) ?? [];\n        if (reqFields.length > 0) {\n          lines.push('        body = json.loads(request.content)');\n          for (const f of reqFields) {\n            const testVal = generateTestValue(f.type, f.name);\n            // Only assert primitives (strings, numbers, booleans) — skip complex types\n            if (f.type.kind === 'primitive' || f.type.kind === 'enum' || f.type.kind === 'literal') {\n              lines.push(`        assert body[\"${f.name}\"] == ${testVal}`);\n            } else {\n              lines.push(`        assert \"${f.name}\" in body`);\n            }\n          }\n        }\n      }\n    } else {\n      lines.push(`    def test_${method}(self, workos, httpx_mock):`);\n      lines.push('        httpx_mock.add_response(json={})');\n      const args = buildTestArgs(op, spec, hiddenParams);\n      lines.push(`        workos.${propName}.${method}(${args})`);\n      // Request assertions for void-returning methods\n      const voidPath = buildExpectedPath(op);\n      lines.push('        request = httpx_mock.get_request()');\n      lines.push(`        assert request.method == \"${op.httpMethod.toUpperCase()}\"`);\n      lines.push(`        assert request.url.path.endswith(\"/${voidPath}\")`);\n    }\n\n    if (op.queryParams.length > 0 && !isRedirectEndpoint(op)) {\n      const queryArgs = buildQueryEncodingTestArgs(op, spec);\n      const queryAssertions = buildQueryEncodingAssertions(op, spec);\n      if (queryArgs && queryAssertions.length > 0) {\n        const responseSetup = buildQueryEncodingResponseSetup(op, plan);\n        lines.push('');\n        lines.push(`    def test_${method}_encodes_query_params(self, workos, httpx_mock):`);\n        for (const setupLine of responseSetup) {\n          lines.push(`        ${setupLine}`);\n        }\n        lines.push(`        workos.${propName}.${method}(${queryArgs})`);\n        lines.push('        request = httpx_mock.get_request()');\n        for (const assertion of queryAssertions) {\n          lines.push(`        ${assertion}`);\n        }\n      }\n    }\n  }\n\n  // Generate tests for wrapper (union-split) methods (sync)\n  emitWrapperTests(lines, resolvedOps, propName, spec, ctx, false);\n\n  // Add a RequestOptions propagation test for the first non-redirect operation\n  const firstRequestOptionsOp = service.operations.find((op) => !isRedirectEndpoint(op));\n  if (firstRequestOptionsOp) {\n    const roMethod = resolveMethodName(firstRequestOptionsOp, service, ctx);\n    const roPlan = planOperation(firstRequestOptionsOp);\n    const roResponseSetup = buildQueryEncodingResponseSetup(firstRequestOptionsOp, roPlan);\n    const roArgs = buildTestArgs(\n      firstRequestOptionsOp,\n      spec,\n      buildHiddenParams(lookupResolved(firstRequestOptionsOp, resolvedLookup)),\n    );\n    const roArgsWithOpts = roArgs\n      ? `${roArgs}, request_options={\"extra_headers\": {\"X-Custom\": \"value\"}}`\n      : 'request_options={\"extra_headers\": {\"X-Custom\": \"value\"}}';\n    lines.push('');\n    lines.push(`    def test_${roMethod}_with_request_options(self, workos, httpx_mock):`);\n    for (const setupLine of roResponseSetup) {\n      lines.push(`        ${setupLine}`);\n    }\n    lines.push(`        workos.${propName}.${roMethod}(${roArgsWithOpts})`);\n    lines.push('        request = httpx_mock.get_request()');\n    lines.push('        assert request.headers[\"X-Custom\"] == \"value\"');\n  }\n\n  // Add an error test for the first non-delete, non-redirect operation\n  const firstNonDelete = service.operations.find((op) => !planOperation(op).isDelete && !isRedirectEndpoint(op));\n  if (firstNonDelete) {\n    const method = resolveMethodName(firstNonDelete, service, ctx);\n    lines.push('');\n    lines.push(`    def test_${method}_unauthorized(self, workos, httpx_mock):`);\n    lines.push('        httpx_mock.add_response(');\n    lines.push('            status_code=401,');\n    lines.push('            json={\"message\": \"Unauthorized\"},');\n    lines.push('        )');\n    lines.push('        with pytest.raises(AuthenticationError):');\n    const args = buildTestArgs(firstNonDelete, spec, buildHiddenParams(lookupResolved(firstNonDelete, resolvedLookup)));\n    lines.push(`            workos.${propName}.${method}(${args})`);\n\n    lines.push('');\n    lines.push(`    def test_${method}_not_found(self, httpx_mock):`);\n    lines.push('        workos = WorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push('            httpx_mock.add_response(status_code=404, json={\"message\": \"Not found\"})');\n    lines.push('            with pytest.raises(NotFoundError):');\n    lines.push(`                workos.${propName}.${method}(${args})`);\n    lines.push('        finally:');\n    lines.push('            workos.close()');\n\n    lines.push('');\n    lines.push(`    def test_${method}_rate_limited(self, httpx_mock):`);\n    lines.push('        workos = WorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push(\n      '            httpx_mock.add_response(status_code=429, headers={\"Retry-After\": \"0\"}, json={\"message\": \"Slow down\"})',\n    );\n    lines.push('            with pytest.raises(RateLimitExceededError):');\n    lines.push(`                workos.${propName}.${method}(${args})`);\n    lines.push('        finally:');\n    lines.push('            workos.close()');\n\n    lines.push('');\n    lines.push(`    def test_${method}_server_error(self, httpx_mock):`);\n    lines.push('        workos = WorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push('            httpx_mock.add_response(status_code=500, json={\"message\": \"Server error\"})');\n    lines.push('            with pytest.raises(ServerError):');\n    lines.push(`                workos.${propName}.${method}(${args})`);\n    lines.push('        finally:');\n    lines.push('            workos.close()');\n  }\n\n  // Add 400/422 error tests for the first non-delete, non-redirect operation\n  const firstErrorTargetOp = service.operations.find((op) => !planOperation(op).isDelete && !isRedirectEndpoint(op));\n  if (firstErrorTargetOp) {\n    const writeMethod = resolveMethodName(firstErrorTargetOp, service, ctx);\n    const writeArgs = buildTestArgs(\n      firstErrorTargetOp,\n      spec,\n      buildHiddenParams(lookupResolved(firstErrorTargetOp, resolvedLookup)),\n    );\n\n    lines.push('');\n    lines.push(`    def test_${writeMethod}_bad_request(self, httpx_mock):`);\n    lines.push('        workos = WorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push('            httpx_mock.add_response(status_code=400, json={\"message\": \"Bad request\"})');\n    lines.push('            with pytest.raises(BadRequestError):');\n    lines.push(`                workos.${propName}.${writeMethod}(${writeArgs})`);\n    lines.push('        finally:');\n    lines.push('            workos.close()');\n\n    lines.push('');\n    lines.push(`    def test_${writeMethod}_unprocessable(self, httpx_mock):`);\n    lines.push('        workos = WorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push('            httpx_mock.add_response(status_code=422, json={\"message\": \"Unprocessable\"})');\n    lines.push('            with pytest.raises(UnprocessableEntityError):');\n    lines.push(`                workos.${propName}.${writeMethod}(${writeArgs})`);\n    lines.push('        finally:');\n    lines.push('            workos.close()');\n  }\n\n  // --- Async test class ---\n  lines.push('');\n  lines.push('');\n  lines.push(`class TestAsync${resolvedName}:`);\n\n  const asyncEmittedTestMethods = new Set<string>();\n  for (const op of service.operations) {\n    const plan = planOperation(op);\n    const asyncResolvedOp = lookupResolved(op, resolvedLookup);\n    const asyncHiddenParams = buildHiddenParams(asyncResolvedOp);\n    let method = resolveMethodName(op, service, ctx);\n\n    if (asyncEmittedTestMethods.has(method)) {\n      const fallback = toSnakeCase(op.name);\n      if (fallback !== method && !asyncEmittedTestMethods.has(fallback)) {\n        method = fallback;\n      } else {\n        continue;\n      }\n    }\n    asyncEmittedTestMethods.add(method);\n\n    const isDelete = plan.isDelete;\n    const isPaginated = plan.isPaginated;\n    const isAsyncArrayResponse = op.response.kind === 'array' && op.response.items.kind === 'model';\n    const asyncArgs = buildTestArgs(op, spec, asyncHiddenParams);\n\n    lines.push('');\n\n    if (isPaginated) {\n      const itemType = op.pagination!.itemType;\n      let itemName = itemType.kind === 'model' ? itemType.name : null;\n      if (itemName) {\n        const wrapperModel = spec.models.find((m) => m.name === itemName);\n        if (wrapperModel && isListWrapperModel(wrapperModel)) {\n          const dataField = wrapperModel.fields.find((f) => f.name === 'data');\n          if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n            itemName = dataField.type.items.name;\n          }\n        }\n      }\n      // Skip fixture-based testing for models with no fields (discriminated unions)\n      // Save the unwrapped name before nulling — needed for discriminator check below\n      const unwrappedItemName = itemName;\n      if (itemName) {\n        const itemModel = spec.models.find((m) => m.name === itemName);\n        if (itemModel && itemModel.fields.length === 0) itemName = null;\n      }\n      const fixtureName = itemName ? `list_${fileName(itemName)}.json` : null;\n\n      const asyncPaginatedItemClass = resolvePaginatedItemClass(itemName, spec);\n\n      pushAsyncTestDef(lines, `    async def test_${method}(self, async_workos, httpx_mock):`);\n      if (fixtureName) {\n        lines.push(`        httpx_mock.add_response(json=load_fixture(\"${fixtureName}\"))`);\n        lines.push(`        page = await async_workos.${propName}.${method}(${asyncArgs})`);\n        lines.push('        assert isinstance(page, AsyncPage)');\n        lines.push('        assert len(page.data) == 1');\n        lines.push(`        assert isinstance(page.data[0], ${asyncPaginatedItemClass})`);\n\n        lines.push('');\n        pushAsyncTestDef(lines, `    async def test_${method}_empty_page(self, async_workos, httpx_mock):`);\n        lines.push('        httpx_mock.add_response(json={\"data\": [], \"list_metadata\": {}})');\n        lines.push(`        page = await async_workos.${propName}.${method}(${asyncArgs})`);\n        lines.push('        assert isinstance(page, AsyncPage)');\n        lines.push('        assert page.data == []');\n      } else {\n        // Check if the unwrapped item is a discriminated union — test dispatch through pagination\n        const discModel = unwrappedItemName ? spec.models.find((m) => m.name === unwrappedItemName) : null;\n        const disc =\n          discModel && (discModel as any).discriminator\n            ? ((discModel as any).discriminator as { property: string; mapping: Record<string, string> })\n            : null;\n        const discEntries = disc ? Object.entries(disc.mapping).sort(([a], [b]) => a.localeCompare(b)) : [];\n        if (disc && discEntries.length > 0) {\n          const [, firstVariantName] = discEntries[0];\n          const variantFixture = `${fileName(firstVariantName)}.json`;\n          const variantClass = className(firstVariantName);\n          lines.push('        httpx_mock.add_response(');\n          lines.push(`            json={\"data\": [load_fixture(\"${variantFixture}\")], \"list_metadata\": {}},`);\n          lines.push('        )');\n          lines.push(`        page = await async_workos.${propName}.${method}(${asyncArgs})`);\n          lines.push('        assert isinstance(page, AsyncPage)');\n          lines.push('        assert len(page.data) == 1');\n          lines.push(`        assert isinstance(page.data[0], ${variantClass})`);\n        } else {\n          lines.push('        httpx_mock.add_response(json={\"data\": [], \"list_metadata\": {}})');\n          lines.push(`        page = await async_workos.${propName}.${method}(${asyncArgs})`);\n          lines.push('        assert isinstance(page, AsyncPage)');\n        }\n      }\n    } else if (isDelete) {\n      const deletePath = buildExpectedPath(op);\n      pushAsyncTestDef(lines, `    async def test_${method}(self, async_workos, httpx_mock):`);\n      lines.push(`        ${buildDeleteSuccessResponseSetup(op)}`);\n      lines.push(`        result = await async_workos.${propName}.${method}(${asyncArgs})`);\n      lines.push('        assert result is None');\n      lines.push('        request = httpx_mock.get_request()');\n      lines.push(`        assert request.method == \"DELETE\"`);\n      lines.push(`        assert request.url.path.endswith(\"/${deletePath}\")`);\n    } else if (isRedirectEndpoint(op)) {\n      // Redirect methods are sync (def, not async def) even in the async class\n      lines.push(`    def test_${method}(self, async_workos):`);\n      lines.push(`        result = async_workos.${propName}.${method}(${asyncArgs})`);\n      lines.push('        assert isinstance(result, str)');\n      lines.push('        assert result.startswith(\"http\")');\n    } else if (isAsyncArrayResponse) {\n      const modelClass = className(plan.responseModelName!);\n      const fixtureName = `${fileName(plan.responseModelName!)}.json`;\n      pushAsyncTestDef(lines, `    async def test_${method}(self, async_workos, httpx_mock):`);\n      lines.push(`        httpx_mock.add_response(json=[load_fixture(\"${fixtureName}\")])`);\n      lines.push(`        result = await async_workos.${propName}.${method}(${asyncArgs})`);\n      lines.push('        assert isinstance(result, list)');\n      lines.push(`        assert len(result) == 1`);\n      lines.push(`        assert isinstance(result[0], ${modelClass})`);\n    } else if (plan.responseModelName) {\n      const modelName = plan.responseModelName;\n      const fixtureName = `${fileName(modelName)}.json`;\n      const modelClass = className(modelName);\n\n      // For discriminated union responses, resolve to the concrete variant class\n      const asyncResolvedClass = resolvePaginatedItemClass(modelName, spec) ?? modelClass;\n      const asyncResolvedModelName =\n        asyncResolvedClass !== modelClass\n          ? (() => {\n              const responseModel = spec.models.find((m) => m.name === modelName);\n              const disc = (responseModel as any)?.discriminator as { mapping: Record<string, string> } | undefined;\n              if (disc) {\n                for (const variantName of Object.values(disc.mapping)) {\n                  if (className(variantName) === asyncResolvedClass) return variantName;\n                }\n              }\n              return modelName;\n            })()\n          : modelName;\n\n      pushAsyncTestDef(lines, `    async def test_${method}(self, async_workos, httpx_mock):`);\n      lines.push(`        httpx_mock.add_response(json=load_fixture(\"${fixtureName}\"))`);\n      lines.push(`        result = await async_workos.${propName}.${method}(${asyncArgs})`);\n      lines.push(`        assert isinstance(result, ${asyncResolvedClass})`);\n      // Field-value assertions\n      const assertFields = pickAssertableFields(asyncResolvedModelName, spec);\n      for (const af of assertFields) {\n        const op_ = af.isBool ? 'is' : '==';\n        lines.push(`        assert result.${af.field} ${op_} ${af.value}`);\n      }\n      // Request assertions\n      const expectedPath = buildExpectedPath(op);\n      lines.push('        request = httpx_mock.get_request()');\n      lines.push(`        assert request.method == \"${op.httpMethod.toUpperCase()}\"`);\n      lines.push(`        assert request.url.path.endswith(\"/${expectedPath}\")`);\n    } else {\n      const voidPath = buildExpectedPath(op);\n      pushAsyncTestDef(lines, `    async def test_${method}(self, async_workos, httpx_mock):`);\n      lines.push('        httpx_mock.add_response(json={})');\n      lines.push(`        await async_workos.${propName}.${method}(${asyncArgs})`);\n      lines.push('        request = httpx_mock.get_request()');\n      lines.push(`        assert request.method == \"${op.httpMethod.toUpperCase()}\"`);\n      lines.push(`        assert request.url.path.endswith(\"/${voidPath}\")`);\n    }\n\n    if (op.queryParams.length > 0 && !isRedirectEndpoint(op)) {\n      const queryArgs = buildQueryEncodingTestArgs(op, spec);\n      const queryAssertions = buildQueryEncodingAssertions(op, spec);\n      if (queryArgs && queryAssertions.length > 0) {\n        const responseSetup = buildQueryEncodingResponseSetup(op, plan);\n        lines.push('');\n        pushAsyncTestDef(lines, `    async def test_${method}_encodes_query_params(self, async_workos, httpx_mock):`);\n        for (const setupLine of responseSetup) {\n          lines.push(`        ${setupLine}`);\n        }\n        lines.push(`        await async_workos.${propName}.${method}(${queryArgs})`);\n        lines.push('        request = httpx_mock.get_request()');\n        for (const assertion of queryAssertions) {\n          lines.push(`        ${assertion}`);\n        }\n      }\n    }\n  }\n\n  // Generate tests for wrapper (union-split) methods (async)\n  emitWrapperTests(lines, resolvedOps, propName, spec, ctx, true);\n\n  // Add async RequestOptions propagation test\n  const asyncFirstRequestOptionsOp = service.operations.find((op) => !isRedirectEndpoint(op));\n  if (asyncFirstRequestOptionsOp) {\n    const asyncRoMethod = resolveMethodName(asyncFirstRequestOptionsOp, service, ctx);\n    const asyncRoPlan = planOperation(asyncFirstRequestOptionsOp);\n    const asyncRoResponseSetup = buildQueryEncodingResponseSetup(asyncFirstRequestOptionsOp, asyncRoPlan);\n    const asyncRoArgs = buildTestArgs(\n      asyncFirstRequestOptionsOp,\n      spec,\n      buildHiddenParams(lookupResolved(asyncFirstRequestOptionsOp, resolvedLookup)),\n    );\n    const asyncRoArgsWithOpts = asyncRoArgs\n      ? `${asyncRoArgs}, request_options={\"extra_headers\": {\"X-Custom\": \"value\"}}`\n      : 'request_options={\"extra_headers\": {\"X-Custom\": \"value\"}}';\n    lines.push('');\n    pushAsyncTestDef(\n      lines,\n      `    async def test_${asyncRoMethod}_with_request_options(self, async_workos, httpx_mock):`,\n    );\n    for (const setupLine of asyncRoResponseSetup) {\n      lines.push(`        ${setupLine}`);\n    }\n    lines.push(`        await async_workos.${propName}.${asyncRoMethod}(${asyncRoArgsWithOpts})`);\n    lines.push('        request = httpx_mock.get_request()');\n    lines.push('        assert request.headers[\"X-Custom\"] == \"value\"');\n  }\n\n  // Async error tests for the first non-delete operation\n  const asyncFirstNonDelete = service.operations.find((op) => !planOperation(op).isDelete && !isRedirectEndpoint(op));\n  if (asyncFirstNonDelete) {\n    const asyncErrMethod = resolveMethodName(asyncFirstNonDelete, service, ctx);\n    const asyncErrArgs = buildTestArgs(\n      asyncFirstNonDelete,\n      spec,\n      buildHiddenParams(lookupResolved(asyncFirstNonDelete, resolvedLookup)),\n    );\n    lines.push('');\n    pushAsyncTestDef(lines, `    async def test_${asyncErrMethod}_unauthorized(self, async_workos, httpx_mock):`);\n    lines.push('        httpx_mock.add_response(status_code=401, json={\"message\": \"Unauthorized\"})');\n    lines.push('        with pytest.raises(AuthenticationError):');\n    lines.push(`            await async_workos.${propName}.${asyncErrMethod}(${asyncErrArgs})`);\n    lines.push('');\n    pushAsyncTestDef(lines, `    async def test_${asyncErrMethod}_not_found(self, httpx_mock):`);\n    lines.push('        workos = AsyncWorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push('            httpx_mock.add_response(status_code=404, json={\"message\": \"Not found\"})');\n    lines.push('            with pytest.raises(NotFoundError):');\n    lines.push(`                await workos.${propName}.${asyncErrMethod}(${asyncErrArgs})`);\n    lines.push('        finally:');\n    lines.push('            await workos.close()');\n    lines.push('');\n    pushAsyncTestDef(lines, `    async def test_${asyncErrMethod}_rate_limited(self, httpx_mock):`);\n    lines.push('        workos = AsyncWorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push(\n      '            httpx_mock.add_response(status_code=429, headers={\"Retry-After\": \"0\"}, json={\"message\": \"Slow down\"})',\n    );\n    lines.push('            with pytest.raises(RateLimitExceededError):');\n    lines.push(`                await workos.${propName}.${asyncErrMethod}(${asyncErrArgs})`);\n    lines.push('        finally:');\n    lines.push('            await workos.close()');\n    lines.push('');\n    pushAsyncTestDef(lines, `    async def test_${asyncErrMethod}_server_error(self, httpx_mock):`);\n    lines.push('        workos = AsyncWorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push('            httpx_mock.add_response(status_code=500, json={\"message\": \"Server error\"})');\n    lines.push('            with pytest.raises(ServerError):');\n    lines.push(`                await workos.${propName}.${asyncErrMethod}(${asyncErrArgs})`);\n    lines.push('        finally:');\n    lines.push('            await workos.close()');\n  }\n\n  // Async 400/422 error tests for the first non-delete, non-redirect operation\n  const asyncFirstErrorTargetOp = service.operations.find(\n    (op) => !planOperation(op).isDelete && !isRedirectEndpoint(op),\n  );\n  if (asyncFirstErrorTargetOp) {\n    const asyncWriteMethod = resolveMethodName(asyncFirstErrorTargetOp, service, ctx);\n    const asyncWriteArgs = buildTestArgs(\n      asyncFirstErrorTargetOp,\n      spec,\n      buildHiddenParams(lookupResolved(asyncFirstErrorTargetOp, resolvedLookup)),\n    );\n\n    lines.push('');\n    pushAsyncTestDef(lines, `    async def test_${asyncWriteMethod}_bad_request(self, httpx_mock):`);\n    lines.push('        workos = AsyncWorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push('            httpx_mock.add_response(status_code=400, json={\"message\": \"Bad request\"})');\n    lines.push('            with pytest.raises(BadRequestError):');\n    lines.push(`                await workos.${propName}.${asyncWriteMethod}(${asyncWriteArgs})`);\n    lines.push('        finally:');\n    lines.push('            await workos.close()');\n\n    lines.push('');\n    pushAsyncTestDef(lines, `    async def test_${asyncWriteMethod}_unprocessable(self, httpx_mock):`);\n    lines.push('        workos = AsyncWorkOSClient(api_key=\"sk_test_123\", client_id=\"client_test\", max_retries=0)');\n    lines.push('        try:');\n    lines.push('            httpx_mock.add_response(status_code=422, json={\"message\": \"Unprocessable\"})');\n    lines.push('            with pytest.raises(UnprocessableEntityError):');\n    lines.push(`                await workos.${propName}.${asyncWriteMethod}(${asyncWriteArgs})`);\n    lines.push('        finally:');\n    lines.push('            await workos.close()');\n  }\n\n  return {\n    path: `tests/test_${fileName(resolvedName)}.py`,\n    content: lines.join('\\n'),\n    integrateTarget: true,\n    overwriteExisting: true,\n  };\n}\n\n/**\n * Emit tests for wrapper (union-split) methods.\n *\n * For each resolved operation that has wrappers, emit a test per wrapper\n * that calls the wrapper method, asserts the response type, and verifies\n * that constant defaults appear in the request body.\n */\nfunction emitWrapperTests(\n  lines: string[],\n  resolvedOps: ResolvedOperation[] | undefined,\n  propName: string,\n  spec: ApiSpec,\n  ctx: EmitterContext,\n  isAsync: boolean,\n): void {\n  if (!resolvedOps) return;\n\n  for (const r of resolvedOps) {\n    if (!r.wrappers || r.wrappers.length === 0) continue;\n\n    for (const wrapper of r.wrappers) {\n      const method = wrapper.name;\n      const wrapperParams = resolveWrapperParams(wrapper, ctx);\n      const resolvedResponseClass = wrapper.responseModelName\n        ? (resolvePaginatedItemClass(wrapper.responseModelName, spec) ?? className(wrapper.responseModelName))\n        : null;\n      const fixtureName = wrapper.responseModelName ? `${fileName(wrapper.responseModelName)}.json` : null;\n\n      // Build test args for required wrapper params\n      const argParts: string[] = [];\n      for (const { paramName, field, isOptional } of wrapperParams) {\n        if (isOptional) continue;\n        const pyName = fieldName(paramName);\n        const testVal = field ? generateTestValue(field.type, field.name) : '\"test_value\"';\n        argParts.push(`${pyName}=${testVal}`);\n      }\n      const args = argParts.join(', ');\n\n      lines.push('');\n      if (isAsync) {\n        pushAsyncTestDef(lines, `    async def test_${method}(self, async_workos, httpx_mock):`);\n        if (fixtureName) {\n          lines.push(`        httpx_mock.add_response(json=load_fixture(\"${fixtureName}\"))`);\n          lines.push(`        result = await async_workos.${propName}.${method}(${args})`);\n          if (resolvedResponseClass) {\n            lines.push(`        assert isinstance(result, ${resolvedResponseClass})`);\n          }\n        } else {\n          lines.push('        httpx_mock.add_response(json={})');\n          lines.push(`        await async_workos.${propName}.${method}(${args})`);\n        }\n      } else {\n        lines.push(`    def test_${method}(self, workos, httpx_mock):`);\n        if (fixtureName) {\n          lines.push(`        httpx_mock.add_response(json=load_fixture(\"${fixtureName}\"))`);\n          lines.push(`        result = workos.${propName}.${method}(${args})`);\n          if (resolvedResponseClass) {\n            lines.push(`        assert isinstance(result, ${resolvedResponseClass})`);\n          }\n        } else {\n          lines.push('        httpx_mock.add_response(json={})');\n          lines.push(`        workos.${propName}.${method}(${args})`);\n        }\n      }\n\n      // Assert the request body contains the correct defaults\n      lines.push('        request = httpx_mock.get_request()');\n      lines.push(`        assert request.method == \"${r.operation.httpMethod.toUpperCase()}\"`);\n\n      if (Object.keys(wrapper.defaults).length > 0) {\n        lines.push('        body = json.loads(request.content)');\n        for (const [key, value] of Object.entries(wrapper.defaults)) {\n          lines.push(`        assert body[\"${key}\"] == ${pythonLiteral(value)}`);\n        }\n      }\n    }\n  }\n}\n\n/**\n * Pick up to N scalar fields from a model fixture to use for value assertions.\n * Returns tuples of [snake_case_field_name, python_literal_value].\n */\nfunction pickAssertableFields(\n  modelName: string,\n  spec: ApiSpec,\n  maxFields: number = 2,\n): { field: string; value: string; isBool?: boolean }[] {\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n  const model = modelMap.get(modelName);\n  if (!model) return [];\n\n  const fixture = generateModelFixture(model, modelMap, enumMap);\n  const results: { field: string; value: string; isBool?: boolean }[] = [];\n\n  for (const f of model.fields) {\n    if (results.length >= maxFields) break;\n    const val = fixture[f.name];\n    if (val === undefined || val === null) continue;\n    if (typeof val === 'string') {\n      // Skip strings containing characters that are hard to represent as Python literals\n      if (val.includes('\"') || val.includes(\"'\") || val.includes('{') || val.includes('\\\\') || val.includes('\\n'))\n        continue;\n      // DOMAIN identifier: asserted as `result.<attr>` (honors `domainName`).\n      results.push({ field: domainFieldName(f), value: `\"${val}\"` });\n    } else if (typeof val === 'boolean') {\n      // Use \"is True/False\" to satisfy ruff E712\n      results.push({ field: domainFieldName(f), value: val ? 'True' : 'False', isBool: true });\n    } else if (typeof val === 'number') {\n      results.push({ field: domainFieldName(f), value: String(val) });\n    }\n  }\n  return results;\n}\n\n/**\n * Build a Python string literal for the expected request URL suffix.\n * Replaces path params with their test values.\n */\nfunction buildExpectedPath(op: Operation): string {\n  let path = op.path.replace(/^\\//, '');\n  for (const param of op.pathParams) {\n    path = path.replace(`{${param.name}}`, `test_${param.name}`);\n  }\n  return path;\n}\n\n/**\n * Build test arguments string for an operation call.\n */\nfunction buildTestArgs(op: Operation, spec: ApiSpec, hiddenParams?: Set<string>): string {\n  const args: string[] = [];\n\n  // Path params as positional args\n  for (const param of op.pathParams) {\n    args.push(`\"test_${param.name}\"`);\n  }\n\n  const pathParamNames = new Set(op.pathParams.map((p) => fieldName(p.name)));\n\n  // Required body fields as keyword args (matching the expanded-field signature)\n  const plan = planOperation(op);\n  if (plan.hasBody && op.requestBody?.kind === 'model') {\n    const requestBodyName = op.requestBody.name;\n    const bodyModel = spec.models.find((m) => m.name === requestBodyName);\n    if (bodyModel) {\n      const reqFields = bodyModel.fields.filter((f) => f.required && !hiddenParams?.has(f.name));\n      for (const f of reqFields) {\n        const paramName = bodyParamName(f, pathParamNames);\n        args.push(`${paramName}=${generateTestValue(f.type, f.name)}`);\n      }\n    }\n  } else if (plan.hasBody && op.requestBody?.kind === 'union') {\n    // Union body — pick the first variant model and use its fixture\n    const variants = (op.requestBody as any).variants ?? [];\n    const firstModelVariant = variants.find((v: any) => v.kind === 'model');\n    if (firstModelVariant) {\n      args.push(`body=load_fixture(\"${fileName(firstModelVariant.name)}.json\")`);\n    } else {\n      args.push('body={}');\n    }\n  }\n\n  // Per-operation Bearer token auth (e.g., access_token for SSO)\n  const hasBearerOverride = op.security?.some((s) => s.schemeName !== 'bearerAuth') ?? false;\n  if (hasBearerOverride) {\n    const tokenParamName = fieldName(op.security!.find((s) => s.schemeName !== 'bearerAuth')!.schemeName);\n    args.push(`${tokenParamName}=\"test_${tokenParamName}\"`);\n  }\n\n  // Parameter group args — emit first variant constructor\n  const groupedParamNames = collectGroupedParamNames(op);\n  for (const group of op.parameterGroups ?? []) {\n    const variant = group.variants[0];\n    const variantClass = className(`${group.name}_${variant.name}`);\n    const variantArgs = variant.parameters.map((p) => `${fieldName(p.name)}=\"test_value\"`).join(', ');\n    args.push(`${fieldName(group.name)}=${variantClass}(${variantArgs})`);\n  }\n\n  // Required query params (for all methods, including paginated)\n  if (plan.hasQueryParams) {\n    for (const param of op.queryParams) {\n      // Skip hidden/injected params\n      if (hiddenParams?.has(param.name)) continue;\n      // Skip params that belong to parameter groups\n      if (groupedParamNames.has(param.name)) continue;\n      // Skip pagination params (they're optional)\n      if (plan.isPaginated && ['limit', 'before', 'after', 'order'].includes(param.name)) continue;\n      // Skip params already covered by body fields\n      if (plan.hasBody && op.requestBody?.kind === 'model') {\n        const rbName = op.requestBody.name;\n        const bodyModel = spec.models.find((m) => m.name === rbName);\n        // Compare the body field's DOMAIN identifier (honors `domainName`)\n        // against the param kwarg name; the param has no domainName override.\n        if (bodyModel?.fields.some((f) => domainFieldName(f) === fieldName(param.name))) continue;\n      }\n      if (param.required && !pathParamNames.has(fieldName(param.name))) {\n        args.push(`${fieldName(param.name)}=${generateTestValue(param.type, param.name)}`);\n      }\n    }\n  }\n\n  return args.join(', ');\n}\n\nfunction buildQueryEncodingTestArgs(op: Operation, spec: ApiSpec): string {\n  const args: string[] = [];\n  const groupedParamNames = collectGroupedParamNames(op);\n\n  for (const param of op.pathParams) {\n    args.push(`\"test_${param.name}\"`);\n  }\n\n  const pathParamNames = new Set(op.pathParams.map((p) => fieldName(p.name)));\n  const plan = planOperation(op);\n\n  if (plan.hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = spec.models.find((m) => m.name === (op.requestBody as { kind: string; name: string }).name);\n    const bodyArgGrouped = collectGroupedParamNames(op);\n    for (const field of bodyModel?.fields.filter((f) => f.required && !bodyArgGrouped.has(f.name)) ?? []) {\n      args.push(`${bodyParamName(field, pathParamNames)}=${generateTestValue(field.type, field.name)}`);\n    }\n  } else if (plan.hasBody && op.requestBody?.kind === 'union') {\n    const variants = (op.requestBody as any).variants ?? [];\n    const firstModelVariant = variants.find((v: any) => v.kind === 'model');\n    args.push(firstModelVariant ? `body=load_fixture(\"${fileName(firstModelVariant.name)}.json\")` : 'body={}');\n  }\n\n  // Parameter group args — emit first variant constructor\n  for (const group of op.parameterGroups ?? []) {\n    const variant = group.variants[0];\n    const variantClass = className(`${group.name}_${variant.name}`);\n    const variantArgs = variant.parameters\n      .map((p) => `${fieldName(p.name)}=${generateQueryEncodingValue(p.type, p.name)}`)\n      .join(', ');\n    args.push(`${fieldName(group.name)}=${variantClass}(${variantArgs})`);\n  }\n\n  if (plan.isPaginated) {\n    args.push('limit=10');\n    args.push('before=\"cursor before\"');\n    args.push('after=\"cursor/after\"');\n    const orderParam = op.queryParams.find((param) => param.name === 'order');\n    if (orderParam) {\n      args.push(`order=${generateQueryEncodingValue(orderParam.type, 'order')}`);\n    }\n  }\n\n  for (const param of op.queryParams) {\n    if (plan.isPaginated && ['limit', 'before', 'after', 'order'].includes(param.name)) continue;\n    if (groupedParamNames.has(param.name)) continue;\n    // Include explode=false array params; skip other array params (complex serialization)\n    if (param.type.kind === 'array' && (param as any).explode !== false) continue;\n    const paramName = fieldName(param.name);\n    if (pathParamNames.has(paramName)) continue;\n    if (plan.hasBody && op.requestBody?.kind === 'model') {\n      const bodyModel = spec.models.find((m) => m.name === (op.requestBody as { kind: string; name: string }).name);\n      if (bodyModel?.fields.some((field) => bodyParamName(field, pathParamNames) === paramName)) continue;\n    }\n    if ((param as any).explode === false && param.type.kind === 'array') {\n      args.push(`${paramName}=[\"val1\", \"val2\"]`);\n    } else {\n      args.push(`${paramName}=${generateQueryEncodingValue(param.type, param.name)}`);\n    }\n  }\n\n  return args.join(', ');\n}\n\nfunction buildQueryEncodingResponseSetup(op: Operation, plan: ReturnType<typeof planOperation>): string[] {\n  if (plan.isPaginated) {\n    return ['httpx_mock.add_response(json={\"data\": [], \"list_metadata\": {}})'];\n  }\n  if (plan.isDelete) {\n    return [buildDeleteSuccessResponseSetup(op)];\n  }\n  if (op.response.kind === 'array') {\n    if (op.response.items.kind === 'model') {\n      return [`httpx_mock.add_response(json=[load_fixture(\"${fileName(op.response.items.name)}.json\")])`];\n    }\n    return ['httpx_mock.add_response(json=[])'];\n  }\n  if (plan.responseModelName) {\n    return [`httpx_mock.add_response(json=load_fixture(\"${fileName(plan.responseModelName)}.json\"))`];\n  }\n  return ['httpx_mock.add_response(json={})'];\n}\n\nfunction buildQueryEncodingAssertions(op: Operation, spec: ApiSpec): string[] {\n  const assertions: string[] = [];\n  const plan = planOperation(op);\n  const pathParamNames = new Set(op.pathParams.map((param) => fieldName(param.name)));\n  const groupedParamNames = collectGroupedParamNames(op);\n\n  // Assert first variant's params from parameter groups\n  for (const group of op.parameterGroups ?? []) {\n    const variant = group.variants[0];\n    for (const param of variant.parameters) {\n      assertions.push(\n        `assert request.url.params[\"${param.name}\"] == ${toPythonLiteral(expectedQueryEncodingValue(param.type, param.name))}`,\n      );\n    }\n  }\n\n  if (plan.isPaginated) {\n    assertions.push('assert request.url.params[\"limit\"] == \"10\"');\n    assertions.push('assert request.url.params[\"before\"] == \"cursor before\"');\n    assertions.push('assert request.url.params[\"after\"] == \"cursor/after\"');\n    const orderParam = op.queryParams.find((param) => param.name === 'order');\n    if (orderParam) {\n      assertions.push(\n        `assert request.url.params[\"order\"] == ${toPythonLiteral(expectedQueryEncodingValue(orderParam.type, 'order'))}`,\n      );\n    }\n  }\n\n  for (const param of op.queryParams) {\n    if (plan.isPaginated && ['limit', 'before', 'after', 'order'].includes(param.name)) continue;\n    if (groupedParamNames.has(param.name)) continue;\n    // Include explode=false array params; skip other array params (complex serialization)\n    if (param.type.kind === 'array' && (param as any).explode !== false) continue;\n    const paramName = fieldName(param.name);\n    if (pathParamNames.has(paramName)) continue;\n    if (plan.hasBody && op.requestBody?.kind === 'model') {\n      const bodyModel = spec.models.find(\n        (model) => model.name === (op.requestBody as { kind: string; name: string }).name,\n      );\n      if (bodyModel?.fields.some((field) => bodyParamName(field, pathParamNames) === paramName)) continue;\n    }\n    if ((param as any).explode === false && param.type.kind === 'array') {\n      assertions.push(`assert request.url.params[\"${param.name}\"] == \"val1,val2\"`);\n    } else {\n      assertions.push(\n        `assert request.url.params[\"${param.name}\"] == ${toPythonLiteral(expectedQueryEncodingValue(param.type, param.name))}`,\n      );\n    }\n  }\n\n  return assertions;\n}\n\n/**\n * Generate a representative Python value literal for a given type, for use in tests.\n */\nfunction generateTestValue(ref: TypeRef, name: string): string {\n  switch (ref.kind) {\n    case 'primitive':\n      switch (ref.type) {\n        case 'string':\n          return `\"test_${name}\"`;\n        case 'integer':\n          return '1';\n        case 'number':\n          return '1.0';\n        case 'boolean':\n          return 'True';\n        default:\n          return '{}';\n      }\n    case 'array':\n      return '[]';\n    case 'enum': {\n      const enumValues = (ref as any).values as (string | number)[] | undefined;\n      const enumClass = className(ref.name);\n      if (enumValues && enumValues.length > 0) {\n        const first = enumValues[0];\n        const literal = typeof first === 'string' ? `\"${first}\"` : String(first);\n        return `${enumClass}(${literal})`;\n      }\n      return `${enumClass}(\"test\")`;\n    }\n    case 'model':\n      return `${className(ref.name)}.from_dict(load_fixture(\"${fileName(ref.name)}.json\"))`;\n    case 'nullable':\n      return generateTestValue(ref.inner, name);\n    case 'map':\n      return '{}';\n    case 'literal':\n      return typeof ref.value === 'string' ? `\"${ref.value}\"` : String(ref.value);\n    case 'union':\n      if (ref.variants.length > 0) return generateTestValue(ref.variants[0], name);\n      return 'None';\n    default:\n      return '{}';\n  }\n}\n\nfunction generateQueryEncodingValue(ref: TypeRef, name: string): string {\n  switch (ref.kind) {\n    case 'primitive':\n      switch (ref.type) {\n        case 'string':\n          return `\"${expectedQueryEncodingValue(ref, name)}\"`;\n        case 'integer':\n          return '7';\n        case 'number':\n          return '7.5';\n        case 'boolean':\n          return 'True';\n        default:\n          return '{}';\n      }\n    case 'enum': {\n      const value = expectedQueryEncodingValue(ref, name);\n      return `${className(ref.name)}(\"${value}\")`;\n    }\n    case 'nullable':\n      return generateQueryEncodingValue(ref.inner, name);\n    case 'literal':\n      return toPythonLiteral(ref.value);\n    default:\n      return generateTestValue(ref, name);\n  }\n}\n\nfunction expectedQueryEncodingValue(ref: TypeRef, name: string): string | number {\n  switch (ref.kind) {\n    case 'primitive':\n      switch (ref.type) {\n        case 'string':\n          return `value ${name}/test`;\n        case 'integer':\n          return 7;\n        case 'number':\n          return 7.5;\n        case 'boolean':\n          return 'true';\n        default:\n          return `value ${name}`;\n      }\n    case 'enum': {\n      const enumValues = (ref as any).values as (string | number)[] | undefined;\n      if (enumValues && enumValues.length > 0) return enumValues[0];\n      return `value_${name}`;\n    }\n    case 'nullable':\n      return expectedQueryEncodingValue(ref.inner, name);\n    case 'literal': {\n      const v = ref.value;\n      if (typeof v === 'boolean') return v ? 'true' : 'false';\n      return v ?? `value_${name}`;\n    }\n    default:\n      return `value_${name}`;\n  }\n}\n\nfunction buildMinimalModelPayload(model: Model, fixture: Record<string, unknown>): Record<string, unknown> {\n  const payload: Record<string, unknown> = {};\n  for (const field of model.fields) {\n    if (!field.required) continue;\n    if (field.type.kind === 'nullable') {\n      payload[field.name] = null;\n      continue;\n    }\n    payload[field.name] = fixture[field.name];\n  }\n  return payload;\n}\n\nfunction buildPayloadWithoutOptionalNonNullableFields(\n  model: Model,\n  fixture: Record<string, unknown>,\n): Record<string, unknown> {\n  const payload: Record<string, unknown> = { ...fixture };\n  for (const field of model.fields) {\n    if (!field.required && field.type.kind !== 'nullable') {\n      delete payload[field.name];\n    }\n  }\n  return payload;\n}\n\nfunction buildPayloadWithNullableFieldsSetToNull(\n  model: Model,\n  fixture: Record<string, unknown>,\n): Record<string, unknown> | null {\n  const nullableFields = model.fields.filter((field) => field.type.kind === 'nullable');\n  if (nullableFields.length === 0) return null;\n  const payload: Record<string, unknown> = { ...fixture };\n  for (const field of nullableFields) {\n    payload[field.name] = null;\n  }\n  return payload;\n}\n\nfunction buildPayloadWithUnknownEnumValue(\n  model: Model,\n  fixture: Record<string, unknown>,\n): Record<string, unknown> | null {\n  const payload: Record<string, unknown> = { ...fixture };\n  const enumField = model.fields.find((field) => field.type.kind === 'enum');\n  if (!enumField) return null;\n  payload[enumField.name] = `unexpected_${fileName(model.name)}_${fieldName(enumField.name)}`;\n  return payload;\n}\n\nfunction toPythonLiteral(value: unknown): string {\n  if (value === null) return 'None';\n  if (typeof value === 'string') return JSON.stringify(value);\n  if (typeof value === 'number' || typeof value === 'boolean')\n    return JSON.stringify(value).replace('true', 'True').replace('false', 'False');\n  if (Array.isArray(value)) return `[${value.map((item) => toPythonLiteral(item)).join(', ')}]`;\n  if (typeof value === 'object') {\n    const entries = Object.entries(value as Record<string, unknown>).map(\n      ([key, inner]) => `${JSON.stringify(key)}: ${toPythonLiteral(inner)}`,\n    );\n    return `{${entries.join(', ')}}`;\n  }\n  return 'None';\n}\n\n/**\n * Generate model round-trip tests: Model.from_dict(instance.to_dict()) == instance\n */\nfunction generateModelRoundTripTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile | null {\n  // Collect models used as request bodies only (not returned in responses)\n  const responseModelNames = new Set<string>();\n  const requestOnlyModelNames = new Set<string>();\n  for (const svc of spec.services) {\n    for (const op of svc.operations) {\n      const plan = planOperation(op);\n      if (plan.responseModelName) responseModelNames.add(plan.responseModelName);\n      if (op.requestBody?.kind === 'model') requestOnlyModelNames.add(op.requestBody.name);\n      // Also collect union body variant models as request-only\n      if (op.requestBody?.kind === 'union') {\n        for (const v of (op.requestBody as any).variants ?? []) {\n          if (v.kind === 'model') requestOnlyModelNames.add(v.name);\n        }\n      }\n    }\n  }\n  // A model is request-only if it's used as a request body but never as a response\n  for (const name of responseModelNames) requestOnlyModelNames.delete(name);\n\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(spec.services);\n  const listMetadataNeeded = collectReferencedListMetadataModels(spec.models, nonPaginatedRefs);\n\n  // The round-trip test imports models from their *natural* (pre-relocation)\n  // service so existing callers keep working — those imports resolve via the\n  // BC re-exports that the model emitter writes into each service barrel.\n  const placement = computeSchemaPlacement(spec, ctx);\n  const modelToService = placement.originalModelToService;\n  // The per-model FILE is written to the RELOCATED dir; use it to compute the\n  // gate's relPath so it lines up with the prior manifest.\n  const relocatedModelToService = placement.modelToService;\n  const roundTripDirMap = buildMountDirMap(ctx);\n  const resolveDir = (irService: string | undefined) =>\n    irService ? (roundTripDirMap.get(irService) ?? 'common') : 'common';\n\n  // Scoped runs: the round-trip test must only reference a model whose per-model\n  // file exists on disk after the run (in-scope, or already present from the\n  // prior manifest). A brand-new out-of-scope model is excluded — its file is\n  // never emitted, so importing it would raise ModuleNotFoundError. A full run\n  // keeps every model (fileExistsAfterRun ⇒ true).\n  const modelFileExists = (name: string): boolean => {\n    const dir = resolveDir(relocatedModelToService.get(name));\n    const path = `src/${ctx.namespace}/${dir}/models/${fileName(name)}.py`;\n    return fileExistsAfterRun(path, isModelInScope(name, ctx), ctx);\n  };\n\n  const models = spec.models.filter(\n    (m) =>\n      !(isListWrapperModel(m) && !nonPaginatedRefs.has(m.name)) &&\n      !(isListMetadataModel(m) && !listMetadataNeeded.has(m.name)) &&\n      !requestOnlyModelNames.has(m.name) &&\n      modelFileExists(m.name),\n  );\n  if (models.length === 0) return null;\n\n  const lines: string[] = [];\n  lines.push('\"\"\"Model round-trip tests: from_dict(to_dict()) preserves data.\"\"\"');\n  lines.push('');\n  lines.push('import pytest');\n  lines.push('');\n  lines.push('from tests.generated_helpers import load_fixture');\n  lines.push('');\n\n  // Collect imports by directory\n  const importsByDir = new Map<string, string[]>();\n  for (const model of models) {\n    const service = modelToService.get(model.name);\n    const dirName = resolveDir(service);\n    if (!importsByDir.has(dirName)) importsByDir.set(dirName, []);\n    importsByDir.get(dirName)!.push(className(model.name));\n  }\n  // Add discriminator Unknown variant classes to imports for dispatch tests\n  for (const model of models) {\n    if (!(model as any).discriminator) continue;\n    const service = modelToService.get(model.name);\n    const dirName = resolveDir(service);\n    if (!importsByDir.has(dirName)) importsByDir.set(dirName, []);\n    importsByDir.get(dirName)!.push(`${className(model.name)}Unknown`);\n  }\n\n  for (const [dirName, names] of [...importsByDir].sort()) {\n    lines.push(`from ${ctx.namespace}.${dirToModule(dirName)}.models import ${names.sort().join(', ')}`);\n  }\n\n  lines.push('');\n  lines.push('');\n  lines.push('class TestModelRoundTrip:');\n\n  for (const model of models) {\n    // Skip models with no fields or discriminated union dispatchers — these\n    // don't have a to_dict() and their round-trip semantics differ.\n    if (model.fields.length === 0) continue;\n    if ((model as any).discriminator) continue;\n    // Deduplicate fields by DOMAIN identifier (mirrors models.ts, which honors\n    // `domainName`); the wire key stays `field.name`.\n    const seenFieldNames = new Set<string>();\n    const dedupFields = model.fields.filter((f) => {\n      const pyName = domainFieldName(f);\n      if (seenFieldNames.has(pyName)) return false;\n      seenFieldNames.add(pyName);\n      return true;\n    });\n    const dedupModel = { ...model, fields: dedupFields };\n\n    const modelClass = className(model.name);\n    const fixtureName = `${fileName(model.name)}.json`;\n    const fullFixture = generateModelFixture(\n      dedupModel,\n      new Map(spec.models.map((m) => [m.name, m])),\n      new Map(spec.enums.map((e) => [e.name, e])),\n    );\n    const minimalPayload = buildMinimalModelPayload(dedupModel, fullFixture);\n    const absentOptionalPayload = buildPayloadWithoutOptionalNonNullableFields(dedupModel, fullFixture);\n    const nullablePayload = buildPayloadWithNullableFieldsSetToNull(dedupModel, fullFixture);\n    const unknownEnumPayload = buildPayloadWithUnknownEnumValue(dedupModel, fullFixture);\n\n    lines.push('');\n    lines.push(`    def test_${fileName(model.name)}_round_trip(self):`);\n    lines.push(`        data = load_fixture(\"${fixtureName}\")`);\n    lines.push(`        instance = ${modelClass}.from_dict(data)`);\n    lines.push('        serialized = instance.to_dict()');\n    lines.push('        assert serialized == data');\n    lines.push(`        restored = ${modelClass}.from_dict(serialized)`);\n    lines.push('        assert restored.to_dict() == serialized');\n\n    const requiredFields = dedupFields.filter((field) => field.required);\n    lines.push('');\n    lines.push(`    def test_${fileName(model.name)}_minimal_payload(self):`);\n    lines.push(`        data = ${toPythonLiteral(minimalPayload)}`);\n    lines.push(`        instance = ${modelClass}.from_dict(data)`);\n    if (requiredFields.length > 0) {\n      lines.push('        serialized = instance.to_dict()');\n      for (const field of requiredFields) {\n        lines.push(`        assert serialized[${toPythonLiteral(field.name)}] == data[${toPythonLiteral(field.name)}]`);\n      }\n    } else {\n      lines.push('        assert instance.to_dict() is not None');\n    }\n\n    if (Object.keys(absentOptionalPayload).length !== Object.keys(fullFixture).length) {\n      lines.push('');\n      lines.push(`    def test_${fileName(model.name)}_omits_absent_optional_non_nullable_fields(self):`);\n      lines.push(`        data = ${toPythonLiteral(absentOptionalPayload)}`);\n      lines.push(`        instance = ${modelClass}.from_dict(data)`);\n      lines.push('        serialized = instance.to_dict()');\n      for (const field of dedupFields.filter((field) => !field.required && field.type.kind !== 'nullable')) {\n        lines.push(`        assert ${toPythonLiteral(field.name)} not in serialized`);\n      }\n    }\n\n    if (nullablePayload) {\n      lines.push('');\n      lines.push(`    def test_${fileName(model.name)}_preserves_nullable_fields(self):`);\n      lines.push(`        data = ${toPythonLiteral(nullablePayload)}`);\n      lines.push(`        instance = ${modelClass}.from_dict(data)`);\n      lines.push('        serialized = instance.to_dict()');\n      for (const field of dedupFields.filter((field) => field.type.kind === 'nullable')) {\n        lines.push(`        assert serialized[${toPythonLiteral(field.name)}] is None`);\n      }\n    }\n\n    if (unknownEnumPayload) {\n      lines.push('');\n      lines.push(`    def test_${fileName(model.name)}_round_trips_unknown_enum_values(self):`);\n      lines.push(`        data = ${toPythonLiteral(unknownEnumPayload)}`);\n      lines.push(`        instance = ${modelClass}.from_dict(data)`);\n      lines.push('        assert instance.to_dict() == data');\n    }\n  }\n\n  // Discriminator dispatch tests — targeted coverage for from_dict routing\n  const discriminatorModels = models.filter((m) => (m as any).discriminator);\n  if (discriminatorModels.length > 0) {\n    lines.push('');\n    lines.push('');\n    lines.push('class TestDiscriminatorDispatch:');\n\n    for (const model of discriminatorModels) {\n      const disc = (model as any).discriminator as { property: string; mapping: Record<string, string> };\n      const modelClass = className(model.name);\n      const unknownClass = `${modelClass}Unknown`;\n\n      // Pick the first variant (alphabetically by discriminator value) for tests\n      const sortedEntries = Object.entries(disc.mapping).sort(([a], [b]) => a.localeCompare(b));\n      if (sortedEntries.length === 0) continue;\n      const [, firstVariantName] = sortedEntries[0];\n      const firstVariantClass = className(firstVariantName);\n      const firstVariantFixture = `${fileName(firstVariantName)}.json`;\n\n      lines.push('');\n      lines.push(`    def test_${fileName(model.name)}_dispatches_known_variant(self):`);\n      lines.push(`        data = load_fixture(\"${firstVariantFixture}\")`);\n      lines.push(`        result = ${modelClass}.from_dict(data)`);\n      lines.push(`        assert isinstance(result, ${firstVariantClass})`);\n\n      lines.push('');\n      lines.push(`    def test_${fileName(model.name)}_returns_unknown_for_unrecognized_type(self):`);\n      lines.push(`        data = load_fixture(\"${firstVariantFixture}\")`);\n      lines.push(`        data = {**data, \"${disc.property}\": \"future.unrecognized.type\"}`);\n      lines.push(`        result = ${modelClass}.from_dict(data)`);\n      lines.push(`        assert isinstance(result, ${unknownClass})`);\n      lines.push('        assert result.raw_data == data');\n\n      lines.push('');\n      lines.push(`    def test_${fileName(model.name)}_raises_on_missing_discriminator(self):`);\n      lines.push(`        data = load_fixture(\"${firstVariantFixture}\")`);\n      lines.push(`        data = {k: v for k, v in data.items() if k != \"${disc.property}\"}`);\n      lines.push('        with pytest.raises(Exception):');\n      lines.push(`            ${modelClass}.from_dict(data)`);\n\n      lines.push('');\n      lines.push(`    def test_${fileName(model.name)}_raises_on_none_discriminator(self):`);\n      lines.push(`        data = load_fixture(\"${firstVariantFixture}\")`);\n      lines.push(`        data = {**data, \"${disc.property}\": None}`);\n      lines.push('        with pytest.raises(Exception):');\n      lines.push(`            ${modelClass}.from_dict(data)`);\n    }\n  }\n\n  return {\n    path: 'tests/test_models_round_trip.py',\n    content: lines.join('\\n'),\n    integrateTarget: true,\n    overwriteExisting: true,\n  };\n}\n","import type { ApiSpec, EmitterContext, OperationsMap } from '@workos/oagen';\nimport { resolveMethodName } from './naming.js';\nimport { buildServiceAccessPaths } from './client.js';\nimport { buildResolvedLookup, lookupResolved, getMountTarget } from '../shared/resolved-ops.js';\n\n/**\n * Build operation-to-SDK-method mapping for the manifest.\n */\nexport function buildOperationsMap(spec: ApiSpec, ctx: EmitterContext): OperationsMap {\n  const manifest: OperationsMap = {};\n  const accessPaths = buildServiceAccessPaths(spec.services, ctx);\n  const resolvedLookup = buildResolvedLookup(ctx);\n\n  for (const service of spec.services) {\n    // For mounted services, look up the mount target's access path\n    let serviceProp = accessPaths.get(service.name);\n    if (!serviceProp) {\n      const mountTarget = getMountTarget(service, ctx);\n      serviceProp = accessPaths.get(mountTarget);\n    }\n    if (!serviceProp) {\n      throw new Error(`Missing public client access path for service ${service.name}`);\n    }\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const method = resolveMethodName(op, service, ctx);\n\n      // Use per-operation mountOn when it differs from the service default\n      const resolved = lookupResolved(op, resolvedLookup);\n      const propName = (resolved && accessPaths.get(resolved.mountOn)) ?? serviceProp;\n\n      manifest[httpKey] = { sdkMethod: method, service: propName };\n    }\n  }\n\n  return manifest;\n}\n","import type {\n  Emitter,\n  EmitterContext,\n  FormatCommand,\n  GeneratedFile,\n  ApiSpec,\n  Model,\n  Enum,\n  Service,\n} from '@workos/oagen';\n\nimport { generateModels } from './models.js';\nimport { detectDiscriminators } from '../shared/model-utils.js';\nimport { AUTOGEN_NOTICE } from '../shared/file-header.js';\nimport { generateEnums } from './enums.js';\nimport { generateResources } from './resources.js';\nimport { generateClient } from './client.js';\nimport { generateTests } from './tests.js';\nimport { buildOperationsMap } from './manifest.js';\n/** Ensure every generated file's content ends with a trailing newline. */\nfunction ensureTrailingNewlines(files: GeneratedFile[]): GeneratedFile[] {\n  for (const f of files) {\n    if (f.content && !f.content.endsWith('\\n')) {\n      f.content += '\\n';\n    }\n  }\n  return files;\n}\n\n/**\n * Annotate models with implicit discriminator info (without full oneOf\n * field flattening which can break existing model structures/fixtures).\n */\nfunction withDiscriminators(ctx: EmitterContext): EmitterContext {\n  const annotated = detectDiscriminators(ctx.spec.models);\n  if (annotated === ctx.spec.models) return ctx;\n  const spec: ApiSpec = { ...ctx.spec, models: annotated };\n  return { ...ctx, spec };\n}\n\nexport const pythonEmitter: Emitter = {\n  language: 'python',\n\n  generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n    const annotated = detectDiscriminators(models);\n    return ensureTrailingNewlines(generateModels(annotated, ctx));\n  },\n\n  generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateEnums(enums, ctx));\n  },\n\n  generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateResources(services, withDiscriminators(ctx)));\n  },\n\n  generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateClient(spec, withDiscriminators(ctx)));\n  },\n\n  generateErrors(): GeneratedFile[] {\n    // _errors.py is now hand-maintained in the target SDK (@oagen-ignore-file)\n    return [];\n  },\n\n  generateTypeSignatures(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    void spec;\n    void ctx;\n    // Python uses inline type annotations — no separate type signature files needed\n    return [];\n  },\n\n  generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    // Use original spec for model filtering (requestOnlyModelNames etc.) but\n    // annotate discriminator models so dispatch tests are generated.\n    const annotated = detectDiscriminators(spec.models);\n    // Only replace discriminator-annotated models, keep the rest unchanged\n    // so request-only filtering and field-based logic work correctly.\n    const annotatedByName = new Map(annotated.filter((m: any) => m.discriminator).map((m) => [m.name, m]));\n    const testModels = spec.models.map((m) => annotatedByName.get(m.name) ?? m);\n    const testSpec: ApiSpec = { ...spec, models: testModels };\n    return ensureTrailingNewlines(generateTests(testSpec, { ...ctx, spec: testSpec }));\n  },\n\n  buildOperationsMap(spec: ApiSpec, ctx: EmitterContext) {\n    return buildOperationsMap(spec, ctx);\n  },\n\n  fileHeader(): string {\n    return `# ${AUTOGEN_NOTICE}`;\n  },\n\n  formatCommand(_targetDir: string): FormatCommand | null {\n    return {\n      cmd: 'bash',\n      args: [\n        '-c',\n        'PY_FILES=$(printf \"%s\\\\n\" \"$@\" | grep \"\\\\.py$\" || true); if [ -n \"$PY_FILES\" ]; then echo \"$PY_FILES\" | xargs ruff check --fix --quiet 2>/dev/null; echo \"$PY_FILES\" | xargs ruff format --quiet; fi',\n        '--',\n      ],\n      batchSize: 1000,\n    };\n  },\n};\n","import type { Service, Operation, EmitterContext, Enum } from '@workos/oagen';\nimport { toPascalCase, toCamelCase, toSnakeCase } from '@workos/oagen';\nimport { buildResolvedLookup, lookupMethodName } from '../shared/resolved-ops.js';\nimport { stripUrnPrefix, applyAcronymFixes } from '../shared/naming-utils.js';\nimport {\n  buildExportedClassNameSet as buildExportedClassNameSetShared,\n  resolveServiceTarget as resolveServiceTargetShared,\n} from '../shared/service-name-collision.js';\n\n/** Namespace grouping result (shared with client.ts). */\nexport interface NamespaceGroup {\n  prefix: string;\n  entries: { service: Service; subProp: string; resolvedName: string }[];\n  baseEntry?: { service: Service; resolvedName: string };\n}\n\n/** Grouping result returned by groupServicesByNamespace. */\nexport interface NamespaceGrouping {\n  standalone: { service: Service; prop: string; resolvedName: string }[];\n  namespaces: NamespaceGroup[];\n}\n\n/**\n * PHP reserved class names that would collide with builtins.\n */\nconst PHP_RESERVED_CLASS_NAMES = new Set([\n  'Array',\n  'List',\n  'Callable',\n  'Iterable',\n  'Mixed',\n  'Never',\n  'Null',\n  'Object',\n  'Self',\n  'Static',\n  'Void',\n  'True',\n  'False',\n  'Int',\n  'Float',\n  'String',\n  'Bool',\n]);\n\n// ─── Enum deduplication ───────────────────────────────────────────────\n\nlet enumAliasMap = new Map<string, string>();\n\n/**\n * Initialize enum deduplication by hashing sorted enum case values.\n * Enums with identical value sets are aliased to the one with the shortest PHP class name.\n */\nexport function initializeEnumDedup(enums: Enum[]): void {\n  enumAliasMap = new Map();\n  const groups = new Map<string, Enum[]>();\n\n  for (const e of enums) {\n    const hash = [...e.values]\n      .sort((a, b) => String(a.value).localeCompare(String(b.value)))\n      .map((v) => String(v.value))\n      .join('\\0');\n    if (!groups.has(hash)) groups.set(hash, []);\n    groups.get(hash)!.push(e);\n  }\n\n  for (const [, group] of groups) {\n    if (group.length <= 1) continue;\n    // Pick shortest PHP class name as canonical\n    const sorted = [...group].sort((a, b) => className(a.name).length - className(b.name).length);\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      enumAliasMap.set(sorted[i].name, canonical.name);\n    }\n  }\n}\n\n/** Resolve an enum name to its canonical (deduplicated) name. */\nexport function resolveEnumName(name: string): string {\n  return enumAliasMap.get(name) ?? name;\n}\n\n/** PHP class name for an enum, with dedup resolution + PascalCase + acronym preservation. */\nexport function enumClassName(name: string): string {\n  return className(resolveEnumName(name));\n}\n\n/** PascalCase class name with acronym preservation. */\nexport function className(name: string): string {\n  let result = applyAcronymFixes(toPascalCase(stripUrnPrefix(name)));\n  if (PHP_RESERVED_CLASS_NAMES.has(result)) {\n    result += 'Model';\n  }\n  return result;\n}\n\n/**\n * Build the set of model + enum class names exported by the SDK. Used to\n * detect collisions with operation-client class names — a colliding service\n * gets a `Service` suffix appended.\n */\nexport function buildExportedClassNameSet(ctx: EmitterContext): Set<string> {\n  return buildExportedClassNameSetShared(ctx, className);\n}\n\n/**\n * Resolve a service's mount-target identifier, appending `Service` on\n * collision with an exported model/enum class. Used in `\\Service\\…` files\n * to avoid `use WorkOS\\Resource\\X; class X` PHP fatal errors.\n */\nexport function resolveServiceTarget(target: string, exportedClasses: Set<string>): string {\n  return resolveServiceTargetShared(target, exportedClasses, className);\n}\n\n/** PascalCase file name (without extension) — PSR-4 convention. */\nexport function fileName(name: string): string {\n  return className(name);\n}\n\n/** camelCase method name. */\nexport function methodName(name: string): string {\n  return toCamelCase(name);\n}\n\n/** Resolve the SDK method name for an operation, using resolved operations first. */\nexport function resolveMethodName(op: Operation, _service: Service, ctx: EmitterContext): string {\n  const lookup = buildResolvedLookup(ctx);\n  const resolved = lookupMethodName(op, lookup);\n  if (resolved) return toCamelCase(resolved);\n  const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const existing = ctx.overlayLookup?.methodByOperation?.get(httpKey);\n  if (existing) return existing.methodName;\n  return toCamelCase(op.name);\n}\n\n/** camelCase field/property name. */\nexport function fieldName(name: string): string {\n  return toCamelCase(name);\n}\n\n/**\n * camelCase DOMAIN property name for a model field, honoring a `domainName`\n * override (set via the `fieldHints` config) so a wire field can surface under\n * a friendlier PHP property name. The wire key (see {@link wireName}) still\n * derives from `field.name`. No-op when `domainName` is unset.\n */\nexport function domainFieldName(field: { name: string; domainName?: string }): string {\n  return fieldName(field.domainName ?? field.name);\n}\n\n/** snake_case name for fixtures and other snake_case contexts. */\nexport function snakeName(name: string): string {\n  return toSnakeCase(stripUrnPrefix(name));\n}\n\n/** snake_case wire name (preserves the original API field name). */\nexport function wireName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/** camelCase property name for service accessors on the client. */\nexport function servicePropertyName(name: string): string {\n  return toCamelCase(name);\n}\n\n/** Resolve the effective service name, using the overlay-resolved class name. */\nexport function resolveServiceName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n/** Build a map from IR service name to resolved service name. */\nexport function buildServiceNameMap(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of services) {\n    map.set(service.name, resolveServiceName(service, ctx));\n  }\n  return map;\n}\n\n/** Resolve the SDK class name for a service, using resolved operations' mountOn. */\nexport function resolveClassName(service: Service, ctx: EmitterContext): string {\n  // Use resolved ops mountOn as canonical class name\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (r.service.name === service.name) return r.mountOn;\n  }\n  // Fallback to overlay, then IR name\n  if (ctx.overlayLookup?.methodByOperation) {\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const existing = ctx.overlayLookup.methodByOperation.get(httpKey);\n      if (existing) return existing.className;\n    }\n  }\n  return toPascalCase(service.name);\n}\n\n/** Resolve the type name for a model, checking overlay first. */\nexport function resolveTypeName(name: string, ctx: EmitterContext): string {\n  const existing = ctx.overlayLookup?.interfaceByName?.get(name);\n  if (existing) return existing;\n  return toPascalCase(stripUrnPrefix(name));\n}\n\n// ─── Service grouping ─────────────────────────────────────────────────\n\n/**\n * Group services by shared camelCase prefix for nested namespaces.\n */\nexport function groupServicesByNamespace(services: Service[], ctx: EmitterContext): NamespaceGrouping {\n  // Build entries, deduplicating props — when the overlay causes two services to\n  // resolve to the same accessor name (e.g., OrganizationDomains → Organizations),\n  // fall back to the IR name for the duplicate to keep both reachable.\n  const usedProps = new Set<string>();\n  const entries = services.map((service) => {\n    const resolvedName = resolveClassName(service, ctx);\n    let prop = servicePropertyName(resolvedName);\n    if (usedProps.has(prop)) {\n      // Collision — fall back to the raw IR service name\n      prop = servicePropertyName(toPascalCase(service.name));\n    }\n    usedProps.add(prop);\n    return { service, prop, resolvedName };\n  });\n\n  const allProps = new Set(entries.map((e) => e.prop));\n  const VIRTUAL_NAMESPACES = new Set(['userManagement']);\n\n  // Count how many property names contain each possible camelCase prefix\n  // For PHP we use the snake_case version for prefix detection then convert back\n  const snakeEntries = entries.map((e) => ({ ...e, snakeProp: toSnakeCase(e.prop) }));\n  const prefixCount = new Map<string, number>();\n  for (const entry of snakeEntries) {\n    prefixCount.set(entry.snakeProp, (prefixCount.get(entry.snakeProp) || 0) + 1);\n    const parts = entry.snakeProp.split('_');\n    for (let len = 1; len < parts.length; len++) {\n      const prefix = parts.slice(0, len).join('_');\n      prefixCount.set(prefix, (prefixCount.get(prefix) || 0) + 1);\n    }\n  }\n\n  const entryPrefix = new Map<string, string>();\n  for (const entry of snakeEntries) {\n    const parts = entry.snakeProp.split('_');\n    for (let len = parts.length - 1; len >= 1; len--) {\n      const prefix = parts.slice(0, len).join('_');\n      const camelPrefix = toCamelCase(prefix);\n      if (\n        (prefixCount.get(prefix) ?? 0) >= 2 &&\n        prefix !== entry.snakeProp &&\n        (allProps.has(camelPrefix) || VIRTUAL_NAMESPACES.has(camelPrefix))\n      ) {\n        entryPrefix.set(entry.prop, camelPrefix);\n        break;\n      }\n    }\n  }\n\n  const namespacesMap = new Map<string, NamespaceGroup['entries']>();\n  const standalone: typeof entries = [];\n\n  for (const entry of entries) {\n    const prefix = entryPrefix.get(entry.prop);\n    if (prefix) {\n      if (!namespacesMap.has(prefix)) namespacesMap.set(prefix, []);\n      // Compute sub-property: remove prefix from the camelCase name\n      const snakePrefix = toSnakeCase(prefix);\n      const snakeProp = toSnakeCase(entry.prop);\n      const subSnake = snakeProp.slice(snakePrefix.length + 1);\n      const subProp = toCamelCase(subSnake);\n      namespacesMap.get(prefix)!.push({ service: entry.service, subProp, resolvedName: entry.resolvedName });\n    } else {\n      standalone.push(entry);\n    }\n  }\n\n  const namespacePrefixes = new Set(namespacesMap.keys());\n  const colliding = new Map<string, (typeof entries)[0]>();\n  const filteredStandalone = standalone.filter((entry) => {\n    if (namespacePrefixes.has(entry.prop)) {\n      colliding.set(entry.prop, entry);\n      return false;\n    }\n    return true;\n  });\n\n  const namespaces: NamespaceGroup[] = [...namespacesMap].map(([prefix, nsEntries]) => ({\n    prefix,\n    entries: nsEntries,\n    baseEntry: colliding.get(prefix)\n      ? { service: colliding.get(prefix)!.service, resolvedName: colliding.get(prefix)!.resolvedName }\n      : undefined,\n  }));\n  return { standalone: filteredStandalone, namespaces };\n}\n\n/** Build a map from IR service name to the resolved directory name. */\nexport function buildServiceDirMap(grouping: NamespaceGrouping): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const entry of grouping.standalone) {\n    map.set(entry.service.name, toPascalCase(entry.resolvedName));\n  }\n  for (const ns of grouping.namespaces) {\n    if (ns.baseEntry) {\n      map.set(ns.baseEntry.service.name, toPascalCase(ns.prefix));\n    }\n    for (const entry of ns.entries) {\n      map.set(entry.service.name, `${toPascalCase(ns.prefix)}/${toPascalCase(entry.subProp)}`);\n    }\n  }\n  return map;\n}\n","import type { TypeRef, PrimitiveType, UnionType } from '@workos/oagen';\nimport { mapTypeRef as irMapTypeRef } from '@workos/oagen';\nimport { className, enumClassName } from './naming.js';\n\n/**\n * Map an IR TypeRef to a PHP type hint string.\n */\nexport function mapTypeRef(ref: TypeRef, opts?: { qualified?: boolean }): string {\n  const qualify = opts?.qualified ?? false;\n  const prefix = qualify ? '\\\\WorkOS\\\\Resource\\\\' : '';\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (_ref, _items) => 'array',\n    model: (r) => `${prefix}${className(r.name)}`,\n    enum: (r) => `${prefix}${enumClassName(r.name)}`,\n    union: (r, variants) => joinUnionVariants(r, variants),\n    nullable: (_ref, inner) => `?${inner}`,\n    literal: (r) =>\n      typeof r.value === 'number'\n        ? Number.isInteger(r.value)\n          ? 'int'\n          : 'float'\n        : typeof r.value === 'boolean'\n          ? 'bool'\n          : 'string',\n    map: (_ref, _value) => 'array',\n  });\n}\n\n/**\n * Map an IR TypeRef to a PHPDoc type string for richer documentation.\n * Uses fully-qualified names (leading \\) so types resolve correctly\n * regardless of the namespace the docblock appears in.\n */\nexport function mapTypeRefForPHPDoc(ref: TypeRef, opts?: { prefix?: string }): string {\n  const prefix = opts?.prefix ?? '\\\\WorkOS\\\\Resource\\\\';\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitiveDoc,\n    array: (_ref, items) => `array<${items}>`,\n    model: (r) => `${prefix}${className(r.name)}`,\n    enum: (r) => `${prefix}${enumClassName(r.name)}`,\n    union: (r, variants) => joinDocUnionVariants(r, variants),\n    nullable: (_ref, inner) => `${inner}|null`,\n    literal: (r) =>\n      typeof r.value === 'string'\n        ? 'string'\n        : typeof r.value === 'number'\n          ? 'int'\n          : typeof r.value === 'boolean'\n            ? 'bool'\n            : 'string',\n    map: (_ref, value) => `array<string, ${value}>`,\n  });\n}\n\nfunction mapPrimitive(ref: PrimitiveType): string {\n  if (ref.format === 'date-time') return '\\\\DateTimeImmutable';\n  switch (ref.type) {\n    case 'string':\n      return 'string';\n    case 'integer':\n      return 'int';\n    case 'number':\n      return 'float';\n    case 'boolean':\n      return 'bool';\n    case 'unknown':\n      return 'mixed';\n  }\n}\n\nfunction mapPrimitiveDoc(ref: PrimitiveType): string {\n  if (ref.format === 'date-time') return '\\\\DateTimeImmutable';\n  switch (ref.type) {\n    case 'string':\n      return 'string';\n    case 'integer':\n      return 'int';\n    case 'number':\n      return 'float';\n    case 'boolean':\n      return 'bool';\n    case 'unknown':\n      return 'mixed';\n  }\n}\n\nfunction joinUnionVariants(ref: UnionType, variants: string[]): string {\n  if (ref.compositionKind === 'allOf') {\n    return variants[0] ?? 'mixed';\n  }\n  // PHP type declarations forbid the `?T` nullable shorthand inside a `|`\n  // union — `string|?string` is a parse error. Hoist nullability out of the\n  // variants: strip a leading `?`, drop a bare `null`, then re-attach it as a\n  // single `?T` (one non-null type) or trailing `|null` (several). A union of\n  // `string` + nullable-`string` (e.g. from a `oneOf: [string, {string|null}]`\n  // spec shape) thus collapses to `?string` instead of invalid `string|?string`.\n  const { nonNull, nullable } = splitNullable(variants);\n  if (nonNull.includes('mixed')) return 'mixed'; // `mixed` already permits null\n  if (nonNull.length === 0) return 'null';\n  if (nonNull.length === 1) return nullable ? `?${nonNull[0]}` : nonNull[0];\n  return nullable ? `${nonNull.join('|')}|null` : nonNull.join('|');\n}\n\nfunction joinDocUnionVariants(ref: UnionType, variants: string[]): string {\n  if (ref.compositionKind === 'allOf') {\n    return variants[0] ?? 'mixed';\n  }\n  // PHPDoc tolerates `?T`, but normalize the same way for consistency and to\n  // avoid redundant members (the doc nullable form is `T|null`, so split on `|`).\n  const { nonNull, nullable } = splitNullable(variants.flatMap((v) => v.split('|')));\n  if (nonNull.includes('mixed')) return 'mixed';\n  if (nonNull.length === 0) return 'null';\n  return nullable ? `${nonNull.join('|')}|null` : nonNull.join('|');\n}\n\n/**\n * Partition rendered union variants into their non-null types plus a single\n * nullability flag. Recognizes both the `?T` shorthand and a bare `null`/`'null'`\n * variant. Deduplicates the non-null types while preserving first-seen order.\n */\nfunction splitNullable(variants: string[]): { nonNull: string[]; nullable: boolean } {\n  let nullable = false;\n  const nonNull: string[] = [];\n  for (const v of variants) {\n    if (v === 'null' || v === \"'null'\") {\n      nullable = true;\n    } else if (v.startsWith('?')) {\n      nullable = true;\n      nonNull.push(v.slice(1));\n    } else {\n      nonNull.push(v);\n    }\n  }\n  return { nonNull: [...new Set(nonNull)], nullable };\n}\n","/**\n * Render a PHPDoc comment block from a description string.\n * Handles multiline descriptions by prefixing each line with ` * `.\n * Returns the lines with the given indent (default 0 spaces).\n */\nexport function phpDocComment(description: string, indent = 0): string[] {\n  const pad = ' '.repeat(indent);\n  const descLines = description.split('\\n');\n  if (descLines.length === 1) {\n    return [`${pad}/** ${descLines[0]} */`];\n  }\n  const lines: string[] = [`${pad}/**`];\n  for (const line of descLines) {\n    lines.push(line === '' ? `${pad} *` : `${pad} * ${line}`);\n  }\n  lines.push(`${pad} */`);\n  return lines;\n}\n","import type { Model, TypeRef, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { mapTypeRef, mapTypeRefForPHPDoc } from './type-map.js';\nimport { className, enumClassName, domainFieldName } from './naming.js';\nimport { phpDocComment } from './utils.js';\n\n// Import and re-export shared model detection utilities\nimport {\n  isListMetadataModel,\n  isListWrapperModel,\n  collectNonPaginatedResponseModelNames,\n  collectReferencedListMetadataModels,\n} from '../shared/model-utils.js';\nimport { isModelInScope } from '../shared/resolved-ops.js';\nexport { isListMetadataModel, isListWrapperModel };\n\n/**\n * Generate PHP model files from IR models.\n */\nexport function generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n  if (models.length === 0) return [];\n\n  const files: GeneratedFile[] = [];\n\n  // Emit shared JsonSerializableTrait once\n  files.push({\n    path: 'lib/Resource/JsonSerializableTrait.php',\n    content: [\n      `namespace ${ctx.namespacePascal}\\\\Resource;`,\n      '',\n      'trait JsonSerializableTrait',\n      '{',\n      '    public function jsonSerialize(): array',\n      '    {',\n      '        return $this->toArray();',\n      '    }',\n      '}',\n    ].join('\\n'),\n    overwriteExisting: true,\n  });\n\n  // Wrappers referenced as a non-paginated response (e.g. `VersionListResponse`\n  // for `GET /vault/v1/kv/{id}/versions`) must still be emitted — the resource\n  // code references them by name and the pagination iterator doesn't unwrap them.\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(ctx.spec.services);\n  const listMetadataNeeded = collectReferencedListMetadataModels(models, nonPaginatedRefs);\n\n  for (const model of models) {\n    if (isListMetadataModel(model) && !listMetadataNeeded.has(model.name)) continue;\n    if (isListWrapperModel(model) && !nonPaginatedRefs.has(model.name)) continue;\n    const name = className(model.name);\n    const lines: string[] = [];\n\n    // No <?php here — the file header from fileHeader() provides it\n    lines.push(`namespace ${ctx.namespacePascal}\\\\Resource;`);\n    lines.push('');\n    if (model.description) {\n      lines.push(...phpDocComment(model.description, 0));\n    }\n    lines.push(`readonly class ${name} implements \\\\JsonSerializable`);\n    lines.push('{');\n    lines.push('    use JsonSerializableTrait;');\n    lines.push('');\n\n    // Constructor with promoted properties\n    lines.push('    public function __construct(');\n    const requiredFields = model.fields.filter((f) => f.required);\n    const optionalFields = model.fields.filter((f) => !f.required);\n    // Deduplicate fields that map to the same PHP name\n    const seenNames = new Set<string>();\n    const allFields = [...requiredFields, ...optionalFields].filter((f) => {\n      // DOMAIN identifier: the PHP property name (honors a `domainName` override).\n      const phpName = domainFieldName(f);\n      if (seenNames.has(phpName)) return false;\n      seenNames.add(phpName);\n      return true;\n    });\n\n    for (let i = 0; i < allFields.length; i++) {\n      const field = allFields[i];\n      // DOMAIN identifier: the promoted constructor property name.\n      const phpName = domainFieldName(field);\n      const phpType = mapTypeRef(field.type);\n      const isOptional = !field.required;\n      const comma = i < allFields.length - 1 ? ',' : ',';\n\n      const varDocType = mapTypeRefForPHPDoc(field.type);\n      const varNullSuffix = isOptional && !varDocType.endsWith('|null') ? '|null' : '';\n      const varAnnotation = needsVarAnnotation(field.type) ? `@var ${varDocType}${varNullSuffix}` : null;\n      if (field.description || field.deprecated || varAnnotation) {\n        const parts: string[] = [];\n        if (field.description) parts.push(field.description);\n        if (varAnnotation) parts.push(varAnnotation);\n        if (field.deprecated) parts.push('@deprecated');\n        lines.push(...phpDocComment(parts.join('\\n'), 8));\n      }\n\n      if (isOptional) {\n        const nullableType = phpType.startsWith('?') ? phpType : `?${phpType}`;\n        lines.push(`        public ${nullableType} $${phpName} = null${comma}`);\n      } else {\n        lines.push(`        public ${phpType} $${phpName}${comma}`);\n      }\n    }\n    lines.push('    ) {');\n    lines.push('    }');\n\n    // fromArray factory method\n    lines.push('');\n    lines.push(`    public static function fromArray(array $data): self`);\n    lines.push('    {');\n    lines.push(`        return new self(`);\n    for (let i = 0; i < allFields.length; i++) {\n      const field = allFields[i];\n      // DOMAIN identifier: the named constructor argument (PHP property).\n      const phpName = domainFieldName(field);\n      // WIRE key: the JSON key read from `$data[...]` (stays `field.name`).\n      const wireName = field.name;\n      const comma = i < allFields.length - 1 ? ',' : ',';\n      const accessor = generateFromArrayAccessor(field.type, wireName, field.required);\n\n      lines.push(`            ${phpName}: ${accessor}${comma}`);\n    }\n    lines.push('        );');\n    lines.push('    }');\n\n    // toArray method\n    lines.push('');\n    lines.push('    public function toArray(): array');\n    lines.push('    {');\n    lines.push('        return [');\n    for (const field of allFields) {\n      // DOMAIN identifier: the `$this->...` property being serialized.\n      const phpName = domainFieldName(field);\n      // WIRE key: the JSON key emitted into the array (stays `field.name`).\n      const wireName = field.name;\n      const serialized = generateToArrayValue(field.type, `$this->${phpName}`, !field.required);\n      lines.push(`            '${wireName}' => ${serialized},`);\n    }\n    lines.push('        ];');\n    lines.push('    }');\n\n    lines.push('}');\n\n    // FR-1.4: write the per-model FILE only when in scope. PHP uses PSR-4\n    // (one class per file under lib/Resource/, no barrel/index), so an\n    // out-of-scope model is simply left untouched on disk and stays loadable.\n    if (isModelInScope(model.name, ctx)) {\n      files.push({\n        path: `lib/Resource/${name}.php`,\n        content: lines.join('\\n'),\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n\n/**\n * Resolve a degenerate union to a single TypeRef when possible.\n * - allOf: PHP collapses to the first variant (mirrors `mapTypeRef`).\n * - oneOf/anyOf where every variant has the same generated PHP type: collapse\n *   to that variant (e.g. discriminated unions whose branches the IR pinned to\n *   one model name).\n * Returns null when the union is genuinely polymorphic.\n */\nfunction resolveDegenerateUnion(ref: TypeRef): TypeRef | null {\n  if (ref.kind !== 'union') return null;\n  if (ref.compositionKind === 'allOf') return ref.variants[0] ?? null;\n  if (ref.variants.length === 0) return null;\n  const signature = (v: TypeRef): string => {\n    if (v.kind === 'model') return `model:${v.name}`;\n    if (v.kind === 'enum') return `enum:${v.name}`;\n    return `kind:${v.kind}`;\n  };\n  const first = ref.variants[0];\n  const firstSig = signature(first);\n  for (const v of ref.variants) {\n    if (signature(v) !== firstSig) return null;\n  }\n  return first;\n}\n\n/**\n * Generate the fromArray accessor expression for a field.\n */\nfunction generateFromArrayAccessor(ref: TypeRef, wireName: string, required: boolean): string {\n  // For nullable types, always guard with isset() regardless of required flag\n  const isNullable = ref.kind === 'nullable';\n  if (!required || isNullable) {\n    const innerRef = isNullable ? ref.inner : ref;\n    const inner = generateFromArrayValue(innerRef, `$data['${wireName}']`);\n    if (isComplexType(innerRef)) {\n      return `isset($data['${wireName}']) ? ${inner} : null`;\n    }\n    if (isNullable) {\n      return `$data['${wireName}'] ?? null`;\n    }\n    return `$data['${wireName}'] ?? null`;\n  }\n  // Literal fields have a statically known value; use ?? with a default\n  // so deserialization is resilient when the API omits the key.\n  if (ref.kind === 'literal') {\n    return `$data['${wireName}'] ?? ${phpLiteralDefault(ref.value)}`;\n  }\n  // Required field: access directly\n  return generateFromArrayValue(ref, `$data['${wireName}']`);\n}\n\n/**\n * Generate the fromArray value expression for a type.\n */\nfunction generateFromArrayValue(ref: TypeRef, accessor: string): string {\n  switch (ref.kind) {\n    case 'primitive':\n      if (ref.format === 'date-time') {\n        // Always access directly — nullable fields are already guarded by isset() in\n        // generateFromArrayAccessor(). Required fields should error if missing.\n        return `new \\\\DateTimeImmutable(${accessor})`;\n      }\n      return accessor;\n    case 'model': {\n      const name = className(ref.name);\n      return `${name}::fromArray(${accessor})`;\n    }\n    case 'enum': {\n      const name = enumClassName(ref.name);\n      return `${name}::from(${accessor})`;\n    }\n    case 'array':\n      if (ref.items.kind === 'model') {\n        const itemName = className(ref.items.name);\n        return `array_map(fn ($item) => ${itemName}::fromArray($item), ${accessor})`;\n      }\n      if (ref.items.kind === 'enum') {\n        const itemName = enumClassName(ref.items.name);\n        return `array_map(fn ($item) => ${itemName}::from($item), ${accessor})`;\n      }\n      if (ref.items.kind === 'primitive' && ref.items.format === 'date-time') {\n        return `array_map(fn ($item) => new \\\\DateTimeImmutable($item), ${accessor})`;\n      }\n      return accessor;\n    case 'nullable':\n      return generateFromArrayValue(ref.inner, accessor);\n    case 'union': {\n      // Discriminated union: dispatch via match() on the discriminator\n      // property to call the matching variant's fromArray. An unknown\n      // discriminator value would otherwise assign a raw array to a typed\n      // property and crash later with a confusing TypeError, so throw\n      // immediately with the offending value.\n      if (ref.discriminator && ref.discriminator.mapping) {\n        const entries = Object.entries(ref.discriminator.mapping);\n        if (entries.length > 0) {\n          const arms = entries\n            .map(([value, modelName]) => `'${value}' => ${className(modelName)}::fromArray(${accessor})`)\n            .join(', ');\n          const discProp = ref.discriminator.property;\n          const throwArm = `default => throw new \\\\UnexpectedValueException(sprintf('Unknown ${discProp}: %s', json_encode(${accessor}['${discProp}'] ?? null)))`;\n          return `match (${accessor}['${discProp}'] ?? null) { ${arms}, ${throwArm} }`;\n        }\n      }\n      const resolved = resolveDegenerateUnion(ref);\n      if (resolved) return generateFromArrayValue(resolved, accessor);\n      return accessor;\n    }\n    case 'map':\n      return accessor;\n    case 'literal':\n      return accessor;\n  }\n}\n\n/** Convert a LiteralType value to a PHP default expression for use with ??. */\nfunction phpLiteralDefault(value: string | number | boolean | null): string {\n  if (value === null) return 'null';\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  if (typeof value === 'string') return `'${value}'`;\n  return String(value);\n}\n\n/**\n * Check if a TypeRef needs special handling (not a simple key access).\n */\nfunction isComplexType(ref: TypeRef): boolean {\n  switch (ref.kind) {\n    case 'primitive':\n      return ref.format === 'date-time';\n    case 'model':\n    case 'enum':\n      return true;\n    case 'array':\n      return isComplexType(ref.items);\n    case 'nullable':\n      return isComplexType(ref.inner);\n    case 'union': {\n      const resolved = resolveDegenerateUnion(ref);\n      return resolved ? isComplexType(resolved) : false;\n    }\n    default:\n      return false;\n  }\n}\n\n/**\n * Generate the toArray serialization expression for a field value.\n */\nfunction generateToArrayValue(ref: TypeRef, accessor: string, nullable = false): string {\n  const ns = nullable ? '?' : '';\n  switch (ref.kind) {\n    case 'primitive':\n      if (ref.format === 'date-time') {\n        return `${accessor}${ns}->format(\\\\DateTimeInterface::RFC3339_EXTENDED)`;\n      }\n      return accessor;\n    case 'model':\n      return `${accessor}${ns}->toArray()`;\n    case 'enum':\n      return nullable ? `${accessor}?->value` : `${accessor}->value`;\n    case 'array':\n      if (ref.items.kind === 'model') {\n        return nullable\n          ? `${accessor} !== null ? array_map(fn ($item) => $item->toArray(), ${accessor}) : null`\n          : `array_map(fn ($item) => $item->toArray(), ${accessor})`;\n      }\n      if (ref.items.kind === 'enum') {\n        return nullable\n          ? `${accessor} !== null ? array_map(fn ($item) => $item->value, ${accessor}) : null`\n          : `array_map(fn ($item) => $item->value, ${accessor})`;\n      }\n      if (ref.items.kind === 'primitive' && ref.items.format === 'date-time') {\n        return nullable\n          ? `${accessor} !== null ? array_map(fn ($item) => $item->format(\\\\DateTimeInterface::RFC3339_EXTENDED), ${accessor}) : null`\n          : `array_map(fn ($item) => $item->format(\\\\DateTimeInterface::RFC3339_EXTENDED), ${accessor})`;\n      }\n      return accessor;\n    case 'nullable':\n      return generateToArrayValue(ref.inner, accessor, true);\n    case 'map':\n      return accessor;\n    case 'union': {\n      const resolved = resolveDegenerateUnion(ref);\n      if (resolved) return generateToArrayValue(resolved, accessor, nullable);\n      // Polymorphic union of model variants: PHP dispatches to the concrete\n      // instance's toArray() at runtime, so a single ->toArray() call serializes\n      // any branch correctly without a match here.\n      if (ref.variants.every((v) => v.kind === 'model')) {\n        return `${accessor}${ns}->toArray()`;\n      }\n      // Heterogeneous unions involving models or enums have no uniform\n      // serialization strategy (->toArray() vs ->value vs raw scalar), so fail\n      // at codegen time rather than silently emitting a raw object that breaks\n      // the toArray contract. Pure scalar unions (e.g. string|int) fall\n      // through to the bare accessor below — that is correct.\n      if (ref.variants.some((v) => v.kind === 'model' || v.kind === 'enum')) {\n        const summary = ref.variants\n          .map((v) => (v.kind === 'model' ? `model:${v.name}` : v.kind === 'enum' ? `enum:${v.name}` : v.kind))\n          .join(' | ');\n        throw new Error(\n          `[php emitter] Cannot generate toArray for heterogeneous union: ${summary}. ` +\n            `Unions must be all-model or all-scalar; mixed and all-enum unions are not yet supported.`,\n        );\n      }\n      return accessor;\n    }\n    case 'literal':\n      return accessor;\n  }\n}\n\n/**\n * Check if a TypeRef needs a @var PHPDoc annotation because the PHP type hint\n * loses information (e.g., `array` vs `array<ConnectionDomain>`).\n */\nfunction needsVarAnnotation(ref: TypeRef): boolean {\n  switch (ref.kind) {\n    case 'array':\n    case 'map':\n      return true;\n    case 'nullable':\n      return needsVarAnnotation(ref.inner);\n    default:\n      return false;\n  }\n}\n","import type { Enum, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { toPascalCase } from '@workos/oagen';\nimport { className, resolveEnumName } from './naming.js';\nimport { phpDocComment } from './utils.js';\nimport { isEnumInScope } from '../shared/resolved-ops.js';\n\n/**\n * Generate PHP enum files from IR enums.\n */\nexport function generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n  if (enums.length === 0) return [];\n\n  const files: GeneratedFile[] = [];\n  const emittedCanonical = new Set<string>();\n\n  for (const e of enums) {\n    const canonical = resolveEnumName(e.name);\n    if (emittedCanonical.has(canonical)) continue; // skip aliases\n    emittedCanonical.add(canonical);\n\n    // FR-1.4: write the per-enum FILE only when in scope. PHP dedupes\n    // value-identical enums onto a single canonical class, so the canonical\n    // file is needed when EITHER the canonical name OR any alias resolving to\n    // it is reachable from the selected services. PSR-4 (one class per file\n    // under lib/Resource/, no barrel) means an out-of-scope enum is simply\n    // left untouched on disk and stays loadable.\n    const enumInScope = enums.some(\n      (other) => resolveEnumName(other.name) === canonical && isEnumInScope(other.name, ctx),\n    );\n\n    const name = className(canonical);\n    const _isAllStrings = e.values.every((v) => typeof v.value === 'string');\n    const isAllInts = e.values.every((v) => typeof v.value === 'number' && Number.isInteger(v.value));\n    const backingType = isAllInts ? 'int' : 'string';\n\n    const lines: string[] = [];\n    // No <?php here — the file header from fileHeader() provides it\n    lines.push(`namespace ${ctx.namespacePascal}\\\\Resource;`);\n    lines.push('');\n    lines.push(`enum ${name}: ${backingType}`);\n    lines.push('{');\n\n    // Deduplicate case names\n    const usedNames = new Map<string, number>();\n    for (const val of e.values) {\n      let caseName = toPascalCase(val.name.toLowerCase());\n      const baseName = caseName;\n      const count = usedNames.get(baseName) ?? 0;\n      if (count > 0) {\n        caseName = `${baseName}${count + 1}`;\n      }\n      usedNames.set(baseName, count + 1);\n\n      if (val.description || val.deprecated) {\n        const parts: string[] = [];\n        if (val.description) parts.push(val.description);\n        if (val.deprecated) parts.push('@deprecated');\n        lines.push(...phpDocComment(parts.join('\\n'), 4));\n      }\n\n      if (typeof val.value === 'string') {\n        lines.push(`    case ${caseName} = '${val.value}';`);\n      } else {\n        lines.push(`    case ${caseName} = ${val.value};`);\n      }\n    }\n\n    lines.push('}');\n\n    if (enumInScope) {\n      files.push({\n        path: `lib/Resource/${name}.php`,\n        content: lines.join('\\n'),\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n","import { parsePathTemplate, hasPathParams } from '../shared/path-template.js';\nimport { fieldName } from './naming.js';\n\nexport interface PhpPathOptions {\n  /**\n   * Raw OpenAPI param names whose runtime value is enum- or model-valued and\n   * therefore needs `->value` accessed before encoding. Mirrors the legacy\n   * resources.ts behavior that treated `kind === 'enum'` and `kind === 'model'`\n   * the same way.\n   */\n  valueAccessorParams?: ReadonlySet<string>;\n}\n\n/**\n * Build the PHP expression that the SDK passes to HttpClient as `path:`.\n *\n * Concatenation, not interpolation: PHP does not allow function calls inside\n * \"...\" strings, and every parameter must be wrapped in `rawurlencode(...)` so\n * that an unencoded \"../\" in a caller-supplied id cannot be normalized by\n * libcurl into a different endpoint of the WorkOS API while still\n * authenticated with the application's API key.\n *\n *   \"/orgs\"            → `'orgs'`\n *   \"/orgs/{id}\"       → `'orgs/' . rawurlencode($id)`\n *   \"/orgs/{id}/users\" → `'orgs/' . rawurlencode($id) . '/users'`\n *   \"/orgs/{id}\" with id ∈ valueAccessorParams → `'orgs/' . rawurlencode($id->value)`\n */\nexport function buildPhpPathExpression(rawPath: string, options: PhpPathOptions = {}): string {\n  const segments = parsePathTemplate(rawPath, { stripLeadingSlash: true });\n  if (segments.length === 0) return \"''\";\n\n  if (!hasPathParams(segments)) {\n    return phpSingleQuoted((segments[0] as { value: string }).value);\n  }\n\n  const valueAccessor = options.valueAccessorParams;\n  const parts: string[] = [];\n  for (const seg of segments) {\n    if (seg.kind === 'literal') {\n      parts.push(phpSingleQuoted(seg.value));\n    } else {\n      const varName = fieldName(seg.name);\n      const accessor = valueAccessor?.has(seg.name) ? `$${varName}->value` : `$${varName}`;\n      parts.push(`rawurlencode(${accessor})`);\n    }\n  }\n  return parts.join(' . ');\n}\n\nfunction phpSingleQuoted(literal: string): string {\n  return `'${literal.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n","import type { EmitterContext, ResolvedOperation, ResolvedWrapper, TypeRef } from '@workos/oagen';\nimport { toCamelCase } from '@workos/oagen';\nimport { mapTypeRef, mapTypeRefForPHPDoc } from './type-map.js';\nimport { className, fieldName } from './naming.js';\nimport { phpDocComment } from './utils.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { buildPhpPathExpression } from './path-expression.js';\n\n/**\n * Generate PHP wrapper methods for split union operations.\n */\nexport function generateWrapperMethods(resolvedOp: ResolvedOperation, ctx: EmitterContext): string[] {\n  const lines: string[] = [];\n  for (const wrapper of resolvedOp.wrappers ?? []) {\n    emitWrapperMethod(lines, resolvedOp, wrapper, ctx);\n  }\n  return lines;\n}\n\nfunction emitWrapperMethod(\n  lines: string[],\n  resolvedOp: ResolvedOperation,\n  wrapper: ResolvedWrapper,\n  ctx: EmitterContext,\n): void {\n  const method = toCamelCase(wrapper.name);\n  const ns = ctx.namespacePascal;\n  const wrapperParams = resolveWrapperParams(wrapper, ctx);\n\n  lines.push('');\n\n  // PHPDoc block\n  const docParts: string[] = [];\n  for (const { paramName, field, isOptional } of wrapperParams) {\n    const docType = field ? mapTypeRefForPHPDoc(field.type) : 'string';\n    const nullSuffix = isOptional && !docType.endsWith('|null') ? '|null' : '';\n    docParts.push(`@param ${docType}${nullSuffix} $${fieldName(paramName)}`);\n  }\n  const op2 = resolvedOp.operation;\n  const returnDocType = op2.response.kind === 'model' ? `\\\\${ns}\\\\Resource\\\\${className(op2.response.name)}` : 'mixed';\n  docParts.push(`@return ${returnDocType}`);\n  docParts.push(`@throws \\\\${ns}\\\\Exception\\\\WorkOSException`);\n  lines.push(...phpDocComment(docParts.join('\\n'), 4));\n\n  lines.push(`    public function ${method}(`);\n\n  // Build params: required first, then optional, to avoid PHP deprecation\n  const requiredParams: string[] = [];\n  const optionalParamLines: string[] = [];\n  for (const { paramName, field, isOptional } of wrapperParams) {\n    const phpName = fieldName(paramName);\n    if (field) {\n      const phpType = mapTypeRef(field.type);\n      if (isOptional) {\n        const nullableType = phpType.startsWith('?') ? phpType : `?${phpType}`;\n        optionalParamLines.push(`        ${nullableType} $${phpName} = null,`);\n      } else {\n        requiredParams.push(`        ${phpType} $${phpName},`);\n      }\n    } else {\n      if (isOptional) {\n        optionalParamLines.push(`        ?string $${phpName} = null,`);\n      } else {\n        requiredParams.push(`        string $${phpName},`);\n      }\n    }\n  }\n  optionalParamLines.push(`        ?\\\\${ns}\\\\RequestOptions $options = null,`);\n  for (const p of [...requiredParams, ...optionalParamLines]) {\n    lines.push(p);\n  }\n\n  // Return type\n  const op = resolvedOp.operation;\n  const responseType = op.response.kind === 'model' ? `\\\\${ns}\\\\Resource\\\\${className(op.response.name)}` : 'mixed';\n  lines.push(`    ): ${responseType} {`);\n\n  // Build body using array_filter for consistency\n  const bodyEntries: string[] = [];\n\n  // Defaults (always included)\n  if (wrapper.defaults) {\n    for (const [key, value] of Object.entries(wrapper.defaults)) {\n      bodyEntries.push(`'${key}' => ${phpLiteral(value)}`);\n    }\n  }\n\n  // Exposed params (extract enum values)\n  for (const { paramName, field } of wrapperParams) {\n    const phpName = fieldName(paramName);\n    if (field && isEnumType(field.type)) {\n      bodyEntries.push(`'${paramName}' => $${phpName}?->value`);\n    } else {\n      bodyEntries.push(`'${paramName}' => $${phpName}`);\n    }\n  }\n\n  lines.push('        $body = array_filter([');\n  for (const entry of bodyEntries) {\n    lines.push(`            ${entry},`);\n  }\n  lines.push('        ], fn ($v) => $v !== null);');\n\n  // inferFromClient fields need special handling (conditional injection)\n  for (const clientField of wrapper.inferFromClient ?? []) {\n    const clientExpr = clientFieldExpression(clientField);\n    lines.push(`        $body['${clientField}'] = ${clientExpr};`);\n  }\n\n  // Delegate to HTTP client\n  const httpMethod = op.httpMethod.toUpperCase();\n  const pathExpr = buildPhpPathExpression(op.path);\n\n  lines.push('');\n  lines.push('        $response = $this->client->request(');\n  lines.push(`            method: '${httpMethod}',`);\n  lines.push(`            path: ${pathExpr},`);\n  lines.push('            body: $body,');\n  lines.push('            options: $options,');\n  lines.push('        );');\n\n  if (op.response.kind === 'model') {\n    lines.push(`        return ${className(op.response.name)}::fromArray($response);`);\n  } else {\n    lines.push('        return $response;');\n  }\n\n  lines.push('    }');\n}\n\nfunction isEnumType(ref: TypeRef): boolean {\n  if (ref.kind === 'enum') return true;\n  if (ref.kind === 'nullable') return isEnumType(ref.inner);\n  return false;\n}\n\nfunction phpLiteral(value: unknown): string {\n  if (typeof value === 'string') return `'${value}'`;\n  if (typeof value === 'number') return String(value);\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  return 'null';\n}\n\nfunction clientFieldExpression(field: string): string {\n  // Map inferFromClient fields to the actual client/config accessors\n  switch (field) {\n    case 'client_id':\n      return '$this->client->requireClientId()';\n    case 'client_secret':\n      return '$this->client->requireApiKey()';\n    default:\n      return `$this->client->${toCamelCase(field)}`;\n  }\n}\n","import type {\n  Service,\n  Operation,\n  Model,\n  EmitterContext,\n  GeneratedFile,\n  ResolvedOperation,\n  Parameter,\n} from '@workos/oagen';\nimport { planOperation, toCamelCase, toPascalCase } from '@workos/oagen';\nimport { mapTypeRef, mapTypeRefForPHPDoc } from './type-map.js';\nimport { className, fieldName, resolveMethodName, buildExportedClassNameSet, resolveServiceTarget } from './naming.js';\nimport { isListWrapperModel } from './models.js';\nimport {\n  scopedMountGroups,\n  buildResolvedLookup,\n  lookupResolved,\n  getOpDefaults,\n  getOpInferFromClient,\n  collectGroupedParamNames,\n  collectBodyFieldTypes,\n} from '../shared/resolved-ops.js';\nimport { generateWrapperMethods } from './wrappers.js';\nimport { phpDocComment } from './utils.js';\nimport { buildPhpPathExpression } from './path-expression.js';\n\n/**\n * Resolve the resource class name for a service (used by client.ts).\n */\nexport function resolveResourceClassName(service: Service, ctx: EmitterContext): string {\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (r.service.name === service.name) return r.mountOn;\n  }\n  return className(service.name);\n}\n\n/**\n * Generate PHP resource class files from IR services.\n * Uses mount-based grouping: one resource file per mount target.\n */\nexport function generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n  if (services.length === 0) return [];\n\n  const files: GeneratedFile[] = [];\n  const modelMap = new Map(ctx.spec.models.map((m) => [m.name, m]));\n\n  // Group operations by mount target. In a scoped (`--services`) run this\n  // returns only the selected post-mount services so we emit per-service\n  // resource files for those alone.\n  const mountGroups = scopedMountGroups(ctx);\n  const entries: Array<{ name: string; operations: Operation[] }> =\n    mountGroups.size > 0 || ctx.scopedServices?.size\n      ? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations }))\n      : services.map((s) => ({ name: className(s.name), operations: s.operations }));\n\n  const exportedClasses = buildExportedClassNameSet(ctx);\n  for (const { name: mountName, operations } of entries) {\n    if (operations.length === 0) continue;\n    const resourceName = className(resolveServiceTarget(mountName, exportedClasses));\n    const mergedService: Service = { name: mountName, operations };\n    const lines: string[] = [];\n\n    // No <?php here — the file header from fileHeader() provides it\n    lines.push(`namespace ${ctx.namespacePascal}\\\\Service;`);\n    lines.push('');\n\n    // Build resolved lookup early — used by both imports and method generation\n    const resolvedLookup = buildResolvedLookup(ctx);\n\n    // Collect imports\n    const imports = collectImports(mergedService, ctx, resolvedLookup);\n    for (const imp of imports) {\n      lines.push(`use ${imp};`);\n    }\n    if (imports.length > 0) lines.push('');\n\n    lines.push(`class ${resourceName}`);\n    lines.push('{');\n    lines.push('    public function __construct(');\n    lines.push(`        private readonly \\\\${ctx.namespacePascal}\\\\HttpClient $client,`);\n    lines.push('    ) {');\n    lines.push('    }');\n\n    // Track emitted method names to avoid duplicates\n    const emittedMethods = new Set<string>();\n    for (const op of operations) {\n      const method = resolveMethodName(op, mergedService, ctx);\n      if (emittedMethods.has(method)) continue;\n      emittedMethods.add(method);\n      const resolved = lookupResolved(op, resolvedLookup);\n\n      // When wrappers exist, skip the base method and only emit wrappers\n      if (resolved?.wrappers && resolved.wrappers.length > 0) {\n        lines.push(...generateWrapperMethods(resolved, ctx));\n      } else {\n        lines.push('');\n        generateMethod(lines, op, mergedService, ctx, modelMap, resolved ?? undefined);\n      }\n    }\n\n    lines.push('}');\n\n    files.push({\n      path: `lib/Service/${resourceName}.php`,\n      content: lines.join('\\n'),\n      overwriteExisting: true,\n    });\n\n    // Generate variant class files for operations with parameter groups\n    for (const op of operations) {\n      if ((op.parameterGroups?.length ?? 0) > 0) {\n        files.push(...generateParameterGroupFiles(op, ctx, modelMap));\n      }\n    }\n  }\n\n  return files;\n}\n\n/**\n * Check if an operation is a redirect endpoint that should construct a URL\n * instead of making an HTTP request.\n *\n * Detection: GET endpoints with no response body (primitive unknown) and query\n * params are redirect endpoints (e.g., SSO/OAuth authorize and logout flows).\n * Also respects an explicit urlBuilder flag on the resolved operation and\n * catches endpoints with 302 success responses.\n */\nexport function isRedirectEndpoint(op: Operation, resolvedOp?: ResolvedOperation): boolean {\n  if ((resolvedOp as any)?.urlBuilder) return true;\n  if ((op as any).successResponses?.some((r: any) => r.statusCode >= 300 && r.statusCode < 400)) return true;\n  if (\n    op.httpMethod === 'get' &&\n    op.response.kind === 'primitive' &&\n    (op.response as any).type === 'unknown' &&\n    op.queryParams.length > 0\n  ) {\n    return true;\n  }\n  return false;\n}\n\n// ---------------------------------------------------------------------------\n// Mutually-exclusive parameter group support\n// ---------------------------------------------------------------------------\n\n/** PHP class name for a parameter group variant (e.g. ParentResourceById). */\nfunction groupVariantClassName(groupName: string, variantName: string): string {\n  return `${className(groupName)}${className(variantName)}`;\n}\n\n/**\n * Derive a short PHP property name for a parameter within a variant class.\n * Strips the group name prefix when present to avoid stuttering\n * (e.g. parent_resource_id in group parent_resource -> id -> camelCase).\n */\nexport function deriveVariantFieldName(paramName: string, groupName: string): string {\n  const prefix = groupName + '_';\n  const stripped = paramName.startsWith(prefix) ? paramName.slice(prefix.length) : paramName;\n  return fieldName(stripped);\n}\n\n/**\n * Generate PHP variant class files for all parameter groups on an operation.\n * Each variant becomes a simple PHP class with readonly constructor properties.\n */\nfunction generateParameterGroupFiles(\n  op: Operation,\n  ctx: EmitterContext,\n  modelMap: Map<string, Model>,\n): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const bodyFieldTypes = collectBodyFieldTypes(op, [...modelMap.values()]);\n\n  for (const group of op.parameterGroups ?? []) {\n    for (const variant of group.variants) {\n      const variantClass = groupVariantClassName(group.name, variant.name);\n      const lines: string[] = [];\n\n      lines.push(`namespace ${ctx.namespacePascal}\\\\Service;`);\n      lines.push('');\n      lines.push(`class ${variantClass}`);\n      lines.push('{');\n      lines.push('    public function __construct(');\n      for (let i = 0; i < variant.parameters.length; i++) {\n        const param = variant.parameters[i];\n        const effectiveType = bodyFieldTypes.get(param.name) ?? param.type;\n        const phpType = mapTypeRef(effectiveType, { qualified: true });\n        const phpName = deriveVariantFieldName(param.name, group.name);\n        const comma = ',';\n        lines.push(`        public readonly ${phpType} $${phpName}${comma}`);\n      }\n      lines.push('    ) {');\n      lines.push('    }');\n      lines.push('}');\n\n      files.push({\n        path: `lib/Service/${variantClass}.php`,\n        content: lines.join('\\n'),\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n\n/**\n * Generate instanceof dispatch lines to serialize a grouped parameter\n * into a target array ($query or $body) using each variant's wire names.\n */\nfunction generateGroupDispatch(op: Operation, indent: string, target: '$query' | '$body' = '$query'): string[] {\n  const lines: string[] = [];\n\n  for (const group of op.parameterGroups ?? []) {\n    const phpParamName = fieldName(group.name);\n\n    for (let vi = 0; vi < group.variants.length; vi++) {\n      const variant = group.variants[vi];\n      const variantClass = groupVariantClassName(group.name, variant.name);\n      const keyword = vi === 0 ? 'if' : 'elseif';\n\n      lines.push(`${indent}${keyword} ($${phpParamName} instanceof ${variantClass}) {`);\n\n      for (const param of variant.parameters) {\n        const phpField = deriveVariantFieldName(param.name, group.name);\n        lines.push(`${indent}    ${target}['${param.name}'] = $${phpParamName}->${phpField};`);\n      }\n\n      lines.push(`${indent}}`);\n    }\n  }\n\n  return lines;\n}\n\nfunction generateMethod(\n  lines: string[],\n  op: Operation,\n  service: Service,\n  ctx: EmitterContext,\n  modelMap: Map<string, Model>,\n  resolvedOp?: ResolvedOperation,\n): void {\n  const plan = planOperation(op);\n  const method = resolveMethodName(op, service, ctx);\n\n  // Build the set of params hidden from the method signature\n  // (injected from client config or as constant defaults)\n  const hiddenParams = new Set<string>([\n    ...Object.keys(getOpDefaults(resolvedOp)),\n    ...getOpInferFromClient(resolvedOp),\n  ]);\n\n  const isRedirect = isRedirectEndpoint(op, resolvedOp);\n  const materializeQueryDefaults = !isRedirect;\n  const params = buildMethodParams(op, plan, modelMap, ctx, hiddenParams, { materializeQueryDefaults });\n  const returnType = isRedirect ? 'string' : getReturnType(plan, ctx);\n\n  // PHPDoc block\n  const docParts: string[] = [];\n  if (op.description) docParts.push(op.description);\n  const seenDocParams = new Set<string>();\n\n  // @param for path params\n  for (const p of op.pathParams) {\n    const docType = mapTypeRefForPHPDoc(p.type);\n    const phpName = fieldName(p.name);\n    seenDocParams.add(phpName);\n    const prefix = p.deprecated ? '(deprecated) ' : '';\n    let desc = p.description ? ` ${prefix}${p.description}` : p.deprecated ? ' (deprecated)' : '';\n    if (p.default != null) desc += ` Defaults to ${JSON.stringify(p.default)}.`;\n    docParts.push(`@param ${docType} $${phpName}${desc}`);\n  }\n\n  // @param for body fields\n  const groupedParamNames = collectGroupedParamNames(op);\n  if (plan.hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = modelMap.get(op.requestBody.name);\n    if (bodyModel) {\n      const bodyParamMap = buildBodyParamMap(op, bodyModel);\n      for (const field of bodyModel.fields) {\n        if (hiddenParams.has(field.name)) continue;\n        if (groupedParamNames.has(field.name)) continue;\n        const docType = mapTypeRefForPHPDoc(field.type);\n        const phpName = bodyParamMap.get(field.name) ?? fieldName(field.name);\n        if (seenDocParams.has(phpName)) continue;\n        seenDocParams.add(phpName);\n        const nullSuffix = !field.required && !docType.endsWith('|null') ? '|null' : '';\n        const prefix = field.deprecated ? '(deprecated) ' : '';\n        const desc = field.description ? ` ${prefix}${field.description}` : field.deprecated ? ' (deprecated)' : '';\n        docParts.push(`@param ${docType}${nullSuffix} $${phpName}${desc}`);\n      }\n    }\n  }\n\n  // @param for parameter groups (union-typed)\n  for (const group of op.parameterGroups ?? []) {\n    const phpName = fieldName(group.name);\n    if (seenDocParams.has(phpName)) continue;\n    seenDocParams.add(phpName);\n    const variantTypes = group.variants.map((v) => groupVariantClassName(group.name, v.name));\n    const unionDocType = variantTypes.join('|');\n    const nullPrefix = group.optional ? 'null|' : '';\n    docParts.push(`@param ${nullPrefix}${unionDocType} $${phpName}`);\n  }\n\n  // @param for query params (skip grouped params — they appear as group union params)\n  for (const q of op.queryParams) {\n    if (hiddenParams.has(q.name)) continue;\n    if (groupedParamNames.has(q.name)) continue;\n    const docType = mapTypeRefForPHPDoc(q.type);\n    const phpName = fieldName(q.name);\n    if (seenDocParams.has(phpName)) continue;\n    seenDocParams.add(phpName);\n    // Spec-defaulted enum params on HTTP calls are non-nullable because the\n    // signature default is the enum case. URL builders keep them nullable so\n    // omitted optional query params stay omitted from the generated URL.\n    const hasEnumDefault = shouldMaterializeQueryDefault(q, materializeQueryDefaults);\n    const nullSuffix = !q.required && !hasEnumDefault && !docType.endsWith('|null') ? '|null' : '';\n    const prefix = q.deprecated ? '(deprecated) ' : '';\n    let desc = q.description ? ` ${prefix}${q.description}` : q.deprecated ? ' (deprecated)' : '';\n    if (q.default != null) desc += ` Defaults to ${JSON.stringify(q.default)}.`;\n    docParts.push(`@param ${docType}${nullSuffix} $${phpName}${desc}`);\n  }\n\n  // @return -- use generic annotation for paginated responses\n  if (plan.isPaginated && op.pagination?.itemType.kind === 'model') {\n    const itemType = op.pagination.itemType;\n    const itemModel = ctx.spec.models.find((m) => m.name === itemType.name);\n    let resolvedName = itemType.name;\n    if (itemModel && isListWrapperModel(itemModel)) {\n      const dataField = itemModel.fields.find((f) => f.name === 'data');\n      if (dataField?.type.kind === 'array' && dataField.type.items.kind === 'model') {\n        resolvedName = dataField.type.items.name;\n      }\n    }\n    const itemClass = className(resolvedName);\n    docParts.push(\n      `@return \\\\${ctx.namespacePascal}\\\\PaginatedResponse<\\\\${ctx.namespacePascal}\\\\Resource\\\\${itemClass}>`,\n    );\n  } else {\n    docParts.push(`@return ${returnType}`);\n  }\n\n  // @throws — scope to what the method actually calls\n  if (!isRedirect) {\n    // HTTP methods can throw any WorkOSException (config, transport, API response)\n    docParts.push(`@throws \\\\${ctx.namespacePascal}\\\\Exception\\\\WorkOSException`);\n  } else if (getOpInferFromClient(resolvedOp).length > 0) {\n    // Redirect endpoints that inject client fields can throw ConfigurationException\n    docParts.push(`@throws \\\\${ctx.namespacePascal}\\\\Exception\\\\ConfigurationException`);\n  }\n  // Redirect endpoints with no inferFromClient: buildUrl() is pure, no @throws\n\n  if (op.deprecated) docParts.push('@deprecated');\n  lines.push(...phpDocComment(docParts.join('\\n'), 4));\n\n  // Method signature\n  lines.push(`    public function ${method}(`);\n  for (let i = 0; i < params.length; i++) {\n    const comma = i < params.length - 1 ? ',' : ',';\n    lines.push(`        ${params[i]}${comma}`);\n  }\n  lines.push(`    ): ${returnType} {`);\n\n  // Method body\n  const httpMethod = op.httpMethod.toUpperCase();\n  const path = buildPathString(op);\n\n  if (isRedirect) {\n    // Redirect endpoint: construct URL client-side instead of making HTTP request\n    const queryLines = buildQueryArray(op, hiddenParams, { materializeQueryDefaults });\n    const hasDefaults = Object.keys(getOpDefaults(resolvedOp)).length > 0;\n    const hasInferred = getOpInferFromClient(resolvedOp).length > 0;\n    const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n    const needsQuery = queryLines.length > 0 || hasDefaults || hasInferred || hasGroups;\n\n    if (needsQuery) {\n      const groupedParams = collectGroupedParamNames(op);\n      const hasOptionalQuery = op.queryParams.some(\n        (q) => !q.required && !hiddenParams.has(q.name) && !groupedParams.has(q.name),\n      );\n      if (hasOptionalQuery) {\n        lines.push('        $query = array_filter([');\n      } else if (queryLines.length > 0) {\n        lines.push('        $query = [');\n      } else {\n        lines.push('        $query = [');\n      }\n      for (const q of queryLines) {\n        lines.push(`            ${q}`);\n      }\n      // Inject constant defaults\n      for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n        lines.push(`            '${key}' => ${phpLiteral(value)},`);\n      }\n      if (hasOptionalQuery) {\n        lines.push('        ], fn ($v) => $v !== null);');\n      } else {\n        lines.push('        ];');\n      }\n      // Inject fields from client config\n      for (const clientField of getOpInferFromClient(resolvedOp)) {\n        lines.push(`        $query['${clientField}'] = ${clientFieldExpression(clientField)};`);\n      }\n      // Inject parameter group dispatch (instanceof checks)\n      lines.push(...generateGroupDispatch(op, '        '));\n      lines.push(`        return $this->client->buildUrl(path: ${path}, query: $query, options: $options);`);\n    } else {\n      lines.push(`        return $this->client->buildUrl(path: ${path}, query: [], options: $options);`);\n    }\n  } else if (plan.isPaginated) {\n    const queryLines = buildQueryArray(op);\n    const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n    const needsQuery = queryLines.length > 0 || hasGroups;\n    if (needsQuery) {\n      if (queryLines.length > 0) {\n        lines.push('        $query = array_filter([');\n        for (const q of queryLines) {\n          lines.push(`            ${q}`);\n        }\n        lines.push('        ], fn ($v) => $v !== null);');\n      } else {\n        lines.push('        $query = [];');\n      }\n      // Inject parameter group dispatch (instanceof checks)\n      lines.push(...generateGroupDispatch(op, '        '));\n    }\n    lines.push('        return $this->client->requestPage(');\n    lines.push(`            method: '${httpMethod}',`);\n    lines.push(`            path: ${path},`);\n    if (needsQuery) {\n      lines.push('            query: $query,');\n    }\n    const itemType = op.pagination?.itemType;\n    if (itemType?.kind === 'model') {\n      // Unwrap list wrapper models to the inner item type\n      const itemModel = ctx.spec.models.find((m) => m.name === itemType.name);\n      let resolvedName = itemType.name;\n      if (itemModel && isListWrapperModel(itemModel)) {\n        const dataField = itemModel.fields.find((f) => f.name === 'data');\n        if (dataField?.type.kind === 'array' && dataField.type.items.kind === 'model') {\n          resolvedName = dataField.type.items.name;\n        }\n      }\n      const itemClass = className(resolvedName);\n      lines.push(`            modelClass: ${itemClass}::class,`);\n    }\n    lines.push('            options: $options,');\n    lines.push('        );');\n  } else if (plan.isDelete) {\n    // Build body if the operation has a request body (e.g., DELETE with criteria)\n    if (plan.hasBody) {\n      const bodyModel = op.requestBody?.kind === 'model' ? modelMap.get(op.requestBody.name) : null;\n      const bodyParamMap = buildBodyParamMap(op, bodyModel ?? null);\n      const deleteGroupedParams = collectGroupedParamNames(op);\n      const visibleFields =\n        bodyModel?.fields.filter((f) => !hiddenParams.has(f.name) && !deleteGroupedParams.has(f.name)) ?? [];\n      const hasOptionalFields = visibleFields.some((f) => !f.required);\n      if (hasOptionalFields) {\n        lines.push('        $body = array_filter([');\n      } else {\n        lines.push('        $body = [');\n      }\n      for (const field of visibleFields) {\n        const phpName = bodyParamMap.get(field.name) ?? fieldName(field.name);\n        const nullsafe = field.required ? '' : '?';\n        const valueExpr = isEnumType(field.type) ? `$${phpName}${nullsafe}->value` : `$${phpName}`;\n        lines.push(`            '${field.name}' => ${valueExpr},`);\n      }\n      // Inject constant defaults\n      for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n        lines.push(`            '${key}' => ${phpLiteral(value)},`);\n      }\n      if (hasOptionalFields) {\n        lines.push('        ], fn ($v) => $v !== null);');\n      } else {\n        lines.push('        ];');\n      }\n      // Inject fields from client config\n      for (const clientField of getOpInferFromClient(resolvedOp)) {\n        lines.push(`        $body['${clientField}'] = ${clientFieldExpression(clientField)};`);\n      }\n      // Inject parameter group dispatch into body\n      if ((op.parameterGroups?.length ?? 0) > 0) {\n        lines.push(...generateGroupDispatch(op, '        ', '$body'));\n      }\n    }\n    // Build query params if present\n    const deleteQueryLines = buildQueryArray(op);\n    if (deleteQueryLines.length > 0) {\n      lines.push('        $query = array_filter([');\n      for (const q of deleteQueryLines) {\n        lines.push(`            ${q}`);\n      }\n      lines.push('        ], fn ($v) => $v !== null);');\n    }\n\n    lines.push('        $this->client->request(');\n    lines.push(`            method: '${httpMethod}',`);\n    lines.push(`            path: ${path},`);\n    if (plan.hasBody) {\n      lines.push('            body: $body,');\n    }\n    if (deleteQueryLines.length > 0) {\n      lines.push('            query: $query,');\n    }\n    lines.push('            options: $options,');\n    lines.push('        );');\n  } else if (plan.hasBody) {\n    const bodyModel = op.requestBody?.kind === 'model' ? modelMap.get(op.requestBody.name) : null;\n    const bodyParamMap = buildBodyParamMap(op, bodyModel ?? null);\n    const bodyGroupedParams = collectGroupedParamNames(op);\n    const visibleFields =\n      bodyModel?.fields.filter((f) => !hiddenParams.has(f.name) && !bodyGroupedParams.has(f.name)) ?? [];\n    const hasOptionalFields = visibleFields.some((f) => !f.required);\n    if (hasOptionalFields) {\n      lines.push('        $body = array_filter([');\n    } else {\n      lines.push('        $body = [');\n    }\n    for (const field of visibleFields) {\n      const phpName = bodyParamMap.get(field.name) ?? fieldName(field.name);\n      const nullsafe = field.required ? '' : '?';\n      const valueExpr = isEnumType(field.type) ? `$${phpName}${nullsafe}->value` : `$${phpName}`;\n      lines.push(`            '${field.name}' => ${valueExpr},`);\n    }\n    // Inject constant defaults\n    for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n      lines.push(`            '${key}' => ${phpLiteral(value)},`);\n    }\n    if (hasOptionalFields) {\n      lines.push('        ], fn ($v) => $v !== null);');\n    } else {\n      lines.push('        ];');\n    }\n    // Inject fields from client config\n    for (const clientField of getOpInferFromClient(resolvedOp)) {\n      lines.push(`        $body['${clientField}'] = ${clientFieldExpression(clientField)};`);\n    }\n    // Inject parameter group dispatch into body so sensitive fields\n    // (passwords, role slugs) never leak into the URL query string.\n    if ((op.parameterGroups?.length ?? 0) > 0) {\n      lines.push(...generateGroupDispatch(op, '        ', '$body'));\n    }\n    lines.push('        $response = $this->client->request(');\n    lines.push(`            method: '${httpMethod}',`);\n    lines.push(`            path: ${path},`);\n    lines.push('            body: $body,');\n    lines.push('            options: $options,');\n    lines.push('        );');\n\n    if (plan.responseModelName) {\n      const responseClass = className(plan.responseModelName);\n      if (op.response.kind === 'array') {\n        lines.push(`        return array_map(fn ($item) => ${responseClass}::fromArray($item), $response);`);\n      } else {\n        lines.push(`        return ${responseClass}::fromArray($response);`);\n      }\n    } else {\n      lines.push('        return $response;');\n    }\n  } else {\n    const queryLines = buildQueryArray(op, hiddenParams);\n    const hasDefaults = Object.keys(getOpDefaults(resolvedOp)).length > 0;\n    const hasInferred = getOpInferFromClient(resolvedOp).length > 0;\n    const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n    const needsQuery = queryLines.length > 0 || hasDefaults || hasInferred || hasGroups;\n\n    if (needsQuery) {\n      const groupedParams = collectGroupedParamNames(op);\n      const hasOptionalQuery = op.queryParams.some(\n        (q) => !q.required && !hiddenParams.has(q.name) && !groupedParams.has(q.name),\n      );\n      if (hasOptionalQuery) {\n        lines.push('        $query = array_filter([');\n      } else if (queryLines.length > 0) {\n        lines.push('        $query = [');\n      } else {\n        lines.push('        $query = [');\n      }\n      for (const q of queryLines) {\n        lines.push(`            ${q}`);\n      }\n      // Inject constant defaults\n      for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n        lines.push(`            '${key}' => ${phpLiteral(value)},`);\n      }\n      if (hasOptionalQuery) {\n        lines.push('        ], fn ($v) => $v !== null);');\n      } else {\n        lines.push('        ];');\n      }\n      // Inject fields from client config\n      for (const clientField of getOpInferFromClient(resolvedOp)) {\n        lines.push(`        $query['${clientField}'] = ${clientFieldExpression(clientField)};`);\n      }\n      // Inject parameter group dispatch (instanceof checks)\n      lines.push(...generateGroupDispatch(op, '        '));\n    }\n    lines.push('        $response = $this->client->request(');\n    lines.push(`            method: '${httpMethod}',`);\n    lines.push(`            path: ${path},`);\n    if (needsQuery) {\n      lines.push('            query: $query,');\n    }\n    lines.push('            options: $options,');\n    lines.push('        );');\n\n    if (plan.responseModelName) {\n      const responseClass = className(plan.responseModelName);\n      if (op.response.kind === 'array') {\n        lines.push(`        return array_map(fn ($item) => ${responseClass}::fromArray($item), $response);`);\n      } else {\n        lines.push(`        return ${responseClass}::fromArray($response);`);\n      }\n    } else {\n      lines.push('        return $response;');\n    }\n  }\n\n  lines.push('    }');\n}\n\nfunction buildMethodParams(\n  op: Operation,\n  plan: ReturnType<typeof planOperation>,\n  modelMap: Map<string, Model>,\n  ctx: EmitterContext,\n  hiddenParams?: Set<string>,\n  opts?: { materializeQueryDefaults?: boolean },\n): string[] {\n  // Collect all params into required/optional buckets to avoid\n  // PHP's \"required after optional\" deprecation.\n  const required: string[] = [];\n  const optional: string[] = [];\n  const usedNames = new Set<string>();\n  const hidden = hiddenParams ?? new Set();\n  const groupedParams = collectGroupedParamNames(op);\n  // Path params (always required)\n  for (const p of op.pathParams) {\n    const phpType = mapTypeRef(p.type, { qualified: true });\n    let phpName = fieldName(p.name);\n    if (usedNames.has(phpName)) phpName = `path${phpName.charAt(0).toUpperCase()}${phpName.slice(1)}`;\n    usedNames.add(phpName);\n    required.push(`${phpType} $${phpName}`);\n  }\n\n  // Body fields\n  if (plan.hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = modelMap.get(op.requestBody.name);\n    if (bodyModel) {\n      for (const field of bodyModel.fields) {\n        if (hidden.has(field.name)) continue;\n        if (groupedParams.has(field.name)) continue;\n        const phpType = mapTypeRef(field.type, { qualified: true });\n        let phpName = fieldName(field.name);\n        if (usedNames.has(phpName)) {\n          // Disambiguate body field from path param with same name\n          phpName = `body${phpName.charAt(0).toUpperCase()}${phpName.slice(1)}`;\n          if (usedNames.has(phpName)) continue; // truly duplicate, skip\n        }\n        usedNames.add(phpName);\n        if (field.required) {\n          required.push(`${phpType} $${phpName}`);\n        } else {\n          const nullableType = phpType.startsWith('?') ? phpType : `?${phpType}`;\n          optional.push(`${nullableType} $${phpName} = null`);\n        }\n      }\n    }\n  }\n\n  // Parameter group union-typed params (before individual query params)\n  for (const group of op.parameterGroups ?? []) {\n    const phpName = fieldName(group.name);\n    if (usedNames.has(phpName)) continue;\n    usedNames.add(phpName);\n    // PHP 8.0+ union syntax: VariantA|VariantB $paramName\n    const variantTypes = group.variants.map((v) => groupVariantClassName(group.name, v.name));\n    const unionType = variantTypes.join('|');\n    if (group.optional) {\n      optional.push(`null|${unionType} $${phpName} = null`);\n    } else {\n      required.push(`${unionType} $${phpName}`);\n    }\n  }\n\n  // Query params (skip grouped params — they are serialized via group dispatch)\n  for (const q of op.queryParams) {\n    if (hidden.has(q.name)) continue;\n    if (groupedParams.has(q.name)) continue;\n    const phpType = mapTypeRef(q.type, { qualified: true });\n    let phpName = fieldName(q.name);\n    if (usedNames.has(phpName)) continue;\n    usedNames.add(phpName);\n    if (q.required) {\n      required.push(`${phpType} $${phpName}`);\n    } else if (shouldMaterializeQueryDefault(q, opts?.materializeQueryDefaults ?? true)) {\n      // Spec-provided default for an enum-typed param: emit a non-nullable\n      // typed default (e.g. PaginationOrder $order = PaginationOrder::Desc).\n      // Only enums are safe to default this way — primitives stay nullable so\n      // callers can distinguish \"unset\" from \"explicit value\".\n      const enumType = mapTypeRef(q.type, { qualified: true });\n      const caseName = toPascalCase(String(q.default));\n      optional.push(`${enumType} $${phpName} = ${enumType}::${caseName}`);\n    } else {\n      const nullableType = phpType.startsWith('?') ? phpType : `?${phpType}`;\n      optional.push(`${nullableType} $${phpName} = null`);\n    }\n  }\n\n  // RequestOptions (always last, always optional)\n  optional.push(`?\\\\${ctx.namespacePascal}\\\\RequestOptions $options = null`);\n\n  return [...required, ...optional];\n}\n\nfunction getReturnType(plan: ReturnType<typeof planOperation>, ctx: EmitterContext): string {\n  if (plan.isDelete) return 'void';\n  if (plan.isPaginated) return `\\\\${ctx.namespacePascal}\\\\PaginatedResponse`;\n  if (plan.responseModelName) {\n    if (plan.operation.response.kind === 'array') {\n      return 'array';\n    }\n    return `\\\\${ctx.namespacePascal}\\\\Resource\\\\${className(plan.responseModelName)}`;\n  }\n  return 'mixed';\n}\n\n/**\n * Build a mapping from wire name to PHP variable name for body fields,\n * disambiguating collisions with path param names.\n */\nfunction buildBodyParamMap(op: Operation, bodyModel: Model | null): Map<string, string> {\n  const map = new Map<string, string>();\n  if (!bodyModel) return map;\n  const pathParamNames = new Set(op.pathParams.map((p) => fieldName(p.name)));\n  for (const field of bodyModel.fields) {\n    let phpName = fieldName(field.name);\n    if (pathParamNames.has(phpName)) {\n      phpName = `body${phpName.charAt(0).toUpperCase()}${phpName.slice(1)}`;\n    }\n    map.set(field.name, phpName);\n  }\n  return map;\n}\n\nfunction buildPathString(op: Operation): string {\n  const valueAccessor = new Set<string>();\n  for (const p of op.pathParams) {\n    if (p.type.kind === 'enum' || p.type.kind === 'model') valueAccessor.add(p.name);\n  }\n  return buildPhpPathExpression(op.path, { valueAccessorParams: valueAccessor });\n}\n\nfunction isEnumType(ref: import('@workos/oagen').TypeRef): boolean {\n  if (ref.kind === 'enum') return true;\n  if (ref.kind === 'nullable') return isEnumType(ref.inner);\n  return false;\n}\n\nfunction isDateTimeType(ref: import('@workos/oagen').TypeRef): boolean {\n  if (ref.kind === 'primitive' && ref.format === 'date-time') return true;\n  if (ref.kind === 'nullable') return isDateTimeType(ref.inner);\n  return false;\n}\n\nfunction buildQueryArray(\n  op: Operation,\n  hiddenParams?: Set<string>,\n  opts?: { materializeQueryDefaults?: boolean },\n): string[] {\n  const hidden = hiddenParams ?? new Set();\n  const groupedParams = collectGroupedParamNames(op);\n  return op.queryParams\n    .filter((q) => !hidden.has(q.name) && !groupedParams.has(q.name))\n    .map((q) => {\n      const phpName = fieldName(q.name);\n      if (isEnumType(q.type)) {\n        // Mirrors the signature: only materialized enum defaults are\n        // non-nullable, so other optional enum params use the nullsafe op.\n        const hasEnumDefault = shouldMaterializeQueryDefault(q, opts?.materializeQueryDefaults ?? true);\n        const nullsafe = q.required || hasEnumDefault ? '' : '?';\n        return `'${q.name}' => $${phpName}${nullsafe}->value,`;\n      }\n      if (isDateTimeType(q.type)) {\n        const nullsafe = q.required ? '' : '?';\n        return `'${q.name}' => $${phpName}${nullsafe}->format(\\\\DateTimeInterface::RFC3339_EXTENDED),`;\n      }\n      return `'${q.name}' => $${phpName},`;\n    });\n}\n\nfunction shouldMaterializeQueryDefault(param: Parameter, enabled: boolean): boolean {\n  return enabled && param.default != null && param.type.kind === 'enum';\n}\n\nfunction phpLiteral(value: unknown): string {\n  if (typeof value === 'string') return `'${value}'`;\n  if (typeof value === 'number') return String(value);\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  return 'null';\n}\n\nfunction clientFieldExpression(field: string): string {\n  switch (field) {\n    case 'client_id':\n      return '$this->client->requireClientId()';\n    case 'client_secret':\n      return '$this->client->requireApiKey()';\n    default:\n      return `$this->client->${toCamelCase(field)}`;\n  }\n}\n\nfunction collectImports(\n  service: Service,\n  ctx: EmitterContext,\n  resolvedLookup?: Map<string, ResolvedOperation>,\n): string[] {\n  const imports = new Set<string>();\n  const ns = ctx.namespacePascal;\n\n  for (const op of service.operations) {\n    const plan = planOperation(op);\n    const resolved = resolvedLookup ? lookupResolved(op, resolvedLookup) : undefined;\n    if (plan.responseModelName && !plan.isPaginated && !isRedirectEndpoint(op, resolved)) {\n      imports.add(`${ns}\\\\Resource\\\\${className(plan.responseModelName)}`);\n    }\n    if (op.pagination?.itemType.kind === 'model') {\n      // Unwrap list wrapper models to import the inner item type\n      const itemModel = ctx.spec.models.find((m) => m.name === (op.pagination!.itemType as { name: string }).name);\n      let resolvedName = (op.pagination!.itemType as { name: string }).name;\n      if (itemModel && isListWrapperModel(itemModel)) {\n        const dataField = itemModel.fields.find((f) => f.name === 'data');\n        if (dataField?.type.kind === 'array' && dataField.type.items.kind === 'model') {\n          resolvedName = dataField.type.items.name;\n        }\n      }\n      imports.add(`${ns}\\\\Resource\\\\${className(resolvedName)}`);\n    }\n  }\n\n  return [...imports].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));\n}\n","import type { ApiSpec, Service, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { toPascalCase, toCamelCase } from '@workos/oagen';\nimport { className, servicePropertyName, buildExportedClassNameSet, resolveServiceTarget } from './naming.js';\nimport { getMountTarget } from '../shared/resolved-ops.js';\nimport { NON_SPEC_SERVICES } from '../shared/non-spec-services.js';\n\n/**\n * PHP-specific class-name overrides for non-spec services.\n * If a service id isn't listed here, PascalCase(id) is used.\n */\nconst PHP_NON_SPEC_CLASS_NAMES: Record<string, string> = {\n  webhook_verification: 'WebhookVerification',\n  session_manager: 'SessionManager',\n  pkce: 'PKCEHelper',\n};\n\n/** Derive PHP class name + property name from a non-spec service id. */\nfunction phpNonSpecAccessor(id: string): { className: string; propName: string } {\n  return {\n    className: PHP_NON_SPEC_CLASS_NAMES[id] ?? toPascalCase(id),\n    propName:\n      id === 'webhook_verification'\n        ? 'webhookVerification'\n        : id === 'session_manager'\n          ? 'sessionManager'\n          : toCamelCase(id),\n  };\n}\n\n/**\n * Generate the main PHP client class (service wiring only).\n *\n * Static infrastructure (HttpClient, PaginatedResponse, RequestOptions) is\n * now hand-maintained in the target SDK with @oagen-ignore-file.\n */\nexport function generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const ns = ctx.namespacePascal;\n  const dedupedServices = deduplicateByMount(spec.services, ctx);\n\n  return [\n    {\n      path: `lib/${ns}.php`,\n      content: generateMainClient(spec, dedupedServices, ctx),\n      overwriteExisting: true,\n    },\n  ];\n}\n\n/**\n * Build a map from IR service name to the client accessor property name.\n */\nexport function buildServiceAccessPaths(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of services) {\n    const target = getMountTarget(service, ctx);\n    map.set(service.name, servicePropertyName(target));\n    map.set(target, servicePropertyName(target));\n  }\n  return map;\n}\n\nfunction deduplicateByMount(services: Service[], ctx: EmitterContext): { name: string; propName: string }[] {\n  const seen = new Map<string, { name: string; propName: string }>();\n  const exportedClasses = buildExportedClassNameSet(ctx);\n  for (const service of services) {\n    const target = getMountTarget(service, ctx);\n    if (!seen.has(target)) {\n      seen.set(target, {\n        name: className(resolveServiceTarget(target, exportedClasses)),\n        propName: servicePropertyName(target),\n      });\n    }\n  }\n  return [...seen.values()];\n}\n\nfunction generateMainClient(\n  spec: ApiSpec,\n  services: { name: string; propName: string }[],\n  ctx: EmitterContext,\n): string {\n  const ns = ctx.namespacePascal;\n  const lines: string[] = [];\n\n  // No <?php here — the file header from fileHeader() provides it\n  lines.push(`namespace ${ns};`);\n  lines.push('');\n\n  // Use imports (sorted case-insensitively for PSR-12)\n  const nonSpecAccessors = NON_SPEC_SERVICES.map((s) => phpNonSpecAccessor(s.id));\n  const allImports: string[] = [];\n  for (const svc of services) {\n    allImports.push(`use ${ns}\\\\Service\\\\${svc.name};`);\n  }\n  allImports.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));\n  for (const imp of allImports) {\n    lines.push(imp);\n  }\n  lines.push('');\n\n  lines.push(`class ${ns}`);\n  lines.push('{');\n  lines.push('    private static ?string $apiKey = null;');\n  lines.push('    private static ?string $clientId = null;');\n  lines.push('    private ?HttpClient $httpClient = null;');\n  lines.push('');\n  lines.push('    public static function getApiKey(): ?string');\n  lines.push('    {');\n  lines.push('        return self::$apiKey;');\n  lines.push('    }');\n  lines.push('');\n  lines.push('    public static function setApiKey(?string $key): void');\n  lines.push('    {');\n  lines.push('        self::$apiKey = $key;');\n  lines.push('    }');\n  lines.push('');\n  lines.push('    public static function getClientId(): ?string');\n  lines.push('    {');\n  lines.push('        return self::$clientId;');\n  lines.push('    }');\n  lines.push('');\n  lines.push('    public static function setClientId(?string $id): void');\n  lines.push('    {');\n  lines.push('        self::$clientId = $id;');\n  lines.push('    }');\n\n  // Nullable resource properties\n  for (const svc of services) {\n    lines.push(`    private ?Service\\\\${svc.name} $${svc.propName} = null;`);\n  }\n  // Non-spec service properties — wrapped in ignore markers so the target\n  // SDK can hand-maintain the list. The emitter provides a positional anchor.\n  lines.push('    // @oagen-ignore-start — non-spec service properties (hand-maintained)');\n  for (const a of nonSpecAccessors) {\n    lines.push(`    private ?${a.className} $${a.propName} = null;`);\n  }\n  lines.push('    // @oagen-ignore-end');\n\n  lines.push('');\n  lines.push('    public function __construct(');\n  lines.push('        ?string $apiKey = null,');\n  lines.push('        ?string $clientId = null,');\n  lines.push(`        string $baseUrl = '${spec.baseUrl}',`);\n  lines.push('        int $timeout = 60,');\n  lines.push('        int $maxRetries = 3,');\n  lines.push('        ?\\\\GuzzleHttp\\\\HandlerStack $handler = null,');\n  lines.push('        ?string $userAgent = null,');\n  lines.push('    ) {');\n  lines.push(\"        $apiKey ??= getenv('WORKOS_API_KEY') ?: self::$apiKey ?? '';\");\n  lines.push(\"        $clientId ??= getenv('WORKOS_CLIENT_ID') ?: self::$clientId;\");\n  lines.push(\n    '        $this->httpClient = new HttpClient($apiKey, $clientId, $baseUrl, $timeout, $maxRetries, $handler, $userAgent);',\n  );\n  lines.push('    }');\n\n  // Resource accessors\n  for (const svc of services) {\n    lines.push('');\n    lines.push(`    public function ${svc.propName}(): ${svc.name}`);\n    lines.push('    {');\n    lines.push(`        return $this->${svc.propName} ??= new Service\\\\${svc.name}($this->httpClient);`);\n    lines.push('    }');\n  }\n\n  // Non-spec service accessors — wrapped in ignore markers so the target\n  // SDK can hand-maintain these. The emitter provides a positional anchor.\n  lines.push('');\n  lines.push('    // @oagen-ignore-start — non-spec service accessors (hand-maintained)');\n  for (const a of nonSpecAccessors) {\n    lines.push('');\n    lines.push(`    public function ${a.propName}(): ${a.className}`);\n    lines.push('    {');\n    lines.push(`        return $this->${a.propName} ??= new ${a.className}($this->httpClient);`);\n    lines.push('    }');\n  }\n  lines.push('    // @oagen-ignore-end');\n\n  lines.push('}');\n  return lines.join('\\n');\n}\n","import type { Model, TypeRef, Enum } from '@workos/oagen';\nimport { isListMetadataModel, isListWrapperModel } from './models.js';\nimport { collectNonPaginatedResponseModelNames, collectReferencedListMetadataModels } from '../shared/model-utils.js';\nimport { snakeName } from './naming.js';\n\n/**\n * Prefix mapping for generating realistic ID fixture values.\n */\nexport const ID_PREFIXES: Record<string, string> = {\n  Connection: 'conn_',\n  Organization: 'org_',\n  OrganizationMembership: 'om_',\n  User: 'user_',\n  Directory: 'directory_',\n  DirectoryGroup: 'dir_grp_',\n  DirectoryUser: 'dir_usr_',\n  Invitation: 'inv_',\n  Session: 'session_',\n  AuthenticationFactor: 'auth_factor_',\n  EmailVerification: 'email_verification_',\n  MagicAuth: 'magic_auth_',\n  PasswordReset: 'password_reset_',\n};\n\n/**\n * Generate JSON fixture files for test data.\n */\nexport function generateFixtures(spec: {\n  models: Model[];\n  enums: Enum[];\n  services: any[];\n}): { path: string; content: string }[] {\n  if (spec.models.length === 0) return [];\n\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n  const files: { path: string; content: string }[] = [];\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(spec.services);\n  const listMetadataNeeded = collectReferencedListMetadataModels(spec.models, nonPaginatedRefs);\n\n  for (const model of spec.models) {\n    if (isListMetadataModel(model) && !listMetadataNeeded.has(model.name)) continue;\n    if (isListWrapperModel(model)) continue;\n\n    const fixture = generateModelFixture(model, modelMap, enumMap);\n\n    files.push({\n      path: `tests/Fixtures/${snakeName(model.name)}.json`,\n      content: JSON.stringify(fixture, null, 2),\n    });\n  }\n\n  // Generate list fixtures for paginated responses\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      if (op.pagination) {\n        let itemModel = op.pagination.itemType.kind === 'model' ? modelMap.get(op.pagination.itemType.name) : null;\n        if (itemModel) {\n          const unwrapped = unwrapListModel(itemModel, modelMap);\n          if (unwrapped) itemModel = unwrapped;\n          if (itemModel.fields.length === 0) continue;\n          const fixture = generateModelFixture(itemModel, modelMap, enumMap);\n          const listFixture = {\n            data: [fixture],\n            list_metadata: {\n              before: null,\n              after: null,\n            },\n          };\n          files.push({\n            path: `tests/Fixtures/list_${snakeName(itemModel.name)}.json`,\n            content: JSON.stringify(listFixture, null, 2),\n          });\n        }\n      }\n    }\n  }\n\n  return files;\n}\n\nexport function unwrapListModel(model: Model, modelMap: Map<string, Model>): Model | null {\n  const dataField = model.fields.find((f) => f.name === 'data');\n  const hasListMetadata = model.fields.some((f) => f.name === 'list_metadata' || f.name === 'listMetadata');\n  if (dataField && hasListMetadata && dataField.type.kind === 'array') {\n    const itemType = dataField.type.items;\n    if (itemType.kind === 'model') {\n      return modelMap.get(itemType.name) ?? null;\n    }\n  }\n  return null;\n}\n\nexport function generateModelFixture(\n  model: Model,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): Record<string, any> {\n  const fixture: Record<string, any> = {};\n\n  for (const field of model.fields) {\n    const wireName = field.name;\n    if (field.example !== undefined) {\n      fixture[wireName] = field.example;\n    } else {\n      fixture[wireName] = generateFieldValue(field.type, field.name, model.name, modelMap, enumMap);\n    }\n  }\n\n  return fixture;\n}\n\nfunction generateFieldValue(\n  ref: TypeRef,\n  fieldName: string,\n  modelName: string,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): any {\n  switch (ref.kind) {\n    case 'primitive':\n      return generatePrimitiveValue(ref.type, ref.format, fieldName, modelName);\n    case 'literal':\n      return ref.value;\n    case 'enum': {\n      const e = enumMap.get(ref.name);\n      return e?.values[0]?.value ?? 'unknown';\n    }\n    case 'model': {\n      const nested = modelMap.get(ref.name);\n      if (nested) return generateModelFixture(nested, modelMap, enumMap);\n      return {};\n    }\n    case 'array': {\n      if (ref.items.kind === 'enum') {\n        const e = enumMap.get(ref.items.name);\n        if (e && e.values.length > 0) {\n          return e.values.map((v) => v.value);\n        }\n      }\n      const item = generateFieldValue(ref.items, fieldName, modelName, modelMap, enumMap);\n      return [item];\n    }\n    case 'nullable':\n      return generateFieldValue(ref.inner, fieldName, modelName, modelMap, enumMap);\n    case 'union':\n      if (ref.variants.length > 0) {\n        return generateFieldValue(ref.variants[0], fieldName, modelName, modelMap, enumMap);\n      }\n      return null;\n    case 'map':\n      return {\n        key: generateFieldValue(ref.valueType, 'value', modelName, modelMap, enumMap),\n      };\n  }\n}\n\nfunction generatePrimitiveValue(type: string, format: string | undefined, name: string, modelName: string): any {\n  switch (type) {\n    case 'string':\n      if (format === 'date-time') return '2023-01-01T00:00:00.000Z';\n      if (format === 'date') return '2023-01-01';\n      if (format === 'uuid') return '00000000-0000-0000-0000-000000000000';\n      if (name === 'id') {\n        const prefix = ID_PREFIXES[modelName] ?? '';\n        return `${prefix}01234`;\n      }\n      if (name.includes('id')) return `${name}_01234`;\n      if (name.includes('email')) return 'test@example.com';\n      if (name.includes('url') || name.includes('uri')) return 'https://example.com';\n      if (name.includes('name')) return 'Test';\n      return `test_${name}`;\n    case 'integer':\n      return 1;\n    case 'number':\n      return 1.0;\n    case 'boolean':\n      return true;\n    case 'unknown':\n      return {};\n    default:\n      return null;\n  }\n}\n","import type {\n  ApiSpec,\n  Service,\n  Operation,\n  EmitterContext,\n  GeneratedFile,\n  Model,\n  ResolvedOperation,\n} from '@workos/oagen';\nimport { planOperation, toCamelCase, toPascalCase } from '@workos/oagen';\nimport {\n  className,\n  enumClassName,\n  resolveMethodName,\n  snakeName,\n  servicePropertyName,\n  domainFieldName,\n} from './naming.js';\nimport { isListWrapperModel } from './models.js';\nimport { generateFixtures } from './fixtures.js';\nimport {\n  getMountTarget,\n  scopedMountGroups,\n  buildHiddenParams,\n  getOpDefaults,\n  getOpInferFromClient,\n  collectGroupedParamNames,\n} from '../shared/resolved-ops.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { isRedirectEndpoint, deriveVariantFieldName } from './resources.js';\n\n/**\n * Generate PHPUnit test files and fixture JSON files.\n */\nexport function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  // TestHelper is now hand-maintained in the target SDK (@oagen-ignore-file).\n\n  // Collect all operations per mount target using resolved per-operation mounts.\n  // This correctly handles operationHint mountOn overrides (e.g., audit_logs_retention → AuditLogs).\n  // In a scoped (`--services`) run this returns only the selected post-mount\n  // services so we emit per-service test files for those alone. ClientTest.php\n  // and fixtures below are built from `spec` and stay full.\n  const mountGroupsFromResolved = scopedMountGroups(ctx);\n  const mountGroups = new Map<string, { op: Operation; service: Service; resolvedOp?: ResolvedOperation }[]>();\n  if (mountGroupsFromResolved.size > 0 || ctx.scopedServices?.size) {\n    for (const [target, group] of mountGroupsFromResolved) {\n      mountGroups.set(\n        target,\n        group.resolvedOps.map((r) => ({ op: r.operation, service: r.service, resolvedOp: r })),\n      );\n    }\n  } else {\n    // Fallback: group by service\n    for (const service of spec.services) {\n      const target = getMountTarget(service, ctx);\n      if (!mountGroups.has(target)) mountGroups.set(target, []);\n      for (const op of service.operations) {\n        mountGroups.get(target)!.push({ op, service });\n      }\n    }\n  }\n\n  // Generate resource tests (one per mount target, all operations included)\n  // Use overwriteExisting so the integration step always writes the latest\n  // test content rather than attempting additive AST merge.\n  for (const [target, ops] of mountGroups) {\n    files.push({\n      path: `tests/Service/${className(target)}Test.php`,\n      content: generateMountGroupTest(target, ops, ctx),\n      overwriteExisting: true,\n    });\n  }\n\n  // Generate client test\n  files.push({\n    path: 'tests/ClientTest.php',\n    content: generateClientTest(ctx),\n    overwriteExisting: true,\n  });\n\n  // Generate fixture JSON files\n  const fixtures = generateFixtures(spec);\n  for (const fixture of fixtures) {\n    files.push({\n      path: fixture.path,\n      content: fixture.content,\n      headerPlacement: 'skip',\n    });\n  }\n\n  return files;\n}\n\nfunction generateMountGroupTest(\n  target: string,\n  ops: { op: Operation; service: Service; resolvedOp?: ResolvedOperation }[],\n  ctx: EmitterContext,\n): string {\n  const ns = ctx.namespacePascal;\n  const name = className(target);\n  const accessor = servicePropertyName(target);\n  const lines: string[] = [];\n\n  // No <?php here — the file header from fileHeader() provides it\n  lines.push('namespace Tests\\\\Service;');\n  lines.push('');\n  lines.push('use PHPUnit\\\\Framework\\\\TestCase;');\n  lines.push('use WorkOS\\\\TestHelper;');\n  lines.push('');\n  lines.push(`class ${name}Test extends TestCase`);\n  lines.push('{');\n  lines.push('    use TestHelper;');\n\n  // Track emitted test names to avoid duplicates\n  const emitted = new Set<string>();\n\n  // Generate tests for all operations across all services in the mount group.\n  // Uses the hand-maintained TestHelper API:\n  //   - loadFixture(name) appends .json automatically\n  //   - createMockClient([['status' => N, 'body' => [...]]]) wraps into Response\n  for (const { op, service, resolvedOp } of ops) {\n    // Skip base method when wrappers exist (matches resources.ts)\n    if (resolvedOp?.wrappers && resolvedOp.wrappers.length > 0) continue;\n\n    const plan = planOperation(op);\n    const method = resolveMethodName(op, service, ctx);\n    const testName = `test${method.charAt(0).toUpperCase()}${method.slice(1)}`;\n    const hidden = buildHiddenParams(resolvedOp);\n\n    if (emitted.has(testName)) continue;\n    emitted.add(testName);\n\n    lines.push('');\n    lines.push(`    public function ${testName}(): void`);\n    lines.push('    {');\n\n    const expectedPath = buildExpectedPath(op, ctx);\n\n    if (plan.isDelete) {\n      lines.push(\"        $client = $this->createMockClient([['status' => 204]]);\");\n      lines.push(`        $client->${accessor}()->${method}(${buildTestArgs(op, ctx, { hidden })});`);\n      // Request assertions\n      lines.push('        $request = $this->getLastRequest();');\n      lines.push(\"        $this->assertSame('DELETE', $request->getMethod());\");\n      lines.push(`        $this->assertStringEndsWith('${expectedPath}', $request->getUri()->getPath());`);\n      // Body assertions for DELETE-with-body\n      if (plan.hasBody && op.requestBody?.kind === 'model') {\n        emitBodyAssertions(lines, op, ctx, hidden);\n      }\n    } else if (plan.isPaginated && op.pagination?.itemType.kind === 'model') {\n      const fixtureName = `list_${resolveFixtureModelName(op.pagination.itemType.name, ctx)}`;\n      // Pass all params (including optional enums) to verify serialization\n      lines.push(`        $fixture = $this->loadFixture('${fixtureName}');`);\n      lines.push(\"        $client = $this->createMockClient([['status' => 200, 'body' => $fixture]]);\");\n      lines.push(\n        `        $result = $client->${accessor}()->${method}(${buildTestArgs(op, ctx, { includeOptional: true, hidden })});`,\n      );\n      lines.push(`        $this->assertInstanceOf(\\\\${ns}\\\\PaginatedResponse::class, $result);`);\n      // Request assertions\n      lines.push('        $request = $this->getLastRequest();');\n      lines.push(`        $this->assertSame('${op.httpMethod.toUpperCase()}', $request->getMethod());`);\n      lines.push(`        $this->assertStringEndsWith('${expectedPath}', $request->getUri()->getPath());`);\n      // Query string serialization assertions\n      emitQueryAssertions(lines, op, ctx, hidden);\n    } else if (isRedirectEndpoint(op, resolvedOp)) {\n      // Redirect endpoint: URL is built locally, no HTTP request made.\n      // Pass all params (including optional) to verify they appear in the URL.\n      lines.push('        $client = $this->createMockClient([]);');\n      lines.push(\n        `        $result = $client->${accessor}()->${method}(${buildTestArgs(op, ctx, { includeOptional: true, hidden })});`,\n      );\n      lines.push('        $this->assertIsString($result);');\n      lines.push(`        $this->assertStringContainsString('${expectedPath}', $result);`);\n      // Query param assertions for the generated URL\n      emitRedirectQueryAssertions(lines, op, ctx, hidden, resolvedOp);\n    } else if (plan.responseModelName) {\n      const modelName = className(plan.responseModelName);\n      const fixtureName = `${snakeName(plan.responseModelName)}`;\n      lines.push(`        $fixture = $this->loadFixture('${fixtureName}');`);\n      if (op.response.kind === 'array') {\n        lines.push(\"        $client = $this->createMockClient([['status' => 200, 'body' => [$fixture]]]);\");\n      } else {\n        lines.push(\"        $client = $this->createMockClient([['status' => 200, 'body' => $fixture]]);\");\n      }\n      lines.push(`        $result = $client->${accessor}()->${method}(${buildTestArgs(op, ctx, { hidden })});`);\n      if (op.response.kind === 'array') {\n        lines.push('        $this->assertIsArray($result);');\n        lines.push(`        $this->assertInstanceOf(\\\\${ns}\\\\Resource\\\\${modelName}::class, $result[0]);`);\n        emitFieldHydrationAssertions(lines, plan.responseModelName, '$result[0]', '$fixture', ctx);\n        // Round-trip: fromArray -> toArray must not throw\n        lines.push('        $this->assertIsArray($result[0]->toArray());');\n      } else {\n        lines.push(`        $this->assertInstanceOf(\\\\${ns}\\\\Resource\\\\${modelName}::class, $result);`);\n        emitFieldHydrationAssertions(lines, plan.responseModelName, '$result', '$fixture', ctx);\n        // Round-trip: fromArray -> toArray must not throw\n        lines.push('        $this->assertIsArray($result->toArray());');\n      }\n      // Request assertions\n      lines.push('        $request = $this->getLastRequest();');\n      lines.push(`        $this->assertSame('${op.httpMethod.toUpperCase()}', $request->getMethod());`);\n      lines.push(`        $this->assertStringEndsWith('${expectedPath}', $request->getUri()->getPath());`);\n      // Body assertions for POST/PUT/PATCH\n      if (plan.hasBody && ['post', 'put', 'patch'].includes(op.httpMethod.toLowerCase())) {\n        emitBodyAssertions(lines, op, ctx, hidden);\n      }\n    } else {\n      lines.push(\"        $client = $this->createMockClient([['status' => 200, 'body' => []]]);\");\n      lines.push(`        $client->${accessor}()->${method}(${buildTestArgs(op, ctx, { hidden })});`);\n      // Request assertions\n      lines.push('        $request = $this->getLastRequest();');\n      lines.push(`        $this->assertSame('${op.httpMethod.toUpperCase()}', $request->getMethod());`);\n      lines.push(`        $this->assertStringEndsWith('${expectedPath}', $request->getUri()->getPath());`);\n    }\n\n    lines.push('    }');\n  }\n\n  // Generate tests for wrapper methods (union split operations)\n  for (const resolved of ctx.resolvedOperations ?? []) {\n    if (resolved.mountOn !== target) continue;\n    for (const wrapper of resolved.wrappers ?? []) {\n      const method = toCamelCase(wrapper.name);\n      const testName = `test${method.charAt(0).toUpperCase()}${method.slice(1)}`;\n\n      if (emitted.has(testName)) continue;\n      emitted.add(testName);\n\n      const op = resolved.operation;\n      const responseModel = op.response.kind === 'model' ? op.response.name : null;\n\n      lines.push('');\n      lines.push(`    public function ${testName}(): void`);\n      lines.push('    {');\n\n      // Build required args for wrapper methods\n      const wrapperArgs = buildWrapperTestArgs(wrapper, ctx);\n\n      if (responseModel) {\n        const modelName = className(responseModel);\n        const fixtureName = `${snakeName(responseModel)}`;\n        lines.push(`        $fixture = $this->loadFixture('${fixtureName}');`);\n        lines.push(\"        $client = $this->createMockClient([['status' => 200, 'body' => $fixture]]);\");\n        lines.push(`        $result = $client->${accessor}()->${method}(${wrapperArgs});`);\n        lines.push(`        $this->assertInstanceOf(\\\\${ns}\\\\Resource\\\\${modelName}::class, $result);`);\n      } else {\n        lines.push(\"        $client = $this->createMockClient([['status' => 200, 'body' => []]]);\");\n        lines.push(`        $client->${accessor}()->${method}(${wrapperArgs});`);\n        lines.push('        $this->assertTrue(true);');\n      }\n\n      lines.push('    }');\n    }\n  }\n\n  // Pagination boundary test: verify iteration works when before/after cursors are null\n  const firstPaginatedOp = ops.find(({ op }) => {\n    const p = planOperation(op);\n    return p.isPaginated && op.pagination?.itemType.kind === 'model';\n  });\n  if (firstPaginatedOp) {\n    const testName = 'testPaginationBoundary';\n    if (!emitted.has(testName)) {\n      emitted.add(testName);\n      const op = firstPaginatedOp.op;\n      const paginatedHidden = buildHiddenParams(firstPaginatedOp.resolvedOp);\n      const itemType = op.pagination!.itemType as { name: string };\n      const fixtureName = `list_${resolveFixtureModelName(itemType.name, ctx)}`;\n      const method = resolveMethodName(op, firstPaginatedOp.service, ctx);\n\n      lines.push('');\n      lines.push(`    public function ${testName}(): void`);\n      lines.push('    {');\n      lines.push(`        $fixture = $this->loadFixture('${fixtureName}');`);\n      lines.push('        // Ensure cursors are null (first/last page boundary)');\n      lines.push(\"        $fixture['list_metadata']['before'] = null;\");\n      lines.push(\"        $fixture['list_metadata']['after'] = null;\");\n      lines.push(\"        $client = $this->createMockClient([['status' => 200, 'body' => $fixture]]);\");\n      lines.push(\n        `        $result = $client->${accessor}()->${method}(${buildTestArgs(op, ctx, { hidden: paginatedHidden })});`,\n      );\n      lines.push(`        $this->assertInstanceOf(\\\\${ns}\\\\PaginatedResponse::class, $result);`);\n      lines.push('        // Verify cursors are null on boundary page');\n      lines.push(\"        $this->assertNull($result->listMetadata['before']);\");\n      lines.push(\"        $this->assertNull($result->listMetadata['after']);\");\n      lines.push('        // Iterating should not throw on null cursors');\n      lines.push('        foreach ($result as $item) {');\n      lines.push('            $this->assertNotNull($item);');\n      lines.push('            break;');\n      lines.push('        }');\n      lines.push('    }');\n    }\n  }\n\n  lines.push('}');\n  return lines.join('\\n');\n}\n\nfunction generateClientTest(ctx: EmitterContext): string {\n  const ns = ctx.namespacePascal;\n  const lines: string[] = [];\n\n  // No <?php here — the file header from fileHeader() provides it\n  lines.push('namespace Tests;');\n  lines.push('');\n  lines.push('use PHPUnit\\\\Framework\\\\TestCase;');\n  lines.push(`use ${ns}\\\\${ns};`);\n  lines.push('');\n  lines.push('class ClientTest extends TestCase');\n  lines.push('{');\n  lines.push('    public function testConstructor(): void');\n  lines.push('    {');\n  lines.push(`        $client = new ${ns}(apiKey: 'test-key');`);\n  lines.push('        $this->assertNotNull($client);');\n  lines.push('    }');\n  lines.push('}');\n\n  return lines.join('\\n');\n}\n\nfunction buildTestArgs(\n  op: Operation,\n  ctx: EmitterContext,\n  opts?: { includeOptional?: boolean; hidden?: Set<string> },\n): string {\n  const includeOptional = opts?.includeOptional ?? false;\n  const hidden = opts?.hidden ?? new Set<string>();\n  const args: string[] = [];\n  const usedNames = new Set<string>();\n\n  // Path params (use enum values for enum-typed path params)\n  for (const p of op.pathParams) {\n    if (p.type.kind === 'enum' || p.type.kind === 'model') {\n      args.push(generateTestValue(p.type, ctx));\n    } else {\n      args.push(`'test_${p.name}'`);\n    }\n    usedNames.add(toCamelCase(p.name));\n  }\n\n  // Required body fields\n  if (op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => m.name === (op.requestBody as { name: string }).name);\n    if (bodyModel) {\n      const pathParamNames = new Set(op.pathParams.map((p) => toCamelCase(p.name)));\n      for (const f of bodyModel.fields) {\n        if (hidden.has(f.name)) continue;\n        if (!f.required && !includeOptional) continue;\n        let phpName = toCamelCase(f.name);\n        if (pathParamNames.has(phpName)) {\n          phpName = `body${phpName.charAt(0).toUpperCase()}${phpName.slice(1)}`;\n        }\n        if (usedNames.has(phpName)) continue;\n        usedNames.add(phpName);\n        args.push(`${phpName}: ${generateTestValue(f.type, ctx)}`);\n      }\n    }\n  }\n\n  // Parameter group args (union-typed) — emit first variant constructor\n  const groupedParamNames = collectGroupedParamNames(op);\n  for (const group of op.parameterGroups ?? []) {\n    if (!group.optional || includeOptional) {\n      const variant = group.variants[0];\n      const variantClass = `${className(group.name)}${className(variant.name)}`;\n      const variantArgs = variant.parameters\n        .map((p) => `${deriveVariantFieldName(p.name, group.name)}: 'test_value'`)\n        .join(', ');\n      args.push(`${toCamelCase(group.name)}: new \\\\${ctx.namespacePascal}\\\\Service\\\\${variantClass}(${variantArgs})`);\n    }\n  }\n\n  // Query params (skip grouped params — they're handled above)\n  for (const q of op.queryParams) {\n    if (hidden.has(q.name)) continue;\n    if (groupedParamNames.has(q.name)) continue;\n    if (!q.required && !includeOptional) continue;\n    const phpName = toCamelCase(q.name);\n    if (usedNames.has(phpName)) continue;\n    usedNames.add(phpName);\n    args.push(`${phpName}: ${generateTestValue(q.type, ctx)}`);\n  }\n\n  return args.join(', ');\n}\n\nfunction generateTestValue(\n  ref: { kind: string; type?: string; name?: string; format?: string },\n  ctx?: EmitterContext,\n): string {\n  switch (ref.kind) {\n    case 'primitive':\n      if (ref.format === 'date-time') {\n        return \"new \\\\DateTimeImmutable('2023-01-01T00:00:00Z')\";\n      }\n      switch (ref.type) {\n        case 'string':\n          return \"'test_value'\";\n        case 'integer':\n          return '1';\n        case 'number':\n          return '1.0';\n        case 'boolean':\n          return 'true';\n        default:\n          return \"'test_value'\";\n      }\n    case 'enum': {\n      // Use the first enum value so PHP type-checking passes\n      if (ctx && ref.name) {\n        const e = ctx.spec.enums.find((en) => en.name === ref.name);\n        if (e && e.values.length > 0) {\n          const enumClass = enumClassName(ref.name);\n          // Must match the case-name logic in enums.ts\n          const caseName = toPascalCase(String(e.values[0].name).toLowerCase());\n          return `\\\\WorkOS\\\\Resource\\\\${enumClass}::${caseName}`;\n        }\n      }\n      return \"'test_value'\";\n    }\n    case 'array':\n      return '[]';\n    case 'map':\n      return '[]';\n    case 'nullable':\n      return generateTestValue(\n        (ref as unknown as { inner: { kind: string; type?: string; name?: string } }).inner,\n        ctx,\n      );\n    case 'model': {\n      if (ref.name) {\n        const modelClass = className(ref.name);\n        const fixtureName = snakeName(ref.name);\n        return `\\\\WorkOS\\\\Resource\\\\${modelClass}::fromArray($this->loadFixture('${fixtureName}'))`;\n      }\n      return '[]';\n    }\n    default:\n      return \"'test_value'\";\n  }\n}\n\n/**\n * Build test arguments for wrapper method calls, providing values for required exposed params.\n */\nfunction buildWrapperTestArgs(wrapper: import('@workos/oagen').ResolvedWrapper, ctx: EmitterContext): string {\n  const params = resolveWrapperParams(wrapper, ctx);\n  const args: string[] = [];\n  for (const { paramName, field, isOptional } of params) {\n    if (isOptional) continue;\n    const phpName = toCamelCase(paramName);\n    const value = field ? generateTestValue(field.type, ctx) : \"'test_value'\";\n    args.push(`${phpName}: ${value}`);\n  }\n  return args.join(', ');\n}\n\n/**\n * Resolve the fixture model name, unwrapping list wrapper models to match\n * the fixture generator's naming (which unwraps before naming).\n */\nfunction resolveFixtureModelName(modelName: string, ctx: EmitterContext): string {\n  const model = ctx.spec.models.find((m: Model) => m.name === modelName);\n  if (model && isListWrapperModel(model)) {\n    const dataField = model.fields.find((f) => f.name === 'data');\n    if (dataField?.type.kind === 'array' && dataField.type.items.kind === 'model') {\n      return snakeName(dataField.type.items.name);\n    }\n  }\n  return snakeName(modelName);\n}\n\n/**\n * Build the expected URL path for an operation, substituting test values for path params.\n */\nfunction buildExpectedPath(op: Operation, ctx: EmitterContext): string {\n  let path = op.path.replace(/^\\//, '');\n  for (const p of op.pathParams) {\n    if (p.type.kind === 'enum' && (p.type as { name: string }).name) {\n      // Use the actual first enum backing value for the path\n      const e = ctx.spec.enums.find((en) => en.name === (p.type as { name: string }).name);\n      const firstValue = e?.values[0]?.value;\n      path = path.replace(`{${p.name}}`, firstValue != null ? String(firstValue) : `test_${p.name}`);\n    } else {\n      path = path.replace(`{${p.name}}`, `test_${p.name}`);\n    }\n  }\n  return path;\n}\n\n/**\n * Emit field hydration assertions: verify that deserialized model fields\n * match the fixture data. Checks up to 2 primitive string fields (id + one more).\n */\nfunction emitFieldHydrationAssertions(\n  lines: string[],\n  modelName: string,\n  resultVar: string,\n  fixtureVar: string,\n  ctx: EmitterContext,\n): void {\n  const model = ctx.spec.models.find((m) => m.name === modelName);\n  if (!model) return;\n\n  // Pick required primitive string fields for assertion (id first, then others)\n  const candidates = model.fields.filter(\n    (f) => f.required && f.type.kind === 'primitive' && f.type.type === 'string' && !f.type.format,\n  );\n  const idField = candidates.find((f) => f.name === 'id');\n  const others = candidates.filter((f) => f.name !== 'id');\n  const assertFields = [idField, others[0]].filter(Boolean);\n\n  for (const f of assertFields) {\n    if (!f) continue;\n    // DOMAIN identifier: the deserialized model's PHP property (honors `domainName`).\n    // The fixture key `f.name` is the WIRE key and stays unchanged.\n    const phpProp = domainFieldName(f);\n    lines.push(`        $this->assertSame(${fixtureVar}['${f.name}'], ${resultVar}->${phpProp});`);\n  }\n}\n\n/**\n * Emit query string assertions for list operations.\n * Asserts that all query params (including optional enums) are serialized correctly.\n */\nfunction emitQueryAssertions(lines: string[], op: Operation, ctx: EmitterContext, hidden?: Set<string>): void {\n  if (op.queryParams.length === 0) return;\n  const groupedParams = collectGroupedParamNames(op);\n  lines.push('        parse_str($request->getUri()->getQuery(), $query);');\n  // Assert first variant's params from parameter groups\n  for (const group of op.parameterGroups ?? []) {\n    const variant = group.variants[0];\n    for (const param of variant.parameters) {\n      lines.push(`        $this->assertSame('test_value', $query['${param.name}']);`);\n    }\n  }\n  for (const q of op.queryParams) {\n    if (hidden?.has(q.name)) continue;\n    if (groupedParams.has(q.name)) continue;\n    const innerType =\n      q.type.kind === 'nullable' ? (q.type as { inner: { kind: string; type?: string; name?: string } }).inner : q.type;\n    if (innerType.kind === 'enum' && innerType.name) {\n      // Assert enum is serialized as its backing value, not the enum instance\n      const e = ctx.spec.enums.find((en) => en.name === innerType.name);\n      if (e && e.values.length > 0) {\n        lines.push(`        $this->assertSame('${e.values[0].value}', $query['${q.name}']);`);\n      }\n    } else if (innerType.kind === 'primitive') {\n      if ((innerType as { format?: string }).format === 'date-time') {\n        lines.push(`        $this->assertArrayHasKey('${q.name}', $query);`);\n      } else {\n        switch (innerType.type) {\n          case 'string':\n            lines.push(`        $this->assertSame('test_value', $query['${q.name}']);`);\n            break;\n          case 'integer':\n          case 'number':\n            lines.push(`        $this->assertArrayHasKey('${q.name}', $query);`);\n            break;\n          case 'boolean':\n            lines.push(`        $this->assertArrayHasKey('${q.name}', $query);`);\n            break;\n        }\n      }\n    }\n  }\n}\n\n/**\n * Emit query param assertions for redirect endpoint URLs.\n * Parses the query string from the built URL and asserts visible params,\n * hidden defaults (e.g., response_type), and inferred client fields (e.g., client_id).\n */\nfunction emitRedirectQueryAssertions(\n  lines: string[],\n  op: Operation,\n  ctx: EmitterContext,\n  hidden: Set<string>,\n  resolvedOp?: ResolvedOperation,\n): void {\n  const hasVisibleQueryParams = op.queryParams.some((q) => !hidden.has(q.name));\n  const defaults = getOpDefaults(resolvedOp);\n  const inferred = getOpInferFromClient(resolvedOp);\n  if (!hasVisibleQueryParams && Object.keys(defaults).length === 0 && inferred.length === 0) return;\n\n  lines.push(\"        parse_str(parse_url($result, PHP_URL_QUERY) ?? '', $query);\");\n\n  // Assert visible query params (same logic as emitQueryAssertions but reading from $query parsed from URL)\n  for (const q of op.queryParams) {\n    if (hidden.has(q.name)) continue;\n    const innerType =\n      q.type.kind === 'nullable' ? (q.type as { inner: { kind: string; type?: string; name?: string } }).inner : q.type;\n    if (innerType.kind === 'enum' && innerType.name) {\n      const e = ctx.spec.enums.find((en) => en.name === innerType.name);\n      if (e && e.values.length > 0) {\n        lines.push(`        $this->assertSame('${e.values[0].value}', $query['${q.name}']);`);\n      }\n    } else if (innerType.kind === 'primitive') {\n      switch (innerType.type) {\n        case 'string':\n          lines.push(`        $this->assertSame('test_value', $query['${q.name}']);`);\n          break;\n        case 'integer':\n        case 'number':\n        case 'boolean':\n          lines.push(`        $this->assertArrayHasKey('${q.name}', $query);`);\n          break;\n      }\n    }\n  }\n\n  // Assert hidden defaults (e.g., response_type => 'code')\n  for (const [key, value] of Object.entries(defaults)) {\n    lines.push(`        $this->assertSame('${value}', $query['${key}']);`);\n  }\n\n  // Assert inferred client fields are present (e.g., client_id)\n  for (const key of inferred) {\n    lines.push(`        $this->assertArrayHasKey('${key}', $query);`);\n  }\n}\n\n/**\n * Emit body field assertions for POST/PUT/PATCH operations.\n * Only asserts primitive required fields (strings, numbers, booleans).\n */\nfunction emitBodyAssertions(lines: string[], op: Operation, ctx: EmitterContext, hidden?: Set<string>): void {\n  if (op.requestBody?.kind !== 'model') return;\n  const bodyModel = ctx.spec.models.find((m) => m.name === (op.requestBody as { name: string }).name);\n  if (!bodyModel) return;\n  // Skip fields that collide with path param names (they get deduped in the resource)\n  const pathParamNames = new Set(op.pathParams.map((p) => p.name));\n  const primitiveRequired = bodyModel.fields.filter(\n    (f) =>\n      f.required &&\n      (f.type.kind === 'primitive' || f.type.kind === 'literal') &&\n      !pathParamNames.has(f.name) &&\n      !hidden?.has(f.name),\n  );\n  if (primitiveRequired.length === 0) return;\n\n  lines.push('        $body = json_decode((string) $request->getBody(), true);');\n  for (const f of primitiveRequired) {\n    if (f.type.kind === 'primitive' && f.type.type === 'string') {\n      lines.push(`        $this->assertSame('test_value', $body['${f.name}']);`);\n    } else if (f.type.kind === 'primitive' && f.type.type === 'integer') {\n      lines.push(`        $this->assertSame(1, $body['${f.name}']);`);\n    } else if (f.type.kind === 'primitive' && f.type.type === 'boolean') {\n      lines.push(`        $this->assertTrue($body['${f.name}']);`);\n    } else {\n      lines.push(`        $this->assertArrayHasKey('${f.name}', $body);`);\n    }\n  }\n}\n","import type { ApiSpec, EmitterContext, OperationsMap } from '@workos/oagen';\nimport { resolveMethodName } from './naming.js';\nimport { buildServiceAccessPaths } from './client.js';\nimport { buildResolvedLookup, lookupResolved, getMountTarget } from '../shared/resolved-ops.js';\n\n/**\n * Build operation-to-SDK-method mapping for the manifest.\n */\nexport function buildOperationsMap(spec: ApiSpec, ctx: EmitterContext): OperationsMap {\n  const manifest: OperationsMap = {};\n  const accessPaths = buildServiceAccessPaths(spec.services, ctx);\n  const resolvedLookup = buildResolvedLookup(ctx);\n\n  for (const service of spec.services) {\n    let serviceProp = accessPaths.get(service.name);\n    if (!serviceProp) {\n      const mountTarget = getMountTarget(service, ctx);\n      serviceProp = accessPaths.get(mountTarget);\n    }\n    if (!serviceProp) {\n      throw new Error(`Missing public client access path for service ${service.name}`);\n    }\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const method = resolveMethodName(op, service, ctx);\n\n      // Use per-operation mountOn when it differs from the service default\n      const resolved = lookupResolved(op, resolvedLookup);\n      const propName = (resolved && accessPaths.get(resolved.mountOn)) ?? serviceProp;\n\n      manifest[httpKey] = { sdkMethod: method, service: propName };\n    }\n  }\n\n  return manifest;\n}\n","import type {\n  Emitter,\n  EmitterContext,\n  FormatCommand,\n  GeneratedFile,\n  ApiSpec,\n  Model,\n  Enum,\n  Service,\n} from '@workos/oagen';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { generateModels } from './models.js';\nimport { generateEnums } from './enums.js';\nimport { generateResources } from './resources.js';\nimport { generateClient } from './client.js';\nimport { generateTests } from './tests.js';\nimport { buildOperationsMap } from './manifest.js';\nimport { initializeEnumDedup } from './naming.js';\nimport { enrichModelsFromSpec, getSyntheticEnums } from '../shared/model-utils.js';\nimport { AUTOGEN_NOTICE } from '../shared/file-header.js';\n\n/** Initialize enum deduplication from spec data. */\nfunction ensureNamingInitialized(ctx: EmitterContext): void {\n  initializeEnumDedup(ctx.spec.enums);\n}\n\n/** Ensure every generated file's content ends with a trailing newline. */\nfunction ensureTrailingNewlines(files: GeneratedFile[]): GeneratedFile[] {\n  for (const f of files) {\n    if (f.content && !f.content.endsWith('\\n')) {\n      f.content += '\\n';\n    }\n  }\n  return files;\n}\n\n/**\n * Flatten oneOf / allOf+oneOf variant fields onto each base model and pull\n * in synthetic models / enums for inline variant shapes. PHP emits flat\n * classes (no sum types), so a discriminated base whose IR fields the\n * parser stripped (post-allOf-aware detection) gets its original fields\n * restored to avoid silently dropping variant data.\n *\n * `enums` is forwarded to seed `enrichModelsFromSpec`'s collision set: an\n * inline oneOf enum whose synthetic name (`Parent_field`) snake-collapses\n * onto an existing IR enum (e.g. `DataIntegrationAccessTokenResponse_error`\n * vs `DataIntegrationAccessTokenResponseError`) must NOT spawn a duplicate\n * synthetic. Otherwise both collapse to the same `lib/Resource/X.php` path\n * and the later writer wins by array order — which differs between a full\n * and a scoped (`--services`) run, producing a non-deterministic case order.\n */\nfunction enrichModelsForPhp(models: Model[], enums: Enum[]): Model[] {\n  const enriched = enrichModelsFromSpec(models, enums);\n  const originalByName = new Map(models.map((m) => [m.name, m]));\n  return enriched.map((m) => {\n    if ((m as { discriminator?: unknown }).discriminator && m.fields.length === 0) {\n      const original = originalByName.get(m.name);\n      if (original && original.fields.length > 0) {\n        return { ...m, fields: original.fields };\n      }\n    }\n    return m;\n  });\n}\n\nexport const phpEmitter: Emitter = {\n  language: 'php',\n\n  generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n    ensureNamingInitialized(ctx);\n    return ensureTrailingNewlines(generateModels(enrichModelsForPhp(models, ctx.spec.enums), ctx));\n  },\n\n  generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n    ensureNamingInitialized(ctx);\n    const syntheticEnums = getSyntheticEnums();\n    return ensureTrailingNewlines(generateEnums([...enums, ...syntheticEnums], ctx));\n  },\n\n  generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n    ensureNamingInitialized(ctx);\n    return ensureTrailingNewlines(generateResources(services, ctx));\n  },\n\n  generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    ensureNamingInitialized(ctx);\n    return ensureTrailingNewlines(generateClient(spec, ctx));\n  },\n\n  generateErrors(): GeneratedFile[] {\n    return [];\n  },\n\n  generateTypeSignatures(_spec: ApiSpec, _ctx: EmitterContext): GeneratedFile[] {\n    // PHP uses inline type hints — no separate type signature files needed\n    return [];\n  },\n\n  generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    ensureNamingInitialized(ctx);\n    return ensureTrailingNewlines(generateTests(spec, ctx));\n  },\n\n  buildOperationsMap(spec: ApiSpec, ctx: EmitterContext) {\n    ensureNamingInitialized(ctx);\n    return buildOperationsMap(spec, ctx);\n  },\n\n  fileHeader(): string {\n    return `<?php\\n\\ndeclare(strict_types=1);\\n\\n// ${AUTOGEN_NOTICE}`;\n  },\n\n  formatCommand(targetDir: string): FormatCommand | null {\n    const hasPhpCsFixer =\n      fs.existsSync(path.join(targetDir, '.php-cs-fixer.dist.php')) ||\n      fs.existsSync(path.join(targetDir, '.php-cs-fixer.php'));\n    if (hasPhpCsFixer) {\n      return {\n        cmd: 'bash',\n        args: ['-c', 'php vendor/bin/php-cs-fixer fix --using-cache=no --quiet . || true'],\n        batchSize: 999999,\n      };\n    }\n    return null;\n  },\n};\n","import type { Operation, Service, EmitterContext } from '@workos/oagen';\nimport { toPascalCase, toSnakeCase } from '@workos/oagen';\nimport { buildResolvedLookup, lookupMethodName, getMountTarget } from '../shared/resolved-ops.js';\nimport { stripUrnPrefix, applyAcronymFixes } from '../shared/naming-utils.js';\n\n/**\n * Go-specific acronym extensions beyond the shared base set.\n * Go convention requires ALL_CAPS for well-known initialisms.\n */\nconst GO_EXTRA_ACRONYM_FIXES: [RegExp, string][] = [\n  [/Jwks(?=[A-Z]|$)/g, 'JWKS'],\n  [/Totp(?=[A-Z]|$)/g, 'TOTP'],\n  [/Api(?=[A-Z]|$)/g, 'API'],\n  [/Urls(?=[A-Z]|$)/g, 'URLs'],\n  [/Url(?=[A-Z]|$)/g, 'URL'],\n  [/Uris(?=[A-Z]|$)/g, 'URIs'],\n  [/Uri(?=[A-Z]|$)/g, 'URI'],\n  [/Http(?=[A-Z]|$)/g, 'HTTP'],\n  [/Uuid(?=[A-Z]|$)/g, 'UUID'],\n  [/Json(?=[A-Z]|$)/g, 'JSON'],\n  [/Html(?=[A-Z]|$)/g, 'HTML'],\n  [/Ip(?=[A-Z]|$)/g, 'IP'],\n  [/Pkce/g, 'PKCE'],\n];\n\n/**\n * Fix trailing \"Id\" to \"ID\" in Go convention.\n * Must be applied after PascalCase and other acronym fixes.\n */\nfunction fixTrailingId(s: string): string {\n  // Fix \"Ids\" → \"IDs\" first (plural), then \"Id\" → \"ID\" (singular)\n  let result = s.replace(/Ids(?=[A-Z]|$)/g, 'IDs');\n  result = result.replace(/Id(?=[A-Z]|$)/g, 'ID');\n  return result;\n}\n\n/** Apply all Go acronym conventions to a PascalCase string. */\nfunction applyAcronyms(s: string): string {\n  let result = applyAcronymFixes(s, GO_EXTRA_ACRONYM_FIXES);\n  result = fixTrailingId(result);\n  return result;\n}\n\n/** PascalCase type/struct name with Go acronym conventions. */\nexport function className(name: string): string {\n  return applyAcronyms(toPascalCase(stripUrnPrefix(name)));\n}\n\n/** snake_case file name (without extension). */\nexport function fileName(name: string): string {\n  return toSnakeCase(stripUrnPrefix(name));\n}\n\n/** PascalCase exported method name with Go acronym conventions. */\nexport function methodName(name: string): string {\n  return applyAcronyms(toPascalCase(name));\n}\n\n/** PascalCase exported field name with Go acronym conventions. */\nexport function fieldName(name: string): string {\n  return applyAcronyms(toPascalCase(name));\n}\n\n/**\n * PascalCase domain field name for a model field, honoring a `domainName`\n * override (set via the `fieldHints` config) so a wire field can surface under\n * a friendlier name. The wire name (the `json:\"...\"` struct tag) still derives\n * from `field.name`.\n */\nexport function domainFieldName(field: { name: string; domainName?: string }): string {\n  return applyAcronyms(toPascalCase(field.domainName ?? field.name));\n}\n\n/** snake_case module/directory name. */\nexport function moduleName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/** snake_case property name for service accessors on the client. */\nexport function servicePropertyName(name: string): string {\n  return unexportedName(className(name));\n}\n\n/** Lower-camel identifier with Go acronym conventions preserved. */\nexport function unexportedName(name: string): string {\n  const exported = className(name);\n  if (!exported) return exported;\n\n  const initialism = exported.match(/^[A-Z]+(?=[A-Z][a-z]|[0-9]|$)/)?.[0];\n  if (initialism) {\n    return initialism.toLowerCase() + exported.slice(initialism.length);\n  }\n\n  return exported.charAt(0).toLowerCase() + exported.slice(1);\n}\n\n/** Resolve the effective service name using resolved operations. */\nexport function resolveServiceName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n/** Build a map from IR service name to resolved service name. */\nexport function buildServiceNameMap(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of services) {\n    map.set(service.name, resolveServiceName(service, ctx));\n  }\n  return map;\n}\n\n/** Resolve the output directory for a service. */\nexport function resolveServiceDir(resolvedServiceName: string): string {\n  return moduleName(resolvedServiceName);\n}\n\n/** Resolve the SDK method name for an operation, using resolved operations first. */\nexport function resolveMethodName(op: Operation, _service: Service, ctx: EmitterContext): string {\n  const lookup = buildResolvedLookup(ctx);\n  const resolved = lookupMethodName(op, lookup);\n  if (resolved) return trimMountedResourceFromMethod(methodName(resolved), resolveClassName(_service, ctx));\n  const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const existing = ctx.overlayLookup?.methodByOperation?.get(httpKey);\n  if (existing) return trimMountedResourceFromMethod(methodName(existing.methodName), resolveClassName(_service, ctx));\n  return trimMountedResourceFromMethod(methodName(op.name), resolveClassName(_service, ctx));\n}\n\n/** Resolve the SDK class name for a service using resolved operations' mountOn. */\nexport function resolveClassName(service: Service, ctx: EmitterContext): string {\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (r.service.name === service.name) return className(r.mountOn);\n  }\n  if (ctx.overlayLookup?.methodByOperation) {\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const existing = ctx.overlayLookup.methodByOperation.get(httpKey);\n      if (existing) return className(existing.className);\n    }\n  }\n  return className(service.name);\n}\n\n/** Build a map from IR service name to mount-target directory name. */\nexport function buildMountDirMap(ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of ctx.spec.services) {\n    const target = getMountTarget(service, ctx);\n    map.set(service.name, moduleName(target));\n  }\n  return map;\n}\n\nfunction splitPascalWords(name: string): string[] {\n  return name.match(/[A-Z]+(?:[a-z]+|(?=[A-Z]|$))|[A-Z]?[a-z]+|[0-9]+/g) ?? [name];\n}\n\nfunction singularize(word: string): string {\n  if (word.endsWith('ies') && word.length > 3) {\n    return `${word.slice(0, -3)}y`;\n  }\n  if (word.endsWith('s') && !word.endsWith('ss')) {\n    return word.slice(0, -1);\n  }\n  return word;\n}\n\nfunction wordsMatch(left: string, right: string): boolean {\n  return singularize(left.toLowerCase()) === singularize(right.toLowerCase());\n}\n\nexport function trimMountedResourceFromMethod(method: string, mountName: string): string {\n  const methodWords = splitPascalWords(method);\n  if (methodWords.length < 2) return method;\n\n  const mountWords = splitPascalWords(className(mountName));\n  if (mountWords.length === 0) return method;\n\n  let matched = 0;\n  while (\n    matched < mountWords.length &&\n    matched + 1 < methodWords.length &&\n    wordsMatch(methodWords[matched + 1], mountWords[matched])\n  ) {\n    matched++;\n  }\n\n  if (matched === 0) return method;\n\n  return [methodWords[0], ...methodWords.slice(matched + 1)].join('');\n}\n","import type { TypeRef, PrimitiveType, UnionType } from '@workos/oagen';\nimport { mapTypeRef as irMapTypeRef } from '@workos/oagen';\nimport { className } from './naming.js';\n\n/**\n * Map an IR TypeRef to a Go type string.\n */\nexport function mapTypeRef(ref: TypeRef, asPointer = false): string {\n  const base = irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (_ref, items) => `[]${items}`,\n    model: (r) => `*${className(r.name)}`,\n    enum: (r) => className(r.name),\n    union: (_r, variants) => joinUnionVariants(_r, variants),\n    nullable: (_ref, inner) => {\n      // Slices, maps, and pointer types (models) don't get pointer-wrapped:\n      // nil slice/map + omitempty already handles absence, and double-pointers\n      // are confusing at the call site.\n      if (inner.startsWith('*') || inner.startsWith('[]') || inner.startsWith('map[')) return inner;\n      return `*${inner}`;\n    },\n    literal: (r) => {\n      if (r.value === null) return 'interface{}';\n      if (typeof r.value === 'string') return 'string';\n      if (typeof r.value === 'number') return Number.isInteger(r.value) ? 'int' : 'float64';\n      if (typeof r.value === 'boolean') return 'bool';\n      return 'interface{}';\n    },\n    map: (_ref, value) => `map[string]${value}`,\n  });\n  if (asPointer && !base.startsWith('*') && !base.startsWith('[]') && !base.startsWith('map[')) {\n    return `*${base}`;\n  }\n  return base;\n}\n\n/**\n * Map an IR TypeRef to a Go type string without pointer wrapping for models.\n * Used for response type references where we don't want a double pointer.\n */\nexport function mapTypeRefValue(ref: TypeRef): string {\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (_ref, items) => `[]${items}`,\n    model: (r) => className(r.name),\n    enum: (r) => className(r.name),\n    union: (_r, variants) => joinUnionVariants(_r, variants),\n    nullable: (_ref, inner) => {\n      if (inner.startsWith('*') || inner.startsWith('[]') || inner.startsWith('map[')) return inner;\n      return `*${inner}`;\n    },\n    literal: (r) => {\n      if (r.value === null) return 'interface{}';\n      if (typeof r.value === 'string') return 'string';\n      if (typeof r.value === 'number') return Number.isInteger(r.value) ? 'int' : 'float64';\n      if (typeof r.value === 'boolean') return 'bool';\n      return 'interface{}';\n    },\n    map: (_ref, value) => `map[string]${value}`,\n  });\n}\n\nfunction mapPrimitive(ref: PrimitiveType): string {\n  if (ref.format === 'binary') return '[]byte';\n  switch (ref.type) {\n    case 'string':\n      return 'string';\n    case 'integer':\n      return 'int';\n    case 'number':\n      return 'float64';\n    case 'boolean':\n      return 'bool';\n    case 'unknown':\n      return 'interface{}';\n  }\n}\n\nfunction joinUnionVariants(_ref: UnionType, variants: string[]): string {\n  if (_ref.compositionKind === 'allOf') {\n    return variants[0] ?? 'interface{}';\n  }\n  const unique = [...new Set(variants)];\n  if (unique.length === 1) return unique[0];\n  // Discriminated unions: Go has no sum types, so widen to the discriminator-\n  // resolver type when one is registered downstream (see resolveDiscriminatedUnionType).\n  // Fall back to interface{} for non-discriminated heterogeneous unions.\n  if (_ref.discriminator && _ref.discriminator.mapping) {\n    const resolverName = unionResolverName(_ref);\n    if (resolverName) return resolverName;\n  }\n  return 'interface{}';\n}\n\n/**\n * Pick a stable type name for a discriminated union's runtime resolver. Today\n * we emit no resolver struct, so we treat the union's first model variant as\n * the public type — matching the pre-discriminator behavior where Go just\n * referenced one variant directly. The Owner field stays typed, callers\n * can still inspect Type to detect the user variant (data loss on\n * non-overlapping fields like organization_id is documented in the SDK\n * compat report rather than fixed in the emitter — Go callers who need the\n * user-only fields can json.Unmarshal the raw payload manually).\n */\nfunction unionResolverName(ref: UnionType): string | null {\n  for (const v of ref.variants) {\n    if (v.kind === 'model') return `*${className(v.name)}`;\n  }\n  return null;\n}\n","import type { EmitterContext } from '@workos/oagen';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { isScopedRun } from '../shared/resolved-ops.js';\n\n/**\n * Scoped-run reconciliation for Go's FLAT aggregate files.\n *\n * Unlike Rust (one source file per model/enum), Go inlines every type into a\n * single `models.go` / `enums.go` and every webhook event into one\n * `pkg/events/events.go`. A scoped (`--services`) run regenerates these flat\n * files from the FULL new spec, which breaks scoping two ways:\n *\n *   1. ADDITION — a brand-new model/enum/event that belongs to an OUT-OF-SCOPE\n *      service gets inlined, so a scoped batch leaks unrelated changes\n *      (violates Option B: a scoped batch should contain ONLY the selected\n *      service's changes).\n *   2. REMOVAL / RENAME — a type the new spec renamed away (e.g.\n *      `OrganizationDomainStandAlone` → `OrganizationDomain`) is no longer\n *      produced, so its block vanishes from `models.go`; but an out-of-scope\n *      resource file (NOT regenerated this run) still references the old name →\n *      `undefined: OrganizationDomainStandAlone` and the package won't compile.\n *\n * The fix mirrors the Rust principle: in a scoped run, only the selected\n * services' types should reflect the new spec; everything else must be\n * preserved exactly as it is on disk. Because Go's manifest records the flat\n * FILE path (`models.go`) and not per-type paths, we recover the per-type\n * \"present before\" signal by reading the prior file from `ctx.outputDir`\n * (the emitter already reads `go.mod` from there in tests.ts). A type/const\n * block is then reconciled as:\n *\n *   - KEEP a freshly generated block iff it is IN-SCOPE or its name was present\n *     in the prior file  → drops brand-new out-of-scope additions (fix #1).\n *   - CARRY OVER verbatim any prior block whose name(s) the new spec no longer\n *     produces                          → retains renamed/removed types (fix #2).\n *\n * A full (non-scoped) run skips all of this and emits the new spec verbatim.\n */\n\n/** A single named top-level declaration block in a flat Go file. */\nexport interface NamedBlock {\n  /** Every type/const name this block declares (a batched `type (...)` alias block declares several). */\n  names: string[];\n  /** Verbatim text of the block (no trailing blank line). */\n  text: string;\n  /**\n   * Whether the block's owning model/enum is in scope this run. Set by the\n   * generator for freshly produced blocks; omitted (treated as false) for\n   * blocks parsed from the prior on-disk file.\n   */\n  inScope?: boolean;\n}\n\n/** Read the prior on-disk content of a generated file, or null when unavailable. */\nexport function readPriorFile(relPath: string, ctx: EmitterContext): string | null {\n  if (!ctx.outputDir) return null;\n  const abs = resolve(ctx.outputDir, relPath);\n  if (!existsSync(abs)) return null;\n  try {\n    return readFileSync(abs, 'utf-8');\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Parse a flat Go file into the set of top-level type names it declares, mapped\n * to the verbatim text of each declaration block (including its leading doc\n * comment). Used to recover the per-type \"present before\" signal a scoped run\n * needs. Recognizes the exact shapes the Go emitter produces:\n *   - `type Name struct { ... }`        (brace-balanced)\n *   - `type Name = Other`               (single-line alias)\n *   - `type Name string` + `const ( ... )`  (string enum)\n *   - `type ( A = X\\n B = X )`          (batched alias block — declares many)\n * The leading `package` clause and any standalone trailing `const (...)` block\n * (e.g. the events file) are returned separately by {@link parseFlatGoBlocks}.\n */\nexport function parseFlatGoBlocks(content: string): {\n  blocks: NamedBlock[];\n  byName: Map<string, NamedBlock>;\n} {\n  const lines = content.split('\\n');\n  const blocks: NamedBlock[] = [];\n  let i = 0;\n\n  // Skip the generated header / package clause / leading blanks; those are\n  // re-emitted by the generator, not carried over.\n  while (i < lines.length) {\n    const t = lines[i].trim();\n    if (t.startsWith('package ') || t === '' || t.startsWith('// Code generated')) {\n      i++;\n      continue;\n    }\n    break;\n  }\n\n  while (i < lines.length) {\n    // Collect a leading run of `//` doc-comment lines.\n    const start = i;\n    while (i < lines.length && lines[i].trim().startsWith('//')) i++;\n\n    if (i >= lines.length) break;\n    const line = lines[i];\n    const trimmed = line.trim();\n\n    if (trimmed === 'type (') {\n      // Batched alias block: `type (` ... `)`. Each inner line is `Name = Other`.\n      const names: string[] = [];\n      i++;\n      while (i < lines.length && lines[i].trim() !== ')') {\n        const m = lines[i].trim().match(/^(\\w+)\\s*=/);\n        if (m) names.push(m[1]);\n        i++;\n      }\n      i++; // consume ')'\n      blocks.push({ names, text: lines.slice(start, i).join('\\n') });\n    } else if (/^type\\s+(\\w+)\\s+struct\\s*\\{/.test(trimmed)) {\n      const name = trimmed.match(/^type\\s+(\\w+)/)![1];\n      // Brace-balanced struct body.\n      let depth = 0;\n      let sawOpen = false;\n      while (i < lines.length) {\n        for (const ch of lines[i]) {\n          if (ch === '{') {\n            depth++;\n            sawOpen = true;\n          } else if (ch === '}') depth--;\n        }\n        i++;\n        if (sawOpen && depth === 0) break;\n      }\n      blocks.push({ names: [name], text: lines.slice(start, i).join('\\n') });\n    } else if (/^type\\s+(\\w+)\\s+\\w+\\s+string\\b/.test(trimmed) || /^type\\s+(\\w+)\\s+string\\b/.test(trimmed)) {\n      // String enum: `type Name string` possibly followed by a `const ( ... )`.\n      const name = trimmed.match(/^type\\s+(\\w+)/)![1];\n      i++;\n      // Skip blank lines then an optional const block.\n      let j = i;\n      while (j < lines.length && lines[j].trim() === '') j++;\n      if (j < lines.length && lines[j].trim() === 'const (') {\n        i = j;\n        while (i < lines.length && lines[i].trim() !== ')') i++;\n        i++; // consume ')'\n      }\n      blocks.push({ names: [name], text: lines.slice(start, i).join('\\n') });\n    } else if (/^type\\s+(\\w+)\\s*=/.test(trimmed)) {\n      // Single-line alias: `type Name = Other`.\n      const name = trimmed.match(/^type\\s+(\\w+)/)![1];\n      i++;\n      blocks.push({ names: [name], text: lines.slice(start, i).join('\\n') });\n    } else {\n      // Unrecognized top-level construct (e.g. a standalone `const (...)`).\n      // Skip the line so parsing stays robust; such constructs are never\n      // carried over by name.\n      i++;\n    }\n    // Skip trailing blank lines between blocks (re-added on reassembly).\n    while (i < lines.length && lines[i].trim() === '') i++;\n  }\n\n  const byName = new Map<string, NamedBlock>();\n  for (const b of blocks) for (const n of b.names) byName.set(n, b);\n  return { blocks, byName };\n}\n\n/**\n * Reconcile freshly generated named blocks against the prior on-disk file for a\n * scoped run. Returns the ordered list of block texts to emit. See file-level\n * docs for the keep/carry-over rules. In a scoped run a block is emitted as:\n *   - IN-SCOPE                  → the freshly generated text (apply the new spec).\n *   - out-of-scope, existed before → the PRIOR on-disk text, FROZEN, so an\n *     unrelated change to that type in the same spec delta doesn't leak into a\n *     scoped batch (Option B). (Falls back to fresh text only when the new\n *     block's names span multiple prior blocks — a batched-alias regrouping —\n *     which can't be frozen 1:1.)\n *   - out-of-scope, brand-new   → dropped (the addition that broke the build).\n * Then any prior block the new spec no longer produces at all is carried over\n * verbatim (renamed/removed types still referenced by un-regenerated code).\n *\n * @param newBlocks    Per-type blocks the current spec produced (in emit order),\n *                     each tagged with `inScope`.\n * @param relPath      Flat file path (e.g. `models.go`) for reading the prior file.\n * @param ctx          Emitter context (provides `outputDir` + scope sets).\n * @param alsoEmitted  Names this file emits OUTSIDE `newBlocks` (e.g. the fixed\n *                     `PaginationParams` struct). They must be excluded from the\n *                     carry-over, or the prior copy would be re-appended and\n *                     redeclare the separately-emitted one.\n */\nexport function reconcileFlatBlocks(\n  newBlocks: NamedBlock[],\n  relPath: string,\n  ctx: EmitterContext,\n  alsoEmitted: Set<string> = new Set<string>(),\n): string[] {\n  // Full run: emit everything the new spec produced, unchanged.\n  if (!isScopedRun(ctx)) return newBlocks.map((b) => b.text);\n\n  const prior = readPriorFile(relPath, ctx);\n  // No prior file to reconcile against (first generation / missing output dir):\n  // fall back to scope-only gating so we never leak brand-new out-of-scope\n  // types, but there's nothing on disk to retain.\n  const priorParsed = prior ? parseFlatGoBlocks(prior) : { blocks: [], byName: new Map<string, NamedBlock>() };\n\n  const out: string[] = [];\n  const emittedNames = new Set<string>();\n\n  for (const block of newBlocks) {\n    if (block.inScope) {\n      out.push(block.text);\n      for (const n of block.names) emittedNames.add(n);\n      continue;\n    }\n    // Out of scope: freeze to the prior on-disk text when this block maps 1:1\n    // to a single prior block; that keeps an out-of-scope type byte-identical to\n    // disk even if the new spec changed it. A brand-new out-of-scope block has\n    // no prior block → it is dropped.\n    const priorBlocks = block.names.map((n) => priorParsed.byName.get(n)).filter((b): b is NamedBlock => !!b);\n    const uniquePrior = new Set(priorBlocks);\n    if (uniquePrior.size === 1) {\n      const pb = priorBlocks[0];\n      if (!pb.names.some((n) => emittedNames.has(n))) {\n        out.push(pb.text);\n        for (const n of pb.names) emittedNames.add(n);\n      }\n    } else if (uniquePrior.size > 1) {\n      // A regrouping spread this out-of-scope block's names across several prior\n      // blocks. NEVER regenerate out-of-scope content (the fresh text could\n      // re-point an alias at a renamed canonical the scoped run didn't emit);\n      // instead freeze every distinct prior block verbatim. All names are\n      // on-disk here (the generator only puts in-scope ∪ on-disk names in an\n      // out-of-scope block), so this fully retains them.\n      for (const pb of uniquePrior) {\n        if (pb.names.some((n) => emittedNames.has(n))) continue;\n        out.push(pb.text);\n        for (const n of pb.names) emittedNames.add(n);\n      }\n    }\n    // uniquePrior.size === 0 → brand-new out-of-scope → drop.\n  }\n\n  // Carry over prior blocks the new spec no longer produces at all (renamed /\n  // removed types still referenced by out-of-scope, un-regenerated code),\n  // excluding any name this file emits elsewhere (e.g. PaginationParams).\n  for (const block of priorParsed.blocks) {\n    if (block.names.some((n) => alsoEmitted.has(n))) continue;\n    if (block.names.every((n) => !emittedNames.has(n))) {\n      out.push(block.text);\n      for (const n of block.names) emittedNames.add(n);\n    }\n  }\n\n  return out;\n}\n","import type { Model, EmitterContext, GeneratedFile, TypeRef, Service } from '@workos/oagen';\nimport { walkTypeRef } from '@workos/oagen';\nimport { mapTypeRef } from './type-map.js';\nimport { className, domainFieldName } from './naming.js';\nimport { lowerFirstForDoc, fieldDocComment, articleFor } from '../shared/naming-utils.js';\nimport { isModelInScope, isScopedRun } from '../shared/resolved-ops.js';\nimport { reconcileFlatBlocks, readPriorFile, parseFlatGoBlocks, type NamedBlock } from './flat-merge.js';\n\n// Import and re-export shared model detection utilities\nimport {\n  isListWrapperModel,\n  isListMetadataModel,\n  collectNonPaginatedResponseModelNames,\n  collectReferencedListMetadataModels,\n} from '../shared/model-utils.js';\nexport { isListWrapperModel, isListMetadataModel };\n\n/**\n * Collect names of models that are referenced **only** as a named request body\n * model on an operation, with no other consumers (response types, pagination\n * item types, error types, or fields on other models).\n *\n * The Go emitter synthesizes a `{Service}{Method}Params` struct from those\n * request bodies (see `resources.ts:392`), and the method signature uses the\n * synthesized struct — never the named model. So emitting the named model in\n * `models.go` would leave callers with a duplicate, unused struct (the bug\n * surfaced in workos-go#544 with `CreateUserAPIKey` /\n * `UserManagementCreateAPIKeyParams`).\n *\n * Models in this set are skipped during model emission. Callers parameterize\n * the API surface through `*Params` exclusively, which is the sole consumer\n * of the spec's named request body schema.\n */\nfunction collectRequestBodyOnlyModelNames(services: Service[], models: Model[]): Set<string> {\n  const requestBodyNames = new Set<string>();\n  const otherReferences = new Set<string>();\n\n  const collect = (ref: TypeRef | undefined, into: Set<string>): void => {\n    if (!ref) return;\n    walkTypeRef(ref, {\n      model: (r) => into.add(r.name),\n    });\n  };\n\n  for (const service of services) {\n    for (const op of service.operations) {\n      if (op.requestBody?.kind === 'model') {\n        requestBodyNames.add(op.requestBody.name);\n      }\n      collect(op.response, otherReferences);\n      if (op.pagination) collect(op.pagination.itemType, otherReferences);\n      for (const p of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n        collect(p.type, otherReferences);\n      }\n      if (op.successResponses) {\n        for (const sr of op.successResponses) collect(sr.type, otherReferences);\n      }\n      for (const err of op.errors) {\n        if (err.type) collect(err.type, otherReferences);\n      }\n    }\n  }\n\n  // Field references — a request body model that's also a field type elsewhere\n  // is a reusable schema (e.g. consumed by webhook event data), so we keep it.\n  for (const model of models) {\n    for (const field of model.fields) {\n      collect(field.type, otherReferences);\n    }\n  }\n\n  const result = new Set<string>();\n  for (const name of requestBodyNames) {\n    if (!otherReferences.has(name)) result.add(name);\n  }\n  return result;\n}\n\n/**\n * Generate Go struct definitions from IR Models.\n * All models go into a single models.go file for the flat package.\n */\nexport function generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n  if (models.length === 0) return [];\n\n  const files: GeneratedFile[] = [];\n  const lines: string[] = [];\n\n  lines.push(`package ${ctx.namespace}`);\n  lines.push('');\n\n  const requestBodyOnly = collectRequestBodyOnlyModelNames(ctx.spec.services, models);\n  // Wrappers referenced as a non-paginated response (e.g. `VersionListResponse`\n  // for `GET /vault/v1/kv/{id}/versions`) must still be emitted — the resource\n  // code references them by name and the pagination iterator doesn't unwrap them.\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(ctx.spec.services);\n  const skipAsListWrapper = (m: Model): boolean => isListWrapperModel(m) && !nonPaginatedRefs.has(m.name);\n  // A `ListMetadata`-shape model referenced by a surviving non-paginated\n  // wrapper (e.g. vault's `VersionListResponse`) must still be emitted —\n  // otherwise the wrapper's struct references a type that was never declared.\n  const listMetadataNeeded = collectReferencedListMetadataModels(models, nonPaginatedRefs);\n  const skipAsListMetadata = (m: Model): boolean => isListMetadataModel(m) && !listMetadataNeeded.has(m.name);\n\n  // Build structural hash for deduplication\n  const modelHashMap = new Map<string, string>();\n  const hashGroups = new Map<string, string[]>();\n  for (const model of models) {\n    if (skipAsListWrapper(model) || skipAsListMetadata(model)) continue;\n    if (requestBodyOnly.has(model.name)) continue;\n    const hash = structuralHash(model);\n    modelHashMap.set(model.name, hash);\n    if (!hashGroups.has(hash)) hashGroups.set(hash, []);\n    hashGroups.get(hash)!.push(model.name);\n  }\n\n  // Pick canonical for each duplicate group.\n  // Empty structs (hash '') are now properly populated by oneOf flattening,\n  // so we still skip aliasing them to avoid aliasing truly empty structs.\n  // For the batched-alias block below: in a scoped run, only emit an alias that\n  // is in scope OR already on disk (present in the prior models.go). Otherwise a\n  // `>= 5` structural group containing a single in-scope alias would drag every\n  // brand-new out-of-scope alias in the group into the file. A full run keeps\n  // every alias (isScopedRun is false).\n  const priorModelNames = isScopedRun(ctx)\n    ? new Set(parseFlatGoBlocks(readPriorFile('models.go', ctx) ?? '').blocks.flatMap((b) => b.names))\n    : new Set<string>();\n  const aliasEmitted = (name: string): boolean =>\n    !isScopedRun(ctx) || isModelInScope(name, ctx) || priorModelNames.has(className(name));\n\n  const aliasOf = new Map<string, string>();\n  for (const [hash, names] of hashGroups) {\n    if (names.length <= 1) continue;\n    if (hash === '') continue;\n    const sorted = [...names].sort();\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      aliasOf.set(sorted[i], canonical);\n    }\n  }\n\n  // The structural-dedup canonical is chosen alphabetically, independent of\n  // scope, so an in-scope alias can point at a canonical that is itself out of\n  // scope and brand-new — which the reconciler would drop, leaving the alias\n  // `type InScopeModel = Canonical` dangling (`undefined: Canonical`). Force-\n  // retain any canonical referenced by an in-scope alias. The canonical is\n  // structurally identical to that alias, so its field types are reachable from\n  // the in-scope service and therefore also emitted. In a mixed batched-alias\n  // block the in-scope member forces the shared canonical, covering its on-disk\n  // siblings that emit fresh in the same block.\n  const forcedCanonicals = new Set<string>();\n  if (isScopedRun(ctx)) {\n    for (const [aliasName, canonical] of aliasOf) {\n      if (isModelInScope(aliasName, ctx)) forcedCanonicals.add(canonical);\n    }\n  }\n\n  // Build one NamedBlock per emitted model type. In a scoped run these blocks\n  // are reconciled against the prior models.go (see reconcileFlatBlocks): blocks\n  // for out-of-scope models that didn't exist before are dropped, and prior\n  // blocks for renamed/removed types are carried over verbatim. A full run emits\n  // every block unchanged. Tracking the IR model name(s) per block (a batched\n  // alias group declares several) is what lets the reconciler gate by scope.\n  const modelBlocks: NamedBlock[] = [];\n\n  const batchedAliases = new Set<string>();\n  for (const model of models) {\n    if (skipAsListWrapper(model) || skipAsListMetadata(model)) continue;\n    if (requestBodyOnly.has(model.name)) continue;\n\n    const structName = className(model.name);\n\n    // If this model is a dedup alias, emit a type alias.\n    // For large alias groups (5+), use a compact batch declaration.\n    const canonicalName = aliasOf.get(model.name);\n    if (canonicalName) {\n      // Check if this alias is part of a batch that was already emitted\n      if (batchedAliases.has(model.name)) continue;\n\n      const canonicalStruct = className(canonicalName);\n      // Skip when different IR names map to the same Go type (e.g. synthetic\n      // models from enrichModelsFromSpec whose underscore names collapse to the\n      // same PascalCase as the original model).\n      if (structName === canonicalStruct) continue;\n\n      const hash = modelHashMap.get(model.name)!;\n      const groupNames = hashGroups.get(hash) ?? [];\n      const aliases = groupNames.filter((n) => aliasOf.has(n) && className(n) !== className(aliasOf.get(n)!));\n\n      const blockLines: string[] = [];\n      const blockNames: string[] = [];\n      let blockInScope = false;\n      if (aliases.length >= 5) {\n        // Mark the whole group consumed so its members aren't re-emitted as\n        // singles, but only EMIT aliases that are in scope or already on disk —\n        // dropping brand-new out-of-scope aliases (scope leak fix). On-disk\n        // aliases are retained so out-of-scope code that references them still\n        // compiles.\n        for (const aliasName of aliases) {\n          batchedAliases.add(aliasName);\n        }\n        const emittedAliases = aliases.filter(aliasEmitted);\n        if (emittedAliases.length === 0) continue;\n        blockLines.push(`// The following types are structurally identical to ${canonicalStruct}.`);\n        blockLines.push('type (');\n        for (const aliasName of emittedAliases) {\n          blockLines.push(`\\t${className(aliasName)} = ${canonicalStruct}`);\n          blockNames.push(className(aliasName));\n          if (isModelInScope(aliasName, ctx)) blockInScope = true;\n        }\n        blockLines.push(')');\n      } else {\n        blockLines.push(`// ${structName} is an alias for ${canonicalStruct}.`);\n        blockLines.push(`type ${structName} = ${canonicalStruct}`);\n        blockNames.push(structName);\n        if (isModelInScope(model.name, ctx)) blockInScope = true;\n      }\n      modelBlocks.push({ names: blockNames, text: blockLines.join('\\n'), inScope: blockInScope });\n      continue;\n    }\n\n    // Emit struct\n    const blockLines: string[] = [];\n    if (model.description) {\n      const descLines = model.description.split('\\n').filter((l) => l.trim());\n      blockLines.push(`// ${structName} ${lowerFirst(descLines[0])}`);\n      for (let i = 1; i < descLines.length; i++) {\n        blockLines.push(`// ${descLines[i].trim()}`);\n      }\n    } else {\n      const humanized = humanize(model.name);\n      blockLines.push(`// ${structName} represents ${articleFor(humanized)} ${humanized}.`);\n    }\n    blockLines.push(`type ${structName} struct {`);\n\n    // Deduplicate fields by Go field name\n    const seenFieldNames = new Set<string>();\n    for (const field of model.fields) {\n      // Domain identifier honors a `fieldHints` override (e.g. connection_type\n      // → type); the json struct tag below still derives from `field.name`.\n      const goFieldName = domainFieldName(field);\n      if (seenFieldNames.has(goFieldName)) continue;\n      seenFieldNames.add(goFieldName);\n\n      const isOptional = !field.required;\n      const goType = isOptional ? makeOptional(mapTypeRef(field.type)) : mapTypeRef(field.type);\n\n      const jsonTag = field.required ? `json:\"${field.name}\"` : `json:\"${field.name},omitempty\"`;\n\n      if (field.description) {\n        const fdLines = field.description.split('\\n').filter((l) => l.trim());\n        blockLines.push(`\\t// ${fieldDocComment(goFieldName, fdLines[0])}`);\n        for (let i = 1; i < fdLines.length; i++) {\n          blockLines.push(`\\t// ${fdLines[i].trim()}`);\n        }\n      }\n      if (field.deprecated) {\n        if (field.description) blockLines.push(`\\t//`);\n        const deprecationReason = extractDeprecationReason(field.description);\n        blockLines.push(`\\t// Deprecated: ${deprecationReason}`);\n      }\n      blockLines.push(`\\t${goFieldName} ${goType} \\`${jsonTag}\\``);\n    }\n\n    blockLines.push('}');\n    modelBlocks.push({\n      names: [structName],\n      text: blockLines.join('\\n'),\n      inScope: isModelInScope(model.name, ctx) || forcedCanonicals.has(model.name),\n    });\n  }\n\n  // Scoped runs: drop brand-new out-of-scope blocks; carry over prior blocks the\n  // new spec renamed/removed (still referenced by un-regenerated resource code).\n  // Full runs return every block unchanged.\n  // `PaginationParams` is emitted separately below (not part of modelBlocks),\n  // so exclude it from carry-over or the prior copy would be redeclared.\n  const reconciled = reconcileFlatBlocks(modelBlocks, 'models.go', ctx, new Set(['PaginationParams']));\n  for (const text of reconciled) {\n    lines.push(text);\n    lines.push('');\n  }\n\n  // Emit shared PaginationParams struct for list operations to embed.\n  //\n  // The Order field's type is derived from the spec rather than hardcoded:\n  // when every paginated `order` query parameter $refs the same top-level\n  // enum (typically `PaginationOrder` in the WorkOS spec), we emit the typed\n  // enum so callers get compile-time validation. Otherwise we fall back to\n  // *string. The fallback handles older specs that don't lift the enum into a\n  // named component schema.\n  const orderEnumType = detectSharedOrderEnum(ctx.spec.services);\n  const orderGoType = orderEnumType ? `*${className(orderEnumType)}` : '*string';\n  lines.push('// PaginationParams contains common pagination parameters for list operations.');\n  lines.push('type PaginationParams struct {');\n  lines.push('\\t// Before is a cursor for reverse pagination.');\n  lines.push('\\tBefore *string `url:\"before,omitempty\" json:\"-\"`');\n  lines.push('\\t// After is a cursor for forward pagination.');\n  lines.push('\\tAfter *string `url:\"after,omitempty\" json:\"-\"`');\n  lines.push('\\t// Limit is the maximum number of items to return per page.');\n  lines.push('\\tLimit *int `url:\"limit,omitempty\" json:\"-\"`');\n  lines.push('\\t// Order is the sort order for results.');\n  lines.push(`\\tOrder ${orderGoType} \\`url:\"order,omitempty\" json:\"-\"\\``);\n  lines.push('}');\n  lines.push('');\n\n  files.push({\n    path: 'models.go',\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  });\n\n  return files;\n}\n\n/**\n * Make a Go type optional (pointer) if it isn't already.\n */\nfunction makeOptional(goType: string): string {\n  if (goType.startsWith('*') || goType.startsWith('[]') || goType.startsWith('map[')) {\n    return goType;\n  }\n  return `*${goType}`;\n}\n\nfunction structuralHash(model: Model): string {\n  const fieldHash = model.fields\n    .map((f) => `${f.name}:${JSON.stringify(f.type)}:${f.required}`)\n    .sort()\n    .join('|');\n  // Include entity domain for CRUD-prefixed models to prevent cross-domain\n  // aliasing (e.g. UpdateGroup vs UpdateAuthorizationPermission have identical\n  // fields but belong to different API domains and should stay separate types).\n  const domain = crudEntityDomain(model.name);\n  return domain ? `${domain}::${fieldHash}` : fieldHash;\n}\n\nconst CRUD_PREFIXES = ['Create', 'Update', 'Delete', 'Get', 'List'];\n\n/** Strip CRUD verb prefix to get the entity name, or null if no prefix matches. */\nfunction crudEntityDomain(name: string): string | null {\n  for (const prefix of CRUD_PREFIXES) {\n    if (name.startsWith(prefix) && name.length > prefix.length) {\n      return name.slice(prefix.length);\n    }\n  }\n  return null;\n}\n\n/** Known acronyms to preserve as single tokens during humanization. */\nconst HUMANIZE_ACRONYMS: [RegExp, string][] = [\n  [/OAuth/g, 'OAUTH_ACRN'],\n  [/URN/g, 'URN_ACRN'],\n  [/IETF/g, 'IETF_ACRN'],\n  [/API/g, 'API_ACRN'],\n  [/SSO/g, 'SSO_ACRN'],\n  [/PKCE/g, 'PKCE_ACRN'],\n  [/JWT/g, 'JWT_ACRN'],\n  [/MFA/g, 'MFA_ACRN'],\n  [/TOTP/g, 'TOTP_ACRN'],\n  [/SAML/g, 'SAML_ACRN'],\n  [/SCIM/g, 'SCIM_ACRN'],\n  [/OIDC/g, 'OIDC_ACRN'],\n  [/CORS/g, 'CORS_ACRN'],\n  [/RBAC/g, 'RBAC_ACRN'],\n];\n\nconst HUMANIZE_RESTORE: [RegExp, string][] = [\n  [/oauth_acrn/g, 'OAuth'],\n  [/urn_acrn/g, 'URN'],\n  [/ietf_acrn/g, 'IETF'],\n  [/api_acrn/g, 'API'],\n  [/sso_acrn/g, 'SSO'],\n  [/pkce_acrn/g, 'PKCE'],\n  [/jwt_acrn/g, 'JWT'],\n  [/mfa_acrn/g, 'MFA'],\n  [/totp_acrn/g, 'TOTP'],\n  [/saml_acrn/g, 'SAML'],\n  [/scim_acrn/g, 'SCIM'],\n  [/oidc_acrn/g, 'OIDC'],\n  [/cors_acrn/g, 'CORS'],\n  [/rbac_acrn/g, 'RBAC'],\n];\n\nfunction humanize(name: string): string {\n  // Replace known acronyms with placeholders before splitting\n  let s = name;\n  for (const [pattern, replacement] of HUMANIZE_ACRONYMS) {\n    s = s.replace(pattern, replacement);\n  }\n  // Split camelCase/PascalCase into words\n  let result = s.replace(/([a-z])([A-Z])/g, '$1 $2');\n  result = result.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');\n  result = result.toLowerCase();\n  // Restore acronyms\n  for (const [pattern, replacement] of HUMANIZE_RESTORE) {\n    result = result.replace(pattern, replacement);\n  }\n  return result;\n}\n\nfunction lowerFirst(s: string): string {\n  return lowerFirstForDoc(s);\n}\n\n/**\n * If every paginated list operation's `order` query parameter $refs the same\n * top-level enum, return that enum's IR name. Otherwise return null. When\n * the spec is consistent this lifts `PaginationParams.Order` from `*string`\n * to `*PaginationOrder` (or whatever the spec calls it), giving callers\n * compile-time validation.\n *\n * We require strict consistency: if any operation uses a primitive string for\n * `order`, or two operations reference different enums, we conservatively\n * stay on `*string` so the shared struct doesn't lie about its accepted\n * values.\n */\nfunction detectSharedOrderEnum(services: Service[]): string | null {\n  let candidate: string | null = null;\n  let sawAny = false;\n  for (const service of services) {\n    for (const op of service.operations) {\n      if (!op.pagination) continue;\n      const orderParam = op.queryParams.find((p) => p.name === 'order');\n      if (!orderParam) continue;\n      sawAny = true;\n      const enumName = unwrapEnumName(orderParam.type);\n      if (!enumName) return null;\n      if (candidate === null) candidate = enumName;\n      else if (candidate !== enumName) return null;\n    }\n  }\n  return sawAny ? candidate : null;\n}\n\nfunction unwrapEnumName(ref: TypeRef): string | null {\n  if (ref.kind === 'enum') return ref.name;\n  if (ref.kind === 'nullable') return unwrapEnumName(ref.inner);\n  return null;\n}\n\n/**\n * Extract a deprecation reason from a field description.\n * Looks for patterns like \"Use X instead\", \"Replaced by Y\", etc.\n * Falls back to a generic message if no migration guidance is found.\n */\nfunction extractDeprecationReason(description?: string): string {\n  if (!description) return 'this field is deprecated.';\n\n  // Common patterns: \"Use X instead\", \"Replaced by X\", \"Deprecated in favor of X\"\n  const patterns = [\n    /\\b(use\\s+\\S+(?:\\s+\\S+){0,3}\\s+instead)\\b/i,\n    /\\b(replaced\\s+by\\s+\\S+(?:\\s+\\S+){0,3})\\b/i,\n    /\\b(deprecated\\s+in\\s+favor\\s+of\\s+\\S+(?:\\s+\\S+){0,3})\\b/i,\n    /\\b(prefer\\s+\\S+(?:\\s+\\S+){0,3})\\b/i,\n    /\\b(migrate\\s+to\\s+\\S+(?:\\s+\\S+){0,3})\\b/i,\n  ];\n\n  for (const pattern of patterns) {\n    const match = description.match(pattern);\n    if (match) {\n      let reason = match[1].trim();\n      // Ensure it ends with a period\n      if (!reason.endsWith('.')) reason += '.';\n      return reason;\n    }\n  }\n\n  return 'this field is deprecated.';\n}\n","import type { Enum, EmitterContext, GeneratedFile, Service } from '@workos/oagen';\nimport { walkTypeRef } from '@workos/oagen';\nimport { className } from './naming.js';\nimport { isEnumInScope, isScopedRun } from '../shared/resolved-ops.js';\nimport { reconcileFlatBlocks, readPriorFile, type NamedBlock } from './flat-merge.js';\n\n/**\n * Generate Go typed string enum constants from IR Enum definitions.\n *\n * Each enum becomes a named string type + const block:\n *   type Status string\n *   const (\n *     StatusActive   Status = \"active\"\n *     StatusInactive Status = \"inactive\"\n *   )\n */\nexport function generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n  if (enums.length === 0) return [];\n\n  const aliasOf = collectEnumAliasOf(enums);\n  // An in-scope enum alias emits `type Alias = Canonical` against the current\n  // spec; the canonical may itself be out of scope and brand-new, which the\n  // reconciler would drop, leaving the alias dangling. Force-retain any\n  // canonical referenced by an in-scope alias.\n  const forcedCanonicals = new Set<string>();\n  if (isScopedRun(ctx)) {\n    for (const [aliasName, canonical] of aliasOf) {\n      if (isEnumInScope(aliasName, ctx)) forcedCanonicals.add(canonical);\n    }\n  }\n  const files: GeneratedFile[] = [];\n\n  // Group all enums into a single file per SDK\n  const lines: string[] = [];\n  lines.push(`package ${ctx.namespace}`);\n  lines.push('');\n\n  // Build one NamedBlock per emitted enum type so a scoped run can reconcile\n  // them against the prior enums.go (drop brand-new out-of-scope enums, retain\n  // renamed/removed ones still referenced by un-regenerated code). A full run\n  // emits every block unchanged.\n  const enumBlocks: NamedBlock[] = [];\n  // Go declares every enum in this one file, so the same Go type name must\n  // never be written twice — a second `type X` / `type X = Y` is a hard\n  // \"redeclared in this block\" compile error. The input list can contain\n  // same-named entries when a synthetic enum (from enrichModelsFromSpec)\n  // duplicates an inline enum the parser already emitted. Dedup by the final\n  // Go type name as a backstop, independent of how the list was assembled.\n  const emittedTypeNames = new Set<string>();\n\n  for (const enumDef of enums) {\n    const goTypeName = className(enumDef.name);\n    if (emittedTypeNames.has(goTypeName)) continue;\n    emittedTypeNames.add(goTypeName);\n\n    // If this enum is an alias, emit a simple type alias\n    const canonicalName = aliasOf.get(enumDef.name);\n    if (canonicalName) {\n      const aliasType = className(enumDef.name);\n      const canonicalType = className(canonicalName);\n      // Skip when different IR names map to the same Go type (e.g. synthetic\n      // enums from enrichModelsFromSpec whose underscore names collapse to the\n      // same PascalCase as the original enum).\n      if (aliasType === canonicalType) continue;\n      enumBlocks.push({\n        names: [aliasType],\n        text: [`// ${aliasType} is an alias for ${canonicalType}.`, `type ${aliasType} = ${canonicalType}`].join('\\n'),\n        inScope: isEnumInScope(enumDef.name, ctx),\n      });\n      continue;\n    }\n\n    const typeName = className(enumDef.name);\n\n    if (enumDef.values.length === 0) {\n      const humanized = humanize(enumDef.name);\n      enumBlocks.push({\n        names: [typeName],\n        text: [`// ${typeName} represents ${humanized} values.`, `type ${typeName} = string`].join('\\n'),\n        inScope: isEnumInScope(enumDef.name, ctx) || forcedCanonicals.has(enumDef.name),\n      });\n      continue;\n    }\n\n    // Deduplicate values\n    const seenValues = new Set<string>();\n    const uniqueValues: typeof enumDef.values = [];\n    for (const v of enumDef.values) {\n      const vs = String(v.value);\n      if (!seenValues.has(vs)) {\n        seenValues.add(vs);\n        uniqueValues.push(v);\n      }\n    }\n\n    const humanized = humanize(enumDef.name);\n    const blockLines: string[] = [];\n    blockLines.push(`// ${typeName} represents ${humanized} values.`);\n    blockLines.push(`type ${typeName} string`);\n    blockLines.push('');\n    blockLines.push('const (');\n\n    const usedNames = new Set<string>();\n    for (const v of uniqueValues) {\n      let constSuffix = className(String(v.value));\n      // Avoid collision with the type itself\n      if (usedNames.has(`${typeName}${constSuffix}`)) {\n        let suffix = 2;\n        while (usedNames.has(`${typeName}${constSuffix}${suffix}`)) suffix++;\n        constSuffix = `${constSuffix}${suffix}`;\n      }\n      const constName = `${typeName}${constSuffix}`;\n      usedNames.add(constName);\n      const valueStr = typeof v.value === 'string' ? `\"${v.value}\"` : String(v.value);\n      if (v.description) {\n        blockLines.push(`\\t// ${constName} is ${v.description}.`);\n      }\n      if (v.deprecated) {\n        if (v.description) blockLines.push(`\\t//`);\n        blockLines.push(`\\t// Deprecated: this value is deprecated.`);\n      }\n      blockLines.push(`\\t${constName} ${typeName} = ${valueStr}`);\n    }\n    blockLines.push(')');\n    enumBlocks.push({\n      names: [typeName],\n      text: blockLines.join('\\n'),\n      inScope: isEnumInScope(enumDef.name, ctx) || forcedCanonicals.has(enumDef.name),\n    });\n  }\n\n  const reconciled = reconcileFlatBlocks(enumBlocks, 'enums.go', ctx);\n  for (const text of reconciled) {\n    lines.push(text);\n    lines.push('');\n  }\n\n  files.push({\n    path: 'enums.go',\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  });\n  const eventConstantsFile = generateEventConstantsFile(enums, ctx);\n  if (eventConstantsFile) files.push(eventConstantsFile);\n\n  return files;\n}\n\n/** Known acronyms to preserve as single tokens during humanization. */\nconst HUMANIZE_ACRONYMS: [RegExp, string][] = [\n  [/OAuth/g, 'OAUTH_ACRN'],\n  [/URN/g, 'URN_ACRN'],\n  [/IETF/g, 'IETF_ACRN'],\n  [/API/g, 'API_ACRN'],\n  [/SSO/g, 'SSO_ACRN'],\n  [/PKCE/g, 'PKCE_ACRN'],\n  [/JWT/g, 'JWT_ACRN'],\n  [/MFA/g, 'MFA_ACRN'],\n  [/TOTP/g, 'TOTP_ACRN'],\n  [/SAML/g, 'SAML_ACRN'],\n  [/SCIM/g, 'SCIM_ACRN'],\n  [/OIDC/g, 'OIDC_ACRN'],\n  [/CORS/g, 'CORS_ACRN'],\n  [/RBAC/g, 'RBAC_ACRN'],\n];\n\nconst HUMANIZE_RESTORE: [RegExp, string][] = [\n  [/oauth_acrn/g, 'OAuth'],\n  [/urn_acrn/g, 'URN'],\n  [/ietf_acrn/g, 'IETF'],\n  [/api_acrn/g, 'API'],\n  [/sso_acrn/g, 'SSO'],\n  [/pkce_acrn/g, 'PKCE'],\n  [/jwt_acrn/g, 'JWT'],\n  [/mfa_acrn/g, 'MFA'],\n  [/totp_acrn/g, 'TOTP'],\n  [/saml_acrn/g, 'SAML'],\n  [/scim_acrn/g, 'SCIM'],\n  [/oidc_acrn/g, 'OIDC'],\n  [/cors_acrn/g, 'CORS'],\n  [/rbac_acrn/g, 'RBAC'],\n];\n\nfunction humanize(name: string): string {\n  // Replace known acronyms with placeholders before splitting\n  let s = name;\n  for (const [pattern, replacement] of HUMANIZE_ACRONYMS) {\n    s = s.replace(pattern, replacement);\n  }\n  let result = s.replace(/([a-z])([A-Z])/g, '$1 $2');\n  result = result.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');\n  result = result.toLowerCase();\n  for (const [pattern, replacement] of HUMANIZE_RESTORE) {\n    result = result.replace(pattern, replacement);\n  }\n  return result;\n}\n\nfunction collectEnumAliasOf(enums: Enum[]): Map<string, string> {\n  const hashGroups = new Map<string, string[]>();\n  for (const enumDef of enums) {\n    const hash = [...enumDef.values]\n      .map((v) => String(v.value))\n      .sort()\n      .join('|');\n    if (!hashGroups.has(hash)) hashGroups.set(hash, []);\n    hashGroups.get(hash)!.push(enumDef.name);\n  }\n\n  const aliasOf = new Map<string, string>();\n  for (const [, names] of hashGroups) {\n    if (names.length <= 1) continue;\n    const sorted = [...names].sort();\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      aliasOf.set(sorted[i], canonical);\n    }\n  }\n  return aliasOf;\n}\n\nconst EVENTS_FILE_PATH = 'pkg/events/events.go';\n\nfunction generateEventConstantsFile(enums: Enum[], ctx: EmitterContext): GeneratedFile | null {\n  const enumDef = findWebhookEventEnum(enums);\n  if (!enumDef) return null;\n\n  // Scoped-run gate for the flat events file. Unlike models/enums, an event\n  // value can't be mapped to a single selected service, so there is no\n  // per-event \"in scope\" signal. The correct Option-B behavior is therefore to\n  // keep this aggregate byte-stable in a scoped run: emit only event constants\n  // that already existed in the prior events.go (dropping brand-new additions\n  // such as `session.reauthenticated` from an out-of-scope service) and never\n  // drop a constant that was present before. Equivalent to: in a scoped run,\n  // emit exactly the prior file's constant set.\n  let priorEventConsts: Set<string> | null = null;\n  if (isScopedRun(ctx)) {\n    const prior = readPriorFile(EVENTS_FILE_PATH, ctx);\n    if (prior !== null) {\n      priorEventConsts = collectPriorEventConstNames(prior);\n    }\n  }\n\n  const lines: string[] = [];\n  lines.push('package events');\n  lines.push('');\n  lines.push('// Event is a WorkOS event type.');\n  lines.push('type Event string');\n  lines.push('');\n  lines.push('const (');\n\n  const seenValues = new Set<string>();\n  const usedNames = new Set<string>();\n  for (const value of enumDef.values) {\n    const valueStr = String(value.value);\n    if (seenValues.has(valueStr)) continue;\n    seenValues.add(valueStr);\n\n    const constName = uniqueEventConstantName(valueStr, usedNames);\n\n    // Scoped run: skip a constant that wasn't in the prior file (a brand-new,\n    // out-of-scope event). When there's no prior file to compare against, fall\n    // through and emit everything (first generation / non-target run).\n    if (priorEventConsts !== null && !priorEventConsts.has(constName)) {\n      continue;\n    }\n    usedNames.add(constName);\n\n    if (value.description) {\n      lines.push(`\\t// ${constName} is ${value.description}.`);\n    }\n    if (value.deprecated) {\n      if (value.description) lines.push('\\t//');\n      lines.push('\\t// Deprecated: this value is deprecated.');\n    }\n    // Keep constants untyped so callers can use them as plain strings,\n    // events.Event values, or typed root-package enum values.\n    lines.push(`\\t${constName} = \"${escapeGoString(valueStr)}\"`);\n  }\n\n  lines.push(')');\n  lines.push('');\n\n  return {\n    path: EVENTS_FILE_PATH,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\n/**\n * Collect the constant names declared in a prior `pkg/events/events.go`. Each\n * event constant is emitted as `\\tConstName = \"wire.value\"` inside the single\n * `const (...)` block, so a simple line scan recovers the prior name set used\n * to keep the file byte-stable across scoped runs.\n */\nfunction collectPriorEventConstNames(content: string): Set<string> {\n  const names = new Set<string>();\n  for (const raw of content.split('\\n')) {\n    const m = raw.trim().match(/^(\\w+)\\s*=\\s*\"/);\n    if (m) names.add(m[1]);\n  }\n  return names;\n}\n\nfunction findWebhookEventEnum(enums: Enum[]): Enum | null {\n  return (\n    enums.find((enumDef) => enumDef.name === 'CreateWebhookEndpointEvents') ??\n    enums.find(\n      (enumDef) =>\n        isWebhookEventEnumName(enumDef.name) &&\n        enumDef.values.length > 0 &&\n        enumDef.values.every((value) => typeof value.value === 'string' && value.value.includes('.')),\n    ) ??\n    null\n  );\n}\n\nfunction isWebhookEventEnumName(name: string): boolean {\n  const normalized = name.toLowerCase();\n  return normalized.includes('webhook') && normalized.includes('event');\n}\n\nfunction uniqueEventConstantName(value: string, usedNames: Set<string>): string {\n  const base = className(value);\n  if (!usedNames.has(base)) return base;\n\n  let suffix = 2;\n  while (usedNames.has(`${base}${suffix}`)) suffix++;\n  return `${base}${suffix}`;\n}\n\nfunction escapeGoString(value: string): string {\n  return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\nexport function assignEnumsToServices(enums: Enum[], services: Service[]): Map<string, string> {\n  const enumToService = new Map<string, string>();\n  const enumNames = new Set(enums.map((e) => e.name));\n\n  for (const service of services) {\n    for (const op of service.operations) {\n      const refs = new Set<string>();\n      const collect = (ref: any) => {\n        walkTypeRef(ref, { enum: (r: any) => refs.add(r.name) });\n      };\n      if (op.requestBody) collect(op.requestBody);\n      collect(op.response);\n      for (const p of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n        collect(p.type);\n      }\n      for (const name of refs) {\n        if (enumNames.has(name) && !enumToService.has(name)) {\n          enumToService.set(name, service.name);\n        }\n      }\n    }\n  }\n\n  return enumToService;\n}\n","import type { EmitterContext, ResolvedOperation, ResolvedWrapper } from '@workos/oagen';\nimport {\n  className as goClassName,\n  fieldName as goFieldName,\n  methodName as goMethodName,\n  unexportedName,\n} from './naming.js';\nimport { sortPathParamsByTemplateOrder, paramsStructName } from './resources.js';\nimport { resolveWrapperParams, formatWrapperDescription, type ResolvedWrapperParam } from '../shared/wrapper-utils.js';\nimport { lowerFirstForDoc, fieldDocComment } from '../shared/naming-utils.js';\n\n/**\n * Generate Go wrapper method lines for union split operations.\n *\n * Each wrapper is a typed convenience method that:\n * - Accepts only the exposed params (not the full union body)\n * - Injects constant defaults (e.g., grant_type)\n * - Reads inferred fields from client config (e.g., client_id)\n * - Delegates to the HTTP client with the constructed body\n */\nexport function generateWrapperMethods(\n  serviceType: string,\n  mountName: string,\n  resolvedOp: ResolvedOperation,\n  ctx: EmitterContext,\n): string[] {\n  if (!resolvedOp.wrappers || resolvedOp.wrappers.length === 0) return [];\n\n  const lines: string[] = [];\n\n  for (const wrapper of resolvedOp.wrappers) {\n    const wrapperParams = resolveWrapperParams(wrapper, ctx);\n    lines.push('');\n    emitWrapperParamsStruct(lines, mountName, wrapper, wrapperParams);\n    lines.push('');\n    emitWrapperBodyStruct(lines, wrapper, wrapperParams);\n    lines.push('');\n    emitWrapperMethod(lines, serviceType, mountName, resolvedOp, wrapper, wrapperParams);\n  }\n\n  return lines;\n}\n\n/** Unexported struct name used as the typed JSON body for a wrapper method. */\nfunction wrapperBodyStructName(wrapper: ResolvedWrapper): string {\n  return `${unexportedName(goMethodName(wrapper.name))}Body`;\n}\n\n/**\n * Emit the private body struct used to serialize the JSON request for a\n * wrapper method. Fields come from: constant defaults, required exposed\n * params, client-inferred fields, and optional exposed params (in that\n * order to match how bodies are constructed at call sites).\n */\nfunction emitWrapperBodyStruct(lines: string[], wrapper: ResolvedWrapper, wrapperParams: ResolvedWrapperParam[]): void {\n  const structName = wrapperBodyStructName(wrapper);\n  lines.push(`// ${structName} is the JSON request body for ${goMethodName(wrapper.name)}.`);\n  lines.push(`type ${structName} struct {`);\n\n  // Constant defaults (always sent — no omitempty so the wire format is deterministic)\n  for (const [key, value] of Object.entries(wrapper.defaults)) {\n    const goField = goFieldName(key);\n    const goType = typeof value === 'boolean' ? 'bool' : typeof value === 'number' ? 'int' : 'string';\n    lines.push(`\\t${goField} ${goType} \\`json:\"${key}\"\\``);\n  }\n\n  // Required exposed params\n  for (const { paramName, field, isOptional } of wrapperParams) {\n    if (isOptional) continue;\n    const goField = goFieldName(paramName);\n    const goType = field ? resolveSimpleGoType(field.type) : 'string';\n    lines.push(`\\t${goField} ${goType} \\`json:\"${paramName}\"\\``);\n  }\n\n  // Inferred fields (from client config) — omit when empty\n  for (const inferred of wrapper.inferFromClient) {\n    const goField = goFieldName(inferred);\n    lines.push(`\\t${goField} string \\`json:\"${inferred},omitempty\"\\``);\n  }\n\n  // Optional exposed params\n  for (const { paramName, field, isOptional } of wrapperParams) {\n    if (!isOptional) continue;\n    const goField = goFieldName(paramName);\n    const baseType = field ? resolveSimpleGoType(field.type) : 'string';\n    const optType = baseType.startsWith('*') || baseType.startsWith('[]') ? baseType : `*${baseType}`;\n    lines.push(`\\t${goField} ${optType} \\`json:\"${paramName},omitempty\"\\``);\n  }\n\n  lines.push('}');\n}\n\nfunction emitWrapperParamsStruct(\n  lines: string[],\n  mountName: string,\n  wrapper: ResolvedWrapper,\n  wrapperParams: ResolvedWrapperParam[],\n): void {\n  const structName = paramsStructName(mountName, goMethodName(wrapper.name));\n\n  lines.push(`// ${structName} contains the parameters for ${goMethodName(wrapper.name)}.`);\n  lines.push(`type ${structName} struct {`);\n\n  for (const { paramName, field, isOptional } of wrapperParams) {\n    const goField = goFieldName(paramName);\n    const goType = field ? resolveSimpleGoType(field.type) : 'string';\n\n    if (field?.description) {\n      const fdLines = field.description.split('\\n').filter((l: string) => l.trim());\n      lines.push(`\\t// ${fieldDocComment(goField, fdLines[0])}`);\n      for (let i = 1; i < fdLines.length; i++) {\n        lines.push(`\\t// ${fdLines[i].trim()}`);\n      }\n    }\n    if (isOptional) {\n      const optType = goType.startsWith('*') || goType.startsWith('[]') ? goType : `*${goType}`;\n      lines.push(`\\t${goField} ${optType} \\`json:\"${paramName},omitempty\"\\``);\n    } else {\n      lines.push(`\\t${goField} ${goType} \\`json:\"${paramName}\"\\``);\n    }\n  }\n\n  lines.push('}');\n}\n\nfunction emitWrapperMethod(\n  lines: string[],\n  serviceType: string,\n  mountName: string,\n  resolvedOp: ResolvedOperation,\n  wrapper: ResolvedWrapper,\n  wrapperParams: ResolvedWrapperParam[],\n): void {\n  const op = resolvedOp.operation;\n  const method = goMethodName(wrapper.name);\n  const paramsStruct = paramsStructName(mountName, method);\n\n  // Return type\n  const responseType = wrapper.responseModelName ? goClassName(wrapper.responseModelName) : null;\n\n  // GoDoc\n  lines.push(`// ${method} ${formatWrapperDescription(wrapper.name)}.`);\n\n  // Signature\n  const sigParams: string[] = ['ctx context.Context'];\n\n  // Path params as positional args (sorted by template order)\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    sigParams.push(`${lowerFirstSafe(goFieldName(p.name))} ${resolveSimpleGoType(p.type)}`);\n  }\n\n  sigParams.push(`params *${paramsStruct}`);\n  sigParams.push('opts ...RequestOption');\n\n  if (responseType) {\n    lines.push(`func (s *${serviceType}) ${method}(${sigParams.join(', ')}) (*${responseType}, error) {`);\n  } else {\n    lines.push(`func (s *${serviceType}) ${method}(${sigParams.join(', ')}) error {`);\n  }\n\n  // Build typed body struct — defaults + required params set at literal,\n  // inferred + optional fields assigned after (conditional on presence).\n  const bodyType = wrapperBodyStructName(wrapper);\n  lines.push(`\\tbody := ${bodyType}{`);\n\n  // Constant defaults (e.g., grant_type)\n  for (const [key, value] of Object.entries(wrapper.defaults)) {\n    lines.push(`\\t\\t${goFieldName(key)}: ${goLiteral(value)},`);\n  }\n\n  // Required exposed params\n  for (const { paramName, isOptional } of wrapperParams) {\n    if (isOptional) continue;\n    const goField = goFieldName(paramName);\n    lines.push(`\\t\\t${goField}: params.${goField},`);\n  }\n\n  lines.push('\\t}');\n\n  // Inferred fields from client config — omitempty handles the unset case\n  for (const inferred of wrapper.inferFromClient) {\n    const goField = goFieldName(inferred);\n    lines.push(`\\tbody.${goField} = ${clientFieldExpression(inferred)}`);\n  }\n\n  // Optional exposed params copy through as pointers — encoding/json +\n  // omitempty will drop nil fields on the wire.\n  for (const { paramName, isOptional } of wrapperParams) {\n    if (!isOptional) continue;\n    const goField = goFieldName(paramName);\n    lines.push(`\\tbody.${goField} = params.${goField}`);\n  }\n\n  // Build path expression\n  let pathExpr: string;\n  if (op.pathParams.length > 0) {\n    let fmtStr = op.path;\n    const fmtArgs: string[] = [];\n    for (const p of sortPathParamsByTemplateOrder(op)) {\n      fmtStr = fmtStr.replace(`{${p.name}}`, '%s');\n      fmtArgs.push(`url.PathEscape(string(${lowerFirstSafe(goFieldName(p.name))}))`);\n    }\n    pathExpr = `fmt.Sprintf(\"${fmtStr}\", ${fmtArgs.join(', ')})`;\n  } else {\n    pathExpr = `\"${op.path}\"`;\n  }\n\n  // Make the request\n  if (responseType) {\n    lines.push(`\\tvar result ${responseType}`);\n    lines.push(\n      `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, nil, body, &result, opts)`,\n    );\n    lines.push('\\tif err != nil {');\n    lines.push('\\t\\treturn nil, err');\n    lines.push('\\t}');\n    lines.push('\\treturn &result, nil');\n  } else {\n    lines.push(\n      `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, nil, body, nil, opts)`,\n    );\n    lines.push('\\treturn err');\n  }\n\n  lines.push('}');\n}\n\n/** Convert a value to a Go literal. */\nfunction goLiteral(value: string | number | boolean): string {\n  if (typeof value === 'string') return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  return String(value);\n}\n\n/** Get the Go expression for reading a client config field. */\nfunction clientFieldExpression(field: string): string {\n  switch (field) {\n    case 'client_id':\n      return 's.client.clientID';\n    case 'client_secret':\n      return 's.client.apiKey';\n    default:\n      return `s.client.${lowerFirstSafe(goFieldName(field))}`;\n  }\n}\n\n/** Resolve a TypeRef to a simple Go type string. */\nfunction resolveSimpleGoType(ref: any): string {\n  if (ref.kind === 'primitive') {\n    switch (ref.type) {\n      case 'string':\n        return 'string';\n      case 'integer':\n        return 'int';\n      case 'number':\n        return 'float64';\n      case 'boolean':\n        return 'bool';\n      default:\n        return 'interface{}';\n    }\n  }\n  if (ref.kind === 'nullable') {\n    const inner = resolveSimpleGoType(ref.inner);\n    // Slices, maps, and pointer types don't get pointer-wrapped (mirrors type-map.ts).\n    if (inner.startsWith('*') || inner.startsWith('[]') || inner.startsWith('map[')) return inner;\n    return `*${inner}`;\n  }\n  if (ref.kind === 'array') return `[]${resolveSimpleGoType(ref.items)}`;\n  if (ref.kind === 'model') return `*${goClassName(ref.name)}`;\n  if (ref.kind === 'enum') return goClassName(ref.name);\n  if (ref.kind === 'union') {\n    // For oneOf with a single non-null variant, use that variant's type\n    const nonNull = ref.variants.filter((v: any) => v.kind !== 'literal' || v.value !== null);\n    if (nonNull.length === 1) return resolveSimpleGoType(nonNull[0]);\n    return 'interface{}';\n  }\n  return 'interface{}';\n}\n\n/** Go reserved words set. */\nconst GO_RESERVED = new Set([\n  'break',\n  'case',\n  'chan',\n  'const',\n  'continue',\n  'default',\n  'defer',\n  'else',\n  'fallthrough',\n  'for',\n  'func',\n  'go',\n  'goto',\n  'if',\n  'import',\n  'interface',\n  'map',\n  'package',\n  'range',\n  'return',\n  'select',\n  'struct',\n  'switch',\n  'type',\n  'var',\n]);\n\nfunction lowerFirstSafe(s: string): string {\n  if (!s) return s;\n  const result = unexportedName(s);\n  if (GO_RESERVED.has(result)) return `${result}Param`;\n  return result;\n}\n\nfunction _lowerFirstField(s: string): string {\n  return lowerFirstForDoc(s);\n}\n","import type {\n  Service,\n  Operation,\n  OperationPlan,\n  EmitterContext,\n  GeneratedFile,\n  ResolvedOperation,\n} from '@workos/oagen';\nimport { planOperation, toSnakeCase } from '@workos/oagen';\nimport { isListWrapperModel } from './models.js';\nimport { mapTypeRef, mapTypeRefValue } from './type-map.js';\nimport {\n  className,\n  domainFieldName,\n  fieldName,\n  methodName,\n  resolveClassName,\n  resolveMethodName,\n  unexportedName,\n} from './naming.js';\nimport {\n  buildResolvedLookup,\n  lookupResolved,\n  scopedMountGroups,\n  getOpDefaults,\n  getOpInferFromClient,\n  buildHiddenParams,\n  hasHiddenParams,\n  collectGroupedParamNames,\n  collectBodyFieldTypes,\n} from '../shared/resolved-ops.js';\nimport { lowerFirstForDoc, fieldDocComment } from '../shared/naming-utils.js';\nimport { generateWrapperMethods } from './wrappers.js';\n\n/**\n * Return path params sorted by their first occurrence in the URL template.\n * This ensures fmt.Sprintf args and function signatures match template order.\n */\nexport function sortPathParamsByTemplateOrder(op: Operation): typeof op.pathParams {\n  return [...op.pathParams].sort((a, b) => {\n    const posA = op.path.indexOf(`{${a.name}}`);\n    const posB = op.path.indexOf(`{${b.name}}`);\n    return posA - posB;\n  });\n}\n\n/**\n * Resolve the resource class name for a service.\n */\nexport function resolveResourceClassName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n/**\n * Generate Go resource/service files from IR Service definitions.\n * Each mount group becomes a single .go file with an unexported service struct\n * and exported methods.\n */\nexport function generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n  if (services.length === 0) return [];\n\n  const files: GeneratedFile[] = [];\n  const mountGroups = scopedMountGroups(ctx);\n\n  // If no resolved operations, fall back to raw services\n  const entries: Array<{ name: string; operations: Operation[] }> =\n    mountGroups.size > 0 || ctx.scopedServices?.size\n      ? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations }))\n      : services.map((s) => ({ name: resolveResourceClassName(s, ctx), operations: s.operations }));\n\n  for (const { name: mountName, operations } of entries) {\n    if (operations.length === 0) continue;\n    const file = generateServiceFile(mountName, operations, ctx);\n    if (file) files.push(file);\n  }\n\n  return files;\n}\n\nfunction generateServiceFile(mountName: string, operations: Operation[], ctx: EmitterContext): GeneratedFile | null {\n  const lines: string[] = [];\n  const serviceType = serviceTypeName(mountName);\n  const goFile = `${toSnakeCase(mountName)}.go`;\n\n  // Build resolved lookup once for the whole file\n  const resolvedLookup = buildResolvedLookup(ctx);\n\n  // Determine which imports are needed\n  const needsFmt = operations.some((op) => op.pathParams.length > 0);\n  const needsNetUrl = operations.some((op) => {\n    if (op.pathParams.length > 0) return true;\n    const resolved = lookupResolved(op, resolvedLookup);\n    if (resolved?.urlBuilder) return true;\n    if (resolved && hasHiddenParams(resolved) && op.httpMethod.toLowerCase() === 'get') return true;\n    if ((op.parameterGroups?.length ?? 0) > 0) return true;\n    return false;\n  });\n  const needsStrings = needsStringsImport(operations, resolvedLookup);\n  const needsJson = operations.some((op) => hasBodyGroups(op));\n  // context is needed only for methods that make HTTP calls. URL-builder ops\n  // don't take ctx, so a file that contains *only* URL builders would have\n  // an unused import.\n  const needsContext = operations.some((op) => {\n    const resolved = lookupResolved(op, resolvedLookup);\n    return !resolved?.urlBuilder;\n  });\n\n  lines.push(`package ${ctx.namespace}`);\n  lines.push('');\n  lines.push('import (');\n  if (needsContext) {\n    lines.push('\\t\"context\"');\n  }\n  if (needsJson) {\n    lines.push('\\t\"encoding/json\"');\n  }\n  if (needsFmt) {\n    lines.push('\\t\"fmt\"');\n  }\n  if (needsNetUrl) {\n    lines.push('\\t\"net/url\"');\n  }\n  if (needsStrings) {\n    lines.push('\\t\"strings\"');\n  }\n  lines.push(')');\n  lines.push('');\n\n  // Service struct\n  lines.push(`// ${serviceType} handles ${mountName} operations.`);\n  lines.push(`type ${serviceType} struct {`);\n  lines.push('\\tclient *Client');\n  lines.push('}');\n  lines.push('');\n\n  // Pre-collect all parameter groups across operations and emit deduplicated\n  // type definitions. A group with the same name may appear in both query-param\n  // and body-param contexts; the interface then carries both applyToQuery and\n  // applyToBody methods.\n  const groupTypes = collectFileGroups(mountName, operations);\n  if (groupTypes.length > 0) {\n    // Collect body field types from all operations so variant structs use the\n    // correct IR types (the parser's group-level types can fall back to string).\n    const mergedBodyFieldTypes = new Map<string, import('@workos/oagen').TypeRef>();\n    for (const op of operations) {\n      for (const [k, v] of collectBodyFieldTypes(op, ctx.spec.models)) {\n        mergedBodyFieldTypes.set(k, v);\n      }\n    }\n    lines.push(emitCollectedGroupTypes(mountName, groupTypes, mergedBodyFieldTypes));\n  }\n\n  // Generate params structs and methods for each operation.\n  // Deduplicate by method name -- multiple IR operations can resolve to the same\n  // Go method name when mounted from different IR services.\n  const emittedMethods = new Set<string>();\n  for (const op of operations) {\n    const plan = planOperation(op);\n    const method = resolveGoMethodName(op, mountName, ctx);\n\n    if (emittedMethods.has(method)) continue;\n    emittedMethods.add(method);\n\n    const resolvedOp = lookupResolved(op, resolvedLookup);\n    const hasWrappers = (resolvedOp?.wrappers?.length ?? 0) > 0;\n\n    // When wrappers exist (union-body operations like Authenticate), only\n    // the typed per-variant wrapper methods are emitted. The parent method\n    // would otherwise carry `Body interface{}` and defeat type safety.\n    if (!hasWrappers) {\n      const paramsStruct = generateParamsStruct(mountName, method, op, plan, ctx, resolvedOp);\n      if (paramsStruct) {\n        lines.push(paramsStruct);\n        lines.push('');\n      }\n\n      const methodCode = generateMethod(serviceType, mountName, method, op, plan, ctx, resolvedOp);\n      lines.push(methodCode);\n      lines.push('');\n    }\n\n    // Generate union split wrapper methods (e.g., AuthenticateWithPassword)\n    if (hasWrappers && resolvedOp) {\n      const wrapperLines = generateWrapperMethods(serviceType, mountName, resolvedOp, ctx);\n      lines.push(...wrapperLines);\n      for (const w of resolvedOp.wrappers!) {\n        emittedMethods.add(methodName(w.name));\n      }\n    }\n  }\n\n  return {\n    path: goFile,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\nfunction resolveGoMethodName(op: Operation, mountName: string, ctx: EmitterContext): string {\n  return resolveMethodName(op, { name: mountName, operations: [op] }, ctx);\n}\n\nexport function paramsStructName(mountName: string, method: string): string {\n  // Prefix with mount name to avoid cross-file collisions in flat package\n  const prefix = className(mountName);\n  // If method already starts with the mount name, don't double-prefix\n  if (method.startsWith(prefix)) return `${method}Params`;\n  return `${prefix}${method}Params`;\n}\n\n/**\n * Unexported struct name used as the typed JSON body for a non-wrapper\n * operation that has hidden params (defaults / inferFromClient). Mirrors\n * the wrapper convention (`<methodLowerCamel>Body`).\n */\nfunction hiddenParamsBodyStructName(method: string): string {\n  return `${unexportedName(method)}Body`;\n}\n\n// ---------------------------------------------------------------------------\n// Mutually-exclusive parameter group support\n// ---------------------------------------------------------------------------\n\n/** Check whether an operation has any body-level parameter groups. */\nfunction hasBodyGroups(op: Operation): boolean {\n  return (op.parameterGroups ?? []).some((g) => isBodyGroup(g, op));\n}\n\n/**\n * Check whether a parameter group targets the request body (rather than query params).\n * Body groups' parameter names don't appear in op.queryParams — they come from\n * the body model's oneOf variants.\n */\nfunction isBodyGroup(group: import('@workos/oagen').ParameterGroup, op: Operation): boolean {\n  const queryNames = new Set(op.queryParams.map((qp) => qp.name));\n  // If none of the group's variant params appear in queryParams, it's a body group\n  return group.variants.every((v) => v.parameters.every((p) => !queryNames.has(p.name)));\n}\n\n/** Interface type name for a parameter group (e.g. AuthorizationParentResource). */\nfunction groupInterfaceName(mountName: string, groupName: string): string {\n  return `${className(mountName)}${fieldName(groupName)}`;\n}\n\n/** Variant struct type name (e.g. AuthorizationParentResourceRefByID). */\nfunction groupVariantTypeName(mountName: string, groupName: string, variantName: string): string {\n  return `${groupInterfaceName(mountName, groupName)}${fieldName(variantName)}`;\n}\n\n/**\n * Derive a short field name for a parameter within a variant struct.\n * Strips the group name prefix when present to avoid stuttering\n * (e.g. parent_resource_id in group parent_resource -> ID).\n */\nfunction deriveVariantFieldName(paramName: string, groupName: string): string {\n  const prefix = groupName + '_';\n  const stripped = paramName.startsWith(prefix) ? paramName.slice(prefix.length) : paramName;\n  return fieldName(stripped);\n}\n\n/** Collected group metadata, merged across all operations in a file. */\ninterface CollectedGroup {\n  name: string;\n  needsQuery: boolean;\n  needsBody: boolean;\n  /** Use the first variant set encountered (they should be identical). */\n  variants: import('@workos/oagen').ParameterGroupVariant[];\n}\n\n/**\n * Pre-collect all parameter groups across operations in a mount group,\n * deduplicating by group name and merging query/body usage flags.\n */\nfunction collectFileGroups(mountName: string, operations: Operation[]): CollectedGroup[] {\n  const byName = new Map<string, CollectedGroup>();\n\n  for (const op of operations) {\n    for (const group of op.parameterGroups ?? []) {\n      const existing = byName.get(group.name);\n      const isBody = isBodyGroup(group, op);\n      if (existing) {\n        if (isBody) existing.needsBody = true;\n        else existing.needsQuery = true;\n      } else {\n        byName.set(group.name, {\n          name: group.name,\n          needsQuery: !isBody,\n          needsBody: isBody,\n          variants: group.variants,\n        });\n      }\n    }\n  }\n\n  return [...byName.values()];\n}\n\n/**\n * Emit deduplicated Go interface and variant struct definitions for all\n * collected parameter groups in a file. Groups used in query contexts get\n * applyToQuery; body contexts get applyToBody; groups used in both get both.\n */\nfunction emitCollectedGroupTypes(\n  mountName: string,\n  groups: CollectedGroup[],\n  bodyFieldTypes: Map<string, import('@workos/oagen').TypeRef>,\n): string {\n  const lines: string[] = [];\n\n  for (const group of groups) {\n    const ifaceName = groupInterfaceName(mountName, group.name);\n    const markerMethod = `is${ifaceName}`;\n\n    const variantNames = group.variants.map((v) => groupVariantTypeName(mountName, group.name, v.name));\n    lines.push(`// ${ifaceName} is one of:`);\n    for (const vn of variantNames) {\n      lines.push(`//   - ${vn}`);\n    }\n    lines.push(`type ${ifaceName} interface {`);\n    lines.push(`\\t${markerMethod}()`);\n    if (group.needsQuery) {\n      lines.push('\\tapplyToQuery(url.Values)');\n    }\n    if (group.needsBody) {\n      lines.push('\\tapplyToBody(map[string]any)');\n    }\n    lines.push('}');\n    lines.push('');\n\n    for (const variant of group.variants) {\n      const typeName = groupVariantTypeName(mountName, group.name, variant.name);\n\n      lines.push(`type ${typeName} struct {`);\n      for (const param of variant.parameters) {\n        const goField = deriveVariantFieldName(param.name, group.name);\n        const effectiveType = bodyFieldTypes.get(param.name) ?? param.type;\n        const goType = mapTypeRefValue(effectiveType);\n        lines.push(`\\t${goField} ${goType}`);\n      }\n      lines.push('}');\n      lines.push('');\n\n      lines.push(`func (p ${typeName}) ${markerMethod}() {}`);\n\n      if (group.needsQuery) {\n        lines.push(`func (p ${typeName}) applyToQuery(v url.Values) {`);\n        for (const param of variant.parameters) {\n          const goField = deriveVariantFieldName(param.name, group.name);\n          lines.push(`\\tv.Set(\"${param.name}\", ${formatQueryValue(`p.${goField}`, param.type)})`);\n        }\n        lines.push('}');\n      }\n\n      if (group.needsBody) {\n        lines.push(`func (p ${typeName}) applyToBody(m map[string]any) {`);\n        for (const param of variant.parameters) {\n          const goField = deriveVariantFieldName(param.name, group.name);\n          lines.push(`\\tm[\"${param.name}\"] = p.${goField}`);\n        }\n        lines.push('}');\n      }\n\n      lines.push('');\n    }\n  }\n\n  return lines.join('\\n');\n}\n\nfunction generateParamsStruct(\n  mountName: string,\n  method: string,\n  op: Operation,\n  plan: OperationPlan,\n  ctx: EmitterContext,\n  resolvedOp?: ResolvedOperation,\n): string | null {\n  // Build set of hidden param names (defaults + inferFromClient)\n  const hidden = buildHiddenParams(resolvedOp);\n  const groupedParams = collectGroupedParamNames(op);\n  const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n\n  const hasQueryParams = op.queryParams.filter((qp) => !hidden.has(qp.name) && !groupedParams.has(qp.name)).length > 0;\n  const hasBody = plan.hasBody && op.requestBody;\n\n  // Check if body has any visible fields after filtering (excluding grouped fields)\n  let hasVisibleBodyFields = false;\n  if (hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) {\n      hasVisibleBodyFields = bodyModel.fields.some((f) => !hidden.has(f.name) && !groupedParams.has(f.name));\n    }\n  } else if (hasBody) {\n    hasVisibleBodyFields = true; // non-model body always visible\n  }\n\n  if (!hasQueryParams && !hasVisibleBodyFields && !hasGroups) return null;\n\n  const lines: string[] = [];\n  const structName = paramsStructName(mountName, method);\n\n  lines.push(`// ${structName} contains the parameters for ${method}.`);\n  lines.push(`type ${structName} struct {`);\n\n  // Track emitted field names to avoid duplicates\n  const emittedFields = new Set<string>();\n\n  // Body fields (if body is a model)\n  if (hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) {\n      for (const field of bodyModel.fields) {\n        if (hidden.has(field.name)) continue;\n        if (groupedParams.has(field.name)) continue;\n        // Domain struct field; the json tag below keeps deriving from field.name.\n        const goField = domainFieldName(field);\n        if (emittedFields.has(goField)) continue;\n        emittedFields.add(goField);\n        const isOptional = !field.required;\n        const goType = isOptional ? makeOptional(mapTypeRef(field.type)) : mapTypeRef(field.type);\n        const jsonTag = field.required ? `json:\"${field.name}\"` : `json:\"${field.name},omitempty\"`;\n        // Body fields are JSON-marshaled into the request body. Emit `url:\"-\"`\n        // so go-querystring's default field-name fallback doesn't also place\n        // them in the URL — important when the spec duplicates a field as both\n        // body and query param (e.g. /sso/token's `code`).\n        const urlTag = ' url:\"-\"';\n        if (field.description) {\n          const fdLines = field.description.split('\\n').filter((l) => l.trim());\n          lines.push(`\\t// ${fieldDocComment(goField, fdLines[0])}`);\n          for (let i = 1; i < fdLines.length; i++) {\n            lines.push(`\\t// ${fdLines[i].trim()}`);\n          }\n        }\n        if (field.deprecated) {\n          if (field.description) lines.push(`\\t//`);\n          lines.push(`\\t// Deprecated: this field is deprecated.`);\n        }\n        lines.push(`\\t${goField} ${goType} \\`${jsonTag}${urlTag}\\``);\n      }\n    }\n  } else if (hasBody) {\n    // Non-model body (generic)\n    lines.push('\\tBody interface{} `json:\"-\"`');\n  }\n\n  // Check if this is a list operation with standard pagination fields.\n  // If so, embed PaginationParams and skip those fields individually.\n  const PAGINATION_FIELDS = new Set(['before', 'after', 'limit', 'order']);\n  const visibleQueryParams = op.queryParams.filter((qp) => !hidden.has(qp.name) && !groupedParams.has(qp.name));\n  const hasPaginationFields = ['before', 'after', 'limit'].every((name) =>\n    visibleQueryParams.some((qp) => qp.name === name),\n  );\n  if (hasPaginationFields) {\n    lines.push('\\tPaginationParams');\n  }\n\n  // Query params (skip any already emitted from body fields, hidden params, grouped params, and pagination fields)\n  for (const param of op.queryParams) {\n    if (hidden.has(param.name)) continue;\n    if (groupedParams.has(param.name)) continue;\n    if (hasPaginationFields && PAGINATION_FIELDS.has(param.name)) continue;\n    const goField = fieldName(param.name);\n    if (emittedFields.has(goField)) continue;\n    emittedFields.add(goField);\n    const isOptional = !param.required;\n    const paramType = mapQueryParamType(param.name, param.type);\n    const goType = isOptional ? makeOptional(paramType) : paramType;\n    const urlTag = param.required ? `url:\"${param.name}\"` : `url:\"${param.name},omitempty\"`;\n    const jsonTag = 'json:\"-\"';\n    if (param.description) {\n      const pdLines = param.description.split('\\n').filter((l) => l.trim());\n      lines.push(`\\t// ${fieldDocComment(goField, pdLines[0])}`);\n      for (let i = 1; i < pdLines.length; i++) {\n        lines.push(`\\t// ${pdLines[i].trim()}`);\n      }\n    }\n    if (param.default != null) {\n      const defaultLine = `\\t// Defaults to ${JSON.stringify(param.default)}.`;\n      if (!param.description) lines.push(defaultLine);\n      else lines.push(defaultLine);\n    }\n    if (param.deprecated) {\n      if (param.description || param.default != null) lines.push(`\\t//`);\n      lines.push(`\\t// Deprecated: this parameter is deprecated.`);\n    }\n    lines.push(`\\t${goField} ${goType} \\`${urlTag} ${jsonTag}\\``);\n  }\n\n  // Parameter group fields (sum-type interfaces, serialized via applyToQuery)\n  for (const group of op.parameterGroups ?? []) {\n    const goField = fieldName(group.name);\n    const goType = groupInterfaceName(mountName, group.name);\n    if (group.optional) {\n      lines.push(`\\t// ${goField} optionally identifies the ${group.name.replace(/_/g, ' ')}.`);\n    } else {\n      lines.push(`\\t// ${goField} identifies the ${group.name.replace(/_/g, ' ')} (required).`);\n    }\n    lines.push(`\\t${goField} ${goType} \\`url:\"-\" json:\"-\"\\``);\n  }\n\n  lines.push('}');\n\n  // Generate MarshalJSON for params structs that have body-level groups.\n  // The method uses a type alias to marshal non-group fields, then merges\n  // the active group variant's fields into the JSON map.\n  const bodyGroupList = (op.parameterGroups ?? []).filter((g) => isBodyGroup(g, op));\n  if (bodyGroupList.length > 0) {\n    lines.push('');\n    lines.push(`// MarshalJSON implements json.Marshaler for ${structName}.`);\n    lines.push(`func (p ${structName}) MarshalJSON() ([]byte, error) {`);\n    lines.push(`\\ttype Alias ${structName}`);\n    lines.push('\\tdata, err := json.Marshal(Alias(p))');\n    lines.push('\\tif err != nil {');\n    lines.push('\\t\\treturn nil, err');\n    lines.push('\\t}');\n    // Check if any group is non-nil; if not, return early\n    const allNilCheck = bodyGroupList.map((g) => `p.${fieldName(g.name)} == nil`).join(' && ');\n    lines.push(`\\tif ${allNilCheck} {`);\n    lines.push('\\t\\treturn data, nil');\n    lines.push('\\t}');\n    lines.push('\\tvar m map[string]any');\n    lines.push('\\tif err := json.Unmarshal(data, &m); err != nil {');\n    lines.push('\\t\\treturn nil, err');\n    lines.push('\\t}');\n    for (const group of bodyGroupList) {\n      const goField = fieldName(group.name);\n      lines.push(`\\tif p.${goField} != nil {`);\n      lines.push(`\\t\\tp.${goField}.applyToBody(m)`);\n      lines.push('\\t}');\n    }\n    lines.push('\\treturn json.Marshal(m)');\n    lines.push('}');\n  }\n\n  return lines.join('\\n');\n}\n\nfunction generateMethod(\n  serviceType: string,\n  mountName: string,\n  method: string,\n  op: Operation,\n  plan: OperationPlan,\n  _ctx: EmitterContext,\n  resolvedOp?: ResolvedOperation,\n): string {\n  const lines: string[] = [];\n  const isPaginated = plan.isPaginated;\n  const isDelete = plan.isDelete;\n  const hasBody = plan.hasBody && op.requestBody;\n  const hidden = buildHiddenParams(resolvedOp);\n  const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n  const hasVisibleQueryParams = op.queryParams.filter((qp) => !hidden.has(qp.name)).length > 0;\n\n  // Check if body has visible fields after filtering hidden params and grouped params\n  const groupedParams = collectGroupedParamNames(op);\n  let hasVisibleBodyFields = false;\n  if (hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = _ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) {\n      hasVisibleBodyFields = bodyModel.fields.some((f) => !hidden.has(f.name) && !groupedParams.has(f.name));\n    }\n  } else if (hasBody) {\n    hasVisibleBodyFields = true;\n  }\n\n  const hasParams = hasVisibleBodyFields || hasVisibleQueryParams || hasGroups;\n  const paramsType = hasParams ? `*${paramsStructName(mountName, method)}` : null;\n  const bodyArg = hasBody && hasParams ? bodyArgument(op) : 'nil';\n  const hasHidden = hasHiddenParams(resolvedOp);\n  const isGet = op.httpMethod.toLowerCase() === 'get';\n  const isUrlBuilder = resolvedOp?.urlBuilder ?? false;\n\n  // Detect if response is a raw array (not paginated)\n  const isArrayResponse = !isPaginated && op.response?.kind === 'array';\n\n  // Emit a typed body struct *before* the method for non-GET ops with hidden\n  // params (defaults / inferFromClient). The struct gives consumers a\n  // deterministic wire format and avoids `map[string]interface{}` literals.\n  if (hasHidden && !isGet && hasBody) {\n    emitHiddenParamsBodyStruct(lines, method, op, _ctx, resolvedOp!);\n    lines.push('');\n  }\n\n  // Return type\n  let returnType: string;\n  if (isUrlBuilder) {\n    returnType = 'string';\n  } else if (isPaginated && op.pagination) {\n    const itemType = resolveIteratorItemType(op.pagination.itemType, _ctx);\n    returnType = `*Iterator[${itemType}]`;\n  } else if (isDelete) {\n    returnType = 'error';\n  } else if (plan.responseModelName) {\n    const respType = className(plan.responseModelName);\n    if (isArrayResponse) {\n      returnType = `([]${respType}, error)`;\n    } else {\n      returnType = `(*${respType}, error)`;\n    }\n  } else {\n    returnType = 'error';\n  }\n\n  // Build godoc -- wrap multi-line descriptions in // comments\n  if (op.description) {\n    const descLines = op.description.split('\\n').filter((l) => l.trim());\n    lines.push(`// ${godocSummary(method, descLines[0])}`);\n    for (let i = 1; i < descLines.length; i++) {\n      lines.push(`// ${descLines[i].trim()}`);\n    }\n  }\n  for (const p of op.pathParams) {\n    if (p.deprecated) {\n      lines.push(`//`);\n      lines.push(`// Deprecated parameter ${fieldName(p.name)}${p.description ? ': ' + p.description : '.'}`);\n    }\n  }\n  if (op.deprecated) {\n    lines.push(`//`);\n    lines.push(`// Deprecated: this operation is deprecated.`);\n  }\n\n  // Method signature — URL builders don't take ctx (no I/O) and return a string.\n  const params: string[] = isUrlBuilder ? [] : ['ctx context.Context'];\n  // Path params as positional args (sorted by template order)\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    params.push(`${lowerFirst(fieldName(p.name))} ${mapTypeRefValue(p.type)}`);\n  }\n  if (paramsType) {\n    params.push(`params ${paramsType}`);\n  }\n  params.push('opts ...RequestOption');\n\n  lines.push(`func (s *${serviceType}) ${method}(${params.join(', ')}) ${returnType} {`);\n\n  // Build path\n  const pathExpr = buildPathExpr(op);\n\n  // URL-builder ops construct the URL client-side and return it without\n  // performing any HTTP I/O.\n  if (isUrlBuilder) {\n    emitUrlBuilderMethod(lines, op, pathExpr, resolvedOp!, paramsType);\n    lines.push('}');\n    return lines.join('\\n');\n  }\n\n  // For GET operations with hidden params or parameter groups, build query\n  // via url.Values so we can inject defaults, inferred values, and/or call\n  // applyToQuery on grouped parameter variants.\n  if ((hasHidden || hasGroups) && isGet) {\n    emitGetWithHiddenParams(\n      lines,\n      op,\n      pathExpr,\n      plan,\n      _ctx,\n      resolvedOp!,\n      paramsType,\n      isPaginated,\n      isDelete,\n      isArrayResponse,\n    );\n  } else if (hasHidden && !isGet && hasBody) {\n    // For non-GET operations with hidden params, build a typed body struct\n    emitBodyWithHiddenParams(\n      lines,\n      op,\n      pathExpr,\n      plan,\n      _ctx,\n      resolvedOp!,\n      paramsType,\n      isPaginated,\n      isDelete,\n      isArrayResponse,\n      method,\n    );\n  } else if (isPaginated && op.pagination) {\n    const itemType = resolveIteratorItemType(op.pagination.itemType, _ctx);\n    const dataPath = op.pagination.dataPath ? `\"${op.pagination.dataPath}\"` : `\"data\"`;\n    const cursorParam = '\"after\"';\n    lines.push(\n      `\\treturn newIterator[${itemType}](ctx, s.client, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, ${hasVisibleQueryParams ? 'params' : 'nil'}, ${cursorParam}, ${dataPath}, opts, ${paginationDefaultsLiteral(op)})`,\n    );\n  } else if (isDelete) {\n    lines.push(\n      `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, ${hasVisibleQueryParams ? 'params' : 'nil'}, ${bodyArg}, nil, opts)`,\n    );\n    lines.push('\\treturn err');\n  } else if (plan.responseModelName) {\n    const respType = className(plan.responseModelName);\n    if (isArrayResponse) {\n      lines.push(`\\tvar result []${respType}`);\n      lines.push(\n        `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, ${hasVisibleQueryParams ? 'params' : 'nil'}, ${bodyArg}, &result, opts)`,\n      );\n      lines.push('\\tif err != nil {');\n      lines.push('\\t\\treturn nil, err');\n      lines.push('\\t}');\n      lines.push('\\treturn result, nil');\n    } else {\n      lines.push(`\\tvar result ${respType}`);\n      lines.push(\n        `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, ${hasVisibleQueryParams ? 'params' : 'nil'}, ${bodyArg}, &result, opts)`,\n      );\n      lines.push('\\tif err != nil {');\n      lines.push('\\t\\treturn nil, err');\n      lines.push('\\t}');\n      lines.push('\\treturn &result, nil');\n    }\n  } else {\n    lines.push(\n      `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, ${hasVisibleQueryParams ? 'params' : 'nil'}, ${bodyArg}, nil, opts)`,\n    );\n    lines.push('\\treturn err');\n  }\n\n  lines.push('}');\n  return lines.join('\\n');\n}\n\n// buildHiddenParams and hasHiddenParams are imported from ../shared/resolved-ops.js\n\n/** Convert a JS value to a Go literal. */\nfunction goLiteral(value: string | number | boolean): string {\n  if (typeof value === 'string') return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  return String(value);\n}\n\n/** Get the Go expression for reading a client config field. */\nfunction clientFieldExpression(field: string): string {\n  switch (field) {\n    case 'client_id':\n      return 's.client.clientID';\n    case 'client_secret':\n      return 's.client.apiKey';\n    default:\n      return `s.client.${lowerFirst(fieldName(field))}`;\n  }\n}\n\n/**\n * Emit method body for GET operations that have hidden params (defaults/inferFromClient).\n * Builds a url.Values manually so we can inject hidden values alongside user-provided query params.\n */\nfunction emitGetWithHiddenParams(\n  lines: string[],\n  op: Operation,\n  pathExpr: string,\n  plan: OperationPlan,\n  ctx: EmitterContext,\n  resolvedOp: ResolvedOperation,\n  paramsType: string | null,\n  isPaginated: boolean,\n  isDelete: boolean,\n  isArrayResponse: boolean,\n): void {\n  const hidden = buildHiddenParams(resolvedOp);\n\n  // Build url.Values with hidden + user-provided params\n  lines.push('\\tquery := url.Values{}');\n\n  // Inject constant defaults\n  for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n    lines.push(`\\tquery.Set(\"${key}\", ${goLiteralForQuery(value as string | number | boolean)})`);\n  }\n\n  // Inject inferred fields from client config\n  for (const field of getOpInferFromClient(resolvedOp)) {\n    const expr = clientFieldExpression(field);\n    lines.push(`\\tif ${expr} != \"\" {`);\n    lines.push(`\\t\\tquery.Set(\"${field}\", ${expr})`);\n    lines.push('\\t}');\n  }\n\n  // Add user-provided query params from the struct (excluding grouped params\n  // which are serialized via their variant's applyToQuery method)\n  if (paramsType) {\n    const groupedParamNames = collectGroupedParamNames(op);\n    const visibleQueryParams = op.queryParams.filter((qp) => !hidden.has(qp.name) && !groupedParamNames.has(qp.name));\n    for (const param of visibleQueryParams) {\n      const goField = fieldName(param.name);\n      const isMap = param.type.kind === 'map';\n      if (isMap) {\n        // Maps use bracket encoding: param[key]=value\n        if (param.required) {\n          lines.push(`\\tfor k, v := range params.${goField} {`);\n          lines.push(`\\t\\tquery.Set(fmt.Sprintf(\"${param.name}[%s]\", k), fmt.Sprintf(\"%v\", v))`);\n          lines.push('\\t}');\n        } else {\n          lines.push(`\\tif params.${goField} != nil {`);\n          lines.push(`\\t\\tfor k, v := range params.${goField} {`);\n          lines.push(`\\t\\t\\tquery.Set(fmt.Sprintf(\"${param.name}[%s]\", k), fmt.Sprintf(\"%v\", v))`);\n          lines.push('\\t\\t}');\n          lines.push('\\t}');\n        }\n      } else if (param.required) {\n        lines.push(`\\tquery.Set(\"${param.name}\", ${formatQueryValue(`params.${goField}`, param.type)})`);\n      } else {\n        // Slices are reference types in Go -- nil-able without pointer wrapping\n        const isRefType = param.type.kind === 'array';\n        const valueExpr = isRefType ? `params.${goField}` : `*params.${goField}`;\n        lines.push(`\\tif params.${goField} != nil {`);\n        lines.push(`\\t\\tquery.Set(\"${param.name}\", ${formatQueryValue(valueExpr, param.type)})`);\n        lines.push('\\t}');\n      }\n    }\n\n    // Apply parameter group variants to the query via applyToQuery\n    for (const group of op.parameterGroups ?? []) {\n      const goField = fieldName(group.name);\n      lines.push(`\\tif params.${goField} != nil {`);\n      lines.push(`\\t\\tparams.${goField}.applyToQuery(query)`);\n      lines.push('\\t}');\n    }\n  }\n\n  // Make the request with query as the 4th arg\n  if (isPaginated && op.pagination) {\n    const itemType = resolveIteratorItemType(op.pagination.itemType, ctx);\n    const dataPath = op.pagination.dataPath ? `\"${op.pagination.dataPath}\"` : `\"data\"`;\n    const cursorParam = '\"after\"';\n    lines.push(\n      `\\treturn newIterator[${itemType}](ctx, s.client, \"GET\", ${pathExpr}, query, ${cursorParam}, ${dataPath}, opts, ${paginationDefaultsLiteral(op)})`,\n    );\n  } else if (isDelete) {\n    lines.push(`\\t_, err := s.client.request(ctx, \"GET\", ${pathExpr}, query, nil, nil, opts)`);\n    lines.push('\\treturn err');\n  } else if (plan.responseModelName) {\n    const respType = className(plan.responseModelName);\n    if (isArrayResponse) {\n      lines.push(`\\tvar result []${respType}`);\n      lines.push(`\\t_, err := s.client.request(ctx, \"GET\", ${pathExpr}, query, nil, &result, opts)`);\n      lines.push('\\tif err != nil {');\n      lines.push('\\t\\treturn nil, err');\n      lines.push('\\t}');\n      lines.push('\\treturn result, nil');\n    } else {\n      lines.push(`\\tvar result ${respType}`);\n      lines.push(`\\t_, err := s.client.request(ctx, \"GET\", ${pathExpr}, query, nil, &result, opts)`);\n      lines.push('\\tif err != nil {');\n      lines.push('\\t\\treturn nil, err');\n      lines.push('\\t}');\n      lines.push('\\treturn &result, nil');\n    }\n  } else {\n    lines.push(`\\t_, err := s.client.request(ctx, \"GET\", ${pathExpr}, query, nil, nil, opts)`);\n    lines.push('\\treturn err');\n  }\n}\n\n/**\n * Emit method body for URL-builder operations (OAuth redirect endpoints).\n * Builds a url.Values from defaults + inferred + user-provided params, then\n * returns `s.client.buildURL(path, query, opts)` without performing any I/O.\n */\nfunction emitUrlBuilderMethod(\n  lines: string[],\n  op: Operation,\n  pathExpr: string,\n  resolvedOp: ResolvedOperation,\n  paramsType: string | null,\n): void {\n  const hidden = buildHiddenParams(resolvedOp);\n\n  lines.push('\\tquery := url.Values{}');\n\n  // Inject constant defaults (e.g., response_type=code)\n  for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n    lines.push(`\\tquery.Set(\"${key}\", ${goLiteralForQuery(value as string | number | boolean)})`);\n  }\n\n  // Inject inferred fields from client config (e.g., client_id)\n  for (const field of getOpInferFromClient(resolvedOp)) {\n    const expr = clientFieldExpression(field);\n    lines.push(`\\tif ${expr} != \"\" {`);\n    lines.push(`\\t\\tquery.Set(\"${field}\", ${expr})`);\n    lines.push('\\t}');\n  }\n\n  // Add user-provided query params from the struct\n  if (paramsType) {\n    const visibleQueryParams = op.queryParams.filter((qp) => !hidden.has(qp.name));\n    for (const param of visibleQueryParams) {\n      const goField = fieldName(param.name);\n      const isMap = param.type.kind === 'map';\n      if (isMap) {\n        if (param.required) {\n          lines.push(`\\tfor k, v := range params.${goField} {`);\n          lines.push(`\\t\\tquery.Set(fmt.Sprintf(\"${param.name}[%s]\", k), fmt.Sprintf(\"%v\", v))`);\n          lines.push('\\t}');\n        } else {\n          lines.push(`\\tif params.${goField} != nil {`);\n          lines.push(`\\t\\tfor k, v := range params.${goField} {`);\n          lines.push(`\\t\\t\\tquery.Set(fmt.Sprintf(\"${param.name}[%s]\", k), fmt.Sprintf(\"%v\", v))`);\n          lines.push('\\t\\t}');\n          lines.push('\\t}');\n        }\n      } else if (param.required) {\n        lines.push(`\\tquery.Set(\"${param.name}\", ${formatQueryValue(`params.${goField}`, param.type)})`);\n      } else {\n        const isRefType = param.type.kind === 'array';\n        const valueExpr = isRefType ? `params.${goField}` : `*params.${goField}`;\n        lines.push(`\\tif params.${goField} != nil {`);\n        lines.push(`\\t\\tquery.Set(\"${param.name}\", ${formatQueryValue(valueExpr, param.type)})`);\n        lines.push('\\t}');\n      }\n    }\n  }\n\n  lines.push(`\\treturn s.client.buildURL(${pathExpr}, query, opts)`);\n}\n\n/**\n * Emit a private typed body struct for a non-GET operation that has hidden\n * params. Field order matches how `emitBodyWithHiddenParams` constructs the\n * body at the call site: defaults → required exposed → inferred → optional\n * exposed. Mirrors `emitWrapperBodyStruct` in `wrappers.ts`.\n */\nfunction emitHiddenParamsBodyStruct(\n  lines: string[],\n  method: string,\n  op: Operation,\n  ctx: EmitterContext,\n  resolvedOp: ResolvedOperation,\n): void {\n  const hidden = buildHiddenParams(resolvedOp);\n  const structName = hiddenParamsBodyStructName(method);\n\n  const bodyModel =\n    op.requestBody?.kind === 'model'\n      ? ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name)\n      : undefined;\n\n  lines.push(`// ${structName} is the JSON request body for ${method}.`);\n  lines.push(`type ${structName} struct {`);\n\n  // Constant defaults (always sent — no omitempty so the wire format is deterministic)\n  for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n    const goField = fieldName(key);\n    const goType = typeof value === 'boolean' ? 'bool' : typeof value === 'number' ? 'int' : 'string';\n    lines.push(`\\t${goField} ${goType} \\`json:\"${key}\"\\``);\n  }\n\n  // Required exposed body fields\n  const groupedParamNames = collectGroupedParamNames(op);\n  if (bodyModel) {\n    for (const field of bodyModel.fields) {\n      if (hidden.has(field.name)) continue;\n      if (groupedParamNames.has(field.name)) continue;\n      if (!field.required) continue;\n      // Domain struct field; the json tag below keeps deriving from field.name.\n      const goField = domainFieldName(field);\n      const goType = mapTypeRef(field.type);\n      lines.push(`\\t${goField} ${goType} \\`json:\"${field.name}\"\\``);\n    }\n  }\n\n  // Inferred fields from client config (omitempty drops empty strings)\n  for (const inferred of getOpInferFromClient(resolvedOp)) {\n    const goField = fieldName(inferred);\n    lines.push(`\\t${goField} string \\`json:\"${inferred},omitempty\"\\``);\n  }\n\n  // Optional exposed body fields (pointer/slice/map + omitempty)\n  if (bodyModel) {\n    for (const field of bodyModel.fields) {\n      if (hidden.has(field.name)) continue;\n      if (groupedParamNames.has(field.name)) continue;\n      if (field.required) continue;\n      // Domain struct field; the json tag below keeps deriving from field.name.\n      const goField = domainFieldName(field);\n      const goType = makeOptional(mapTypeRef(field.type));\n      lines.push(`\\t${goField} ${goType} \\`json:\"${field.name},omitempty\"\\``);\n    }\n  }\n\n  lines.push('}');\n}\n\n/**\n * Emit method body for non-GET operations that have hidden params (defaults\n * / inferFromClient). Builds a typed body struct (declared by\n * `emitHiddenParamsBodyStruct`) so the wire format is deterministic and\n * statically typed.\n */\nfunction emitBodyWithHiddenParams(\n  lines: string[],\n  op: Operation,\n  pathExpr: string,\n  plan: OperationPlan,\n  ctx: EmitterContext,\n  resolvedOp: ResolvedOperation,\n  paramsType: string | null,\n  _isPaginated: boolean,\n  isDelete: boolean,\n  isArrayResponse: boolean,\n  method: string,\n): void {\n  const hidden = buildHiddenParams(resolvedOp);\n  const bodyType = hiddenParamsBodyStructName(method);\n\n  const bodyModel =\n    op.requestBody?.kind === 'model'\n      ? ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name)\n      : undefined;\n\n  // Build typed body struct literal — defaults + required user fields first\n  lines.push(`\\tbody := ${bodyType}{`);\n\n  for (const [key, value] of Object.entries(getOpDefaults(resolvedOp))) {\n    lines.push(`\\t\\t${fieldName(key)}: ${goLiteral(value as string | number | boolean)},`);\n  }\n\n  if (paramsType && bodyModel) {\n    for (const field of bodyModel.fields) {\n      if (hidden.has(field.name)) continue;\n      if (!field.required) continue;\n      // Domain struct field on both the body literal and the params struct.\n      const goField = domainFieldName(field);\n      lines.push(`\\t\\t${goField}: params.${goField},`);\n    }\n  }\n\n  lines.push('\\t}');\n\n  // Inferred fields from client config — omitempty drops empty values\n  for (const inferred of getOpInferFromClient(resolvedOp)) {\n    const goField = fieldName(inferred);\n    lines.push(`\\tbody.${goField} = ${clientFieldExpression(inferred)}`);\n  }\n\n  // Optional exposed body fields — copy through; omitempty drops nil/empty\n  if (paramsType && bodyModel) {\n    for (const field of bodyModel.fields) {\n      if (hidden.has(field.name)) continue;\n      if (field.required) continue;\n      // Domain struct field on both the body struct and the params struct.\n      const goField = domainFieldName(field);\n      lines.push(`\\tbody.${goField} = params.${goField}`);\n    }\n  }\n\n  // Determine query arg (visible query params from struct)\n  const hasVisibleQueryParams = op.queryParams.filter((qp) => !hidden.has(qp.name)).length > 0;\n  const queryArg = hasVisibleQueryParams ? 'params' : 'nil';\n\n  // Make the request\n  if (isDelete) {\n    lines.push(\n      `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, ${queryArg}, body, nil, opts)`,\n    );\n    lines.push('\\treturn err');\n  } else if (plan.responseModelName) {\n    const respType = className(plan.responseModelName);\n    if (isArrayResponse) {\n      lines.push(`\\tvar result []${respType}`);\n      lines.push(\n        `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, ${queryArg}, body, &result, opts)`,\n      );\n      lines.push('\\tif err != nil {');\n      lines.push('\\t\\treturn nil, err');\n      lines.push('\\t}');\n      lines.push('\\treturn result, nil');\n    } else {\n      lines.push(`\\tvar result ${respType}`);\n      lines.push(\n        `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, ${queryArg}, body, &result, opts)`,\n      );\n      lines.push('\\tif err != nil {');\n      lines.push('\\t\\treturn nil, err');\n      lines.push('\\t}');\n      lines.push('\\treturn &result, nil');\n    }\n  } else {\n    lines.push(\n      `\\t_, err := s.client.request(ctx, \"${op.httpMethod.toUpperCase()}\", ${pathExpr}, ${queryArg}, body, nil, opts)`,\n    );\n    lines.push('\\treturn err');\n  }\n}\n\n/** Format a Go value as a string for url.Values.Set(). */\nfunction goLiteralForQuery(value: string | number | boolean): string {\n  if (typeof value === 'string') return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n  if (typeof value === 'boolean') return value ? `\"true\"` : `\"false\"`;\n  return `fmt.Sprintf(\"%v\", ${String(value)})`;\n}\n\n/** Format a Go expression to a string suitable for url.Values.Set(). */\nfunction formatQueryValue(expr: string, type: import('@workos/oagen').TypeRef): string {\n  if (type.kind === 'primitive') {\n    switch (type.type) {\n      case 'string':\n        return expr;\n      case 'integer':\n      case 'number':\n        return `fmt.Sprintf(\"%v\", ${expr})`;\n      case 'boolean':\n        return `fmt.Sprintf(\"%v\", ${expr})`;\n      default:\n        return `fmt.Sprintf(\"%v\", ${expr})`;\n    }\n  }\n  if (type.kind === 'array') {\n    return `strings.Join(${expr}, \",\")`;\n  }\n  return `fmt.Sprintf(\"%v\", ${expr})`;\n}\n\n/**\n * Check if any operations with hidden params also have visible array query params.\n * strings.Join is only generated inside emitGetWithHiddenParams, so the import is\n * only needed when that code path is active AND uses array params.\n */\nfunction needsStringsImport(operations: Operation[], resolvedLookup: Map<string, any>): boolean {\n  for (const op of operations) {\n    const resolved = lookupResolved(op, resolvedLookup);\n    if (!resolved || !hasHiddenParams(resolved)) continue;\n    if (op.httpMethod.toLowerCase() !== 'get') continue;\n    const hidden = buildHiddenParams(resolved);\n    for (const qp of op.queryParams) {\n      if (hidden.has(qp.name)) continue;\n      if (qp.type.kind === 'array') return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Check if any visible query params in operations use map types,\n * requiring bracket-encoded loop generation.\n */\nfunction _hasMapQueryParams(op: Operation, hidden: Set<string>): boolean {\n  return op.queryParams.some((qp) => !hidden.has(qp.name) && qp.type.kind === 'map');\n}\n\nfunction buildPathExpr(op: Operation): string {\n  if (op.pathParams.length === 0) {\n    return `\"${op.path}\"`;\n  }\n  // Build fmt.Sprintf expression (sorted by template order)\n  let fmtStr = op.path;\n  const args: string[] = [];\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    fmtStr = fmtStr.replace(`{${p.name}}`, '%s');\n    const varName = lowerFirst(fieldName(p.name));\n    const needsCast = p.type.kind !== 'primitive' || p.type.type !== 'string';\n    args.push(needsCast ? `url.PathEscape(string(${varName}))` : `url.PathEscape(${varName})`);\n  }\n  return `fmt.Sprintf(\"${fmtStr}\", ${args.join(', ')})`;\n}\n\nfunction bodyArgument(op: Operation): string {\n  if (op.requestBody?.kind === 'model') {\n    return 'params';\n  }\n  return 'params.Body';\n}\n\nfunction mapQueryParamType(name: string, type: import('@workos/oagen').TypeRef): string {\n  if (name === 'limit' && type.kind === 'primitive' && (type.type === 'integer' || type.type === 'number')) {\n    return 'int';\n  }\n  return mapTypeRef(type);\n}\n\nfunction makeOptional(goType: string): string {\n  if (goType.startsWith('*') || goType.startsWith('[]') || goType.startsWith('map[')) {\n    return goType;\n  }\n  return `*${goType}`;\n}\n\n/**\n * Resolve the iterator item type for pagination. If the item type is a list\n * wrapper model (which we skip in models.ts), unwrap it to the actual data item.\n */\nfunction resolveIteratorItemType(itemType: import('@workos/oagen').TypeRef, ctx: EmitterContext): string {\n  if (itemType.kind === 'model') {\n    // Check if this is a list wrapper model -- if so, unwrap to its data array's item type\n    const model = ctx.spec.models.find((m) => m.name === itemType.name);\n    if (model && isListWrapperModel(model)) {\n      const dataField = model.fields.find((f) => f.name === 'data');\n      if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n        return className(dataField.type.items.name);\n      }\n    }\n    return className(itemType.name);\n  }\n  return mapTypeRefValue(itemType);\n}\n\n/** Go reserved words that cannot be used as identifiers. */\nconst GO_RESERVED = new Set([\n  'break',\n  'case',\n  'chan',\n  'const',\n  'continue',\n  'default',\n  'defer',\n  'else',\n  'fallthrough',\n  'for',\n  'func',\n  'go',\n  'goto',\n  'if',\n  'import',\n  'interface',\n  'map',\n  'package',\n  'range',\n  'return',\n  'select',\n  'struct',\n  'switch',\n  'type',\n  'var',\n]);\n\nfunction lowerFirst(s: string): string {\n  if (!s) return s;\n  const result = unexportedName(s);\n  // Escape Go reserved words by appending an underscore\n  if (GO_RESERVED.has(result)) return `${result}Param`;\n  return result;\n}\n\n/** Simple lowercase-first for human-readable descriptions (not identifiers). */\nfunction lowerFirstDesc(s: string): string {\n  return lowerFirstForDoc(s);\n}\n\n/**\n * Build the Go literal for the pagination defaults map passed as the last\n * argument to newIterator.  Collects `default` values from pagination-related\n * query params (limit, order) and returns either `nil` or\n * `map[string]string{\"limit\": \"10\", \"order\": \"desc\"}`.\n */\nfunction paginationDefaultsLiteral(op: Operation): string {\n  const PAGINATION_DEFAULTS = ['limit', 'order'];\n  const entries: string[] = [];\n  for (const name of PAGINATION_DEFAULTS) {\n    const param = op.queryParams.find((qp) => qp.name === name);\n    if (param?.default != null) {\n      entries.push(`\"${name}\": \"${param.default}\"`);\n    }\n  }\n  if (entries.length === 0) return 'nil';\n  return `map[string]string{${entries.join(', ')}}`;\n}\n\n/**\n * Build the godoc summary line for a method.  When every PascalCase word\n * in the method name matches the leading words of the summary\n * (case-insensitive), those words are stripped to avoid stutter:\n *\n *   godocSummary(\"Check\", \"Check authorization\")     → \"Check authorization\"\n *   godocSummary(\"Delete\", \"Delete an API key\")       → \"Delete an API key\"\n *   godocSummary(\"VerifyEmail\", \"Verify email\")       → \"VerifyEmail\"\n *   godocSummary(\"GetJWKS\", \"Get JWKS\")               → \"GetJWKS\"\n *\n * When the summary words diverge from the method name, nothing is stripped:\n *\n *   godocSummary(\"AssignRole\", \"Assign a role\")\n *     → \"AssignRole assign a role\"\n *   godocSummary(\"ListOrganizationMembershipResources\", \"List resources for organization membership\")\n *     → \"ListOrganizationMembershipResources list resources for organization membership\"\n */\nfunction godocSummary(method: string, summary: string): string {\n  const methodWords = method.match(/[A-Z]+(?:[a-z]+|(?=[A-Z]|$))|[A-Z]?[a-z]+|[0-9]+/g) ?? [method];\n  const summaryWords = summary.split(/\\s+/);\n\n  // Check whether all method words match the leading summary words.\n  if (methodWords.length <= summaryWords.length) {\n    const allMatch = methodWords.every((mw, i) => mw.toLowerCase() === summaryWords[i].toLowerCase());\n    if (allMatch) {\n      const rest = summaryWords.slice(methodWords.length).join(' ');\n      if (rest) return `${method} ${lowerFirstDesc(rest)}`;\n      return method;\n    }\n  }\n\n  return `${method} ${lowerFirstDesc(summary)}`;\n}\n\nfunction singularizePascal(name: string): string {\n  if (name.endsWith('ies')) {\n    return `${name.slice(0, -3)}y`;\n  }\n  if (name.endsWith('s') && !name.endsWith('ss')) {\n    return name.slice(0, -1);\n  }\n  return name;\n}\n\nfunction serviceTypeName(name: string): string {\n  return `${className(singularizePascal(name))}Service`;\n}\n","import type { ApiSpec, EmitterContext, GeneratedFile, Service } from '@workos/oagen';\nimport { toPascalCase, toSnakeCase } from '@workos/oagen';\n// naming utilities used indirectly via resolveResourceClassName\nimport { resolveResourceClassName } from './resources.js';\nimport { className, unexportedName } from './naming.js';\nimport { getMountTarget } from '../shared/resolved-ops.js';\nimport { NON_SPEC_SERVICES } from '../shared/non-spec-services.js';\n\n/**\n * Generate the Go client file with service accessors.\n * Produces: workos.go (Client struct + constructor + service accessors).\n * Static files (client.go, pagination.go, errors.go, go.mod, options.go)\n * are hand-maintained in the target SDK with @oagen-ignore-file.\n */\nexport function generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  return [generateWorkOSFile(spec, ctx)];\n}\n\n/**\n * Non-spec services marked with `hasClientAccessor: true` (e.g. passwordless)\n * are included in the generated Client struct, constructor, and accessor methods\n * — identical to spec-driven services. Their service type (e.g. PasswordlessService)\n * is defined in a hand-written @oagen-ignore-file, but the Client wiring is generated.\n *\n * Other non-spec modules (webhook_verification, actions, etc.) remain fully\n * self-contained in their @oagen-ignore-file files.\n */\n\n/**\n * Deduplicate services by mount target.\n */\nfunction deduplicateByMount(services: Service[], ctx: EmitterContext): Service[] {\n  const byTarget = new Map<string, Service>();\n  for (const s of services) {\n    const target = getMountTarget(s, ctx);\n    const existing = byTarget.get(target);\n    if (!existing || toPascalCase(s.name) === target) {\n      byTarget.set(target, s);\n    }\n  }\n  return [...byTarget.values()];\n}\n\n/**\n * Build map of service name -> accessor property name.\n */\nexport function buildServiceAccessPaths(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const topLevel = deduplicateByMount(services, ctx);\n  const paths = new Map<string, string>();\n\n  for (const service of topLevel) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const prop = toSnakeCase(resolvedName);\n    paths.set(service.name, prop);\n  }\n\n  // Also map mount targets\n  for (const service of services) {\n    const target = getMountTarget(service, ctx);\n    if (!paths.has(target)) {\n      const existing = paths.get(service.name);\n      if (existing) paths.set(target, existing);\n    }\n  }\n\n  return paths;\n}\n\nfunction generateWorkOSFile(spec: ApiSpec, ctx: EmitterContext): GeneratedFile {\n  const topLevel = deduplicateByMount(spec.services, ctx);\n  const lines: string[] = [];\n\n  lines.push(`package ${ctx.namespace}`);\n  lines.push('');\n  lines.push('import \"net/http\"');\n  lines.push('');\n\n  // Client struct\n  lines.push('// Client is the WorkOS API client.');\n  lines.push('type Client struct {');\n  lines.push('\\tapiKey       string');\n  lines.push('\\tclientID     string');\n  lines.push('\\tbaseURL      string');\n  lines.push('\\thttpClient   *http.Client');\n  lines.push('\\tmaxRetries   int');\n  lines.push('\\tlogger       Logger');\n  lines.push('\\tappInfo      appInfo');\n  lines.push('');\n  // Service fields\n  for (const service of topLevel) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const fieldNameStr = unexportedName(resolvedName);\n    const serviceTypeName = serviceType(resolvedName);\n    lines.push(`\\t${fieldNameStr} *${serviceTypeName}`);\n  }\n  // Non-spec service fields (hand-written types, generated wiring)\n  for (const ns of NON_SPEC_SERVICES.filter((s) => s.hasClientAccessor)) {\n    const name = className(toPascalCase(ns.id));\n    lines.push(`\\t${unexportedName(name)} *${serviceType(name)}`);\n  }\n  lines.push('}');\n  lines.push('');\n\n  // NewClient constructor\n  lines.push('// NewClient creates a new WorkOS API client.');\n  lines.push('func NewClient(apiKey string, opts ...ClientOption) *Client {');\n  lines.push('\\tc := &Client{');\n  lines.push('\\t\\tapiKey:     apiKey,');\n  lines.push('\\t\\tbaseURL:    defaultBaseURL,');\n  lines.push('\\t\\thttpClient: &http.Client{Timeout: defaultTimeout},');\n  lines.push('\\t\\tmaxRetries: defaultMaxRetries,');\n  lines.push('\\t}');\n  lines.push('\\tfor _, opt := range opts {');\n  lines.push('\\t\\topt(c)');\n  lines.push('\\t}');\n  // Initialize services\n  for (const service of topLevel) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const fieldNameStr = unexportedName(resolvedName);\n    const serviceTypeName = serviceType(resolvedName);\n    lines.push(`\\tc.${fieldNameStr} = &${serviceTypeName}{client: c}`);\n  }\n  // Initialize non-spec services\n  for (const ns of NON_SPEC_SERVICES.filter((s) => s.hasClientAccessor)) {\n    const name = className(toPascalCase(ns.id));\n    lines.push(`\\tc.${unexportedName(name)} = &${serviceType(name)}{client: c}`);\n  }\n  lines.push('\\treturn c');\n  lines.push('}');\n  lines.push('');\n\n  // Service accessor methods\n  for (const service of topLevel) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const accessorName = resolvedName;\n    const fieldNameStr = unexportedName(resolvedName);\n    const serviceTypeName = serviceType(resolvedName);\n    lines.push(`// ${accessorName} returns the ${resolvedName} service.`);\n    lines.push(`func (c *Client) ${accessorName}() *${serviceTypeName} {`);\n    lines.push(`\\treturn c.${fieldNameStr}`);\n    lines.push('}');\n    lines.push('');\n  }\n  // Non-spec service accessor methods\n  for (const ns of NON_SPEC_SERVICES.filter((s) => s.hasClientAccessor)) {\n    const name = className(toPascalCase(ns.id));\n    const typeName = serviceType(name);\n    lines.push(`// ${name} returns the ${name} service.`);\n    lines.push(`func (c *Client) ${name}() *${typeName} {`);\n    lines.push(`\\treturn c.${unexportedName(name)}`);\n    lines.push('}');\n    lines.push('');\n  }\n  return {\n    path: `${ctx.namespace}.go`,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\nfunction singularizePascal(name: string): string {\n  if (name.endsWith('ies')) {\n    return `${name.slice(0, -3)}y`;\n  }\n  if (name.endsWith('s') && !name.endsWith('ss')) {\n    return name.slice(0, -1);\n  }\n  return name;\n}\n\nfunction serviceType(name: string): string {\n  return `${className(singularizePascal(name))}Service`;\n}\n","import type { Model, TypeRef, Enum, EmitterContext } from '@workos/oagen';\nimport { fileName, domainFieldName } from './naming.js';\nimport { isListMetadataModel, isListWrapperModel } from './models.js';\nimport { collectNonPaginatedResponseModelNames, collectReferencedListMetadataModels } from '../shared/model-utils.js';\nimport { isModelInScope, fileExistsAfterRun } from '../shared/resolved-ops.js';\n\n/**\n * Prefix mapping for generating realistic ID fixture values.\n */\nexport const ID_PREFIXES: Record<string, string> = {\n  Connection: 'conn_',\n  Organization: 'org_',\n  OrganizationMembership: 'om_',\n  User: 'user_',\n  Directory: 'directory_',\n  DirectoryGroup: 'dir_grp_',\n  DirectoryUser: 'dir_usr_',\n  Invitation: 'inv_',\n  Session: 'session_',\n  AuthenticationFactor: 'auth_factor_',\n  EmailVerification: 'email_verification_',\n  MagicAuth: 'magic_auth_',\n  PasswordReset: 'password_reset_',\n};\n\n/**\n * Generate JSON fixture files for test data.\n *\n * Scoped runs only emit a fixture for a model whose per-model fixture FILE will\n * exist on disk after the run (in-scope, or already present from a prior run —\n * the fixture path is per-model so the prior manifest records it directly).\n * This drops brand-new out-of-scope fixtures (the round-trip ADDITION case) and\n * keeps prior fixtures untouched, mirroring the Rust fixtures fix. `ctx` is\n * optional so unit tests that assert raw content can call it for a full run.\n */\nexport function generateFixtures(\n  spec: { models: Model[]; enums: Enum[]; services: any[] },\n  ctx?: EmitterContext,\n): {\n  files: { path: string; content: string }[];\n  pathRewrites: Map<string, string>;\n} {\n  if (spec.models.length === 0) return { files: [], pathRewrites: new Map() };\n\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n  const files: { path: string; content: string }[] = [];\n\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(spec.services);\n  const listMetadataNeeded = collectReferencedListMetadataModels(spec.models, nonPaginatedRefs);\n\n  // Full run (no ctx / no scoping): every fixture is in scope.\n  const fixtureInScope = (relPath: string, modelName: string): boolean =>\n    !ctx || fileExistsAfterRun(relPath, isModelInScope(modelName, ctx), ctx);\n\n  for (const model of spec.models) {\n    if (isListMetadataModel(model) && !listMetadataNeeded.has(model.name)) continue;\n    if (isListWrapperModel(model) && !nonPaginatedRefs.has(model.name)) continue;\n\n    const path = `testdata/${fileName(model.name)}.json`;\n    if (!fixtureInScope(path, model.name)) continue;\n\n    const fixture = model.fields.length === 0 ? {} : generateModelFixture(model, modelMap, enumMap);\n\n    files.push({\n      path,\n      content: JSON.stringify(fixture, null, 2),\n    });\n  }\n\n  // Generate list fixtures for paginated responses. Multiple operations may\n  // share the same item model (e.g. several role-assignment list endpoints all\n  // returning UserRoleAssignmentList) — emit each fixture path once so the\n  // content-dedup pass below doesn't see N copies of the same path and drop\n  // the file entirely.\n  const seenListPaths = new Set<string>();\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      if (op.pagination) {\n        let itemModel = op.pagination.itemType.kind === 'model' ? modelMap.get(op.pagination.itemType.name) : null;\n        if (itemModel) {\n          const unwrapped = unwrapListModel(itemModel, modelMap);\n          if (unwrapped) itemModel = unwrapped;\n          if (itemModel.fields.length === 0) continue;\n          const path = `testdata/list_${fileName(itemModel.name)}.json`;\n          if (seenListPaths.has(path)) continue;\n          seenListPaths.add(path);\n          // Scoped run: only emit a list fixture whose file will exist after the\n          // run (in-scope item model, or already on disk). Keyed on the item\n          // model so an out-of-scope paginated endpoint doesn't add a new file.\n          if (!fixtureInScope(path, itemModel.name)) continue;\n          const fixture = generateModelFixture(itemModel, modelMap, enumMap);\n          const listFixture = {\n            data: [fixture],\n            list_metadata: {\n              before: null,\n              after: null,\n            },\n          };\n          files.push({\n            path,\n            content: JSON.stringify(listFixture, null, 2),\n          });\n        }\n      }\n    }\n  }\n\n  // Deduplicate fixtures with identical content.\n  // When multiple fixtures have the same content, emit one shared file and\n  // rewrite the others as references to the shared path.\n  const contentGroups = new Map<string, string[]>();\n  for (const f of files) {\n    if (!contentGroups.has(f.content)) contentGroups.set(f.content, []);\n    contentGroups.get(f.content)!.push(f.path);\n  }\n\n  const pathRewrites = new Map<string, string>();\n  for (const [_content, paths] of contentGroups) {\n    if (paths.length < 3) continue; // only dedup when 3+ files are identical\n    // Use the shortest path as the canonical shared fixture\n    const sorted = [...paths].sort((a, b) => a.length - b.length);\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      pathRewrites.set(sorted[i], canonical);\n    }\n  }\n\n  // Remove duplicate files (they'll reference the canonical)\n  const deduped = files.filter((f) => !pathRewrites.has(f.path));\n\n  return { files: deduped, pathRewrites };\n}\n\nfunction unwrapListModel(model: Model, modelMap: Map<string, Model>): Model | null {\n  const dataField = model.fields.find((f) => f.name === 'data');\n  const hasListMetadata = model.fields.some((f) => f.name === 'list_metadata' || f.name === 'listMetadata');\n  if (dataField && hasListMetadata && dataField.type.kind === 'array') {\n    const itemType = dataField.type.items;\n    if (itemType.kind === 'model') {\n      return modelMap.get(itemType.name) ?? null;\n    }\n  }\n  return null;\n}\n\nexport function generateModelFixture(\n  model: Model,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): Record<string, any> {\n  const fixture: Record<string, any> = {};\n\n  const seenFieldNames = new Set<string>();\n  const deduplicatedFields = model.fields.filter((f) => {\n    // Dedup by the domain Go field name to mirror the struct in models.ts; the\n    // fixture key itself (wireName below) still derives from field.name.\n    const goName = domainFieldName(f);\n    if (seenFieldNames.has(goName)) return false;\n    seenFieldNames.add(goName);\n    return true;\n  });\n\n  for (const field of deduplicatedFields) {\n    const wireName = field.name;\n    if (field.example !== undefined) {\n      fixture[wireName] = field.example;\n    } else {\n      fixture[wireName] = generateFieldValue(field.type, field.name, model.name, modelMap, enumMap);\n    }\n  }\n\n  if (model.discriminator) {\n    const [firstValue, variantName] = Object.entries(model.discriminator.mapping)[0];\n    fixture[model.discriminator.property] = firstValue;\n    const variantModel = modelMap.get(variantName);\n    if (variantModel) {\n      for (const field of variantModel.fields) {\n        if (!(field.name in fixture)) {\n          fixture[field.name] =\n            field.example !== undefined\n              ? field.example\n              : generateFieldValue(field.type, field.name, model.name, modelMap, enumMap);\n        }\n      }\n    }\n  }\n\n  return fixture;\n}\n\nfunction generateFieldValue(\n  ref: TypeRef,\n  fName: string,\n  modelName: string,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): any {\n  switch (ref.kind) {\n    case 'primitive':\n      return generatePrimitiveValue(ref.type, ref.format, fName, modelName);\n    case 'literal':\n      return ref.value;\n    case 'enum': {\n      const e = enumMap.get(ref.name);\n      return e?.values[0]?.value ?? 'unknown';\n    }\n    case 'model': {\n      const nested = modelMap.get(ref.name);\n      if (nested) return generateModelFixture(nested, modelMap, enumMap);\n      return {};\n    }\n    case 'array': {\n      if (ref.items.kind === 'enum') {\n        const e = enumMap.get(ref.items.name);\n        if (e && e.values.length > 0) {\n          return e.values.map((v) => v.value);\n        }\n      }\n      const item = generateFieldValue(ref.items, fName, modelName, modelMap, enumMap);\n      return [item];\n    }\n    case 'nullable':\n      return generateFieldValue(ref.inner, fName, modelName, modelMap, enumMap);\n    case 'union':\n      if (ref.variants.length > 0) {\n        return generateFieldValue(ref.variants[0], fName, modelName, modelMap, enumMap);\n      }\n      return null;\n    case 'map':\n      return {\n        key: generateFieldValue(ref.valueType, 'value', modelName, modelMap, enumMap),\n      };\n  }\n}\n\nfunction generatePrimitiveValue(type: string, format: string | undefined, name: string, modelName: string): any {\n  switch (type) {\n    case 'string':\n      if (format === 'date-time') return '2023-01-01T00:00:00.000Z';\n      if (format === 'date') return '2023-01-01';\n      if (format === 'uuid') return '00000000-0000-0000-0000-000000000000';\n      if (name === 'id') {\n        const prefix = ID_PREFIXES[modelName] ?? '';\n        return `${prefix}01234`;\n      }\n      if (name.includes('id')) return `${name}_01234`;\n      if (name.includes('email')) return 'test@example.com';\n      if (name.includes('url') || name.includes('uri')) return 'https://example.com';\n      if (name.includes('name')) return 'Test';\n      return `test_${name}`;\n    case 'integer':\n      return 1;\n    case 'number':\n      return 1.0;\n    case 'boolean':\n      return true;\n    case 'unknown':\n      return {};\n    default:\n      return null;\n  }\n}\n","import type { ApiSpec, Service, Operation, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { planOperation, toSnakeCase } from '@workos/oagen';\nimport { fileName, fieldName as goFieldName, resolveMethodName, methodName as goMethodName } from './naming.js';\nimport { resolveResourceClassName, paramsStructName, sortPathParamsByTemplateOrder } from './resources.js';\nimport { buildServiceAccessPaths } from './client.js';\nimport { generateFixtures } from './fixtures.js';\nimport { isListWrapperModel } from './models.js';\nimport { scopedMountGroups, buildResolvedLookup, lookupResolved, buildHiddenParams } from '../shared/resolved-ops.js';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nconst DEFAULT_MODULE_PATH = 'github.com/workos/workos-go/v6';\n\n/** Resolve the Go module path from the output directory's go.mod, or use default. */\nfunction resolveModulePath(ctx: EmitterContext): string {\n  if (ctx.outputDir) {\n    const goModPath = resolve(ctx.outputDir, 'go.mod');\n    if (existsSync(goModPath)) {\n      const content = readFileSync(goModPath, 'utf-8');\n      const match = content.match(/^module\\s+(\\S+)/m);\n      if (match) return match[1];\n    }\n  }\n  return DEFAULT_MODULE_PATH;\n}\n\n/**\n * Generate Go test files and JSON fixtures.\n */\nexport function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  // Generate shared test helpers file\n  const helperLines: string[] = [];\n  helperLines.push(`package ${ctx.namespace}_test`);\n  helperLines.push('');\n  helperLines.push('import (');\n  helperLines.push('\\t\"net/http\"');\n  helperLines.push('\\t\"net/http/httptest\"');\n  helperLines.push('\\t\"os\"');\n  helperLines.push('\\t\"testing\"');\n  helperLines.push('');\n  helperLines.push(`\\t\"${resolveModulePath(ctx)}\"`);\n  helperLines.push('\\t\"github.com/stretchr/testify/require\"');\n  helperLines.push(')');\n  helperLines.push('');\n  helperLines.push('func ptrString(s string) *string { return &s }');\n  helperLines.push('func ptrInt(i int) *int { return &i }');\n  helperLines.push('');\n  helperLines.push(\n    `func setupTestServer(t *testing.T, method, path, fixturePath string) (*httptest.Server, *${ctx.namespace}.Client) {`,\n  );\n  helperLines.push('\\tt.Helper()');\n  helperLines.push('\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {');\n  helperLines.push('\\t\\trequire.Equal(t, method, r.Method)');\n  helperLines.push('\\t\\trequire.Equal(t, path, r.URL.Path)');\n  helperLines.push('\\t\\tw.Header().Set(\"Content-Type\", \"application/json\")');\n  helperLines.push('\\t\\tfixture, err := os.ReadFile(fixturePath)');\n  helperLines.push('\\t\\tif err != nil {');\n  helperLines.push('\\t\\t\\tt.Fatalf(\"failed to read fixture: %v\", err)');\n  helperLines.push('\\t\\t}');\n  helperLines.push('\\t\\tw.Write(fixture)');\n  helperLines.push('\\t}))');\n  helperLines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithBaseURL(server.URL))`);\n  helperLines.push('\\treturn server, client');\n  helperLines.push('}');\n  helperLines.push('');\n  files.push({\n    path: 'helpers_test.go',\n    content: helperLines.join('\\n'),\n    overwriteExisting: true,\n  });\n\n  // Generate fixture JSON files. Pass ctx so a scoped run only emits fixtures\n  // for in-scope models (or ones already on disk), dropping brand-new\n  // out-of-scope fixtures while leaving prior fixtures untouched.\n  const { files: fixtures, pathRewrites: fixtureRewrites } = generateFixtures(spec, ctx);\n  for (const fixture of fixtures) {\n    files.push({\n      path: fixture.path,\n      content: fixture.content,\n      headerPlacement: 'skip',\n    });\n  }\n\n  // Build access path map\n  const accessPaths = buildServiceAccessPaths(spec.services, ctx);\n\n  // Generate per-mount-target test files\n  const mountGroups = scopedMountGroups(ctx);\n  const testEntries: Array<{ name: string; operations: Operation[] }> =\n    mountGroups.size > 0 || ctx.scopedServices?.size\n      ? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations }))\n      : spec.services.map((s) => ({\n          name: resolveResourceClassName(s, ctx),\n          operations: s.operations,\n        }));\n\n  for (const { name: mountName, operations } of testEntries) {\n    if (operations.length === 0) continue;\n    const mergedService: Service = { name: mountName, operations };\n    const testFile = generateServiceTest(mergedService, spec, ctx, accessPaths, fixtureRewrites);\n    if (testFile) files.push(testFile);\n  }\n\n  return files;\n}\n\nfunction generateServiceTest(\n  service: Service,\n  spec: ApiSpec,\n  ctx: EmitterContext,\n  _accessPaths: Map<string, string>,\n  fixtureRewrites: Map<string, string>,\n): GeneratedFile | null {\n  if (service.operations.length === 0) return null;\n\n  const resolvedName = resolveResourceClassName(service, ctx);\n  const accessorName = resolvedName;\n  const testFile = `${toSnakeCase(resolvedName)}_test.go`;\n\n  const lines: string[] = [];\n  lines.push(`package ${ctx.namespace}_test`);\n  lines.push('');\n  // Check if any operation uses POST/PUT/PATCH with visible model body fields (for import needs).\n  // Union-type bodies don't trigger body validation so don't need io/json imports.\n  const resolvedLookupForImports = buildResolvedLookup(ctx);\n  const hasBodyOps = service.operations.some((op) => {\n    const httpMethod = op.httpMethod.toUpperCase();\n    if (httpMethod !== 'POST' && httpMethod !== 'PUT' && httpMethod !== 'PATCH') return false;\n    if (op.requestBody?.kind !== 'model') return false;\n    const resolved = lookupResolved(op, resolvedLookupForImports);\n    const hidden = buildHiddenParams(resolved);\n    const bodyModel = spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) return bodyModel.fields.some((f) => !hidden.has(f.name));\n    return false;\n  });\n\n  lines.push('import (');\n  lines.push('\\t\"context\"');\n  if (hasBodyOps) {\n    lines.push('\\t\"encoding/json\"');\n    lines.push('\\t\"io\"');\n  }\n  lines.push('\\t\"net/http\"');\n  lines.push('\\t\"net/http/httptest\"');\n  lines.push('\\t\"os\"');\n  lines.push('\\t\"testing\"');\n  lines.push('');\n  lines.push(`\\t\"${resolveModulePath(ctx)}\"`);\n  lines.push('\\t\"github.com/stretchr/testify/require\"');\n  lines.push(')');\n  lines.push('');\n  // Test helpers (ptrString, ptrInt, setupTestServer) are in helpers_test.go\n\n  // Deduplicate test functions by method name\n  const emittedTestMethods = new Set<string>();\n  const resolvedLookupMain = buildResolvedLookup(ctx);\n  for (const op of service.operations) {\n    const plan = planOperation(op);\n    const method = resolveGoMethodName(op, resolvedName, ctx);\n    const isPaginated = plan.isPaginated;\n    const isDelete = plan.isDelete;\n\n    // Skip duplicate method names (same dedup as resources.ts)\n    if (emittedTestMethods.has(method)) continue;\n    emittedTestMethods.add(method);\n\n    // Skip operations with wrapper splits — the parent method isn't emitted\n    // (see src/go/resources.ts), only the typed wrappers are tested below.\n    const resolvedMain = lookupResolved(op, resolvedLookupMain);\n    if ((resolvedMain?.wrappers?.length ?? 0) > 0) continue;\n\n    const testName = `Test${accessorName}_${method}`;\n    const isUrlBuilder = resolvedMain?.urlBuilder ?? false;\n\n    if (isUrlBuilder) {\n      // URL-builder methods return a string synchronously without making\n      // an HTTP request. Assert the URL contains the expected path.\n      const expectedPath = buildExpectedPath(op);\n      // Call args: no ctx, path params (if any), then params struct.\n      const callArgs: string[] = [];\n      for (const p of sortPathParamsByTemplateOrder(op)) {\n        callArgs.push(`\"test_${p.name}\"`);\n      }\n      const hidden = buildHiddenParams(resolvedMain);\n      const hasVisibleQueryParams = op.queryParams.filter((qp) => !hidden.has(qp.name)).length > 0;\n      if (hasVisibleQueryParams) {\n        const pName = paramsStructName(resolvedName, method);\n        callArgs.push(`&${ctx.namespace}.${pName}{}`);\n      }\n      lines.push(`func ${testName}(t *testing.T) {`);\n      lines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithClientID(\"client_test\"))`);\n      lines.push(`\\turl := client.${accessorName}().${method}(${callArgs.join(', ')})`);\n      lines.push('\\trequire.NotEmpty(t, url)');\n      lines.push(`\\trequire.Contains(t, url, \"${expectedPath}\")`);\n      lines.push('}');\n      lines.push('');\n      continue;\n    }\n\n    if (isPaginated && op.pagination) {\n      // Pagination test\n      // Find the right fixture -- apply the same unwrap logic as fixtures.ts\n      let fixturePath: string | null = null;\n      const paginationItemType = op.pagination.itemType;\n      if (paginationItemType.kind === 'model') {\n        const itemModel = spec.models.find((m) => m.name === paginationItemType.name);\n        if (itemModel) {\n          let resolved = itemModel;\n          if (isListWrapperModel(itemModel)) {\n            const dataField = itemModel.fields.find((f) => f.name === 'data');\n            if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n              const inner = spec.models.find((m) => m.name === (dataField.type as any).items.name);\n              if (inner) resolved = inner;\n            }\n          }\n          fixturePath = `testdata/list_${fileName(resolved.name)}.json`;\n          // If this fixture was deduplicated, use the canonical path\n          if (fixtureRewrites.has(fixturePath)) {\n            fixturePath = fixtureRewrites.get(fixturePath)!;\n          }\n        }\n      }\n\n      const expectedPath = buildExpectedPath(op);\n\n      // Find a filter param to populate (prefer 'limit', then first visible string param)\n      const resolvedLookupPag = buildResolvedLookup(ctx);\n      const resolvedOpPag = lookupResolved(op, resolvedLookupPag);\n      const hiddenPag = buildHiddenParams(resolvedOpPag);\n      const visibleQPs = op.queryParams.filter((qp) => !hiddenPag.has(qp.name));\n      const limitParam = visibleQPs.find((qp) => qp.name === 'limit');\n      const filterParam =\n        limitParam ?? visibleQPs.find((qp) => qp.type.kind === 'primitive' && qp.type.type === 'string');\n\n      lines.push(`func ${testName}(t *testing.T) {`);\n      lines.push('\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {');\n      lines.push(`\\t\\trequire.Equal(t, \"${op.httpMethod.toUpperCase()}\", r.Method)`);\n      lines.push(`\\t\\trequire.Equal(t, \"${expectedPath}\", r.URL.Path)`);\n      // Assert filter param in query string\n      if (filterParam) {\n        const expectedVal = filterParam.name === 'limit' ? '10' : `test_${filterParam.name}`;\n        lines.push(`\\t\\trequire.Equal(t, \"${expectedVal}\", r.URL.Query().Get(\"${filterParam.name}\"))`);\n      }\n      lines.push('\\t\\tw.Header().Set(\"Content-Type\", \"application/json\")');\n      lines.push('\\t\\tw.WriteHeader(http.StatusOK)');\n      if (fixturePath) {\n        lines.push(`\\t\\tfixture, err := os.ReadFile(\"${fixturePath}\")`);\n        lines.push('\\t\\tif err != nil {');\n        lines.push('\\t\\t\\tt.Fatalf(\"failed to read fixture: %v\", err)');\n        lines.push('\\t\\t}');\n        lines.push('\\t\\tw.Write(fixture)');\n      } else {\n        lines.push('\\t\\tw.Write([]byte(`{\"data\":[],\"list_metadata\":{\"before\":null,\"after\":null}}`))');\n      }\n      lines.push('\\t}))');\n      lines.push('\\tdefer server.Close()');\n      lines.push('');\n      lines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithBaseURL(server.URL))`);\n\n      // Build method call with populated filter param\n      const callArgs = buildMethodCallArgsWithFilter(op, plan, ctx, resolvedName, filterParam);\n      lines.push(`\\titer := client.${accessorName}().${method}(${callArgs})`);\n      lines.push('\\trequire.NotNil(t, iter)');\n      if (fixturePath) {\n        lines.push('\\trequire.True(t, iter.Next())');\n        lines.push('\\trequire.NoError(t, iter.Err())');\n        lines.push('\\titem := iter.Current()');\n        lines.push('\\trequire.NotNil(t, item)');\n      }\n      lines.push('}');\n      lines.push('');\n\n      // Empty pagination test\n      lines.push(`func ${testName}_Empty(t *testing.T) {`);\n      lines.push('\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {');\n      lines.push('\\t\\tw.Header().Set(\"Content-Type\", \"application/json\")');\n      lines.push('\\t\\tw.WriteHeader(http.StatusOK)');\n      lines.push('\\t\\tw.Write([]byte(`{\"data\":[],\"list_metadata\":{\"before\":null,\"after\":null}}`))');\n      lines.push('\\t}))');\n      lines.push('\\tdefer server.Close()');\n      lines.push('');\n      lines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithBaseURL(server.URL))`);\n      lines.push(`\\titer := client.${accessorName}().${method}(${callArgs})`);\n      lines.push('\\trequire.False(t, iter.Next())');\n      lines.push('\\trequire.NoError(t, iter.Err())');\n      lines.push('}');\n      lines.push('');\n    } else if (isDelete) {\n      // Delete test\n      const expectedPath = buildExpectedPath(op);\n      lines.push(`func ${testName}(t *testing.T) {`);\n      lines.push('\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {');\n      lines.push(`\\t\\trequire.Equal(t, \"${op.httpMethod.toUpperCase()}\", r.Method)`);\n      lines.push(`\\t\\trequire.Equal(t, \"${expectedPath}\", r.URL.Path)`);\n      lines.push('\\t\\tw.WriteHeader(http.StatusNoContent)');\n      lines.push('\\t}))');\n      lines.push('\\tdefer server.Close()');\n      lines.push('');\n      lines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithBaseURL(server.URL))`);\n\n      const callArgs = buildMethodCallArgs(op, plan, ctx, resolvedName);\n      lines.push(`\\terr := client.${accessorName}().${method}(${callArgs})`);\n      lines.push('\\trequire.NoError(t, err)');\n      lines.push('}');\n      lines.push('');\n    } else if (plan.responseModelName) {\n      // Success test\n      const respModel = plan.responseModelName;\n      const isArrayResponse = !isPaginated && op.response?.kind === 'array';\n      let fixturePath = `testdata/${fileName(respModel)}.json`;\n      if (fixtureRewrites.has(fixturePath)) {\n        fixturePath = fixtureRewrites.get(fixturePath)!;\n      }\n      const expectedPath = buildExpectedPath(op);\n\n      const httpMethodUpper = op.httpMethod.toUpperCase();\n      const isBodyMethod = httpMethodUpper === 'POST' || httpMethodUpper === 'PUT' || httpMethodUpper === 'PATCH';\n\n      lines.push(`func ${testName}(t *testing.T) {`);\n      lines.push('\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {');\n      lines.push(`\\t\\trequire.Equal(t, \"${httpMethodUpper}\", r.Method)`);\n      lines.push(`\\t\\trequire.Equal(t, \"${expectedPath}\", r.URL.Path)`);\n\n      // Validate request body for POST/PUT/PATCH when body fields are actually sent.\n      // Skip for union-type bodies (test sends empty Body interface{}) and operations\n      // where all body fields are hidden.\n      const resolvedLookup = buildResolvedLookup(ctx);\n      const resolvedOp = lookupResolved(op, resolvedLookup);\n      const hiddenSet = buildHiddenParams(resolvedOp);\n      let hasVisibleBody = false;\n      if (isBodyMethod && op.requestBody?.kind === 'model') {\n        const bodyModel = spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n        if (bodyModel) {\n          hasVisibleBody = bodyModel.fields.some((f) => !hiddenSet.has(f.name));\n        }\n      }\n      // Don't validate body for union types -- test sends nil Body\n      if (hasVisibleBody) {\n        lines.push('\\t\\tbody, _ := io.ReadAll(r.Body)');\n        lines.push('\\t\\tvar bodyMap map[string]interface{}');\n        lines.push('\\t\\trequire.NoError(t, json.Unmarshal(body, &bodyMap))');\n      }\n\n      lines.push('\\t\\tw.Header().Set(\"Content-Type\", \"application/json\")');\n      lines.push('\\t\\tw.WriteHeader(http.StatusOK)');\n      if (isArrayResponse) {\n        lines.push(`\\t\\tfixture, err := os.ReadFile(\"${fixturePath}\")`);\n        lines.push('\\t\\tif err != nil {');\n        lines.push('\\t\\t\\tt.Fatalf(\"failed to read fixture: %v\", err)');\n        lines.push('\\t\\t}');\n        lines.push('\\t\\tw.Write([]byte(\"[\" + string(fixture) + \"]\"))');\n      } else {\n        lines.push(`\\t\\tfixture, err := os.ReadFile(\"${fixturePath}\")`);\n        lines.push('\\t\\tif err != nil {');\n        lines.push('\\t\\t\\tt.Fatalf(\"failed to read fixture: %v\", err)');\n        lines.push('\\t\\t}');\n        lines.push('\\t\\tw.Write(fixture)');\n      }\n      lines.push('\\t}))');\n      lines.push('\\tdefer server.Close()');\n      lines.push('');\n      lines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithBaseURL(server.URL))`);\n\n      const callArgs = buildMethodCallArgs(op, plan, ctx, resolvedName);\n      lines.push(`\\tresult, err := client.${accessorName}().${method}(${callArgs})`);\n      lines.push('\\trequire.NoError(t, err)');\n      if (isArrayResponse) {\n        lines.push('\\trequire.NotEmpty(t, result)');\n      } else {\n        lines.push('\\trequire.NotNil(t, result)');\n        // Add specific field value assertions from fixture data\n        const respModelDef = spec.models.find((m) => m.name === respModel);\n        if (respModelDef) {\n          const fixtureAssertions = buildFixtureAssertions(respModelDef, ctx.namespace);\n          for (const assertion of fixtureAssertions) {\n            lines.push(`\\t${assertion}`);\n          }\n        }\n      }\n      lines.push('}');\n      lines.push('');\n    } else {\n      // Void response test\n      const expectedPath = buildExpectedPath(op);\n      lines.push(`func ${testName}(t *testing.T) {`);\n      lines.push('\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {');\n      lines.push(`\\t\\trequire.Equal(t, \"${op.httpMethod.toUpperCase()}\", r.Method)`);\n      lines.push(`\\t\\trequire.Equal(t, \"${expectedPath}\", r.URL.Path)`);\n      lines.push('\\t\\tw.WriteHeader(http.StatusOK)');\n      lines.push('\\t}))');\n      lines.push('\\tdefer server.Close()');\n      lines.push('');\n      lines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithBaseURL(server.URL))`);\n\n      const callArgs = buildMethodCallArgs(op, plan, ctx, resolvedName);\n      lines.push(`\\terr := client.${accessorName}().${method}(${callArgs})`);\n      lines.push('\\trequire.NoError(t, err)');\n      lines.push('}');\n      lines.push('');\n    }\n  }\n\n  // Generate tests for union split wrapper methods (e.g., AuthenticateWithPassword)\n  const resolvedLookup = buildResolvedLookup(ctx);\n  for (const op of service.operations) {\n    const resolved = lookupResolved(op, resolvedLookup);\n    if (!resolved?.wrappers || resolved.wrappers.length === 0) continue;\n\n    for (const wrapper of resolved.wrappers) {\n      const wrapperMethod = goMethodName(wrapper.name);\n      if (emittedTestMethods.has(wrapperMethod)) continue;\n      emittedTestMethods.add(wrapperMethod);\n\n      const wrapperParamsStruct = paramsStructName(resolvedName, wrapperMethod);\n      const responseType = wrapper.responseModelName;\n      const testName = `Test${accessorName}_${wrapperMethod}`;\n      let fixturePath = responseType ? `testdata/${fileName(responseType)}.json` : null;\n      if (fixturePath && fixtureRewrites.has(fixturePath)) {\n        fixturePath = fixtureRewrites.get(fixturePath)!;\n      }\n\n      const wrapperCallArgs: string[] = ['context.Background()'];\n      for (const p of sortPathParamsByTemplateOrder(op)) {\n        wrapperCallArgs.push(`\"test_${p.name}\"`);\n      }\n      wrapperCallArgs.push(`&${ctx.namespace}.${wrapperParamsStruct}{}`);\n\n      lines.push(\n        ...generateWrapperTestLines(\n          testName,\n          accessorName,\n          wrapperMethod,\n          op.httpMethod.toUpperCase(),\n          buildExpectedPath(op),\n          fixturePath,\n          wrapperCallArgs.join(', '),\n          responseType,\n          ctx.namespace,\n        ),\n      );\n    }\n  }\n\n  // Error test (one per file: 401). Skip wrapper-split ops (parent method\n  // isn't emitted) and URL-builder ops (no HTTP call to error-test against).\n  const sampleOp = service.operations.find((o) => {\n    const r = lookupResolved(o, resolvedLookupMain);\n    return (r?.wrappers?.length ?? 0) === 0 && !(r?.urlBuilder ?? false);\n  });\n  if (sampleOp) {\n    const plan = planOperation(sampleOp);\n    const method = resolveGoMethodName(sampleOp, resolvedName, ctx);\n    const callArgs = buildMethodCallArgs(sampleOp, plan, ctx, resolvedName);\n\n    lines.push(`func Test${accessorName}_Error401(t *testing.T) {`);\n    lines.push('\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {');\n    lines.push('\\t\\tw.Header().Set(\"Content-Type\", \"application/json\")');\n    lines.push('\\t\\tw.WriteHeader(http.StatusUnauthorized)');\n    lines.push('\\t\\tw.Write([]byte(`{\"code\":\"unauthorized\",\"message\":\"Unauthorized\"}`))');\n    lines.push('\\t}))');\n    lines.push('\\tdefer server.Close()');\n    lines.push('');\n    lines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithBaseURL(server.URL))`);\n\n    if (plan.isPaginated) {\n      lines.push(`\\titer := client.${accessorName}().${method}(${callArgs})`);\n      lines.push('\\trequire.False(t, iter.Next())');\n      lines.push(`\\trequire.IsType(t, &${ctx.namespace}.AuthenticationError{}, iter.Err())`);\n    } else if (plan.isDelete || !plan.responseModelName) {\n      lines.push(`\\terr := client.${accessorName}().${method}(${callArgs})`);\n      lines.push(`\\trequire.IsType(t, &${ctx.namespace}.AuthenticationError{}, err)`);\n    } else {\n      lines.push(`\\t_, err := client.${accessorName}().${method}(${callArgs})`);\n      lines.push(`\\trequire.IsType(t, &${ctx.namespace}.AuthenticationError{}, err)`);\n    }\n    lines.push('}');\n    lines.push('');\n\n    // Error 404 test\n    lines.push(`func Test${accessorName}_Error404(t *testing.T) {`);\n    lines.push('\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {');\n    lines.push('\\t\\tw.Header().Set(\"Content-Type\", \"application/json\")');\n    lines.push('\\t\\tw.WriteHeader(http.StatusNotFound)');\n    lines.push('\\t\\tw.Write([]byte(`{\"code\":\"not_found\",\"message\":\"Not Found\"}`))');\n    lines.push('\\t}))');\n    lines.push('\\tdefer server.Close()');\n    lines.push('');\n    lines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithBaseURL(server.URL))`);\n\n    if (plan.isPaginated) {\n      lines.push(`\\titer := client.${accessorName}().${method}(${callArgs})`);\n      lines.push('\\trequire.False(t, iter.Next())');\n      lines.push(`\\trequire.IsType(t, &${ctx.namespace}.NotFoundError{}, iter.Err())`);\n    } else if (plan.isDelete || !plan.responseModelName) {\n      lines.push(`\\terr := client.${accessorName}().${method}(${callArgs})`);\n      lines.push(`\\trequire.IsType(t, &${ctx.namespace}.NotFoundError{}, err)`);\n    } else {\n      lines.push(`\\t_, err := client.${accessorName}().${method}(${callArgs})`);\n      lines.push(`\\trequire.IsType(t, &${ctx.namespace}.NotFoundError{}, err)`);\n    }\n    lines.push('}');\n    lines.push('');\n\n    // Error 422 test\n    lines.push(`func Test${accessorName}_Error422(t *testing.T) {`);\n    lines.push('\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {');\n    lines.push('\\t\\tw.Header().Set(\"Content-Type\", \"application/json\")');\n    lines.push('\\t\\tw.WriteHeader(422)');\n    lines.push('\\t\\tw.Write([]byte(`{\"code\":\"unprocessable_entity\",\"message\":\"Unprocessable\"}`))');\n    lines.push('\\t}))');\n    lines.push('\\tdefer server.Close()');\n    lines.push('');\n    lines.push(`\\tclient := ${ctx.namespace}.NewClient(\"sk_test\", ${ctx.namespace}.WithBaseURL(server.URL))`);\n\n    if (plan.isPaginated) {\n      lines.push(`\\titer := client.${accessorName}().${method}(${callArgs})`);\n      lines.push('\\trequire.False(t, iter.Next())');\n      lines.push(`\\trequire.IsType(t, &${ctx.namespace}.UnprocessableEntityError{}, iter.Err())`);\n    } else if (plan.isDelete || !plan.responseModelName) {\n      lines.push(`\\terr := client.${accessorName}().${method}(${callArgs})`);\n      lines.push(`\\trequire.IsType(t, &${ctx.namespace}.UnprocessableEntityError{}, err)`);\n    } else {\n      lines.push(`\\t_, err := client.${accessorName}().${method}(${callArgs})`);\n      lines.push(`\\trequire.IsType(t, &${ctx.namespace}.UnprocessableEntityError{}, err)`);\n    }\n    lines.push('}');\n    lines.push('');\n  }\n\n  return {\n    path: testFile,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\nfunction resolveGoMethodName(op: Operation, mountName: string, ctx: EmitterContext): string {\n  return resolveMethodName(op, { name: mountName, operations: [op] }, ctx);\n}\n\nfunction buildMethodCallArgs(op: Operation, plan: any, ctx: EmitterContext, mountName: string): string {\n  const args: string[] = ['context.Background()'];\n\n  // Path params (sorted by template order)\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    args.push(`\"test_${p.name}\"`);\n  }\n\n  // Params struct if needed — must mirror resources.ts hasParams logic\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const resolvedOp = lookupResolved(op, resolvedLookup);\n  const hidden = buildHiddenParams(resolvedOp);\n  const hasVisibleQueryParams = op.queryParams.filter((qp) => !hidden.has(qp.name)).length > 0;\n  const hasBody = plan.hasBody && op.requestBody;\n  let hasVisibleBodyFields = false;\n  if (hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) {\n      hasVisibleBodyFields = bodyModel.fields.some((f) => !hidden.has(f.name));\n    }\n  } else if (hasBody) {\n    hasVisibleBodyFields = true;\n  }\n\n  if (hasVisibleBodyFields || hasVisibleQueryParams) {\n    const method = resolveGoMethodName(op, mountName, ctx);\n    const pName = paramsStructName(mountName, method);\n    args.push(`&${ctx.namespace}.${pName}{}`);\n  }\n\n  return args.join(', ');\n}\n\n/**\n * Build method call args with a populated filter param for list tests.\n * If filterParam is provided, populates it in the params struct initializer.\n */\nfunction buildMethodCallArgsWithFilter(\n  op: Operation,\n  plan: any,\n  ctx: EmitterContext,\n  mountName: string,\n  filterParam?: { name: string; type: import('@workos/oagen').TypeRef } | null,\n): string {\n  const args: string[] = ['context.Background()'];\n\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    args.push(`\"test_${p.name}\"`);\n  }\n\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const resolvedOp = lookupResolved(op, resolvedLookup);\n  const hidden = buildHiddenParams(resolvedOp);\n  const hasVisibleQueryParams = op.queryParams.filter((qp) => !hidden.has(qp.name)).length > 0;\n  const hasBody = plan.hasBody && op.requestBody;\n  let hasVisibleBodyFields = false;\n  if (hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) {\n      hasVisibleBodyFields = bodyModel.fields.some((f) => !hidden.has(f.name));\n    }\n  } else if (hasBody) {\n    hasVisibleBodyFields = true;\n  }\n\n  if (hasVisibleBodyFields || hasVisibleQueryParams) {\n    const method = resolveGoMethodName(op, mountName, ctx);\n    const pName = paramsStructName(mountName, method);\n    if (filterParam) {\n      const isPaginationField = ['before', 'after', 'limit', 'order'].includes(filterParam.name);\n      // Check if params struct embeds PaginationParams (has before/after/limit)\n      const allQPs = op.queryParams.filter((qp) => !hidden.has(qp.name));\n      const embedsPagination = ['before', 'after', 'limit'].every((name) => allQPs.some((qp) => qp.name === name));\n      const goField = goFieldName(filterParam.name);\n\n      let valExpr: string;\n      if (filterParam.name === 'limit') {\n        valExpr = `${goField}: ptrInt(10)`;\n      } else {\n        valExpr = `${goField}: ptrString(\"test_${filterParam.name}\")`;\n      }\n\n      if (isPaginationField && embedsPagination) {\n        // Pagination fields are embedded — set via embedded struct\n        args.push(`&${ctx.namespace}.${pName}{PaginationParams: ${ctx.namespace}.PaginationParams{${valExpr}}}`);\n      } else {\n        args.push(`&${ctx.namespace}.${pName}{${valExpr}}`);\n      }\n    } else {\n      args.push(`&${ctx.namespace}.${pName}{}`);\n    }\n  }\n\n  return args.join(', ');\n}\n\n/** Build the expected URL path with test placeholder values. */\nfunction buildExpectedPath(op: Operation): string {\n  let expected = op.path;\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    expected = expected.replace(`{${p.name}}`, `test_${p.name}`);\n  }\n  return expected;\n}\n\nfunction generateWrapperTestLines(\n  testName: string,\n  accessorName: string,\n  wrapperMethod: string,\n  httpMethod: string,\n  expectedPath: string,\n  fixturePath: string | null,\n  callArgs: string,\n  responseType: string | null,\n  namespace: string,\n): string[] {\n  const lines: string[] = [];\n  const serverHandler = [\n    '\\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {',\n    `\\t\\trequire.Equal(t, \"${httpMethod}\", r.Method)`,\n    `\\t\\trequire.Equal(t, \"${expectedPath}\", r.URL.Path)`,\n    '\\t\\tw.Header().Set(\"Content-Type\", \"application/json\")',\n    '\\t\\tw.WriteHeader(http.StatusOK)',\n  ];\n  if (fixturePath) {\n    serverHandler.push(`\\t\\tfixture, err := os.ReadFile(\"${fixturePath}\")`);\n    serverHandler.push('\\t\\tif err != nil {');\n    serverHandler.push('\\t\\t\\tt.Fatalf(\"failed to read fixture: %v\", err)');\n    serverHandler.push('\\t\\t}');\n    serverHandler.push('\\t\\tw.Write(fixture)');\n  } else {\n    serverHandler.push('\\t\\tw.Write([]byte(`{}`))');\n  }\n  serverHandler.push('\\t}))');\n\n  // Add body validation for wrapper POST methods before building handler lines\n  const isWrapperBodyMethod = httpMethod === 'POST' || httpMethod === 'PUT' || httpMethod === 'PATCH';\n  if (isWrapperBodyMethod) {\n    const headerIdx = serverHandler.findIndex((l) => l.includes('w.Header().Set'));\n    if (headerIdx >= 0) {\n      serverHandler.splice(\n        headerIdx,\n        0,\n        '\\t\\tbody, _ := io.ReadAll(r.Body)',\n        '\\t\\tvar bodyMap map[string]interface{}',\n        '\\t\\trequire.NoError(t, json.Unmarshal(body, &bodyMap))',\n      );\n    }\n  }\n\n  lines.push(`func ${testName}(t *testing.T) {`);\n  lines.push(...serverHandler);\n  lines.push('\\tdefer server.Close()');\n  lines.push('');\n  lines.push(`\\tclient := ${namespace}.NewClient(\"sk_test\", ${namespace}.WithBaseURL(server.URL))`);\n\n  if (responseType) {\n    lines.push(`\\tresult, err := client.${accessorName}().${wrapperMethod}(${callArgs})`);\n    lines.push('\\trequire.NoError(t, err)');\n    lines.push('\\trequire.NotNil(t, result)');\n  } else {\n    lines.push(`\\terr := client.${accessorName}().${wrapperMethod}(${callArgs})`);\n    lines.push('\\trequire.NoError(t, err)');\n  }\n\n  lines.push('}');\n  lines.push('');\n  return lines;\n}\n\n/**\n * Build field value assertions from fixture data for a response model.\n * Returns Go assertion lines (without leading \\t).\n * Checks id field and 1-2 other required string fields.\n */\nfunction buildFixtureAssertions(model: import('@workos/oagen').Model, _namespace: string): string[] {\n  const assertions: string[] = [];\n  const fixtureValues = generateModelFixtureValues(model);\n\n  // Priority: assert the 'id' field first\n  const idField = model.fields.find((f) => f.required && f.name === 'id');\n  if (idField && fixtureValues[idField.name] != null) {\n    const goField = goFieldName(idField.name);\n    const val = fixtureValues[idField.name];\n    if (typeof val === 'string' && isGoStringSafe(val)) {\n      assertions.push(`require.Equal(t, \"${escapeGoString(val)}\", result.${goField})`);\n    } else {\n      assertions.push(`require.NotEmpty(t, result.${goField})`);\n    }\n  }\n\n  // Assert 1-2 other required string fields\n  let extraCount = 0;\n  for (const field of model.fields) {\n    if (extraCount >= 2) break;\n    if (field.name === 'id') continue;\n    if (!field.required) continue;\n    if (field.type.kind !== 'primitive' || field.type.type !== 'string') continue;\n    const val = fixtureValues[field.name];\n    if (val == null) continue;\n    const goField = goFieldName(field.name);\n    if (typeof val === 'string' && isGoStringSafe(val)) {\n      assertions.push(`require.Equal(t, \"${escapeGoString(val)}\", result.${goField})`);\n    } else {\n      assertions.push(`require.NotEmpty(t, result.${goField})`);\n    }\n    extraCount++;\n  }\n\n  // Fallback: at least assert NotEmpty on the first required string field\n  if (assertions.length === 0) {\n    const targetField =\n      model.fields.find((f) => f.required && f.name === 'id') ||\n      model.fields.find((f) => f.required && f.type.kind === 'primitive' && f.type.type === 'string');\n    if (targetField) {\n      assertions.push(`require.NotEmpty(t, result.${goFieldName(targetField.name)})`);\n    }\n  }\n\n  return assertions;\n}\n\n/** Check if a string value can be safely embedded in a Go double-quoted string. */\nfunction isGoStringSafe(val: string): boolean {\n  // Skip values that look like JSON objects/arrays or contain template expressions\n  if (val.includes('{') || val.includes('}') || val.includes('`')) return false;\n  return true;\n}\n\n/** Escape special characters for a Go double-quoted string. */\nfunction escapeGoString(val: string): string {\n  return val.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n');\n}\n\n/** Generate fixture values for a model (same logic as fixtures.ts but inline). */\nfunction generateModelFixtureValues(model: import('@workos/oagen').Model): Record<string, any> {\n  const fixture: Record<string, any> = {};\n  for (const field of model.fields) {\n    if (field.example !== undefined) {\n      fixture[field.name] = field.example;\n    } else if (field.type.kind === 'primitive' && field.type.type === 'string') {\n      if (field.name === 'id') {\n        const prefix = (ID_PREFIXES as Record<string, string>)[model.name] ?? '';\n        fixture[field.name] = `${prefix}01234`;\n      } else if (field.name.includes('email')) {\n        fixture[field.name] = 'test@example.com';\n      } else if (field.name.includes('name')) {\n        fixture[field.name] = 'Test';\n      } else {\n        fixture[field.name] = `test_${field.name}`;\n      }\n    }\n  }\n  return fixture;\n}\n\n// Re-import fixture ID prefixes\nimport { ID_PREFIXES } from './fixtures.js';\n","import type { ApiSpec, EmitterContext, OperationsMap } from '@workos/oagen';\nimport { resolveMethodName } from './naming.js';\nimport { buildServiceAccessPaths } from './client.js';\nimport { buildResolvedLookup, lookupResolved, getMountTarget } from '../shared/resolved-ops.js';\n\n/**\n * Build operation-to-SDK-method mapping for the manifest.\n */\nexport function buildOperationsMap(spec: ApiSpec, ctx: EmitterContext): OperationsMap {\n  const manifest: OperationsMap = {};\n  const accessPaths = buildServiceAccessPaths(spec.services, ctx);\n  const resolvedLookup = buildResolvedLookup(ctx);\n\n  for (const service of spec.services) {\n    let serviceProp = accessPaths.get(service.name);\n    if (!serviceProp) {\n      const mountTarget = getMountTarget(service, ctx);\n      serviceProp = accessPaths.get(mountTarget);\n    }\n    if (!serviceProp) {\n      throw new Error(`Missing public client access path for service ${service.name}`);\n    }\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const method = resolveMethodName(op, service, ctx);\n\n      // Use per-operation mountOn when it differs from the service default\n      const resolved = lookupResolved(op, resolvedLookup);\n      const propName = (resolved && accessPaths.get(resolved.mountOn)) ?? serviceProp;\n\n      manifest[httpKey] = { sdkMethod: method, service: propName };\n    }\n  }\n\n  return manifest;\n}\n","import type {\n  Emitter,\n  EmitterContext,\n  FormatCommand,\n  GeneratedFile,\n  ApiSpec,\n  Model,\n  Enum,\n  Service,\n} from '@workos/oagen';\n\nimport { generateModels } from './models.js';\nimport { enrichModelsFromSpec, getSyntheticEnums } from '../shared/model-utils.js';\nimport { flattenDiscriminatedUnionFields } from '../shared/union-flatten.js';\nimport { generateEnums } from './enums.js';\nimport { generateResources } from './resources.js';\nimport { generateClient } from './client.js';\nimport { generateTests } from './tests.js';\nimport { buildOperationsMap } from './manifest.js';\n\n/** Ensure every generated file's content ends with a trailing newline. */\nfunction ensureTrailingNewlines(files: GeneratedFile[]): GeneratedFile[] {\n  for (const f of files) {\n    if (f.content && !f.content.endsWith('\\n')) {\n      f.content += '\\n';\n    }\n  }\n  return files;\n}\n\nexport const goEmitter: Emitter = {\n  language: 'go',\n\n  generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n    // Enrich models by flattening oneOf/allOf+oneOf variant fields from the raw\n    // spec. Pass the IR enums so enrichment seeds their names and does NOT mint a\n    // synthetic enum that duplicates one the parser already emitted (e.g. an\n    // inline `error` enum). Go writes every enum into a single enums.go, so a\n    // duplicate name becomes a `type X = Y` redeclaration and fails to compile.\n    // Ruby and PHP already pass `enums` here for the same reason.\n    const enriched = enrichModelsFromSpec(models, ctx.spec.enums);\n    // Go has no sum types, so discriminated union base models (e.g. EventSchema)\n    // need their base fields preserved. enrichModelsFromSpec clears fields for\n    // discriminated models so dispatcher-capable languages can generate sealed\n    // classes; restore the original fields here since Go just emits flat structs.\n    const originalByName = new Map(models.map((m) => [m.name, m]));\n    const goModels = enriched.map((m) => {\n      if ((m as any).discriminator && m.fields.length === 0) {\n        const original = originalByName.get(m.name);\n        if (original && original.fields.length > 0) {\n          return { ...m, fields: original.fields };\n        }\n      }\n      return m;\n    });\n    // Go has no sum types: a discriminated-union field (e.g. ApiKey.owner)\n    // renders as its first variant, dropping fields that only exist on later\n    // variants (organization_id on the user owner). Flatten such unions into a\n    // single superset struct so every variant field survives.\n    return ensureTrailingNewlines(generateModels(flattenDiscriminatedUnionFields(goModels), ctx));\n  },\n\n  generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n    // Merge synthetic enums produced during model enrichment (inline oneOf\n    // definitions) so they get proper type definitions in enums.go.\n    const syntheticEnums = getSyntheticEnums();\n    return ensureTrailingNewlines(generateEnums([...enums, ...syntheticEnums], ctx));\n  },\n\n  generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateResources(services, ctx));\n  },\n\n  generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateClient(spec, ctx));\n  },\n\n  generateErrors(): GeneratedFile[] {\n    return [];\n  },\n\n  generateTypeSignatures(): GeneratedFile[] {\n    // Go uses inline type annotations -- no separate type signature files needed\n    return [];\n  },\n\n  generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateTests(spec, ctx));\n  },\n\n  buildOperationsMap(spec: ApiSpec, ctx: EmitterContext) {\n    return buildOperationsMap(spec, ctx);\n  },\n\n  fileHeader(): string {\n    // Go-specific: this exact form matches the standard generated-file regex\n    // (`^// Code generated .* DO NOT EDIT\\.$`) that gofmt, gopls, golangci-lint,\n    // and other Go tooling use to classify a file as generated. It intentionally\n    // does NOT use the shared AUTOGEN_NOTICE, which would break that detection.\n    return '// Code generated by oagen. DO NOT EDIT.';\n  },\n\n  formatCommand(_targetDir: string): FormatCommand | null {\n    // oagen appends all generated file paths (including .json fixtures) to the\n    // format command. gofmt errors on non-.go files, so filter them out.\n    // Same pattern as the Python emitter's ruff wrapper.\n    return {\n      cmd: 'bash',\n      args: [\n        '-c',\n        'GO_FILES=$(printf \"%s\\\\n\" \"$@\" | grep \"\\\\.go$\"); [ -n \"$GO_FILES\" ] && echo \"$GO_FILES\" | xargs gofmt -w',\n        '--',\n      ],\n      batchSize: 999999,\n    };\n  },\n};\n","import type { Operation, Service, EmitterContext } from '@workos/oagen';\nimport { toPascalCase, toSnakeCase } from '@workos/oagen';\nimport { buildResolvedLookup, lookupMethodName, lookupResolved, getMountTarget } from '../shared/resolved-ops.js';\nimport { stripUrnPrefix } from '../shared/naming-utils.js';\n\n/** PascalCase class/type name. */\nexport function className(name: string): string {\n  return toPascalCase(stripUrnPrefix(name));\n}\n\n/** Display name for a model type, including consumer-friendly aliases. */\nexport function modelClassName(name: string): string {\n  switch (name) {\n    case 'EmailChangeConfirmationUser':\n    case 'UserlandUser':\n      return 'User';\n    default:\n      return className(name);\n  }\n}\n\n/** PascalCase file name (without extension). */\nexport function fileName(name: string): string {\n  return toPascalCase(stripUrnPrefix(name));\n}\n\n/** snake_case file name for fixtures/test data. */\nexport function fixtureFileName(name: string): string {\n  return toSnakeCase(stripUrnPrefix(name));\n}\n\n/** PascalCase method name. */\nexport function methodName(name: string): string {\n  return toPascalCase(name);\n}\n\n/** PascalCase property name. */\nexport function fieldName(name: string): string {\n  return toPascalCase(name);\n}\n\n/**\n * PascalCase domain property name for a model field, honoring a `domainName`\n * override (set via the `fieldHints` config) so a wire field can surface under\n * a friendlier C# property name. The wire/serialization key (the\n * `[JsonPropertyName(\"...\")]` value) still derives from `field.name`.\n */\nexport function domainFieldName(field: { name: string; domainName?: string }): string {\n  return toPascalCase(field.domainName ?? field.name);\n}\n\n/** PascalCase directory name for service modules. */\nexport function moduleName(name: string): string {\n  return toPascalCase(name);\n}\n\n/** PascalCase property name for service accessors on the client. */\nexport function servicePropertyName(name: string): string {\n  return className(name);\n}\n\n/** Resolve the effective service name using resolved operations. */\nexport function resolveServiceName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n/** Build a map from IR service name to resolved service name. */\nexport function buildServiceNameMap(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of services) {\n    map.set(service.name, resolveServiceName(service, ctx));\n  }\n  return map;\n}\n\n/** Resolve the output directory for a service. */\nexport function resolveServiceDir(resolvedServiceName: string): string {\n  return moduleName(resolvedServiceName);\n}\n\nfunction trimAsyncSuffix(name: string): string {\n  return name.endsWith('Async') ? name.slice(0, -5) : name;\n}\n\n/** Append Async once for TAP-style method names. */\nexport function appendAsyncSuffix(name: string): string {\n  return name.endsWith('Async') ? name : `${name}Async`;\n}\n\n/** Resolve the stable method stem for an operation (without any Async suffix). */\nexport function resolveMethodStem(op: Operation, _service: Service, ctx: EmitterContext): string {\n  const lookup = buildResolvedLookup(ctx);\n  const resolved = lookupMethodName(op, lookup);\n  if (resolved) {\n    return trimMountedResourceFromMethod(methodName(trimAsyncSuffix(resolved)), resolveClassName(_service, ctx));\n  }\n  const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const existing = ctx.overlayLookup?.methodByOperation?.get(httpKey);\n  if (existing) {\n    return trimMountedResourceFromMethod(\n      methodName(trimAsyncSuffix(existing.methodName)),\n      resolveClassName(_service, ctx),\n    );\n  }\n  return trimMountedResourceFromMethod(methodName(trimAsyncSuffix(op.name)), resolveClassName(_service, ctx));\n}\n\n/** Resolve the SDK method name for an operation. */\nexport function resolveMethodName(op: Operation, service: Service, ctx: EmitterContext): string {\n  const stem = resolveMethodStem(op, service, ctx);\n  const resolved = lookupResolved(op, buildResolvedLookup(ctx));\n  if (resolved?.urlBuilder ?? false) {\n    return stem;\n  }\n\n  return appendAsyncSuffix(stem);\n}\n\n/** Resolve the SDK class name for a service. */\nexport function resolveClassName(service: Service, ctx: EmitterContext): string {\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (r.service.name === service.name) return className(r.mountOn);\n  }\n  if (ctx.overlayLookup?.methodByOperation) {\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const existing = ctx.overlayLookup.methodByOperation.get(httpKey);\n      if (existing) return className(existing.className);\n    }\n  }\n  return className(service.name);\n}\n\n/** Build a map from IR service name to mount-target directory name. */\nexport function buildMountDirMap(ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of ctx.spec.services) {\n    const target = getMountTarget(service, ctx);\n    map.set(service.name, moduleName(target));\n  }\n  return map;\n}\n\nfunction splitPascalWords(name: string): string[] {\n  return name.match(/[A-Z]+(?:[a-z]+|(?=[A-Z]|$))|[A-Z]?[a-z]+|[0-9]+/g) ?? [name];\n}\n\nfunction singularize(word: string): string {\n  if (word.endsWith('ies') && word.length > 3) {\n    return `${word.slice(0, -3)}y`;\n  }\n  if (word.endsWith('s') && !word.endsWith('ss')) {\n    return word.slice(0, -1);\n  }\n  return word;\n}\n\nfunction wordsMatch(left: string, right: string): boolean {\n  return singularize(left.toLowerCase()) === singularize(right.toLowerCase());\n}\n\nexport function trimMountedResourceFromMethod(method: string, mountName: string): string {\n  const methodWords = splitPascalWords(method);\n  if (methodWords.length < 2) return method;\n\n  const mountWords = splitPascalWords(className(mountName));\n  if (mountWords.length === 0) return method;\n\n  let matched = 0;\n  while (\n    matched < mountWords.length &&\n    matched + 1 < methodWords.length &&\n    wordsMatch(methodWords[matched + 1], mountWords[matched])\n  ) {\n    matched++;\n  }\n\n  if (matched === 0) return method;\n\n  return [methodWords[0], ...methodWords.slice(matched + 1)].join('');\n}\n\n/** Service type name for the class declaration. */\nexport function serviceTypeName(name: string): string {\n  // Preserve pluralization for C# service names (OrganizationsService, not OrganizationService)\n  return `${className(name)}Service`;\n}\n\n/** camelCase for local variables. */\nexport function localName(name: string): string {\n  const pascal = toPascalCase(name);\n  if (!pascal) return pascal;\n  return pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n\n/** Escape a value as a C# literal. */\nexport function csLiteral(value: string | number | boolean): string {\n  if (typeof value === 'string') return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  return String(value);\n}\n\n/** Map a wire field name to the WorkOSClient property expression. */\nexport function clientFieldExpression(field: string): string {\n  switch (field) {\n    case 'client_id':\n      return 'ClientId';\n    case 'client_secret':\n      return 'ApiKey';\n    default:\n      return fieldName(field);\n  }\n}\n\n/** Convert an HTTP method string to the C# HttpMethod static property name. */\nexport function httpMethodCs(method: string): string {\n  const m = method.toLowerCase();\n  switch (m) {\n    case 'get':\n      return 'Get';\n    case 'post':\n      return 'Post';\n    case 'put':\n      return 'Put';\n    case 'patch':\n      return 'Patch';\n    case 'delete':\n      return 'Delete';\n    case 'head':\n      return 'Head';\n    case 'options':\n      return 'Options';\n    default:\n      return 'Get';\n  }\n}\n\n/**\n * Return the name of the Service base-class helper that handles the given\n * HTTP method (e.g., `GetAsync`, `PostAsync`). Used by the resource emitter\n * to produce one-line service methods instead of inlined WorkOSRequest blocks.\n */\nexport function httpMethodHelperName(method: string): string {\n  const m = method.toLowerCase();\n  switch (m) {\n    case 'get':\n      return 'GetAsync';\n    case 'post':\n      return 'PostAsync';\n    case 'put':\n      return 'PutAsync';\n    case 'patch':\n      return 'PatchAsync';\n    case 'delete':\n      return 'DeleteAsync';\n    default:\n      return 'GetAsync';\n  }\n}\n\n/** Escape XML special characters for use in XML doc comments. */\nexport function escapeXml(s: string): string {\n  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n/**\n * Distill a deprecation message from a spec description. Looks for common\n * WorkOS patterns (\"Deprecated. Use X.\", \"Use X instead.\", etc.) and falls\n * back to a generic message scoped to the item kind.\n *\n * Output is suitable for inlining into `[System.Obsolete(\"...\")]`.\n */\nexport function deprecationMessage(\n  description: string | undefined | null,\n  kind: 'field' | 'parameter' | 'operation' | 'value',\n): string {\n  const generic = `This ${kind} is deprecated.`;\n  if (!description) return generic;\n\n  const text = description.replace(/\\s+/g, ' ').trim();\n  if (!text) return generic;\n\n  // Match: \"Deprecated. Use `foo` instead.\" / \"Deprecated: use Foo.\"\n  const deprecatedClause = text.match(/Deprecated[.:][\\s]*(.*?)(?:\\.|$)/i);\n  if (deprecatedClause?.[1]?.trim()) {\n    return `Deprecated. ${deprecatedClause[1].trim().replace(/\\.$/, '')}.`;\n  }\n\n  // Match: \"Use `foo` instead.\" anywhere in the description\n  const useInstead = text.match(/Use\\s+`?([^`.\\s]+)`?\\s+instead/i);\n  if (useInstead) {\n    return `${generic.replace(/\\.$/, '')} Use \\`${useInstead[1]}\\` instead.`;\n  }\n\n  return generic;\n}\n\n/**\n * Escape a C# string literal for use inside `[System.Obsolete(\"...\")]`.\n * Doubles embedded quotes and escapes backslashes.\n */\nexport function escapeCsAttributeString(s: string): string {\n  return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Emit an XML doc summary block from a possibly multi-line spec description.\n * The first non-empty line becomes the `<summary>`. If there are additional\n * non-empty lines, they are emitted as `<remarks>...</remarks>` so users get\n * the full context in tooling (IntelliSense / `dotnet help`) instead of just\n * the first sentence.\n *\n * Returns an empty array if `description` is null/empty so callers can spread\n * the result unconditionally.\n */\nexport function emitXmlDoc(description: string | undefined | null, indent: string): string[] {\n  if (!description) return [];\n  const lines = description\n    .split('\\n')\n    .map((l) => l.trim())\n    .filter((l) => l);\n  if (lines.length === 0) return [];\n\n  const out: string[] = [];\n  out.push(`${indent}/// <summary>${escapeXml(lines[0])}</summary>`);\n  if (lines.length > 1) {\n    out.push(`${indent}/// <remarks>`);\n    for (const remark of lines.slice(1)) {\n      out.push(`${indent}/// ${escapeXml(remark)}`);\n    }\n    out.push(`${indent}/// </remarks>`);\n  }\n  return out;\n}\n\n/**\n * Convert a snake_case or camelCase name to a human-readable string.\n * Preserves acronyms (SSO, API, URL, JWT, OIDC, …) as uppercase tokens and\n * lowercases the rest so generated XML docs read naturally.\n */\nexport function humanize(name: string): string {\n  // Split on underscores and at camelCase boundaries, keeping acronym runs\n  // intact: `SSOConnection` → [\"SSO\", \"Connection\"]; `listUsers` → [\"list\",\n  // \"Users\"]; `api_key` → [\"api\", \"key\"].\n  const parts = name.split('_').flatMap((segment) =>\n    segment\n      .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n      .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n      .split(/\\s+/)\n      .filter(Boolean),\n  );\n  return parts.map((p) => (isAcronymToken(p) ? p : p.toLowerCase())).join(' ');\n}\n\n/** True when a single token looks like a runtime acronym (2+ uppercase letters). */\nfunction isAcronymToken(token: string): boolean {\n  if (token.length < 2) return false;\n  return /^[A-Z0-9]+$/.test(token);\n}\n\n/**\n * Return the English indefinite article (\"a\" or \"an\") appropriate for the\n * given humanized phrase. Uses the first spoken letter of the first word\n * and accounts for common silent-h / vowel-like-consonant cases so\n * generated docs read correctly.\n */\nexport function articleFor(phrase: string): string {\n  const trimmed = phrase.trim();\n  if (!trimmed) return 'a';\n  const firstWord = trimmed.split(/\\s+/)[0];\n  if (!firstWord) return 'a';\n  // Acronyms are voiced letter-by-letter — use the first letter's sound.\n  if (isAcronymToken(firstWord)) {\n    return /^[AEFHILMNORSX]/.test(firstWord) ? 'an' : 'a';\n  }\n  const first = firstWord.toLowerCase();\n  return /^[aeiou]/.test(first) ? 'an' : 'a';\n}\n","import type { TypeRef, PrimitiveType, UnionType } from '@workos/oagen';\nimport { mapTypeRef as irMapTypeRef } from '@workos/oagen';\nimport { className, modelClassName } from './naming.js';\n\n/** Known C# value types that need `?` for nullable. */\nconst VALUE_TYPES = new Set(['int', 'long', 'double', 'bool', 'float', 'decimal', 'byte', 'short', 'DateTimeOffset']);\n\n/**\n * Module-level alias map for structurally-identical enums. Populated by\n * `setEnumAliases` from the current spec's enum list; consulted by\n * `mapTypeRef` so that every reference to a duplicate enum resolves to the\n * canonical name. C# has no first-class type alias for enums, so dedup must\n * happen at reference-rewrite time rather than via a runtime alias.\n */\nconst enumAliases = new Map<string, string>();\n\n/**\n * Names of enums that resolve to a single wire value and should therefore be\n * mapped to C# `string` at reference sites (the owning property emits a\n * const initializer). Populated by `setSingleValueEnumNames`.\n */\nconst singleValueEnumNames = new Set<string>();\n\n/**\n * Module-level alias map for structurally-identical models. Populated by\n * `setModelAliases` from model deduplication; consulted by `mapTypeRef` so\n * that every reference to a duplicate model resolves to the canonical name.\n */\nconst modelAliases = new Map<string, string>();\n\n/** Replace the current enum-alias map. Safe to call more than once. */\nexport function setEnumAliases(aliases: Map<string, string>): void {\n  enumAliases.clear();\n  for (const [k, v] of aliases) enumAliases.set(k, v);\n}\n\n/** Replace the current model-alias map. Safe to call more than once. */\nexport function setModelAliases(aliases: Map<string, string>): void {\n  modelAliases.clear();\n  for (const [k, v] of aliases) modelAliases.set(k, v);\n}\n\n/** Check if a model name is an alias (i.e., structurally identical to another model). */\nexport function isModelAlias(name: string): boolean {\n  return modelAliases.has(name);\n}\n\n/** Resolve a model name to its canonical form (identity if not an alias). */\nexport function resolveModelName(name: string): string {\n  return modelAliases.get(name) ?? name;\n}\n\n/** Replace the set of enum names that are single-value discriminator stand-ins. */\nexport function setSingleValueEnumNames(names: Iterable<string>): void {\n  singleValueEnumNames.clear();\n  for (const n of names) singleValueEnumNames.add(n);\n}\n\n/** Resolve an enum reference name to its canonical form. */\nexport function resolveEnumTypeName(name: string): string {\n  return enumAliases.get(name) ?? name;\n}\n\n/**\n * Map an IR TypeRef to a C# type string.\n */\nexport function mapTypeRef(ref: TypeRef): string {\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (_ref, items) => `List<${items}>`,\n    model: (r) => modelClassName(modelAliases.get(r.name) ?? r.name),\n    enum: (r) => {\n      // Single-value enums (discriminator consts in disguise) map to `string`\n      // so the caller can't misuse a public one-member enum type. The\n      // owning property emits a const initializer separately.\n      if ((r.values?.length ?? 0) === 1) return 'string';\n      if (singleValueEnumNames.has(r.name)) return 'string';\n      return className(resolveEnumTypeName(r.name));\n    },\n    union: (_r, variants) => joinUnionVariants(_r, variants),\n    nullable: (_ref, inner) => {\n      // With <Nullable>enable</Nullable>, all nullable types need `?`\n      if (inner.endsWith('?')) return inner; // already nullable (e.g., nested nullable)\n      return `${inner}?`;\n    },\n    literal: (r) => {\n      if (r.value === null) return 'object';\n      if (typeof r.value === 'string') return 'string';\n      if (typeof r.value === 'number') return Number.isInteger(r.value) ? 'int' : 'double';\n      if (typeof r.value === 'boolean') return 'bool';\n      return 'object';\n    },\n    map: (_ref, value) => `Dictionary<string, ${value}>`,\n  });\n}\n\n/**\n * Map an IR TypeRef to a C# type string, making optional fields nullable.\n * For value types, appends `?`. For reference types, returns as-is.\n */\nexport function mapTypeRefOptional(ref: TypeRef): string {\n  const baseType = mapTypeRef(ref);\n  if (isValueType(baseType)) return `${baseType}?`;\n  return baseType;\n}\n\n/**\n * Check if a C# type is a value type (needs ? for nullable).\n */\nexport function isValueType(csType: string): boolean {\n  // Strip trailing ? if present\n  const bare = csType.endsWith('?') ? csType.slice(0, -1) : csType;\n  if (VALUE_TYPES.has(bare)) return true;\n  // Enums are value types, but we can't detect them purely from the type string.\n  // The caller should handle enum nullability explicitly when needed.\n  return false;\n}\n\n/**\n * Check if an IR TypeRef maps to a C# value type.\n */\nexport function isValueTypeRef(ref: TypeRef): boolean {\n  if (ref.kind === 'enum') return true;\n  if (ref.kind === 'primitive') {\n    // DateTimeOffset is a value type (struct)\n    if (ref.format === 'date-time') return true;\n    switch (ref.type) {\n      case 'integer':\n      case 'number':\n      case 'boolean':\n        return true;\n      default:\n        return false;\n    }\n  }\n  return false;\n}\n\n/**\n * Whether a TypeRef directly names an enum (no nullable wrapper).\n * Used to detect required enum request fields that must not silently serialize\n * their default Unknown sentinel.\n */\nexport function isEnumRef(ref: TypeRef): boolean {\n  return ref.kind === 'enum';\n}\n\n/**\n * Emit JSON attributes for a request-side property. Property name mapping is\n * handled by a global SnakeCaseLower / SnakeCaseNamingStrategy configuration\n * on both serializers, so per-property name attributes are not emitted.\n *\n * When `isRequiredEnum` is true, configure both serializers to skip the field\n * when its value equals the enum default (0 = Unknown sentinel). This converts\n * \"unset required enum\" from a silent `\"unknown\"` wire value into a clean\n * omission so the API returns a clear `missing required field` error instead\n * of a confusing 422.\n */\nexport function emitJsonPropertyAttributes(\n  wireName: string,\n  options: { isRequiredEnum?: boolean; explicitWireName?: boolean } = {},\n): string[] {\n  // When the C# property name doesn't naturally map back to the wire name via\n  // the SnakeCaseLower naming policy (e.g. we suffixed the property to avoid a\n  // CS0542 class/member collision like `Error.Error` → `Error.ErrorValue`), the\n  // caller pins the wire name explicitly so JSON round-trip still works.\n  if (options.explicitWireName) {\n    if (options.isRequiredEnum) {\n      return [\n        `        [JsonProperty(\"${wireName}\", DefaultValueHandling = DefaultValueHandling.Ignore)]`,\n        `        [STJS.JsonIgnore(Condition = STJS.JsonIgnoreCondition.WhenWritingDefault)]`,\n        `        [STJS.JsonPropertyName(\"${wireName}\")]`,\n      ];\n    }\n    return [`        [JsonProperty(\"${wireName}\")]`, `        [STJS.JsonPropertyName(\"${wireName}\")]`];\n  }\n  if (options.isRequiredEnum) {\n    return [\n      `        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]`,\n      `        [STJS.JsonIgnore(Condition = STJS.JsonIgnoreCondition.WhenWritingDefault)]`,\n    ];\n  }\n  // Convention-based: SnakeCaseLower naming policy handles the name mapping.\n  return [];\n}\n\nfunction mapPrimitive(ref: PrimitiveType): string {\n  if (ref.format === 'binary') return 'byte[]';\n  if (ref.format === 'int32') return 'int';\n  if (ref.format === 'int64') return 'long';\n  if (ref.format === 'date-time') return 'DateTimeOffset';\n  switch (ref.type) {\n    case 'string':\n      return 'string';\n    case 'integer':\n      return 'long';\n    case 'number':\n      return 'double';\n    case 'boolean':\n      return 'bool';\n    case 'unknown':\n      return 'object';\n  }\n}\n\n/**\n * Track discriminated unions for downstream model generation.\n * Key = generated base type name, Value = discriminator info.\n */\nexport const discriminatedUnions = new Map<\n  string,\n  { property: string; mapping: Record<string, string>; variantTypes: string[] }\n>();\n\nfunction joinUnionVariants(_ref: UnionType, variants: string[]): string {\n  if (_ref.compositionKind === 'allOf') {\n    return variants[0] ?? 'object';\n  }\n  const unique = [...new Set(variants)];\n\n  // Discriminated union: register for converter generation BEFORE collapsing\n  // single-unique to avoid losing the discriminator when all variants alias\n  // to the same canonical model (structural dedup). The base type used for\n  // the converter name comes from the discriminator's IR variant names so\n  // it stays stable even when the C# class names get rewritten by aliases.\n  if (_ref.discriminator && _ref.discriminator.mapping) {\n    const irVariantNames = _ref.variants\n      .filter((v) => v.kind === 'model')\n      .map((v) => (v.kind === 'model' ? v.name : ''))\n      .filter(Boolean);\n    const baseName = irVariantNames[0] ?? unique[0];\n    discriminatedUnions.set(baseName, {\n      property: _ref.discriminator.property,\n      mapping: _ref.discriminator.mapping,\n      variantTypes: unique,\n    });\n    // Use object with JsonConverter for discriminated unions since\n    // AnyOf<> doesn't support discriminator-based deserialization\n    return 'object';\n  }\n\n  if (unique.length === 1) return unique[0];\n\n  if (unique.length >= 2 && unique.length <= 9) return `OneOf.OneOf<${unique.join(', ')}>`;\n  // OneOf supports arity 2-9. Higher-arity unions collapse to `object`,\n  // losing type information. Warn so the author knows the spec outgrew the\n  // runtime support instead of silently degrading.\n  if (unique.length >= 10) {\n    console.warn(\n      `[oagen:dotnet] Union with ${unique.length} variants exceeds OneOf<T0..T8> arity; falling back to object. Variants: ${unique.join(', ')}`,\n    );\n  }\n  return 'object';\n}\n","import type { Model, EmitterContext, GeneratedFile, TypeRef, Service } from '@workos/oagen';\nimport { walkTypeRef } from '@workos/oagen';\nimport {\n  mapTypeRef,\n  isValueTypeRef,\n  isEnumRef,\n  emitJsonPropertyAttributes,\n  setModelAliases,\n  isModelAlias,\n  resolveModelName,\n} from './type-map.js';\nimport {\n  articleFor,\n  fieldName,\n  domainFieldName,\n  humanize,\n  emitXmlDoc,\n  deprecationMessage,\n  escapeCsAttributeString,\n  modelClassName,\n} from './naming.js';\n\n// Import and re-export shared model detection utilities\nimport {\n  isListWrapperModel,\n  isListMetadataModel,\n  collectNonPaginatedResponseModelNames,\n} from '../shared/model-utils.js';\nimport { isModelInScope } from '../shared/resolved-ops.js';\nexport { isListWrapperModel, isListMetadataModel };\n\n/**\n * Context for discriminated union inheritance in generated models.\n * When present, base models get a [JsonConverter] attribute and variant\n * models extend the base class, inheriting common fields.\n */\nexport interface DiscriminatorContext {\n  /** Model names that are discriminated union bases. */\n  discriminatorBases: Set<string>;\n  /** Maps variant model name → base model name. */\n  variantToBase: Map<string, string>;\n  /** Maps base model name → wire name of the discriminator property. */\n  discriminatorProperties?: Map<string, string>;\n}\n\n/**\n * Generate C# model classes from IR Models.\n * Each model becomes a separate .cs file under Services/{mount}/Entities/.\n * For initial generation, all models go into a flat Entities/ directory.\n */\nexport function generateModels(models: Model[], ctx: EmitterContext, discCtx?: DiscriminatorContext): GeneratedFile[] {\n  if (models.length === 0) return [];\n\n  // Build a lookup from enum name → single wire value for 1-value enums so\n  // we can emit a const initializer on the owning property without needing\n  // the full EnumRef.values payload (which the IR sometimes omits on refs).\n  const enumConstByName = new Map<string, string>();\n  for (const e of ctx.spec.enums) {\n    if (e.values.length === 1) {\n      enumConstByName.set(e.name, String(e.values[0].value));\n    }\n  }\n\n  const files: GeneratedFile[] = [];\n\n  // Compute and publish model aliases so mapTypeRef rewrites references.\n  // Must run BEFORE collectRequestBodyOnlyModelNames so the body/non-body\n  // tally collapses aliased pairs onto their canonical name — otherwise a\n  // model that's only a request body in name (e.g. `AddRolePermissionDto`)\n  // but is the canonical for a field-referenced alias (e.g. `SlimRole`)\n  // would be wrongly classified as body-only and skipped from emission,\n  // leaving every alias-rewritten field reference dangling.\n  primeModelAliases(models);\n\n  // Models that are referenced ONLY as an operation request body (not by any\n  // response, field, or other operation type) are dead surface in .NET because\n  // the wrapper generator emits a per-operation `*Options` class containing\n  // the same fields. The method signature consumes the Options class — the\n  // named entity is never instantiated by callers and just clutters the SDK\n  // (see workos-dotnet#248 with `CreateUserApiKey` /\n  // `UserManagementCreateApiKeyOptions`). Skip emission for those.\n  const requestBodyOnlyNames = collectRequestBodyOnlyModelNames(ctx.spec.services, models);\n  // Wrappers referenced as a non-paginated response (e.g. `VersionListResponse`\n  // for `GET /vault/v1/kv/{id}/versions`) must still be emitted — the resource\n  // code references them by name and the pagination iterator doesn't unwrap them.\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(ctx.spec.services);\n  const skipAsListWrapper = (m: Model): boolean => isListWrapperModel(m) && !nonPaginatedRefs.has(m.name);\n\n  // Build a lookup of base model field C# names → C# types for inheritance.\n  // Variant models skip inherited fields and use `new` for type-divergent ones.\n  const baseFieldLookup = new Map<string, Map<string, string>>();\n  if (discCtx) {\n    for (const model of models) {\n      if (discCtx.discriminatorBases.has(model.name)) {\n        const baseClassName = modelClassName(model.name);\n        const fieldMap = new Map<string, string>();\n        for (const field of model.fields) {\n          // DOMAIN identifier: the C# property name used for inheritance\n          // comparison (honors a `domainName` override). Must match the\n          // property name emitted below so variant fields dedup correctly.\n          let csName = domainFieldName(field);\n          if (csName === baseClassName) csName = `${csName}Value`;\n          fieldMap.set(csName, mapTypeRef(field.type));\n        }\n        baseFieldLookup.set(model.name, fieldMap);\n      }\n    }\n  }\n\n  for (const model of models) {\n    if (skipAsListWrapper(model) || isListMetadataModel(model)) continue;\n    if (requestBodyOnlyNames.has(model.name)) continue;\n\n    const csClassName = modelClassName(model.name);\n\n    // Skip alias models — all references are already rewritten to the\n    // canonical type by mapTypeRef, so the alias class would be dead code.\n    if (isModelAlias(model.name)) continue;\n\n    const lines: string[] = [];\n    const fieldTypes = model.fields.map((f) => mapTypeRef(f.type));\n    const needsCollections = fieldTypes.some((t) => t.startsWith('List<') || t.startsWith('Dictionary<'));\n    const needsSystem = fieldTypes.some((t) => t.includes('DateTimeOffset'));\n    // Required enums need JsonProperty / STJS; a field whose PascalCase name\n    // collides with the enclosing class needs the same imports for the wire-\n    // name override emitted below.\n    // DOMAIN identifier: the emitted C# property name (honors `domainName`)\n    // is what can collide with the enclosing class name.\n    const hasClassNameCollision = model.fields.some((f) => domainFieldName(f) === csClassName);\n    // A `domainName` override renames the C# property away from the wire key\n    // (e.g. wire `connection_type` surfaced as domain `Type`). The\n    // SnakeCaseLower naming policy would otherwise serialize the domain name,\n    // so these fields need an explicit pinned wire name (and thus the imports).\n    const hasDomainRename = model.fields.some((f) => domainFieldName(f) !== fieldName(f.name));\n    const needsJsonAttrs =\n      hasClassNameCollision || hasDomainRename || model.fields.some((f) => f.required && isEnumRef(f.type));\n\n    lines.push(`namespace ${ctx.namespacePascal}`);\n    lines.push('{');\n    if (needsSystem) {\n      lines.push('    using System;');\n    }\n    if (needsCollections) {\n      lines.push('    using System.Collections.Generic;');\n    }\n    if (needsJsonAttrs) {\n      lines.push('    using Newtonsoft.Json;');\n      lines.push('    using STJS = System.Text.Json.Serialization;');\n    }\n    lines.push('');\n\n    // XML doc comment\n    if (model.description) {\n      lines.push(...emitXmlDoc(model.description, '    '));\n    } else {\n      const human = humanize(model.name);\n      lines.push(`    /// <summary>Represents ${articleFor(human)} ${human}.</summary>`);\n    }\n\n    // Discriminated union base: add JsonConverter so the deserializer dispatches\n    // to the correct variant subclass.\n    const isDiscBase = discCtx?.discriminatorBases.has(model.name) ?? false;\n    if (isDiscBase) {\n      lines.push(`    [Newtonsoft.Json.JsonConverter(typeof(${csClassName}DiscriminatorConverter))]`);\n    }\n\n    // Variant: extend the base class to inherit common fields.\n    const baseName = discCtx?.variantToBase.get(model.name);\n    const baseClassName = baseName ? modelClassName(baseName) : null;\n    const baseFields = baseName ? baseFieldLookup.get(baseName) : undefined;\n\n    if (baseClassName) {\n      lines.push(`    public class ${csClassName} : ${baseClassName}`);\n    } else {\n      lines.push(`    public class ${csClassName}`);\n    }\n    lines.push('    {');\n\n    // Track Dictionary<string, object> fields so we can emit a typed\n    // accessor helper per field at the end of the class body.\n    const dictObjectFields: Array<{ csName: string; typeText: string }> = [];\n\n    // Deduplicate fields by C# property name\n    const seenFieldNames = new Set<string>();\n    for (const field of model.fields) {\n      // CS0542: a property can't share its enclosing class's name. Spec schemas\n      // like `Error.error` PascalCase into `Error.Error`, so suffix with `Value`\n      // when that happens. Track the rename so we emit an explicit\n      // `[JsonProperty]` attribute below — the SnakeCaseLower naming policy\n      // would otherwise serialize `ErrorValue` as `error_value`, not `error`.\n      // DOMAIN identifier: the C# property name, honoring a `domainName`\n      // override (e.g. wire `connection_type` → domain `Type`). The wire key\n      // passed to `emitJsonPropertyAttributes` below still derives from\n      // `field.name`.\n      let csFieldName = domainFieldName(field);\n      const collidesWithClassName = csFieldName === csClassName;\n      if (collidesWithClassName) csFieldName = `${csFieldName}Value`;\n      // When the domain rename diverges from the wire key, the SnakeCaseLower\n      // naming policy can't recover the wire name from the property — pin it.\n      const hasDomainOverride = domainFieldName(field) !== fieldName(field.name);\n      if (seenFieldNames.has(csFieldName)) continue;\n      seenFieldNames.add(csFieldName);\n\n      // Inheritance: if this variant extends a base class, check each field\n      // against the base. Same C# type → skip (inherited). Different C# type\n      // → emit with `new` keyword so the variant has its own typed property.\n      let useNewModifier = false;\n      if (baseFields) {\n        const baseType = baseFields.get(csFieldName);\n        if (baseType !== undefined) {\n          const variantType = mapTypeRef(field.type);\n          if (baseType === variantType) {\n            continue; // Inherited from base — skip\n          }\n          useNewModifier = true;\n        }\n      }\n\n      const isOptional = !field.required;\n      const baseType = mapTypeRef(field.type);\n      const isAlreadyNullable = baseType.endsWith('?');\n      const constInit = singleValueConstInitializer(field.type, enumConstByName);\n      let csType: string;\n      let initializer = '';\n      let setterModifier = '';\n\n      // On a discriminated union base, the discriminator property (e.g. \"event\")\n      // should be non-public-settable even though it lacks a single const value\n      // (each variant has a different value). Consumers must never mutate it.\n      const discProp = isDiscBase ? discCtx?.discriminatorProperties?.get(model.name) : undefined;\n      const isDiscriminatorField = discProp !== undefined && field.name === discProp;\n\n      if (constInit !== null && !isOptional) {\n        // Discriminator-style single-value enum/literal: emit with a const\n        // initializer and a non-public setter so callers can't drift the\n        // wire value. The converter still reads whatever the server sends.\n        // Only for required fields — optional literal fields must be nullable\n        // so absent keys round-trip correctly.\n        csType = baseType;\n        initializer = ` = ${constInit};`;\n        setterModifier = 'internal ';\n      } else if (isDiscriminatorField) {\n        // Discriminator property on the base class: varies per variant but\n        // should still be non-public-settable so consumers can't change it.\n        csType = baseType;\n        if (!isAlreadyNullable && !isValueTypeRef(field.type)) {\n          initializer = ' = default!;';\n        }\n        setterModifier = 'internal ';\n      } else if (isOptional) {\n        if (isAlreadyNullable) {\n          csType = baseType;\n        } else if (isValueTypeRef(field.type)) {\n          csType = `${baseType}?`;\n        } else {\n          // With nullable enabled, optional reference types need `?`\n          csType = `${baseType}?`;\n        }\n      } else {\n        csType = baseType;\n        // Required non-nullable reference types need = default! to suppress CS8618\n        if (!isAlreadyNullable && !isValueTypeRef(field.type)) {\n          initializer = ' = default!;';\n        }\n      }\n\n      // Field description (full multi-line, with continuations as <remarks>)\n      const fieldDocs = emitXmlDoc(field.description, '        ');\n      if (fieldDocs.length > 0) {\n        lines.push('');\n        lines.push(...fieldDocs);\n      }\n\n      if (field.deprecated) {\n        const msg = escapeCsAttributeString(deprecationMessage(field.description, 'field'));\n        lines.push(`        [System.Obsolete(\"${msg}\")]`);\n      }\n\n      const isRequiredEnum = field.required && isEnumRef(field.type) && constInit === null;\n      // WIRE key: always derives from `field.name`. Pin it explicitly when the\n      // C# property name (collision suffix or `domainName` override) no longer\n      // round-trips to the wire name via the SnakeCaseLower naming policy.\n      lines.push(\n        ...emitJsonPropertyAttributes(field.name, {\n          isRequiredEnum,\n          explicitWireName: collidesWithClassName || hasDomainOverride,\n        }),\n      );\n      // Discriminated-union-typed field: attach the variant-dispatching converter\n      // so Newtonsoft picks the right subtype on deserialization. The converter\n      // name is keyed off the first IR variant model name (matches how\n      // `joinUnionVariants` registered it in `discriminatedUnions`).\n      const discriminatedUnionConverter = discriminatedUnionConverterName(field.type);\n      if (discriminatedUnionConverter) {\n        lines.push(`        [Newtonsoft.Json.JsonConverter(typeof(${discriminatedUnionConverter}))]`);\n      }\n      const newMod = useNewModifier ? 'new ' : '';\n      lines.push(`        public ${newMod}${csType} ${csFieldName} { get; ${setterModifier}set; }${initializer}`);\n\n      // Track additional-properties / metadata dictionaries for typed accessors.\n      // Skip deprecated fields so the generated accessor doesn't reference\n      // a field marked `[System.Obsolete]` (which would fail the build).\n      if (isDictionaryOfObject(csType) && !field.deprecated) {\n        dictObjectFields.push({ csName: csFieldName, typeText: csType });\n      }\n    }\n\n    for (const dict of dictObjectFields) {\n      lines.push('');\n      lines.push(`        /// <summary>`);\n      lines.push(`        /// Typed accessor for <see cref=\"${dict.csName}\"/>. Returns the value stored under`);\n      lines.push(`        /// <paramref name=\"key\"/> coerced to <typeparamref name=\"T\"/>, or the default`);\n      lines.push(`        /// value when the key is missing or the value is not convertible.`);\n      lines.push(`        /// </summary>`);\n      if (isDiscBase) {\n        lines.push(`        /// <remarks>`);\n        lines.push(`        /// Variant subclasses provide strongly-typed <c>${dict.csName}</c> properties that`);\n        lines.push(`        /// shadow this dictionary. This accessor is intended for forward-compatible handling`);\n        lines.push(`        /// of types not yet known to this SDK version. For recognized types, cast to the`);\n        lines.push(`        /// specific subclass and access its typed <c>${dict.csName}</c> property directly.`);\n        lines.push(`        /// </remarks>`);\n      }\n      lines.push(`        /// <typeparam name=\"T\">Expected value type.</typeparam>`);\n      lines.push(`        /// <param name=\"key\">The key to look up.</param>`);\n      lines.push(`        public T? Get${dict.csName}Attribute<T>(string key)`);\n      lines.push('        {');\n      lines.push(`            if (this.${dict.csName} == null)`);\n      lines.push('            {');\n      lines.push('                return default;');\n      lines.push('            }');\n      lines.push('');\n      lines.push(`            if (!this.${dict.csName}.TryGetValue(key, out var value))`);\n      lines.push('            {');\n      lines.push('                return default;');\n      lines.push('            }');\n      lines.push('');\n      lines.push('            if (value is T typed)');\n      lines.push('            {');\n      lines.push('                return typed;');\n      lines.push('            }');\n      lines.push('');\n      lines.push('            if (value is Newtonsoft.Json.Linq.JToken token)');\n      lines.push('            {');\n      lines.push('                return token.ToObject<T>();');\n      lines.push('            }');\n      lines.push('');\n      lines.push('            if (value is System.Text.Json.JsonElement element)');\n      lines.push('            {');\n      lines.push('                return System.Text.Json.JsonSerializer.Deserialize<T>(element.GetRawText());');\n      lines.push('            }');\n      lines.push('');\n      lines.push('            return default;');\n      lines.push('        }');\n    }\n\n    lines.push('    }');\n    lines.push('}');\n\n    // FR-1.4: write the per-model FILE only when in scope. .NET uses a flat\n    // Entities/ directory with C# namespaces (no barrel/index), so an\n    // out-of-scope model left untouched on disk stays referenceable.\n    if (isModelInScope(model.name, ctx)) {\n      files.push({\n        path: `Entities/${csClassName}.cs`,\n        content: lines.join('\\n'),\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n\n/**\n * Compute the name of the discriminator converter class for a field whose\n * type is a discriminated union, mirroring the keying used in\n * `joinUnionVariants` (first IR model variant name + \"DiscriminatorConverter\").\n * Returns null when the type isn't a discriminated union with a populated\n * mapping. Also walks through `nullable` so an optional discriminated field\n * still gets the converter applied.\n */\nfunction discriminatedUnionConverterName(ref: TypeRef): string | null {\n  const inner = ref.kind === 'nullable' ? ref.inner : ref;\n  if (inner.kind !== 'union') return null;\n  if (!inner.discriminator || !inner.discriminator.mapping) return null;\n  if (Object.keys(inner.discriminator.mapping).length === 0) return null;\n  const firstModel = inner.variants.find((v) => v.kind === 'model');\n  if (!firstModel || firstModel.kind !== 'model') return null;\n  return `${modelClassName(firstModel.name)}DiscriminatorConverter`;\n}\n\n/**\n * Whether the emitted C# type is `Dictionary<string, object>` or its\n * nullable variant — the usual shape of metadata / additional-properties\n * fields that get typed accessors.\n */\nfunction isDictionaryOfObject(csType: string): boolean {\n  const bare = csType.endsWith('?') ? csType.slice(0, -1) : csType;\n  return bare === 'Dictionary<string, object>';\n}\n\n/**\n * If the given TypeRef is a single-value enum / literal (a discriminator\n * const masquerading as an enum), return the C# literal expression (already\n * quoted for strings, bare for bool/number) so the emitter can lock the\n * field down with a const initializer and non-public setter. Returns null\n * for any other type.\n */\nfunction singleValueConstInitializer(ref: TypeRef, enumConstByName: Map<string, string>): string | null {\n  // OpenAPI `enum: [value]` (single-value) is normalized by the IR to a\n  // LiteralType on the field, not an EnumRef. Emit per-type: booleans and\n  // numbers are bare literals; strings get JSON-quoted.\n  if (ref.kind === 'literal') {\n    if (ref.value === null) return null;\n    if (typeof ref.value === 'boolean') return ref.value ? 'true' : 'false';\n    if (typeof ref.value === 'number') return String(ref.value);\n    if (typeof ref.value === 'string') return JSON.stringify(ref.value);\n    return null;\n  }\n  if (ref.kind !== 'enum') return null;\n  let wire: string | null = null;\n  if (ref.values && ref.values.length === 1) {\n    const v = ref.values[0] as string | number | { value: string | number };\n    wire = typeof v === 'string' || typeof v === 'number' ? String(v) : String(v.value);\n  } else {\n    wire = enumConstByName.get(ref.name) ?? null;\n  }\n  if (wire === null) return null;\n  // Enum wire values serialize as strings in JSON, and mapTypeRef returns\n  // `string` for single-value enums — so always quote.\n  return JSON.stringify(wire);\n}\n\n/**\n * Compute and publish the model alias map. Safe to call multiple times\n * (idempotent for a given set of models). Must be invoked before any emitter\n * phase that calls `mapTypeRef` with model references.\n */\nexport function primeModelAliases(models: Model[]): void {\n  const eligibleModels = models.filter((m) => !isListWrapperModel(m) && !isListMetadataModel(m));\n  const aliasOf = new Map<string, string>();\n  while (true) {\n    const hashGroups = new Map<string, string[]>();\n    for (const model of eligibleModels) {\n      const hash = structuralHash(model, aliasOf);\n      if (!hashGroups.has(hash)) hashGroups.set(hash, []);\n      hashGroups.get(hash)!.push(model.name);\n    }\n\n    let added = false;\n    for (const [hash, names] of hashGroups) {\n      if (names.length <= 1) continue;\n      if (hash === '') continue;\n      const sorted = [...names].sort();\n      const canonical = sorted[0];\n      for (let i = 1; i < sorted.length; i++) {\n        const name = sorted[i];\n        if (aliasOf.get(name) !== canonical) {\n          aliasOf.set(name, canonical);\n          added = true;\n        }\n      }\n    }\n    if (!added) break;\n  }\n  setModelAliases(aliasOf);\n}\n\n/**\n * Normalize a TypeRef for structural comparison.\n * Enum references are normalized to their values (not names) so that\n * structurally identical enums with different names still match.\n * Model references are rewritten to their canonical alias (if any) so that\n * parents whose only difference is an already-aliased child collapse too.\n */\nfunction normalizeTypeForHash(ref: TypeRef, aliasOf: Map<string, string>): any {\n  if (ref.kind === 'enum') {\n    // Normalize enum refs by their sorted values, not their name\n    const vals = ref.values ? [...ref.values].sort() : [];\n    return { kind: 'enum', values: vals };\n  }\n  if (ref.kind === 'model') {\n    return { kind: 'model', name: aliasOf.get(ref.name) ?? ref.name };\n  }\n  if (ref.kind === 'nullable') {\n    return { kind: 'nullable', inner: normalizeTypeForHash(ref.inner, aliasOf) };\n  }\n  if (ref.kind === 'array') {\n    return { kind: 'array', items: normalizeTypeForHash(ref.items, aliasOf) };\n  }\n  if (ref.kind === 'union') {\n    return { kind: 'union', variants: ref.variants.map((v) => normalizeTypeForHash(v, aliasOf)) };\n  }\n  if (ref.kind === 'map') {\n    return { kind: 'map', valueType: normalizeTypeForHash(ref.valueType, aliasOf) };\n  }\n  return ref;\n}\n\nfunction structuralHash(model: Model, aliasOf: Map<string, string> = new Map()): string {\n  return model.fields\n    .map((f) => `${f.name}:${JSON.stringify(normalizeTypeForHash(f.type, aliasOf))}:${f.required}`)\n    .sort()\n    .join('|');\n}\n\n/**\n * Names of models referenced **only** as a named operation request body —\n * i.e. never appearing in a response, an error, a paginated item type, or as\n * a field type on another model. The .NET wrapper generator emits a\n * per-operation `*Options` class containing the same fields, so the named\n * entity is never instantiated by callers and just clutters the SDK\n * (workos-dotnet#248: `CreateUserApiKey` vs `UserManagementCreateApiKeyOptions`).\n */\nfunction collectRequestBodyOnlyModelNames(services: Service[], models: Model[]): Set<string> {\n  const requestBodyNames = new Set<string>();\n  const otherReferences = new Set<string>();\n\n  // Resolve every reference through the alias map so structurally-identical\n  // models share a body/non-body classification. Without this, an alias being\n  // used as a field would only mark the alias name as non-body — leaving its\n  // canonical (which carries the same shape and gets emitted) wrongly tagged\n  // as body-only and skipped.\n  const collect = (ref: TypeRef | undefined, into: Set<string>): void => {\n    if (!ref) return;\n    walkTypeRef(ref, {\n      model: (r) => into.add(resolveModelName(r.name)),\n    });\n  };\n\n  for (const service of services) {\n    for (const op of service.operations) {\n      if (op.requestBody?.kind === 'model') {\n        requestBodyNames.add(resolveModelName(op.requestBody.name));\n      }\n      collect(op.response, otherReferences);\n      if (op.pagination) collect(op.pagination.itemType, otherReferences);\n      for (const p of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n        collect(p.type, otherReferences);\n      }\n      if (op.successResponses) {\n        for (const sr of op.successResponses) collect(sr.type, otherReferences);\n      }\n      for (const err of op.errors) {\n        if (err.type) collect(err.type, otherReferences);\n      }\n    }\n  }\n\n  for (const model of models) {\n    for (const field of model.fields) {\n      collect(field.type, otherReferences);\n    }\n  }\n\n  const result = new Set<string>();\n  for (const name of requestBodyNames) {\n    if (!otherReferences.has(name)) result.add(name);\n  }\n  return result;\n}\n","import type { Enum, EmitterContext, GeneratedFile, Service } from '@workos/oagen';\nimport { walkTypeRef } from '@workos/oagen';\nimport { className, deprecationMessage, escapeCsAttributeString, humanize } from './naming.js';\nimport { setEnumAliases, setSingleValueEnumNames } from './type-map.js';\nimport { enrichModelsFromSpec } from '../shared/model-utils.js';\nimport { isEnumInScope } from '../shared/resolved-ops.js';\n\n/**\n * Generate C# enum definitions from IR Enum definitions.\n * Each enum becomes a separate .cs file. Structurally-identical enums are\n * deduplicated: only the canonical (alphabetically-first) name is emitted,\n * and every reference to a duplicate enum is rewritten to the canonical one\n * by `mapTypeRef` via `setEnumAliases`.\n */\nexport function generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n  if (enums.length === 0) return [];\n\n  // Publish the alias map + single-value enum set so model/options/wrapper\n  // emitters all resolve duplicate enum references to the canonical name and\n  // rewrite 1-value enum refs to `string`.\n  const aliasOf = collectEnumAliasOf(enums);\n  setEnumAliases(aliasOf);\n  setSingleValueEnumNames(enums.filter((e) => e.values.length === 1).map((e) => e.name));\n  diagnoseDivergentEnums(enums);\n\n  // Collect all enum names actually referenced by models and operations so we\n  // can suppress orphan enums that would otherwise be emitted but never used.\n  const referencedEnums = collectReferencedEnumNames(ctx);\n\n  const files: GeneratedFile[] = [];\n\n  for (const enumDef of enums) {\n    const typeName = className(enumDef.name);\n\n    // Skip duplicate enums — their references are retargeted to the canonical.\n    if (aliasOf.has(enumDef.name)) continue;\n\n    // Skip empty and single-value enums — the single-value case is a discriminator\n    // masquerading as an enum, and mapTypeRef rewrites such refs to `string` with\n    // a const initializer on the owning property.\n    if (enumDef.values.length <= 1) continue;\n\n    // Skip orphan enums that are not referenced by any model field or operation\n    // parameter. Resolve aliases so that a canonical enum is kept if any of its\n    // aliases are referenced.\n    const isReferenced =\n      referencedEnums.has(enumDef.name) ||\n      [...aliasOf.entries()].some(([alias, canon]) => canon === enumDef.name && referencedEnums.has(alias));\n    if (!isReferenced) continue;\n\n    // Deduplicate values\n    const seenValues = new Set<string>();\n    const uniqueValues: typeof enumDef.values = [];\n    for (const v of enumDef.values) {\n      const vs = String(v.value);\n      if (!seenValues.has(vs)) {\n        seenValues.add(vs);\n        uniqueValues.push(v);\n      }\n    }\n\n    const lines: string[] = [];\n    lines.push(`namespace ${ctx.namespacePascal}`);\n    lines.push('{');\n    lines.push('    using System.Runtime.Serialization;');\n    lines.push('    using Newtonsoft.Json;');\n    lines.push('    using STJS = System.Text.Json.Serialization;');\n    lines.push('');\n    lines.push(`    /// <summary>Represents ${humanize(enumDef.name)} values.</summary>`);\n    lines.push('    [JsonConverter(typeof(WorkOSNewtonsoftStringEnumConverter))]');\n    lines.push('    [STJS.JsonConverter(typeof(WorkOSStringEnumConverterFactory))]');\n    lines.push(`    public enum ${typeName}`);\n    lines.push('    {');\n\n    // If the spec defines a default that matches a member, promote it to\n    // ordinal 0 so `default(EnumType)` returns that variant. Other members\n    // get explicit ascending ordinals, and the Unknown sentinel is pushed\n    // to a high explicit ordinal (99) so it never sits at 0.\n    const defaultMatch =\n      enumDef.default !== undefined ? uniqueValues.find((v) => v.value === enumDef.default) : undefined;\n\n    const orderedValues = defaultMatch\n      ? [defaultMatch, ...uniqueValues.filter((v) => v !== defaultMatch)]\n      : uniqueValues;\n\n    const usedNames = new Set<string>();\n    const usedWireValues = new Set<string>();\n\n    if (defaultMatch) {\n      // Reserve the sentinel name and wire value so spec values that collide\n      // with \"unknown\"/Unknown still get the existing skip/dedup behavior.\n      usedNames.add('Unknown');\n      usedWireValues.add('unknown');\n    } else {\n      // Existing behavior: Unknown sentinel at ordinal 0.\n      lines.push(`        [EnumMember(Value = \"unknown\")]`);\n      lines.push(`        Unknown,`);\n      lines.push('');\n      usedNames.add('Unknown');\n      usedWireValues.add('unknown');\n    }\n\n    for (let i = 0; i < orderedValues.length; i++) {\n      const v = orderedValues[i];\n      // Skip values whose wire representation collides with the sentinel\n      if (usedWireValues.has(String(v.value))) continue;\n      usedWireValues.add(String(v.value));\n      let memberName = className(String(v.value));\n      // Avoid collision with the type itself or previously used names\n      if (memberName === typeName || usedNames.has(memberName)) {\n        let suffix = 2;\n        while (usedNames.has(`${memberName}${suffix}`)) suffix++;\n        memberName = `${memberName}${suffix}`;\n      }\n      usedNames.add(memberName);\n\n      if (v.description) {\n        lines.push(`        /// <summary>${escapeXml(v.description)}</summary>`);\n      }\n      if (v.deprecated) {\n        const msg = escapeCsAttributeString(deprecationMessage(v.description, 'value'));\n        lines.push(`        [System.Obsolete(\"${msg}\")]`);\n      }\n      lines.push(`        [EnumMember(Value = \"${v.value}\")]`);\n      // Explicit ordinals only when we promoted a default to position 0.\n      const ordinal = defaultMatch ? ` = ${i}` : '';\n      lines.push(`        ${memberName}${ordinal},`);\n    }\n\n    if (defaultMatch) {\n      lines.push('');\n      lines.push(`        [EnumMember(Value = \"unknown\")]`);\n      lines.push(`        Unknown = 99,`);\n    }\n\n    lines.push('    }');\n    lines.push('}');\n\n    // FR-1.4: write the per-enum FILE only when in scope. .NET uses a flat\n    // Enums/ directory with C# namespaces (no barrel/index), so an\n    // out-of-scope enum left untouched on disk stays referenceable.\n    if (isEnumInScope(enumDef.name, ctx)) {\n      files.push({\n        path: `Enums/${typeName}.cs`,\n        content: lines.join('\\n'),\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n\nfunction escapeXml(s: string): string {\n  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n/**\n * Populate the module-level enum alias resolver from the given spec's enums.\n * Call from every emitter entrypoint that uses `mapTypeRef` so enum\n * references resolve to their canonical names regardless of which emitter\n * phase runs first.\n */\nexport function primeEnumAliases(enums: Enum[]): void {\n  setEnumAliases(collectEnumAliasOf(enums));\n  setSingleValueEnumNames(enums.filter((e) => e.values.length === 1).map((e) => e.name));\n}\n\n/**\n * Warn when two enums share a trailing stem (e.g., `ConnectionType`) but\n * carry *contradictory* wire values — each side has values the other lacks.\n * Pure subset relationships (event-specific payloads that narrow a shared\n * base set — the usual shape of WorkOS event enums) are legitimate and not\n * flagged. Only true divergences, which typically indicate spec drift, are\n * reported.\n */\nexport function diagnoseDivergentEnums(enums: Enum[]): void {\n  const byStem = new Map<string, Enum[]>();\n  for (const e of enums) {\n    if (e.values.length < 2) continue;\n    const stem = trailingPascalStem(e.name);\n    if (!stem) continue;\n    if (!byStem.has(stem)) byStem.set(stem, []);\n    byStem.get(stem)!.push(e);\n  }\n\n  for (const [stem, group] of byStem) {\n    if (group.length < 2) continue;\n    // Skip generic event-payload stems (`DataState`, `DataStatus`,\n    // `DataActorSource`, …). Many unrelated event subtypes expose a\n    // `data.{state,status}` field whose allowed values are scoped per\n    // event; grouping them by the generic `Data*` suffix surfaces\n    // false-positive divergences, not real drift.\n    if (stem.startsWith('Data')) continue;\n    // Identical value sets are handled by the alias/dedupe pass.\n    const distinctSigs = new Set(group.map(valueSignature));\n    if (distinctSigs.size === 1) continue;\n    // Only warn when some pair is *mutually exclusive*: each enum has a\n    // value the other doesn't. Subsets are not drift.\n    if (!hasMutuallyExclusivePair(group)) continue;\n    const summary = group.map((e) => `${e.name}[${e.values.length}]`).join(', ');\n    console.warn(`[oagen:dotnet] Divergent enums sharing stem \"${stem}\": ${summary}`);\n  }\n}\n\n/**\n * True if some pair in the group both:\n *   (a) shares enough values to plausibly be the same concept, AND\n *   (b) has values exclusive to each side (i.e., is not a subset/equal).\n * Sharing the trailing stem alone is insufficient — `DataStatus` shows up on\n * unrelated domains (connection link state vs. membership state) that only\n * coincidentally overlap on a sentinel like `unknown`. Require a non-trivial\n * intersection before treating two enums as the same logical enum.\n */\nfunction hasMutuallyExclusivePair(group: Enum[]): boolean {\n  // Compare case-insensitively so cosmetic drift like `GitHubOAuth` vs\n  // `GithubOAuth` — an intentional historical spelling carried forward by\n  // the spec — doesn't register as divergence.\n  const valueSets = group.map((e) => new Set(e.values.map((v) => String(v.value).toLowerCase())));\n  for (let i = 0; i < valueSets.length; i++) {\n    for (let j = i + 1; j < valueSets.length; j++) {\n      const a = valueSets[i];\n      const b = valueSets[j];\n      // Concept-similarity gate: two enums are treated as the same logical\n      // enum only when they share >= 3 values AND those shared values\n      // dominate both sides (>= 50% of the larger set). A handful of\n      // shared sentinels (`unknown`, `pending`) recurs across unrelated\n      // domains (`AuthMethod` on Radar assessments vs. sessions: only\n      // `password`/`passkey`/`sso`/`unknown` overlap out of ~15 total), and\n      // that sparse overlap shouldn't count as drift.\n      let shared = 0;\n      for (const v of a) {\n        if (b.has(v)) shared++;\n      }\n      if (shared < 3) continue;\n      const larger = Math.max(a.size, b.size);\n      if (larger === 0 || shared / larger < 0.5) continue;\n      // Both sides must have values the other lacks — a subset is legitimate\n      // narrowing, not drift.\n      let aHasExtra = false;\n      for (const v of a) {\n        if (!b.has(v)) {\n          aHasExtra = true;\n          break;\n        }\n      }\n      if (!aHasExtra) continue;\n      for (const v of b) {\n        if (!a.has(v)) return true;\n      }\n    }\n  }\n  return false;\n}\n\nfunction trailingPascalStem(name: string): string | null {\n  // Extract the last two PascalCase segments so that `SSOConnectionType`\n  // and `ConnectionFindResponseConnectionType` both map to `ConnectionType`.\n  const segments = name.match(/[A-Z]+[a-z0-9]*/g);\n  if (!segments || segments.length < 2) return null;\n  return segments.slice(-2).join('');\n}\n\nfunction valueSignature(e: Enum): string {\n  return [...e.values]\n    .map((v) => String(v.value))\n    .sort()\n    .join('|');\n}\n\nfunction collectEnumAliasOf(enums: Enum[]): Map<string, string> {\n  const hashGroups = new Map<string, string[]>();\n  for (const enumDef of enums) {\n    const hash = [...enumDef.values]\n      .map((v) => String(v.value))\n      .sort()\n      .join('|');\n    if (!hashGroups.has(hash)) hashGroups.set(hash, []);\n    hashGroups.get(hash)!.push(enumDef.name);\n  }\n\n  const aliasOf = new Map<string, string>();\n  for (const [, names] of hashGroups) {\n    if (names.length <= 1) continue;\n    const sorted = [...names].sort();\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      aliasOf.set(sorted[i], canonical);\n    }\n  }\n  return aliasOf;\n}\n\n/**\n * Collect all enum names referenced anywhere in the spec — model fields,\n * operation params, request bodies, and responses. Used to prune orphan\n * enums that the IR extracted from the spec but that no generated code\n * actually references.\n */\nfunction collectReferencedEnumNames(ctx: EmitterContext): Set<string> {\n  const refs = new Set<string>();\n  const collect = (ref: any) => {\n    walkTypeRef(ref, { enum: (r: any) => refs.add(r.name) });\n  };\n  // Walk the enriched models (which include synthetic fields from oneOf\n  // flattening) so synthetic enums are also counted as referenced.\n  const enrichedModels = enrichModelsFromSpec(ctx.spec.models);\n  for (const model of enrichedModels) {\n    for (const field of model.fields) {\n      collect(field.type);\n    }\n  }\n  for (const service of ctx.spec.services) {\n    for (const op of service.operations) {\n      if (op.requestBody) collect(op.requestBody);\n      if (op.response) collect(op.response);\n      for (const p of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n        collect(p.type);\n      }\n    }\n  }\n  return refs;\n}\n\n/** Get the canonical enum name if the given enum is an alias. */\nexport function resolveEnumName(name: string, enums: Enum[]): string {\n  const aliasOf = collectEnumAliasOf(enums);\n  return aliasOf.get(name) ? className(aliasOf.get(name)!) : className(name);\n}\n\nexport function assignEnumsToServices(enums: Enum[], services: Service[]): Map<string, string> {\n  const enumToService = new Map<string, string>();\n  const enumNames = new Set(enums.map((e) => e.name));\n\n  for (const service of services) {\n    for (const op of service.operations) {\n      const refs = new Set<string>();\n      const collect = (ref: any) => {\n        walkTypeRef(ref, { enum: (r: any) => refs.add(r.name) });\n      };\n      if (op.requestBody) collect(op.requestBody);\n      collect(op.response);\n      for (const p of [...op.pathParams, ...op.queryParams, ...op.headerParams, ...(op.cookieParams ?? [])]) {\n        collect(p.type);\n      }\n      for (const name of refs) {\n        if (enumNames.has(name) && !enumToService.has(name)) {\n          enumToService.set(name, service.name);\n        }\n      }\n    }\n  }\n\n  return enumToService;\n}\n","import type { EmitterContext, ResolvedOperation, ResolvedWrapper } from '@workos/oagen';\nimport {\n  fieldName as csFieldName,\n  methodName as csMethodName,\n  localName,\n  csLiteral,\n  clientFieldExpression,\n  httpMethodHelperName,\n  escapeXml,\n  emitXmlDoc,\n  humanize,\n  appendAsyncSuffix,\n  modelClassName,\n} from './naming.js';\nimport { sortPathParamsByTemplateOrder } from './resources.js';\nimport { resolveWrapperParams, formatWrapperDescription, type ResolvedWrapperParam } from '../shared/wrapper-utils.js';\nimport { mapTypeRef, isValueTypeRef, isEnumRef, emitJsonPropertyAttributes } from './type-map.js';\n\n/**\n * Generate C# wrapper method lines for union split operations.\n */\nexport function generateWrapperMethods(\n  _serviceType: string,\n  resolvedOp: ResolvedOperation,\n  ctx: EmitterContext,\n): string[] {\n  if (!resolvedOp.wrappers || resolvedOp.wrappers.length === 0) return [];\n\n  const lines: string[] = [];\n\n  for (const wrapper of resolvedOp.wrappers) {\n    const wrapperParams = resolveWrapperParams(wrapper, ctx);\n    lines.push('');\n    emitWrapperMethod(lines, resolvedOp, wrapper, wrapperParams, ctx);\n  }\n\n  return lines;\n}\n\nfunction emitWrapperMethod(\n  lines: string[],\n  resolvedOp: ResolvedOperation,\n  wrapper: ResolvedWrapper,\n  _wrapperParams: ResolvedWrapperParam[],\n  _ctx: EmitterContext,\n): void {\n  const op = resolvedOp.operation;\n  const methodStem = csMethodName(wrapper.name);\n  const method = appendAsyncSuffix(methodStem);\n  const optionsClass = `${methodStem}Options`;\n  const responseType = wrapper.responseModelName ? modelClassName(wrapper.responseModelName) : null;\n\n  // XML doc\n  lines.push(`        /// <summary>${formatWrapperDescription(wrapper.name)}.</summary>`);\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    const paramDesc = p.description ? escapeXml(p.description) : `The ${humanize(p.name)}.`;\n    lines.push(`        /// <param name=\"${localName(p.name)}\">${paramDesc}</param>`);\n  }\n  lines.push(`        /// <param name=\"options\">Request options.</param>`);\n  lines.push(`        /// <param name=\"requestOptions\">Per-request configuration overrides.</param>`);\n  lines.push(`        /// <param name=\"cancellationToken\">Cancellation token.</param>`);\n  if (responseType) {\n    lines.push(`        /// <returns>The <see cref=\"${responseType}\"/> result.</returns>`);\n  }\n\n  // Signature\n  const sigParams: string[] = [];\n  const argNames: string[] = [];\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    const name = localName(p.name);\n    sigParams.push(`string ${name}`);\n    argNames.push(name);\n  }\n  sigParams.push(`${optionsClass} options`);\n  argNames.push('options');\n  sigParams.push('RequestOptions? requestOptions = null');\n  argNames.push('requestOptions');\n  sigParams.push('CancellationToken cancellationToken = default');\n  argNames.push('cancellationToken');\n\n  const returnType = responseType ? `Task<${responseType}>` : 'Task';\n  lines.push(`        public async ${returnType} ${method}(${sigParams.join(', ')})`);\n  lines.push('        {');\n\n  // Set defaults on options\n  for (const [key, value] of Object.entries(wrapper.defaults)) {\n    lines.push(`            options.${csFieldName(key)} = ${csLiteral(value)};`);\n  }\n\n  // Set inferred fields from client. ClientId is required: fail loudly via RequireClientId()\n  // so that callers who forgot to configure it get a clear error instead of a 422 from the API.\n  for (const field of wrapper.inferFromClient) {\n    if (field === 'client_id') {\n      lines.push(`            options.${csFieldName(field)} = this.Client.RequireClientId();`);\n    } else {\n      lines.push(\n        `            options.${csFieldName(field)} = this.Client.${clientFieldExpression(field)} ?? string.Empty;`,\n      );\n    }\n  }\n\n  // Build path\n  let pathExpr: string;\n  if (op.pathParams.length > 0) {\n    let interpolated = op.path;\n    for (const p of sortPathParamsByTemplateOrder(op)) {\n      interpolated = interpolated.replace(`{${p.name}}`, `{Uri.EscapeDataString(${localName(p.name)})}`);\n    }\n    pathExpr = `$\"${interpolated}\"`;\n  } else {\n    pathExpr = `\"${op.path}\"`;\n  }\n\n  // Use the Service base-class helper so wrappers read as one-liners.\n  const helper = httpMethodHelperName(op.httpMethod);\n  if (responseType) {\n    lines.push(\n      `            return await this.${helper}<${responseType}>(${pathExpr}, options, requestOptions, cancellationToken);`,\n    );\n  } else if (helper === 'DeleteAsync') {\n    lines.push(`            await this.${helper}(${pathExpr}, options, requestOptions, cancellationToken);`);\n  } else {\n    lines.push(`            await this.${helper}<object>(${pathExpr}, options, requestOptions, cancellationToken);`);\n  }\n\n  lines.push('        }');\n\n  lines.push('');\n  lines.push(`        /// <summary>Compatibility wrapper for <see cref=\"${method}\"/>.</summary>`);\n  lines.push(`        public Task${responseType ? `<${responseType}>` : ''} ${methodStem}(${sigParams.join(', ')})`);\n  lines.push('        {');\n  lines.push(`            return this.${method}(${argNames.join(', ')});`);\n  lines.push('        }');\n}\n\n// NOTE: T26 (wrapper DRY) — the AuthenticateWith* wrappers share a small\n// SendAuthenticateAsync helper at runtime to avoid 8x copies of the same\n// MakeAPIRequest call. The helper itself lives in UserManagementService.cs as\n// a hand-maintained method (it can't easily be expressed as a generic because\n// the eight options classes don't share an interface). Keeping each generated\n// wrapper's body short is the practical part of the DRY win.\n\n/**\n * Generate wrapper options classes. Called from resources.ts options generation.\n */\nexport function generateWrapperOptionsClasses(resolvedOp: ResolvedOperation, ctx: EmitterContext): string[] {\n  if (!resolvedOp.wrappers || resolvedOp.wrappers.length === 0) return [];\n\n  const lines: string[] = [];\n\n  for (const wrapper of resolvedOp.wrappers) {\n    const wrapperParams = resolveWrapperParams(wrapper, ctx);\n    const optionsClass = `${csMethodName(wrapper.name)}Options`;\n\n    lines.push('');\n    lines.push(`    public class ${optionsClass} : BaseOptions`);\n    lines.push('    {');\n\n    // Exposed params\n    for (const { paramName, field, isOptional } of wrapperParams) {\n      const csField = csFieldName(paramName);\n      const csType = field ? resolveSimpleCsType(field.type, isOptional) : isOptional ? 'string?' : 'string';\n      const needsDefault = !isOptional && !csType.endsWith('?') && !(field && isValueTypeRef(field.type));\n      const initializer = needsDefault ? ' = default!;' : '';\n\n      const isRequiredEnum = !isOptional && !!field && isEnumRef(field.type);\n      lines.push(...emitXmlDoc(field?.description, '        '));\n      lines.push(...emitJsonPropertyAttributes(paramName, { isRequiredEnum }));\n      lines.push(`        public ${csType} ${csField} { get; set; }${initializer}`);\n      lines.push('');\n    }\n\n    // Hidden fields (defaults + inferred)\n    for (const key of Object.keys(wrapper.defaults)) {\n      const csField = csFieldName(key);\n      lines.push(`        internal string ${csField} { get; set; } = default!;`);\n      lines.push('');\n    }\n    for (const key of wrapper.inferFromClient) {\n      const csField = csFieldName(key);\n      // Skip if already added as a default\n      if (Object.keys(wrapper.defaults).includes(key)) continue;\n      lines.push(`        internal string ${csField} { get; set; } = default!;`);\n      lines.push('');\n    }\n\n    lines.push('    }');\n  }\n\n  return lines;\n}\n\nfunction resolveSimpleCsType(ref: any, isOptional: boolean): string {\n  const base = mapTypeRef(ref);\n  if (isOptional && !base.endsWith('?')) return `${base}?`;\n  return base;\n}\n","import type {\n  Service,\n  Operation,\n  OperationPlan,\n  EmitterContext,\n  GeneratedFile,\n  ResolvedOperation,\n  Model,\n  TypeRef,\n} from '@workos/oagen';\nimport { planOperation } from '@workos/oagen';\nimport { isListWrapperModel } from './models.js';\nimport { mapTypeRef, isValueTypeRef, isEnumRef, emitJsonPropertyAttributes, resolveModelName } from './type-map.js';\nimport {\n  appendAsyncSuffix,\n  className,\n  fieldName,\n  methodName,\n  resolveClassName,\n  resolveMethodName,\n  resolveMethodStem,\n  serviceTypeName,\n  localName,\n  csLiteral,\n  clientFieldExpression,\n  httpMethodCs,\n  httpMethodHelperName,\n  escapeXml,\n  emitXmlDoc,\n  deprecationMessage,\n  escapeCsAttributeString,\n  humanize,\n  modelClassName,\n} from './naming.js';\nimport {\n  buildResolvedLookup,\n  lookupResolved,\n  scopedMountGroups,\n  getOpDefaults,\n  getOpInferFromClient,\n  buildHiddenParams,\n  hasHiddenParams,\n  collectGroupedParamNames,\n  collectBodyFieldTypes,\n} from '../shared/resolved-ops.js';\nimport { generateWrapperMethods } from './wrappers.js';\n\n/**\n * Return path params sorted by their first occurrence in the URL template.\n */\nexport function sortPathParamsByTemplateOrder(op: Operation): typeof op.pathParams {\n  return [...op.pathParams].sort((a, b) => {\n    const posA = op.path.indexOf(`{${a.name}}`);\n    const posB = op.path.indexOf(`{${b.name}}`);\n    return posA - posB;\n  });\n}\n\n/**\n * Resolve the resource class name for a service.\n */\nexport function resolveResourceClassName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n/**\n * Generate C# service files from IR Service definitions.\n * Each mount group becomes a single Service.cs file.\n */\nexport function generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n  if (services.length === 0) return [];\n\n  const files: GeneratedFile[] = [];\n  const mountGroups = scopedMountGroups(ctx);\n\n  const entries: Array<{ name: string; operations: Operation[] }> =\n    mountGroups.size > 0 || ctx.scopedServices?.size\n      ? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations }))\n      : services.map((s) => ({ name: resolveResourceClassName(s, ctx), operations: s.operations }));\n\n  for (const { name: mountName, operations } of entries) {\n    if (operations.length === 0) continue;\n    const serviceFile = generateServiceFile(mountName, operations, ctx);\n    if (serviceFile) files.push(serviceFile);\n    const optionsFile = generateOptionsFile(mountName, operations, ctx);\n    if (optionsFile) files.push(optionsFile);\n  }\n\n  return files;\n}\n\n// ---------------------------------------------------------------------------\n// Mutually-exclusive parameter group support\n// ---------------------------------------------------------------------------\n\n/** Abstract base class name for a parameter group (e.g. UserManagementRole). */\nfunction groupBaseClassName(mountName: string, groupName: string): string {\n  return `${className(mountName)}${className(groupName)}`;\n}\n\n/** Concrete variant class name (e.g. UserManagementRoleSingle). */\nfunction groupVariantClassName(mountName: string, groupName: string, variantName: string): string {\n  return `${className(mountName)}${className(groupName)}${className(variantName)}`;\n}\n\n/**\n * Generate C# abstract base class + concrete subtypes for all parameter groups\n * on an operation. Each group becomes an abstract class with concrete subclasses\n * for each variant containing the variant's parameters as properties.\n */\nfunction generateParameterGroupTypes(\n  mountName: string,\n  op: Operation,\n  models: Model[],\n  emitted?: Set<string>,\n): string[] {\n  const lines: string[] = [];\n  const bodyFieldTypes = collectBodyFieldTypes(op, models);\n\n  for (const group of op.parameterGroups ?? []) {\n    const baseName = groupBaseClassName(mountName, group.name);\n    if (emitted?.has(baseName)) continue;\n    emitted?.add(baseName);\n\n    lines.push('');\n    lines.push(`    public abstract class ${baseName} { }`);\n\n    for (const variant of group.variants) {\n      const variantName = groupVariantClassName(mountName, group.name, variant.name);\n      lines.push('');\n      lines.push(`    public class ${variantName} : ${baseName}`);\n      lines.push('    {');\n      for (const param of variant.parameters) {\n        const csField = fieldName(param.name);\n        const effectiveType = bodyFieldTypes.get(param.name) ?? param.type;\n        const csType = mapTypeRef(effectiveType);\n        lines.push(`        public ${csType} ${csField} { get; set; } = default!;`);\n        lines.push('');\n      }\n      lines.push('    }');\n    }\n  }\n\n  return lines;\n}\n\n/**\n * Emit manual serialization for parameter group variants in the service\n * method body. Each group field on the options class is pattern-matched via\n * `is` checks and its variant parameters are added to the appropriate target\n * (query string or request body).\n */\nfunction emitGroupSerialization(\n  mountName: string,\n  op: Operation,\n  indent: string,\n  models: Model[],\n  target: 'query' | 'body',\n): string[] {\n  const lines: string[] = [];\n  const bodyFieldTypes = collectBodyFieldTypes(op, models);\n\n  for (const group of op.parameterGroups ?? []) {\n    const groupField = fieldName(group.name);\n    let first = true;\n\n    for (const variant of group.variants) {\n      const variantName = groupVariantClassName(mountName, group.name, variant.name);\n      // Use a short local variable derived from the variant name\n      const localVar = localName(variant.name);\n      const keyword = first ? 'if' : 'else if';\n      first = false;\n\n      lines.push(`${indent}${keyword} (options?.${groupField} is ${variantName} ${localVar})`);\n      lines.push(`${indent}{`);\n      let prevWasBlock = false;\n      for (const param of variant.parameters) {\n        const csField = fieldName(param.name);\n        const effectiveType = bodyFieldTypes.get(param.name) ?? param.type;\n        const accessor = `${localVar}.${csField}`;\n        const paramLines = emitParamValue(param.name, accessor, effectiveType, indent + '    ', target);\n        // SA1513: closing brace must be followed by a blank line before the next statement\n        if (prevWasBlock) lines.push('');\n        lines.push(...paramLines);\n        prevWasBlock = paramLines.length > 1;\n      }\n      lines.push(`${indent}}`);\n    }\n  }\n\n  return lines;\n}\n\n/**\n * Emit one or more lines to add a param to the query string or request body,\n * adapting to the parameter's IR type: enums use JsonConvert for wire-value\n * serialization, arrays are comma-joined, and reference types (string, List)\n * get a null guard.\n *\n * Reference types always get a null guard because variant classes are shared\n * across operations whose body models may disagree on nullability.\n */\nfunction emitParamValue(\n  wireName: string,\n  accessor: string,\n  typeRef: TypeRef,\n  indent: string,\n  target: 'query' | 'body',\n): string[] {\n  const method = target === 'body' ? 'AddBodyParam' : 'AddQueryParam';\n  const isNullable = typeRef.kind === 'nullable';\n  const inner: TypeRef = isNullable ? (typeRef as { kind: 'nullable'; inner: TypeRef }).inner : typeRef;\n\n  // Reference types (arrays, strings, models) are always guarded for null\n  // because the variant class property may be nullable even when the current\n  // operation's body model says \"required\".\n  const needsNullGuard = isNullable || !isValueTypeRef(inner);\n\n  if (inner.kind === 'array') {\n    // Body params pass the list directly so it serializes as a JSON array;\n    // query params comma-join into a single string value.\n    const valueExpr = target === 'body' ? accessor : `string.Join(\",\", ${accessor})`;\n    if (needsNullGuard) {\n      return [\n        `${indent}if (${accessor} != null)`,\n        `${indent}{`,\n        `${indent}    request.${method}(\"${wireName}\", ${valueExpr});`,\n        `${indent}}`,\n      ];\n    }\n    return [`${indent}request.${method}(\"${wireName}\", ${valueExpr});`];\n  }\n\n  if (inner.kind === 'enum') {\n    const serExpr = `JsonConvert.SerializeObject(${accessor}).Trim('\"')`;\n    if (isNullable) {\n      return [\n        `${indent}if (${accessor} != null)`,\n        `${indent}{`,\n        `${indent}    request.${method}(\"${wireName}\", ${serExpr});`,\n        `${indent}}`,\n      ];\n    }\n    return [`${indent}request.${method}(\"${wireName}\", ${serExpr});`];\n  }\n\n  if (needsNullGuard) {\n    return [\n      `${indent}if (${accessor} != null)`,\n      `${indent}{`,\n      `${indent}    request.${method}(\"${wireName}\", ${accessor});`,\n      `${indent}}`,\n    ];\n  }\n\n  return [`${indent}request.${method}(\"${wireName}\", ${accessor});`];\n}\n\n/** Check whether any parameter group variant contains an enum-typed parameter. */\nfunction groupsNeedJsonConvert(operations: Operation[], models: Model[]): boolean {\n  for (const op of operations) {\n    const bodyFieldTypes = collectBodyFieldTypes(op, models);\n    for (const group of op.parameterGroups ?? []) {\n      for (const variant of group.variants) {\n        for (const param of variant.parameters) {\n          const effectiveType = bodyFieldTypes.get(param.name) ?? param.type;\n          const inner: TypeRef =\n            effectiveType.kind === 'nullable'\n              ? (effectiveType as { kind: 'nullable'; inner: TypeRef }).inner\n              : effectiveType;\n          if (inner.kind === 'enum') return true;\n        }\n      }\n    }\n  }\n  return false;\n}\n\nfunction generateServiceFile(mountName: string, operations: Operation[], ctx: EmitterContext): GeneratedFile | null {\n  const lines: string[] = [];\n  const svcTypeName = serviceTypeName(mountName);\n  const csFile = `Services/${className(mountName)}/${svcTypeName}.cs`;\n\n  const resolvedLookup = buildResolvedLookup(ctx);\n\n  lines.push(`namespace ${ctx.namespacePascal}`);\n  lines.push('{');\n  lines.push('    using System;');\n  lines.push('    using System.Collections.Generic;');\n  lines.push('    using System.Net.Http;');\n  lines.push('    using System.Threading;');\n  lines.push('    using System.Threading.Tasks;');\n  if (groupsNeedJsonConvert(operations, ctx.spec.models)) {\n    lines.push('    using Newtonsoft.Json;');\n  }\n  lines.push('');\n  lines.push(\n    `    /// <summary>Service that exposes the ${humanize(mountName)} API operations on <see cref=\"WorkOSClient\"/>.</summary>`,\n  );\n  lines.push(`    public class ${svcTypeName} : Service`);\n  lines.push('    {');\n  lines.push(`        /// <summary>`);\n  lines.push(\n    `        /// Initializes a new instance of the <see cref=\"${svcTypeName}\"/> class for mocking. The service uses the singleton`,\n  );\n  lines.push(`        /// client configured via <see cref=\"WorkOSConfiguration.WorkOSClient\"/>.`);\n  lines.push(`        /// </summary>`);\n  lines.push(`        public ${svcTypeName}() { }`);\n  lines.push('');\n  lines.push(`        /// <summary>`);\n  lines.push(`        /// Initializes a new instance of the <see cref=\"${svcTypeName}\"/> class bound to the`);\n  lines.push(`        /// supplied <paramref name=\"client\"/>.`);\n  lines.push(`        /// </summary>`);\n  lines.push(`        /// <param name=\"client\">The HTTP client used to make API requests.</param>`);\n  lines.push(`        public ${svcTypeName}(WorkOSClient client) : base(client) { }`);\n\n  const emittedMethods = new Set<string>();\n  for (const op of operations) {\n    const plan = planOperation(op);\n    const methodStem = resolveCsMethodStem(op, mountName, ctx);\n    const method = resolveCsMethodName(op, mountName, ctx);\n\n    if (emittedMethods.has(method)) continue;\n    emittedMethods.add(method);\n\n    const resolvedOp = lookupResolved(op, resolvedLookup);\n    const isUnionSplit = (resolvedOp?.wrappers?.length ?? 0) > 0;\n\n    // For union-split operations (e.g. POST /user_management/authenticate), do\n    // NOT emit the raw method — its options class is empty and any caller will\n    // get a 422 from the API. Only emit the typed AuthenticateWith* wrappers.\n    if (!isUnionSplit) {\n      lines.push('');\n      const methodCode = generateMethod(svcTypeName, mountName, method, methodStem, op, plan, ctx, resolvedOp);\n      lines.push(methodCode);\n\n      if (!(resolvedOp?.urlBuilder ?? false) && method !== methodStem) {\n        lines.push('');\n        lines.push(generateCompatibilityMethod(mountName, method, methodStem, op, plan, ctx, resolvedOp));\n      }\n\n      // Generate auto-pagination method for paginated list operations\n      if (plan.isPaginated && op.pagination) {\n        lines.push('');\n        const autoPagingCode = generateAutoPagingMethod(mountName, method, methodStem, op, plan, ctx, resolvedOp);\n        lines.push(autoPagingCode);\n      }\n    }\n\n    // Generate union split wrapper methods\n    if (isUnionSplit) {\n      const wrapperLines = generateWrapperMethods(svcTypeName, resolvedOp!, ctx);\n      lines.push(...wrapperLines);\n      for (const w of resolvedOp!.wrappers!) {\n        emittedMethods.add(appendAsyncSuffix(methodName(w.name)));\n      }\n    }\n  }\n\n  lines.push('    }');\n  lines.push('}');\n\n  return {\n    path: csFile,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\nfunction generateOptionsFile(mountName: string, operations: Operation[], ctx: EmitterContext): GeneratedFile | null {\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const optionsLines: string[] = [];\n  let hasOptions = false;\n\n  optionsLines.push(`namespace ${ctx.namespacePascal}`);\n  optionsLines.push('{');\n  optionsLines.push('    using System;');\n  optionsLines.push('    using System.Collections.Generic;');\n  optionsLines.push('    using Newtonsoft.Json;');\n  optionsLines.push('    using STJS = System.Text.Json.Serialization;');\n\n  const emittedOptions = new Set<string>();\n  const emittedGroupTypes = new Set<string>();\n  for (const op of operations) {\n    const plan = planOperation(op);\n    const method = resolveCsMethodName(op, mountName, ctx);\n    const resolvedOp = lookupResolved(op, resolvedLookup);\n    const hidden = buildHiddenParams(resolvedOp);\n\n    // Union-split operations expose typed wrapper option classes\n    // (AuthenticateWith*Options) instead of a generic raw options class.\n    // Skip emitting an empty *CreateAuthenticateOptions placeholder.\n    if ((resolvedOp?.wrappers?.length ?? 0) > 0) continue;\n\n    const optionsClass = optionsClassName(mountName, method);\n    if (emittedOptions.has(optionsClass)) continue;\n\n    const groupedParams = collectGroupedParamNames(op);\n    const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n    const hasVisibleQueryParams =\n      op.queryParams.filter((qp) => !hidden.has(qp.name) && !groupedParams.has(qp.name)).length > 0;\n    const hasBody = plan.hasBody && op.requestBody;\n    let hasVisibleBodyFields = false;\n    if (hasBody && op.requestBody?.kind === 'model') {\n      const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n      if (bodyModel) hasVisibleBodyFields = bodyModel.fields.some((f) => !hidden.has(f.name));\n    } else if (hasBody) {\n      hasVisibleBodyFields = true;\n    }\n\n    if (!hasVisibleQueryParams && !hasVisibleBodyFields && !hasGroups) continue;\n\n    emittedOptions.add(optionsClass);\n    hasOptions = true;\n\n    // Determine base class: ListOptions for paginated list operations, BaseOptions otherwise\n    const isPaginated = plan.isPaginated;\n    const baseClass = isPaginated ? 'ListOptions' : 'BaseOptions';\n\n    optionsLines.push('');\n    const opSummary = op.description?.split('\\n').find((l) => l.trim()) ?? `${method} on ${mountName}`;\n    optionsLines.push(\n      `    /// <summary>Request options for <see cref=\"${className(mountName)}Service.${method}\"/>: ${escapeXml(opSummary.trim())}</summary>`,\n    );\n    optionsLines.push(`    public class ${optionsClass} : ${baseClass}`);\n    optionsLines.push('    {');\n\n    const emittedFields = new Set<string>();\n\n    // Body fields\n    if (hasBody && op.requestBody?.kind === 'model') {\n      const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n      if (bodyModel) {\n        for (const field of bodyModel.fields) {\n          if (hidden.has(field.name)) continue;\n          if (groupedParams.has(field.name)) continue;\n          const csField = fieldName(field.name);\n          if (emittedFields.has(csField)) continue;\n          emittedFields.add(csField);\n\n          const isOptional = !field.required;\n          const baseType = mapTypeRef(field.type);\n          const isAlreadyNullable = baseType.endsWith('?');\n          let csType: string;\n          let initializer = '';\n\n          if (isOptional) {\n            if (isAlreadyNullable) {\n              csType = baseType;\n            } else if (isValueTypeRef(field.type)) {\n              csType = `${baseType}?`;\n            } else {\n              csType = `${baseType}?`;\n            }\n          } else {\n            csType = baseType;\n            if (!isAlreadyNullable && !isValueTypeRef(field.type)) {\n              initializer = ' = default!;';\n            }\n          }\n\n          const isRequiredEnum = field.required && isEnumRef(field.type);\n          optionsLines.push(...emitXmlDoc(field.description, '        '));\n          if (field.deprecated) {\n            const msg = escapeCsAttributeString(deprecationMessage(field.description, 'field'));\n            optionsLines.push(`        [System.Obsolete(\"${msg}\")]`);\n          }\n          optionsLines.push(...emitJsonPropertyAttributes(field.name, { isRequiredEnum }));\n          optionsLines.push(`        public ${csType} ${csField} { get; set; }${initializer}`);\n          optionsLines.push('');\n        }\n      }\n    }\n\n    // Query params (skip pagination fields for list options — they're in ListOptions base,\n    // and skip grouped params which get their own abstract class hierarchy)\n    const PAGINATION_FIELDS = new Set(['before', 'after', 'limit', 'order']);\n    for (const param of op.queryParams) {\n      if (hidden.has(param.name)) continue;\n      if (groupedParams.has(param.name)) continue;\n      if (isPaginated && PAGINATION_FIELDS.has(param.name)) continue;\n      const csField = fieldName(param.name);\n      if (emittedFields.has(csField)) continue;\n      emittedFields.add(csField);\n\n      const isOptional = !param.required;\n      const baseType = mapTypeRef(param.type);\n      const isAlreadyNullable = baseType.endsWith('?');\n      let csType: string;\n      let initializer = '';\n\n      if (isOptional) {\n        if (isAlreadyNullable) {\n          csType = baseType;\n        } else if (isValueTypeRef(param.type)) {\n          csType = `${baseType}?`;\n        } else {\n          csType = `${baseType}?`;\n        }\n      } else {\n        csType = baseType;\n        if (!isAlreadyNullable && !isValueTypeRef(param.type)) {\n          initializer = ' = default!;';\n        }\n      }\n\n      const isRequiredEnum = param.required && isEnumRef(param.type);\n      optionsLines.push(...emitXmlDoc(param.description, '        '));\n      if (param.deprecated) {\n        const msg = escapeCsAttributeString(deprecationMessage(param.description, 'parameter'));\n        optionsLines.push(`        [System.Obsolete(\"${msg}\")]`);\n      }\n      optionsLines.push(...emitJsonPropertyAttributes(param.name, { isRequiredEnum }));\n      optionsLines.push(`        public ${csType} ${csField} { get; set; }${initializer}`);\n      optionsLines.push('');\n    }\n\n    // Hidden fields that need to be set programmatically (e.g., grant_type, client_id)\n    const defaults = getOpDefaults(resolvedOp);\n    const inferFromClient = getOpInferFromClient(resolvedOp);\n    for (const key of Object.keys(defaults)) {\n      const csField = fieldName(key);\n      if (emittedFields.has(csField)) continue;\n      emittedFields.add(csField);\n      optionsLines.push(`        internal string ${csField} { get; set; } = default!;`);\n      optionsLines.push('');\n    }\n    for (const key of inferFromClient) {\n      const csField = fieldName(key);\n      if (emittedFields.has(csField)) continue;\n      emittedFields.add(csField);\n      optionsLines.push(`        internal string ${csField} { get; set; } = default!;`);\n      optionsLines.push('');\n    }\n\n    // Parameter group properties (serialized manually in the service method, not by JSON)\n    for (const group of op.parameterGroups ?? []) {\n      const baseName = groupBaseClassName(mountName, group.name);\n      const csField = fieldName(group.name);\n      optionsLines.push('        [JsonIgnore]');\n      optionsLines.push('        [STJS.JsonIgnore]');\n      const initializer = group.optional ? '' : ' = default!;';\n      const csType = group.optional ? `${baseName}?` : baseName;\n      optionsLines.push(`        public ${csType} ${csField} { get; set; }${initializer}`);\n      optionsLines.push('');\n    }\n\n    optionsLines.push('    }');\n\n    // Emit parameter group abstract base + concrete variant classes\n    if (hasGroups) {\n      optionsLines.push(...generateParameterGroupTypes(mountName, op, ctx.spec.models, emittedGroupTypes));\n    }\n  }\n\n  optionsLines.push('}');\n\n  if (!hasOptions) return null;\n\n  return {\n    path: `Services/${className(mountName)}/_interfaces/${className(mountName)}Options.cs`,\n    content: optionsLines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\nfunction generateMethod(\n  _serviceType: string,\n  mountName: string,\n  method: string,\n  methodStem: string,\n  op: Operation,\n  plan: OperationPlan,\n  ctx: EmitterContext,\n  resolvedOp?: ResolvedOperation,\n): string {\n  const lines: string[] = [];\n  const isPaginated = plan.isPaginated;\n  const isDelete = plan.isDelete;\n  const hasBody = plan.hasBody && op.requestBody;\n  const hidden = buildHiddenParams(resolvedOp);\n  const groupedParams = collectGroupedParamNames(op);\n  const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n  const hasVisibleQueryParams =\n    op.queryParams.filter((qp) => !hidden.has(qp.name) && !groupedParams.has(qp.name)).length > 0;\n\n  let hasVisibleBodyFields = false;\n  if (hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) hasVisibleBodyFields = bodyModel.fields.some((f) => !hidden.has(f.name));\n  } else if (hasBody) {\n    hasVisibleBodyFields = true;\n  }\n\n  const hasParams = hasVisibleBodyFields || hasVisibleQueryParams || hasGroups;\n  const optionsClass = hasParams ? optionsClassName(mountName, methodStem) : null;\n  const hasHidden = hasHiddenParams(resolvedOp);\n\n  // Per-operation Bearer token auth (e.g., SSO GetProfile uses access_token instead of API key)\n  const hasBearerOverride = op.security?.some((s: any) => s.schemeName !== 'bearerAuth') ?? false;\n  const bearerParamName = hasBearerOverride\n    ? op.security!.find((s: any) => s.schemeName !== 'bearerAuth')!.schemeName\n    : null;\n\n  // URL-builder operations (e.g., /sso/authorize redirect endpoints) build a URL\n  // string for the caller to redirect to instead of issuing an HTTP request.\n  const isUrlBuilder = resolvedOp?.urlBuilder ?? false;\n\n  // Return type\n  let returnType: string;\n  if (isUrlBuilder) {\n    returnType = 'string';\n  } else if (isPaginated && op.pagination) {\n    const itemType = resolveListItemType(op.pagination.itemType, ctx);\n    returnType = `Task<WorkOSList<${itemType}>>`;\n  } else if (isDelete) {\n    returnType = 'Task';\n  } else if (plan.responseModelName) {\n    const respType = modelClassName(resolveModelName(plan.responseModelName));\n    if (!isPaginated && op.response?.kind === 'array') {\n      returnType = `Task<List<${respType}>>`;\n    } else {\n      returnType = `Task<${respType}>`;\n    }\n  } else {\n    returnType = 'Task';\n  }\n\n  // XML doc comment (full multi-line description from the spec)\n  lines.push(...emitXmlDoc(op.description, '        '));\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    const paramDesc = p.description ? escapeXml(p.description) : `The ${humanize(p.name)}.`;\n    lines.push(`        /// <param name=\"${localName(p.name)}\">${paramDesc}</param>`);\n  }\n  if (hasBearerOverride && bearerParamName) {\n    lines.push(`        /// <param name=\"${localName(bearerParamName)}\">The bearer token for authentication.</param>`);\n  }\n  if (optionsClass) {\n    lines.push(`        /// <param name=\"options\">Request options.</param>`);\n  }\n  if (!isUrlBuilder) {\n    lines.push(`        /// <param name=\"requestOptions\">Per-request configuration overrides.</param>`);\n    lines.push(`        /// <param name=\"cancellationToken\">Cancellation token.</param>`);\n  }\n  if (isUrlBuilder) {\n    lines.push(`        /// <returns>The fully-qualified URL for the caller to redirect to.</returns>`);\n  } else if (isPaginated && op.pagination) {\n    const itemType = resolveListItemType(op.pagination.itemType, ctx);\n    lines.push(`        /// <returns>A page of <see cref=\"${itemType}\"/> results.</returns>`);\n  } else if (plan.responseModelName) {\n    const respType = modelClassName(resolveModelName(plan.responseModelName));\n    lines.push(`        /// <returns>The <see cref=\"${respType}\"/> result.</returns>`);\n  }\n  if (op.deprecated) {\n    const msg = escapeCsAttributeString(deprecationMessage(op.description, 'operation'));\n    lines.push(`        [System.Obsolete(\"${msg}\")]`);\n  }\n\n  // Method signature\n  const params: string[] = [];\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    params.push(`string ${localName(p.name)}`);\n  }\n  if (hasBearerOverride && bearerParamName) {\n    params.push(`string ${localName(bearerParamName)}`);\n  }\n  if (optionsClass) {\n    const isRequired = hasVisibleBodyFields && !isPaginated;\n    params.push(isRequired ? `${optionsClass} options` : `${optionsClass}? options = null`);\n  }\n  if (!isUrlBuilder) {\n    params.push('RequestOptions? requestOptions = null');\n    params.push('CancellationToken cancellationToken = default');\n  }\n\n  const asyncKeyword = isUrlBuilder ? '' : 'async ';\n  lines.push(`        public virtual ${asyncKeyword}${returnType} ${method}(${params.join(', ')})`);\n  lines.push('        {');\n\n  // Inject hidden params\n  if (hasHidden && optionsClass) {\n    const isOptionalParam = !hasVisibleBodyFields || isPaginated;\n    if (isOptionalParam) {\n      lines.push(`            options ??= new ${optionsClass}();`);\n    }\n    const defaults = getOpDefaults(resolvedOp);\n    const inferFromClient = getOpInferFromClient(resolvedOp);\n    for (const [key, value] of Object.entries(defaults)) {\n      lines.push(`            options.${fieldName(key)} = ${csLiteral(value as string | number | boolean)};`);\n    }\n    for (const field of inferFromClient) {\n      if (field === 'client_id') {\n        lines.push(`            options.${fieldName(field)} = this.Client.RequireClientId();`);\n      } else {\n        lines.push(\n          `            options.${fieldName(field)} = this.Client.${clientFieldExpression(field)} ?? string.Empty;`,\n        );\n      }\n    }\n  }\n\n  // Build path\n  const pathExpr = buildPathExpr(op);\n\n  // URL-builders, bearer-override operations, and operations with parameter\n  // groups keep the inlined WorkOSRequest form because the Service helpers\n  // don't expose BuildRequestUri, AccessToken configuration, or manual\n  // query param injection. Everything else uses the helper one-liners.\n  const needsInlineRequest = isUrlBuilder || (hasBearerOverride && !!bearerParamName) || hasGroups;\n  const optionsArg = optionsClass ? 'options' : 'null';\n\n  if (needsInlineRequest) {\n    lines.push('            var request = new WorkOSRequest');\n    lines.push('            {');\n    lines.push(`                Method = HttpMethod.${httpMethodCs(op.httpMethod)},`);\n    lines.push(`                Path = ${pathExpr},`);\n    if (optionsClass) {\n      lines.push('                Options = options,');\n    }\n    if (hasBearerOverride && bearerParamName) {\n      lines.push(`                AccessToken = ${localName(bearerParamName)},`);\n    }\n    if (!isUrlBuilder) {\n      lines.push(`                RequestOptions = requestOptions,`);\n    }\n    lines.push('            };');\n\n    // Serialize parameter group variants into query params (GET/DELETE)\n    // or body params (POST/PUT/PATCH) so sensitive fields like passwords\n    // never leak into the URL.  DELETE is routed to query because the\n    // dotnet HTTP client only sends body content for non-GET/DELETE methods.\n    if (hasGroups) {\n      const groupTarget = hasBody && !isDelete ? 'body' : 'query';\n      lines.push('');\n      lines.push(...emitGroupSerialization(mountName, op, '            ', ctx.spec.models, groupTarget));\n      lines.push('');\n    }\n\n    if (isUrlBuilder) {\n      lines.push('            return this.Client.BuildRequestUri(request).ToString();');\n    } else if (returnType.startsWith('Task<')) {\n      const innerType = returnType.slice(5, -1);\n      lines.push(`            return await this.Client.MakeAPIRequest<${innerType}>(request, cancellationToken);`);\n    } else {\n      lines.push('            await this.Client.MakeRawAPIRequest(request, cancellationToken);');\n    }\n  } else if (isDelete) {\n    lines.push(`            await this.DeleteAsync(${pathExpr}, ${optionsArg}, requestOptions, cancellationToken);`);\n  } else if (returnType.startsWith('Task<')) {\n    const innerType = returnType.slice(5, -1);\n    const helper = httpMethodHelperName(op.httpMethod);\n    lines.push(\n      `            return await this.${helper}<${innerType}>(${pathExpr}, ${optionsArg}, requestOptions, cancellationToken);`,\n    );\n  } else {\n    const helper = httpMethodHelperName(op.httpMethod);\n    lines.push(\n      `            await this.${helper}<object>(${pathExpr}, ${optionsArg}, requestOptions, cancellationToken);`,\n    );\n  }\n\n  lines.push('        }');\n  return lines.join('\\n');\n}\n\nfunction generateAutoPagingMethod(\n  mountName: string,\n  method: string,\n  methodStem: string,\n  op: Operation,\n  plan: OperationPlan,\n  ctx: EmitterContext,\n  resolvedOp?: ResolvedOperation,\n): string {\n  const lines: string[] = [];\n  const hidden = buildHiddenParams(resolvedOp);\n  const groupedParams = collectGroupedParamNames(op);\n  const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n  const hasVisibleQueryParams =\n    op.queryParams.filter((qp) => !hidden.has(qp.name) && !groupedParams.has(qp.name)).length > 0;\n\n  let hasVisibleBodyFields = false;\n  if (plan.hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) hasVisibleBodyFields = bodyModel.fields.some((f) => !hidden.has(f.name));\n  }\n\n  const hasParams = hasVisibleBodyFields || hasVisibleQueryParams || hasGroups;\n  const optionsClass = hasParams ? optionsClassName(mountName, methodStem) : null;\n\n  const itemType = resolveListItemType(op.pagination!.itemType, ctx);\n\n  // XML doc\n  lines.push(\n    `        /// <summary>Auto-paging variant of <see cref=\"${method}\"/>. Yields individual items across all pages.</summary>`,\n  );\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    const paramDesc = p.description ? escapeXml(p.description) : `The ${humanize(p.name)}.`;\n    lines.push(`        /// <param name=\"${localName(p.name)}\">${paramDesc}</param>`);\n  }\n  if (optionsClass) {\n    lines.push(`        /// <param name=\"options\">Request options.</param>`);\n  }\n  lines.push(`        /// <param name=\"requestOptions\">Per-request configuration overrides.</param>`);\n  lines.push(`        /// <param name=\"cancellationToken\">Cancellation token.</param>`);\n  lines.push(`        /// <returns>An async sequence of <see cref=\"${itemType}\"/> items.</returns>`);\n\n  // Signature\n  const params: string[] = [];\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    params.push(`string ${localName(p.name)}`);\n  }\n  if (optionsClass) {\n    params.push(`${optionsClass}? options = null`);\n  }\n  params.push('RequestOptions? requestOptions = null');\n  params.push('CancellationToken cancellationToken = default');\n\n  lines.push(`        public virtual IAsyncEnumerable<${itemType}> ${methodStem}AutoPagingAsync(${params.join(', ')})`);\n  lines.push('        {');\n\n  const pathExpr = buildPathExpr(op);\n  const optionsArg = optionsClass ? 'options' : 'null';\n  lines.push(\n    `            return this.ListAutoPagingAsync<${itemType}>(${pathExpr}, ${optionsArg}, requestOptions, cancellationToken);`,\n  );\n  lines.push('        }');\n\n  return lines.join('\\n');\n}\n\nfunction resolveCsMethodName(op: Operation, mountName: string, ctx: EmitterContext): string {\n  return resolveMethodName(op, { name: mountName, operations: [op] }, ctx);\n}\n\nexport function resolveCsMethodStem(op: Operation, mountName: string, ctx: EmitterContext): string {\n  return resolveMethodStem(op, { name: mountName, operations: [op] }, ctx);\n}\n\nexport function optionsClassName(mountName: string, method: string): string {\n  const methodStem = method.endsWith('Async') ? method.slice(0, -5) : method;\n  const prefix = className(mountName);\n  if (methodStem.startsWith(prefix)) return `${methodStem}Options`;\n  return `${prefix}${methodStem}Options`;\n}\n\nfunction buildPathExpr(op: Operation): string {\n  if (op.pathParams.length === 0) {\n    return `\"${op.path}\"`;\n  }\n  // Build C# string interpolation\n  let interpolated = op.path;\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    interpolated = interpolated.replace(`{${p.name}}`, `{Uri.EscapeDataString(${localName(p.name)})}`);\n  }\n  return `$\"${interpolated}\"`;\n}\n\nfunction resolveListItemType(itemType: import('@workos/oagen').TypeRef, ctx: EmitterContext): string {\n  if (itemType.kind === 'model') {\n    const model = ctx.spec.models.find((m) => m.name === itemType.name);\n    if (model && isListWrapperModel(model)) {\n      const dataField = model.fields.find((f) => f.name === 'data');\n      if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n        return modelClassName(resolveModelName(dataField.type.items.name));\n      }\n    }\n    return modelClassName(resolveModelName(itemType.name));\n  }\n  return mapTypeRef(itemType);\n}\n\nfunction generateCompatibilityMethod(\n  mountName: string,\n  asyncMethod: string,\n  methodStem: string,\n  op: Operation,\n  plan: OperationPlan,\n  ctx: EmitterContext,\n  resolvedOp?: ResolvedOperation,\n): string {\n  const lines: string[] = [];\n  const hidden = buildHiddenParams(resolvedOp);\n  const groupedParams = collectGroupedParamNames(op);\n  const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n  const hasVisibleQueryParams =\n    op.queryParams.filter((qp) => !hidden.has(qp.name) && !groupedParams.has(qp.name)).length > 0;\n\n  let hasVisibleBodyFields = false;\n  if (plan.hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) hasVisibleBodyFields = bodyModel.fields.some((f) => !hidden.has(f.name));\n  } else if (plan.hasBody && op.requestBody) {\n    hasVisibleBodyFields = true;\n  }\n\n  const hasParams = hasVisibleBodyFields || hasVisibleQueryParams || hasGroups;\n  const optionsClass = hasParams ? optionsClassName(mountName, methodStem) : null;\n\n  let returnType = 'Task';\n  if (plan.isPaginated && op.pagination) {\n    const itemType = resolveListItemType(op.pagination.itemType, ctx);\n    returnType = `Task<WorkOSList<${itemType}>>`;\n  } else if (plan.responseModelName) {\n    const respType = modelClassName(resolveModelName(plan.responseModelName));\n    returnType = !plan.isPaginated && op.response?.kind === 'array' ? `Task<List<${respType}>>` : `Task<${respType}>`;\n  }\n\n  const params: string[] = [];\n  const args: string[] = [];\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    const name = localName(p.name);\n    params.push(`string ${name}`);\n    args.push(name);\n  }\n\n  const hasBearerOverride = op.security?.some((s: any) => s.schemeName !== 'bearerAuth') ?? false;\n  if (hasBearerOverride) {\n    const bearerParamName = op.security!.find((s: any) => s.schemeName !== 'bearerAuth')!.schemeName;\n    const bearerLocal = localName(bearerParamName);\n    params.push(`string ${bearerLocal}`);\n    args.push(bearerLocal);\n  }\n\n  if (optionsClass) {\n    const isRequired = hasVisibleBodyFields && !plan.isPaginated;\n    params.push(isRequired ? `${optionsClass} options` : `${optionsClass}? options = null`);\n    args.push('options');\n  }\n\n  params.push('RequestOptions? requestOptions = null');\n  params.push('CancellationToken cancellationToken = default');\n  args.push('requestOptions');\n  args.push('cancellationToken');\n\n  lines.push(`        /// <summary>Compatibility wrapper for <see cref=\"${asyncMethod}\"/>.</summary>`);\n  lines.push(`        public virtual ${returnType} ${methodStem}(${params.join(', ')})`);\n  lines.push('        {');\n  lines.push(`            return this.${asyncMethod}(${args.join(', ')});`);\n  lines.push('        }');\n\n  return lines.join('\\n');\n}\n","import type { ApiSpec, EmitterContext, GeneratedFile, Service } from '@workos/oagen';\nimport { toPascalCase, toSnakeCase } from '@workos/oagen';\nimport { resolveResourceClassName } from './resources.js';\nimport { className, serviceTypeName, humanize } from './naming.js';\nimport { getMountTarget } from '../shared/resolved-ops.js';\n\n/**\n * Generate the C# client file with service accessors.\n * Produces: WorkOSClient.Generated.cs (partial class with service properties).\n */\nexport function generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  return [generateClientFile(spec, ctx)];\n}\n\n/**\n * Deduplicate services by mount target.\n */\nfunction deduplicateByMount(services: Service[], ctx: EmitterContext): Service[] {\n  const byTarget = new Map<string, Service>();\n  for (const s of services) {\n    const target = getMountTarget(s, ctx);\n    const existing = byTarget.get(target);\n    if (!existing || toPascalCase(s.name) === target) {\n      byTarget.set(target, s);\n    }\n  }\n  return [...byTarget.values()];\n}\n\n/**\n * Build map of service name -> accessor property name.\n */\nexport function buildServiceAccessPaths(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const topLevel = deduplicateByMount(services, ctx);\n  const paths = new Map<string, string>();\n\n  for (const service of topLevel) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const prop = toSnakeCase(resolvedName);\n    paths.set(service.name, prop);\n  }\n\n  // Also map mount targets\n  for (const service of services) {\n    const target = getMountTarget(service, ctx);\n    if (!paths.has(target)) {\n      const existing = paths.get(service.name);\n      if (existing) paths.set(target, existing);\n    }\n  }\n\n  return paths;\n}\n\nfunction generateClientFile(spec: ApiSpec, ctx: EmitterContext): GeneratedFile {\n  const topLevel = deduplicateByMount(spec.services, ctx);\n  const lines: string[] = [];\n\n  lines.push(`namespace ${ctx.namespacePascal}`);\n  lines.push('{');\n  lines.push('    /// <summary>');\n  lines.push('    /// Generated service accessors for WorkOSClient.');\n  lines.push('    /// </summary>');\n  lines.push('    public partial class WorkOSClient');\n  lines.push('    {');\n\n  // Service properties with lazy initialization\n  for (const service of topLevel) {\n    const resolvedName = resolveResourceClassName(service, ctx);\n    const propName = className(resolvedName);\n    const svcType = serviceTypeName(resolvedName);\n    const backingField = propName.charAt(0).toLowerCase() + propName.slice(1);\n    const human = humanize(resolvedName);\n    lines.push(`        private ${svcType} ${backingField};`);\n    lines.push('');\n    lines.push(`        /// <summary>Gets the <see cref=\"${svcType}\"/> for ${human} API operations.</summary>`);\n    lines.push(`        public virtual ${svcType} ${propName} => this.${backingField} ??= new ${svcType}(this);`);\n    lines.push('');\n  }\n\n  lines.push('    }');\n  lines.push('}');\n\n  return {\n    path: 'Client/WorkOSClient.Generated.cs',\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n","import type { Model, TypeRef, Enum, EmitterContext } from '@workos/oagen';\nimport { fixtureFileName, domainFieldName } from './naming.js';\nimport { isListMetadataModel, isListWrapperModel } from './models.js';\nimport { collectNonPaginatedResponseModelNames } from '../shared/model-utils.js';\nimport { isModelInScope, fileExistsAfterRun } from '../shared/resolved-ops.js';\n\n/**\n * Prefix the per-model fixture path with the .NET test project layout so the\n * scoped-run gate can compare it against the prefixed paths recorded in the\n * prior manifest. Must mirror `TEST_PREFIX` in index.ts; the fixture path\n * itself (`testdata/<name>.json`) is what `prefixTestPaths` later prepends to.\n */\nconst TEST_PREFIX = 'test/WorkOSTests/';\n\n/**\n * Prefix mapping for generating realistic ID fixture values.\n */\nexport const ID_PREFIXES: Record<string, string> = {\n  Connection: 'conn_',\n  Organization: 'org_',\n  OrganizationMembership: 'om_',\n  User: 'user_',\n  Directory: 'directory_',\n  DirectoryGroup: 'dir_grp_',\n  DirectoryUser: 'dir_usr_',\n  Invitation: 'inv_',\n  Session: 'session_',\n  AuthenticationFactor: 'auth_factor_',\n  EmailVerification: 'email_verification_',\n  MagicAuth: 'magic_auth_',\n  PasswordReset: 'password_reset_',\n};\n\n/**\n * Generate JSON fixture files for test data.\n */\nexport function generateFixtures(\n  spec: {\n    models: Model[];\n    enums: Enum[];\n    services: any[];\n  },\n  ctx: EmitterContext,\n): { path: string; content: string }[] {\n  if (spec.models.length === 0) return [];\n\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n  const files: { path: string; content: string }[] = [];\n\n  // List-wrappers are normally represented only by the per-operation\n  // `list_<item>.json` fixtures generated from paginated operations below. But\n  // a wrapper returned by a NON-paginated operation (e.g.\n  // `PUT /authorization/groups/{id}/role_assignments` -> GroupRoleAssignmentList)\n  // is emitted as a real model (see models.ts) and its generated test references\n  // `testdata/<type>.json` (tests.ts). Emit that envelope fixture too, mirroring\n  // the non-wrapper `VersionListResponse` precedent — otherwise the test loads a\n  // file that was never written.\n  const nonPaginatedWrapperRefs = collectNonPaginatedResponseModelNames(spec.services);\n\n  for (const model of spec.models) {\n    if (isListMetadataModel(model)) continue;\n    if (isListWrapperModel(model) && !nonPaginatedWrapperRefs.has(model.name)) continue;\n\n    // Scoped-run gate: only emit a per-model fixture whose file will exist on\n    // disk after the run (in-scope, or already present from a prior manifest).\n    // A brand-new out-of-scope model's fixture would be a stray file for a\n    // model no in-scope test can reference; a renamed/removed-but-on-disk one\n    // is retained. Full runs emit everything. `relPath` carries the\n    // `test/WorkOSTests/` prefix so it matches the prefixed prior-manifest paths.\n    const fixturePath = `testdata/${fixtureFileName(model.name)}.json`;\n    if (!fileExistsAfterRun(`${TEST_PREFIX}${fixturePath}`, isModelInScope(model.name, ctx), ctx)) continue;\n\n    const fixture = model.fields.length === 0 ? {} : generateModelFixture(model, modelMap, enumMap);\n\n    files.push({\n      path: fixturePath,\n      content: JSON.stringify(fixture, null, 2),\n    });\n\n    // Generate null-field variant for models with nullable/optional fields\n    const hasNullableFields = model.fields.some((f) => !f.required || f.type.kind === 'nullable');\n    if (hasNullableFields && model.fields.length > 0) {\n      const nullFixture: Record<string, any> = {};\n      for (const field of model.fields) {\n        if (!field.required || field.type.kind === 'nullable') {\n          nullFixture[field.name] = null;\n        } else {\n          nullFixture[field.name] = fixture[field.name] ?? null;\n        }\n      }\n      files.push({\n        path: `testdata/${fixtureFileName(model.name)}_nulls.json`,\n        content: JSON.stringify(nullFixture, null, 2),\n      });\n    }\n  }\n\n  // Generate list fixtures for paginated responses\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      if (op.pagination) {\n        let itemModel = op.pagination.itemType.kind === 'model' ? modelMap.get(op.pagination.itemType.name) : null;\n        if (itemModel) {\n          const unwrapped = unwrapListModel(itemModel, modelMap);\n          if (unwrapped) itemModel = unwrapped;\n          if (itemModel.fields.length === 0) continue;\n          const fixture = generateModelFixture(itemModel, modelMap, enumMap);\n          const listFixture = {\n            data: [fixture],\n            list_metadata: {\n              before: null,\n              after: null,\n            },\n          };\n          files.push({\n            path: `testdata/list_${fixtureFileName(itemModel.name)}.json`,\n            content: JSON.stringify(listFixture, null, 2),\n          });\n        }\n      }\n    }\n  }\n\n  // Generate empty list fixtures for paginated responses\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      if (op.pagination) {\n        let itemModel = op.pagination.itemType.kind === 'model' ? modelMap.get(op.pagination.itemType.name) : null;\n        if (itemModel) {\n          const unwrapped = unwrapListModel(itemModel, modelMap);\n          if (unwrapped) itemModel = unwrapped;\n          const emptyFixture = {\n            data: [],\n            list_metadata: {\n              before: null,\n              after: null,\n            },\n          };\n          files.push({\n            path: `testdata/list_empty_${fixtureFileName(itemModel.name)}.json`,\n            content: JSON.stringify(emptyFixture, null, 2),\n          });\n        }\n      }\n    }\n  }\n\n  // Deduplicate fixtures by path (keep last-written for each path)\n  const byPath = new Map<string, { path: string; content: string }>();\n  for (const f of files) {\n    byPath.set(f.path, f);\n  }\n\n  return [...byPath.values()];\n}\n\nfunction unwrapListModel(model: Model, modelMap: Map<string, Model>): Model | null {\n  const dataField = model.fields.find((f) => f.name === 'data');\n  const hasListMetadata = model.fields.some((f) => f.name === 'list_metadata' || f.name === 'listMetadata');\n  if (dataField && hasListMetadata && dataField.type.kind === 'array') {\n    const itemType = dataField.type.items;\n    if (itemType.kind === 'model') {\n      return modelMap.get(itemType.name) ?? null;\n    }\n  }\n  return null;\n}\n\nexport function generateModelFixture(\n  model: Model,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): Record<string, any> {\n  const fixture: Record<string, any> = {};\n\n  const seenFieldNames = new Set<string>();\n  const deduplicatedFields = model.fields.filter((f) => {\n    // Dedup on the DOMAIN identifier (the C# property name, honoring a\n    // `domainName` override) to mirror the dedup in models.ts. The fixture\n    // payload below still keys on the wire name (`field.name`).\n    const csName = domainFieldName(f);\n    if (seenFieldNames.has(csName)) return false;\n    seenFieldNames.add(csName);\n    return true;\n  });\n\n  for (const field of deduplicatedFields) {\n    const wireName = field.name;\n    if (field.example !== undefined) {\n      fixture[wireName] = field.example;\n    } else {\n      fixture[wireName] = generateFieldValue(field.type, field.name, model.name, modelMap, enumMap);\n    }\n  }\n\n  return fixture;\n}\n\nfunction generateFieldValue(\n  ref: TypeRef,\n  fName: string,\n  modelName: string,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): any {\n  switch (ref.kind) {\n    case 'primitive':\n      return generatePrimitiveValue(ref.type, ref.format, fName, modelName);\n    case 'literal':\n      return ref.value;\n    case 'enum': {\n      const e = enumMap.get(ref.name);\n      return e?.values[0]?.value ?? 'unknown';\n    }\n    case 'model': {\n      const nested = modelMap.get(ref.name);\n      if (nested) return generateModelFixture(nested, modelMap, enumMap);\n      return {};\n    }\n    case 'array': {\n      if (ref.items.kind === 'enum') {\n        const e = enumMap.get(ref.items.name);\n        if (e && e.values.length > 0) {\n          return e.values.map((v) => v.value);\n        }\n      }\n      const item = generateFieldValue(ref.items, fName, modelName, modelMap, enumMap);\n      return [item];\n    }\n    case 'nullable':\n      return generateFieldValue(ref.inner, fName, modelName, modelMap, enumMap);\n    case 'union':\n      if (ref.variants.length > 0) {\n        return generateFieldValue(ref.variants[0], fName, modelName, modelMap, enumMap);\n      }\n      return null;\n    case 'map':\n      return {\n        key: generateFieldValue(ref.valueType, 'value', modelName, modelMap, enumMap),\n      };\n  }\n}\n\nfunction generatePrimitiveValue(type: string, format: string | undefined, name: string, modelName: string): any {\n  switch (type) {\n    case 'string':\n      if (format === 'date-time') return '2023-01-01T00:00:00.000Z';\n      if (format === 'date') return '2023-01-01';\n      if (format === 'uuid') return '00000000-0000-0000-0000-000000000000';\n      if (name === 'id') {\n        const prefix = ID_PREFIXES[modelName] ?? '';\n        return `${prefix}01234`;\n      }\n      if (name.includes('id')) return `${name}_01234`;\n      if (name.includes('email')) return 'test@example.com';\n      if (name.includes('url') || name.includes('uri')) return 'https://example.com';\n      if (name.includes('name')) return 'Test';\n      return `test_${name}`;\n    case 'integer':\n      return 1;\n    case 'number':\n      return 1.0;\n    case 'boolean':\n      return true;\n    case 'unknown':\n      return {};\n    default:\n      return null;\n  }\n}\n","import type { ApiSpec, Service, Operation, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { planOperation } from '@workos/oagen';\nimport {\n  fixtureFileName,\n  fieldName as csFieldName,\n  domainFieldName as csDomainFieldName,\n  methodName as csMethodName,\n  appendAsyncSuffix,\n  modelClassName,\n  resolveMethodName,\n  resolveMethodStem,\n  serviceTypeName,\n} from './naming.js';\nimport { resolveModelName } from './type-map.js';\nimport { resolveResourceClassName, sortPathParamsByTemplateOrder, optionsClassName } from './resources.js';\nimport { generateFixtures, generateModelFixture } from './fixtures.js';\nimport { isListWrapperModel } from './models.js';\nimport {\n  scopedMountGroups,\n  buildResolvedLookup,\n  lookupResolved,\n  buildHiddenParams,\n  collectGroupedParamNames,\n} from '../shared/resolved-ops.js';\n\n/**\n * Generate C# test files and JSON fixtures.\n */\nexport function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  // Generate fixture JSON files\n  const fixtures = generateFixtures(spec, ctx);\n  for (const fixture of fixtures) {\n    files.push({\n      path: fixture.path,\n      content: fixture.content,\n      headerPlacement: 'skip',\n    });\n  }\n\n  // Generate per-mount-target test files\n  const mountGroups = scopedMountGroups(ctx);\n  const testEntries: Array<{ name: string; operations: Operation[] }> =\n    mountGroups.size > 0 || ctx.scopedServices?.size\n      ? [...mountGroups].map(([name, group]) => ({ name, operations: group.operations }))\n      : spec.services.map((s) => ({\n          name: resolveResourceClassName(s, ctx),\n          operations: s.operations,\n        }));\n\n  for (const { name: mountName, operations } of testEntries) {\n    if (operations.length === 0) continue;\n    const mergedService: Service = { name: mountName, operations };\n    const testFile = generateServiceTest(mergedService, spec, ctx);\n    if (testFile) files.push(testFile);\n  }\n\n  return files;\n}\n\nfunction generateServiceTest(service: Service, spec: ApiSpec, ctx: EmitterContext): GeneratedFile | null {\n  if (service.operations.length === 0) return null;\n\n  const resolvedName = resolveResourceClassName(service, ctx);\n  const svcType = serviceTypeName(resolvedName);\n  const testClassName = `${svcType}Test`;\n  const testFile = `Tests/${testClassName}.cs`;\n\n  const lines: string[] = [];\n  lines.push(`namespace ${ctx.namespacePascal}Tests`);\n  lines.push('{');\n  lines.push('    using System.Collections.Generic;');\n  lines.push('    using System.Net;');\n  lines.push('    using System.Net.Http;');\n  lines.push('    using System.Threading.Tasks;');\n  lines.push(`    using ${ctx.namespacePascal};`);\n  lines.push('    using Xunit;');\n  lines.push('');\n  lines.push(`    public class ${testClassName}`);\n  lines.push('    {');\n  lines.push('        private readonly HttpMock httpMock;');\n  lines.push(`        private readonly ${svcType} service;`);\n  lines.push('');\n  lines.push(`        public ${testClassName}()`);\n  lines.push('        {');\n  lines.push('            this.httpMock = new HttpMock();');\n  lines.push(`            var client = new WorkOSClient(new WorkOSOptions`);\n  lines.push('            {');\n  lines.push('                ApiKey = \"sk_test\",');\n  lines.push('                ClientId = \"client_test\",');\n  lines.push('                HttpClient = this.httpMock.HttpClient,');\n  lines.push('            });');\n  lines.push(`            this.service = new ${svcType}(client);`);\n  lines.push('        }');\n\n  const emittedTestMethods = new Set<string>();\n  const resolvedLookupForTests = buildResolvedLookup(ctx);\n\n  for (const op of service.operations) {\n    const plan = planOperation(op);\n    const method = resolveCsMethodName(op, resolvedName, ctx);\n    const isPaginated = plan.isPaginated;\n    const isDelete = plan.isDelete;\n    const resolvedOp = lookupResolved(op, resolvedLookupForTests);\n    const isUrlBuilder = resolvedOp?.urlBuilder ?? false;\n    const isUnionSplit = (resolvedOp?.wrappers?.length ?? 0) > 0;\n\n    // Union-split operations (e.g. POST /user_management/authenticate) don't\n    // expose the base method or options class — only the typed wrappers —\n    // so skip the generic base test; the wrapper loop below emits tests for\n    // each AuthenticateWith* / CreateOAuthApplication variant instead.\n    if (isUnionSplit) continue;\n\n    if (emittedTestMethods.has(method)) continue;\n    emittedTestMethods.add(method);\n\n    const testName = `Test${method}`;\n    const expectedPath = buildExpectedPath(op);\n    if (isUrlBuilder) {\n      // URL-builder operations return a string synchronously without issuing\n      // an HTTP request. Assert the URL structure instead of mocking HTTP.\n      const callArgs = buildMethodCallArgs(op, plan, ctx, resolvedName);\n      lines.push('');\n      lines.push('        [Fact]');\n      lines.push(`        public void ${testName}()`);\n      lines.push('        {');\n      lines.push(`            var url = this.service.${method}(${callArgs});`);\n      lines.push('            Assert.NotNull(url);');\n      lines.push(`            Assert.Contains(\"${expectedPath}\", url);`);\n      lines.push('            Assert.Empty(this.httpMock.CapturedRequests);');\n      lines.push('        }');\n      continue;\n    }\n    if (isPaginated && op.pagination) {\n      // Paginated test\n      let fixturePath: string | null = null;\n      const paginationItemType = op.pagination.itemType;\n      if (paginationItemType.kind === 'model') {\n        const itemModel = spec.models.find((m) => m.name === paginationItemType.name);\n        if (itemModel) {\n          let resolved = itemModel;\n          if (isListWrapperModel(itemModel)) {\n            const dataField = itemModel.fields.find((f) => f.name === 'data');\n            if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n              const inner = spec.models.find((m) => m.name === (dataField.type as any).items.name);\n              if (inner) resolved = inner;\n            }\n          }\n          fixturePath = `testdata/list_${fixtureFileName(resolved.name)}.json`;\n        }\n      }\n\n      lines.push('');\n      lines.push('        [Fact]');\n      lines.push(`        public async Task ${testName}()`);\n      lines.push('        {');\n      if (fixturePath) {\n        lines.push(`            var fixture = System.IO.File.ReadAllText(\"${fixturePath}\");`);\n        lines.push(\n          `            this.httpMock.MockResponse(HttpMethod.Get, \"${expectedPath}\", HttpStatusCode.OK, fixture);`,\n        );\n      } else {\n        lines.push(\n          `            this.httpMock.MockResponse(HttpMethod.Get, \"${expectedPath}\", HttpStatusCode.OK, \"{\\\\\"data\\\\\":[],\\\\\"list_metadata\\\\\":{\\\\\"before\\\\\":null,\\\\\"after\\\\\":null}}\");`,\n        );\n      }\n      const callArgs = buildMethodCallArgs(op, plan, ctx, resolvedName);\n      lines.push(`            var result = await this.service.${method}(${callArgs});`);\n      lines.push('            Assert.NotNull(result);');\n      if (fixturePath) {\n        lines.push('            Assert.NotEmpty(result.Data);');\n      }\n      lines.push(`            this.httpMock.AssertRequestWasMade(HttpMethod.Get, \"${expectedPath}\");`);\n      lines.push('        }');\n\n      // Empty list test\n      const emptyTestName = `Test${method}Empty`;\n      if (!emittedTestMethods.has(emptyTestName)) {\n        emittedTestMethods.add(emptyTestName);\n        const callArgsEmpty = buildMethodCallArgs(op, plan, ctx, resolvedName);\n        lines.push('');\n        lines.push('        [Fact]');\n        lines.push(`        public async Task ${emptyTestName}()`);\n        lines.push('        {');\n        lines.push(\n          `            this.httpMock.MockResponse(HttpMethod.Get, \"${expectedPath}\", HttpStatusCode.OK, \"{\\\\\"data\\\\\":[],\\\\\"list_metadata\\\\\":{\\\\\"before\\\\\":null,\\\\\"after\\\\\":null}}\");`,\n        );\n        lines.push(`            var result = await this.service.${method}(${callArgsEmpty});`);\n        lines.push('            Assert.NotNull(result);');\n        lines.push('            Assert.Empty(result.Data);');\n        lines.push('        }');\n      }\n    } else if (isDelete) {\n      lines.push('');\n      lines.push('        [Fact]');\n      lines.push(`        public async Task ${testName}()`);\n      lines.push('        {');\n      lines.push(\n        `            this.httpMock.MockResponse(HttpMethod.Delete, \"${expectedPath}\", HttpStatusCode.NoContent, \"\");`,\n      );\n      const callArgs = buildMethodCallArgs(op, plan, ctx, resolvedName);\n      lines.push(`            await this.service.${method}(${callArgs});`);\n      lines.push(`            this.httpMock.AssertRequestWasMade(HttpMethod.Delete, \"${expectedPath}\");`);\n      lines.push('        }');\n    } else if (plan.responseModelName) {\n      const respModel = resolveModelName(plan.responseModelName);\n      const fixturePath = `testdata/${fixtureFileName(respModel)}.json`;\n      const httpMethodCs = op.httpMethod.charAt(0).toUpperCase() + op.httpMethod.slice(1).toLowerCase();\n\n      const isArrayResp = !isPaginated && op.response?.kind === 'array';\n      const shapeSeed = buildRequestShapeSeed(op, plan, ctx, resolvedName);\n\n      lines.push('');\n      lines.push('        [Fact]');\n      lines.push(`        public async Task ${testName}()`);\n      lines.push('        {');\n      lines.push(`            var fixture = System.IO.File.ReadAllText(\"${fixturePath}\");`);\n      if (isArrayResp) {\n        // Wrap single-object fixture in array for List<T> deserialization\n        lines.push(\n          `            this.httpMock.MockResponse(HttpMethod.${httpMethodCs}, \"${expectedPath}\", HttpStatusCode.OK, \"[\" + fixture + \"]\");`,\n        );\n      } else {\n        lines.push(\n          `            this.httpMock.MockResponse(HttpMethod.${httpMethodCs}, \"${expectedPath}\", HttpStatusCode.OK, fixture);`,\n        );\n      }\n      const callArgs = shapeSeed.seededCallArgs ?? buildMethodCallArgs(op, plan, ctx, resolvedName);\n      if (shapeSeed.setupLines.length > 0) {\n        for (const setupLine of shapeSeed.setupLines) {\n          lines.push(`            ${setupLine}`);\n        }\n      }\n      lines.push(`            var result = await this.service.${method}(${callArgs});`);\n      lines.push('            Assert.NotNull(result);');\n      if (!isArrayResp) {\n        const respModelDef = spec.models.find((m) => m.name === respModel);\n        if (respModelDef) {\n          const assertions = buildFixtureAssertions(respModelDef, spec);\n          for (const assertion of assertions) {\n            lines.push(`            ${assertion}`);\n          }\n        }\n      }\n\n      lines.push(`            this.httpMock.AssertRequestWasMade(HttpMethod.${httpMethodCs}, \"${expectedPath}\");`);\n      for (const assertLine of shapeSeed.assertLines) {\n        lines.push(`            ${assertLine}`);\n      }\n      lines.push('        }');\n    } else {\n      lines.push('');\n      lines.push('        [Fact]');\n      lines.push(`        public async Task ${testName}()`);\n      lines.push('        {');\n      const httpMethodCs = op.httpMethod.charAt(0).toUpperCase() + op.httpMethod.slice(1).toLowerCase();\n      lines.push(\n        `            this.httpMock.MockResponse(HttpMethod.${httpMethodCs}, \"${expectedPath}\", HttpStatusCode.OK, \"\");`,\n      );\n      const callArgs = buildMethodCallArgs(op, plan, ctx, resolvedName);\n      lines.push(`            await this.service.${method}(${callArgs});`);\n      lines.push(`            this.httpMock.AssertRequestWasMade(HttpMethod.${httpMethodCs}, \"${expectedPath}\");`);\n      lines.push('        }');\n    }\n  }\n\n  // Auto-paging tests (P0-5)\n  const resolvedLookupForPaging = buildResolvedLookup(ctx);\n  for (const op of service.operations) {\n    const plan = planOperation(op);\n    if (!plan.isPaginated || !op.pagination) continue;\n\n    const methodStem = resolveCsMethodStem(op, resolvedName, ctx);\n    const autoPagingMethod = `${methodStem}AutoPagingAsync`;\n    const autoPagingTestName = `Test${autoPagingMethod}`;\n    if (emittedTestMethods.has(autoPagingTestName)) continue;\n    emittedTestMethods.add(autoPagingTestName);\n\n    const expectedPath = buildExpectedPath(op);\n    const paginationItemType = op.pagination.itemType;\n    let itemTypeName: string | null = null;\n    let fixtureName: string | null = null;\n\n    if (paginationItemType.kind === 'model') {\n      const itemModel = spec.models.find((m) => m.name === paginationItemType.name);\n      if (itemModel) {\n        let resolved = itemModel;\n        if (isListWrapperModel(itemModel)) {\n          const dataField = itemModel.fields.find((f) => f.name === 'data');\n          if (dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model') {\n            const inner = spec.models.find((m) => m.name === (dataField.type as any).items.name);\n            if (inner) resolved = inner;\n          }\n        }\n        itemTypeName = modelClassName(resolveModelName(resolved.name));\n        fixtureName = fixtureFileName(resolveModelName(resolved.name));\n      }\n    }\n\n    if (!itemTypeName || !fixtureName) continue;\n\n    const callArgs = buildMethodCallArgs(op, plan, ctx, resolvedName);\n    // Remove the trailing options arg since auto-paging uses the same options\n    const autoPagingArgs = callArgs;\n\n    // Test with two pages\n    lines.push('');\n    lines.push('        [Fact]');\n    lines.push(`        public async Task ${autoPagingTestName}()`);\n    lines.push('        {');\n    lines.push(`            var fixture = System.IO.File.ReadAllText(\"testdata/${fixtureName}.json\");`);\n    lines.push(\n      `            var page1 = \"{\\\\\"data\\\\\":[\" + fixture + \"],\\\\\"list_metadata\\\\\":{\\\\\"before\\\\\":null,\\\\\"after\\\\\":\\\\\"cursor_123\\\\\"}}\";`,\n    );\n    lines.push(\n      `            var page2 = \"{\\\\\"data\\\\\":[\" + fixture + \"],\\\\\"list_metadata\\\\\":{\\\\\"before\\\\\":null,\\\\\"after\\\\\":null}}\";`,\n    );\n    lines.push(\n      `            this.httpMock.MockSequentialResponses(HttpMethod.Get, \"${expectedPath}\", HttpStatusCode.OK, new[] { page1, page2 });`,\n    );\n    lines.push('');\n    lines.push(`            var items = new List<${itemTypeName}>();`);\n    lines.push(`            await foreach (var item in this.service.${autoPagingMethod}(${autoPagingArgs}))`);\n    lines.push('            {');\n    lines.push('                items.Add(item);');\n    lines.push('            }');\n    lines.push('');\n    lines.push('            Assert.Equal(2, items.Count);');\n    lines.push('        }');\n\n    // Test with empty first page\n    const emptyTestName = `Test${autoPagingMethod}Empty`;\n    if (!emittedTestMethods.has(emptyTestName)) {\n      emittedTestMethods.add(emptyTestName);\n      lines.push('');\n      lines.push('        [Fact]');\n      lines.push(`        public async Task ${emptyTestName}()`);\n      lines.push('        {');\n      lines.push(`            var empty = \"{\\\\\"data\\\\\":[],\\\\\"list_metadata\\\\\":{\\\\\"before\\\\\":null,\\\\\"after\\\\\":null}}\";`);\n      lines.push(\n        `            this.httpMock.MockSequentialResponses(HttpMethod.Get, \"${expectedPath}\", HttpStatusCode.OK, new[] { empty });`,\n      );\n      lines.push('');\n      lines.push(`            var items = new List<${itemTypeName}>();`);\n      lines.push(`            await foreach (var item in this.service.${autoPagingMethod}(${autoPagingArgs}))`);\n      lines.push('            {');\n      lines.push('                items.Add(item);');\n      lines.push('            }');\n      lines.push('');\n      lines.push('            Assert.Empty(items);');\n      lines.push('        }');\n    }\n  }\n\n  // Wrapper/convenience method tests (P0-6)\n  for (const op of service.operations) {\n    const resolvedOp = lookupResolved(op, resolvedLookupForPaging);\n    if (!resolvedOp?.wrappers || resolvedOp.wrappers.length === 0) continue;\n\n    for (const wrapper of resolvedOp.wrappers) {\n      const wrapperMethodStem = csMethodName(wrapper.name);\n      const wrapperMethod = appendAsyncSuffix(wrapperMethodStem);\n      const wrapperTestName = `Test${wrapperMethod}`;\n      if (emittedTestMethods.has(wrapperTestName)) continue;\n      emittedTestMethods.add(wrapperTestName);\n\n      const expectedPath = buildExpectedPath(op);\n      const httpMethodCs = op.httpMethod.charAt(0).toUpperCase() + op.httpMethod.slice(1).toLowerCase();\n      const responseType = wrapper.responseModelName;\n\n      lines.push('');\n      lines.push('        [Fact]');\n      lines.push(`        public async Task ${wrapperTestName}()`);\n      lines.push('        {');\n\n      if (responseType) {\n        const fixturePath = `testdata/${fixtureFileName(resolveModelName(responseType))}.json`;\n        lines.push(`            var fixture = System.IO.File.ReadAllText(\"${fixturePath}\");`);\n        lines.push(\n          `            this.httpMock.MockResponse(HttpMethod.${httpMethodCs}, \"${expectedPath}\", HttpStatusCode.OK, fixture);`,\n        );\n      } else {\n        lines.push(\n          `            this.httpMock.MockResponse(HttpMethod.${httpMethodCs}, \"${expectedPath}\", HttpStatusCode.OK, \"\");`,\n        );\n      }\n\n      // Build wrapper call args\n      const wrapperArgs: string[] = [];\n      for (const p of sortPathParamsByTemplateOrder(op)) {\n        wrapperArgs.push(`\"test_${p.name}\"`);\n      }\n      wrapperArgs.push(`new ${wrapperMethodStem}Options()`);\n\n      if (responseType) {\n        lines.push(`            var result = await this.service.${wrapperMethod}(${wrapperArgs.join(', ')});`);\n        lines.push('            Assert.NotNull(result);');\n      } else {\n        lines.push(`            await this.service.${wrapperMethod}(${wrapperArgs.join(', ')});`);\n      }\n\n      lines.push(`            this.httpMock.AssertRequestWasMade(HttpMethod.${httpMethodCs}, \"${expectedPath}\");`);\n      lines.push('        }');\n    }\n  }\n\n  // Error tests — pick the first non-URL-builder operation so the error\n  // assertions run against a real HTTP call.\n  const sampleOp = service.operations.find((o) => !(lookupResolved(o, resolvedLookupForTests)?.urlBuilder ?? false));\n  if (sampleOp) {\n    const plan = planOperation(sampleOp);\n    const method = resolveCsMethodName(sampleOp, resolvedName, ctx);\n    const callArgs = buildMethodCallArgs(sampleOp, plan, ctx, resolvedName);\n\n    // 401\n    lines.push('');\n    lines.push('        [Fact]');\n    lines.push(`        public async Task TestError401()`);\n    lines.push('        {');\n    lines.push(\n      `            this.httpMock.MockResponseForAnyRequest(HttpStatusCode.Unauthorized, \"{\\\\\"code\\\\\":\\\\\"unauthorized\\\\\",\\\\\"message\\\\\":\\\\\"Unauthorized\\\\\"}\");`,\n    );\n    if (plan.isPaginated || plan.isDelete || !plan.responseModelName) {\n      lines.push(\n        `            await Assert.ThrowsAsync<AuthenticationException>(() => this.service.${method}(${callArgs}));`,\n      );\n    } else {\n      lines.push(\n        `            await Assert.ThrowsAsync<AuthenticationException>(() => this.service.${method}(${callArgs}));`,\n      );\n    }\n    lines.push('        }');\n\n    // 404\n    lines.push('');\n    lines.push('        [Fact]');\n    lines.push(`        public async Task TestError404()`);\n    lines.push('        {');\n    lines.push(\n      `            this.httpMock.MockResponseForAnyRequest(HttpStatusCode.NotFound, \"{\\\\\"code\\\\\":\\\\\"not_found\\\\\",\\\\\"message\\\\\":\\\\\"Not Found\\\\\"}\");`,\n    );\n    lines.push(`            await Assert.ThrowsAsync<NotFoundException>(() => this.service.${method}(${callArgs}));`);\n    lines.push('        }');\n\n    // 422\n    lines.push('');\n    lines.push('        [Fact]');\n    lines.push(`        public async Task TestError422()`);\n    lines.push('        {');\n    lines.push(\n      `            this.httpMock.MockResponseForAnyRequest((HttpStatusCode)422, \"{\\\\\"code\\\\\":\\\\\"unprocessable_entity\\\\\",\\\\\"message\\\\\":\\\\\"Unprocessable\\\\\"}\");`,\n    );\n    lines.push(\n      `            await Assert.ThrowsAsync<UnprocessableEntityException>(() => this.service.${method}(${callArgs}));`,\n    );\n    lines.push('        }');\n\n    // 429\n    lines.push('');\n    lines.push('        [Fact]');\n    lines.push(`        public async Task TestError429()`);\n    lines.push('        {');\n    lines.push(\n      `            this.httpMock.MockResponseForAnyRequest((HttpStatusCode)429, \"{\\\\\"code\\\\\":\\\\\"too_many_requests\\\\\",\\\\\"message\\\\\":\\\\\"Too Many Requests\\\\\"}\");`,\n    );\n    lines.push(\n      `            await Assert.ThrowsAsync<RateLimitExceededException>(() => this.service.${method}(${callArgs}));`,\n    );\n    lines.push('        }');\n\n    // 500\n    lines.push('');\n    lines.push('        [Fact]');\n    lines.push(`        public async Task TestError500()`);\n    lines.push('        {');\n    lines.push(\n      `            this.httpMock.MockResponseForAnyRequest(HttpStatusCode.InternalServerError, \"{\\\\\"code\\\\\":\\\\\"server_error\\\\\",\\\\\"message\\\\\":\\\\\"Server Error\\\\\"}\");`,\n    );\n    lines.push(`            await Assert.ThrowsAsync<ServerException>(() => this.service.${method}(${callArgs}));`);\n    lines.push('        }');\n  }\n\n  lines.push('    }');\n  lines.push('}');\n\n  return {\n    path: testFile,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\nfunction resolveCsMethodName(op: Operation, mountName: string, ctx: EmitterContext): string {\n  return resolveMethodName(op, { name: mountName, operations: [op] }, ctx);\n}\n\nfunction resolveCsMethodStem(op: Operation, mountName: string, ctx: EmitterContext): string {\n  return resolveMethodStem(op, { name: mountName, operations: [op] }, ctx);\n}\n\nfunction buildMethodCallArgs(op: Operation, plan: any, ctx: EmitterContext, mountName: string): string {\n  const args: string[] = [];\n\n  // Path params\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    args.push(`\"test_${p.name}\"`);\n  }\n\n  // Bearer auth override param (e.g., SSO GetProfile uses access_token)\n  const hasBearerOverride = op.security?.some((s: any) => s.schemeName !== 'bearerAuth') ?? false;\n  if (hasBearerOverride) {\n    const bearerParamName = op.security!.find((s: any) => s.schemeName !== 'bearerAuth')!.schemeName;\n    args.push(`\"test_${bearerParamName}\"`);\n  }\n\n  // Options struct if needed\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const resolvedOp = lookupResolved(op, resolvedLookup);\n  const hidden = buildHiddenParams(resolvedOp);\n  const groupedParams = collectGroupedParamNames(op);\n  const hasVisibleQueryParams =\n    op.queryParams.filter((qp) => !hidden.has(qp.name) && !groupedParams.has(qp.name)).length > 0 ||\n    (op.parameterGroups?.length ?? 0) > 0;\n  const hasBody = plan.hasBody && op.requestBody;\n  let hasVisibleBodyFields = false;\n  if (hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) hasVisibleBodyFields = bodyModel.fields.some((f) => !hidden.has(f.name));\n  } else if (hasBody) {\n    hasVisibleBodyFields = true;\n  }\n\n  if (hasVisibleBodyFields || hasVisibleQueryParams) {\n    const methodStem = resolveCsMethodStem(op, mountName, ctx);\n    const optName = optionsClassName(mountName, methodStem);\n    args.push(`new ${optName}()`);\n  }\n\n  return args.join(', ');\n}\n\n/**\n * Seed required request fields on the generated options expression and\n * produce matching body/query assertions. Catches snake_case mapping\n * regressions and missing-required-field bugs without requiring\n * hand-written tests.\n */\ninterface RequestShapeSeed {\n  setupLines: string[];\n  seededCallArgs: string | null;\n  assertLines: string[];\n}\n\nfunction buildRequestShapeSeed(op: Operation, plan: any, ctx: EmitterContext, mountName: string): RequestShapeSeed {\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const resolvedOp = lookupResolved(op, resolvedLookup);\n  const hidden = buildHiddenParams(resolvedOp);\n\n  // Collect required simple fields that we can seed with a string literal.\n  const bodySeeds: Array<{ wire: string; prop: string; value: string }> = [];\n  const querySeeds: Array<{ wire: string; prop: string; value: string }> = [];\n\n  const hasBody = plan.hasBody && op.requestBody;\n  if (hasBody && op.requestBody?.kind === 'model') {\n    const bodyModel = ctx.spec.models.find((m) => op.requestBody?.kind === 'model' && m.name === op.requestBody.name);\n    if (bodyModel) {\n      for (const field of bodyModel.fields) {\n        if (hidden.has(field.name)) continue;\n        if (!field.required) continue;\n        if (!isSeedableStringRef(field.type)) continue;\n        bodySeeds.push({\n          wire: field.name,\n          prop: csFieldName(field.name),\n          value: `test_${field.name}`,\n        });\n        if (bodySeeds.length >= 2) break;\n      }\n    }\n  }\n\n  // Wire names already covered by body seeds. For operations that duplicate a\n  // body field as a query param (e.g. POST /sso/token lists `code` in both),\n  // the generated options class only exposes the field once and the service\n  // call sends it via the body — so skip the query assertion to avoid a\n  // false-failing `AssertQueryParam`.\n  const bodyWireNames = new Set(bodySeeds.map((s) => s.wire));\n  const groupedParamNames = collectGroupedParamNames(op);\n  for (const param of op.queryParams) {\n    if (hidden.has(param.name)) continue;\n    if (groupedParamNames.has(param.name)) continue;\n    if (!param.required) continue;\n    if (!isSeedableStringRef(param.type)) continue;\n    // Skip pagination fields — they're set by the caller or the autopaging loop\n    if (['before', 'after', 'limit', 'order'].includes(param.name)) continue;\n    if (bodyWireNames.has(param.name)) continue;\n    querySeeds.push({\n      wire: param.name,\n      prop: csFieldName(param.name),\n      value: `test_${param.name}`,\n    });\n    if (querySeeds.length >= 2) break;\n  }\n\n  if (bodySeeds.length === 0 && querySeeds.length === 0) {\n    return { setupLines: [], seededCallArgs: null, assertLines: [] };\n  }\n\n  const methodStem = resolveCsMethodStem(op, mountName, ctx);\n  const optName = optionsClassName(mountName, methodStem);\n\n  // Rebuild call args with a seeded options variable named `options`.\n  const args: string[] = [];\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    args.push(`\"test_${p.name}\"`);\n  }\n  const hasBearerOverride = op.security?.some((s: any) => s.schemeName !== 'bearerAuth') ?? false;\n  if (hasBearerOverride) {\n    const bearerParamName = op.security!.find((s: any) => s.schemeName !== 'bearerAuth')!.schemeName;\n    args.push(`\"test_${bearerParamName}\"`);\n  }\n  args.push('options');\n\n  const setupLines: string[] = [`var options = new ${optName}();`];\n  for (const s of [...bodySeeds, ...querySeeds]) {\n    setupLines.push(`options.${s.prop} = \"${s.value}\";`);\n  }\n\n  const assertLines: string[] = [];\n  for (const s of bodySeeds) {\n    assertLines.push(`await this.httpMock.AssertRequestBodyContainsAsync(\"${s.wire}\", \"${s.value}\");`);\n  }\n  for (const s of querySeeds) {\n    assertLines.push(`this.httpMock.AssertQueryParam(\"${s.wire}\", \"${s.value}\");`);\n  }\n\n  return { setupLines, seededCallArgs: args.join(', '), assertLines };\n}\n\n/**\n * A TypeRef is seedable as a string literal in a generated test when it maps\n * to C# `string` (plain strings, formats like email/uuid, dates-as-strings).\n * Enums and numeric types need dedicated representations and are skipped here.\n */\nfunction isSeedableStringRef(ref: import('@workos/oagen').TypeRef): boolean {\n  if (ref.kind !== 'primitive') return false;\n  if (ref.type !== 'string') return false;\n  // `binary` maps to byte[], not a string literal\n  if (ref.format === 'binary') return false;\n  return true;\n}\n\nfunction buildExpectedPath(op: Operation): string {\n  let expected = op.path;\n  for (const p of sortPathParamsByTemplateOrder(op)) {\n    expected = expected.replace(`{${p.name}}`, `test_${p.name}`);\n  }\n  return expected;\n}\n\nfunction buildFixtureAssertions(model: import('@workos/oagen').Model, spec: ApiSpec): string[] {\n  const assertions: string[] = [];\n\n  // Compute the exact fixture payload the generator emits for this model so\n  // we can assert against those values verbatim. Mapping regressions\n  // (snake_case drift, nested field loss) fail deterministically instead of\n  // silently passing NotEmpty checks.\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n  let fixture: Record<string, unknown> = {};\n  try {\n    fixture = generateModelFixture(model, modelMap, enumMap);\n  } catch {\n    // Fall back to shape-only assertions if the fixture builder throws.\n  }\n\n  const idField = model.fields.find((f) => f.required && f.name === 'id');\n  if (idField) {\n    const idVal = fixture['id'];\n    if (typeof idVal === 'string' && idVal.length > 0) {\n      assertions.push(`Assert.Equal(${csStringLiteral(idVal)}, result.Id);`);\n    } else {\n      assertions.push(`Assert.NotEmpty(result.Id);`);\n    }\n  }\n\n  // Assert up to 2 additional required simple fields using the exact fixture\n  // value so snake_case mapping is verified. Skip date-time, binary, and\n  // anything that doesn't come out of the fixture as a non-empty string.\n  let extraCount = 0;\n  for (const field of model.fields) {\n    if (extraCount >= 2) break;\n    if (field.name === 'id') continue;\n    if (!field.required) continue;\n    if (field.type.kind !== 'primitive' || field.type.type !== 'string') continue;\n    if (field.type.format === 'date-time' || field.type.format === 'date') continue;\n    if (field.type.format === 'binary') continue;\n    // DOMAIN identifier: the C# property accessed on the deserialized model\n    // (honors a `domainName` override). The fixture lookup below uses the wire\n    // key (`field.name`).\n    const csField = csDomainFieldName(field);\n    const val = fixture[field.name];\n    if (typeof val === 'string' && val.length > 0) {\n      assertions.push(`Assert.Equal(${csStringLiteral(val)}, result.${csField});`);\n    } else {\n      assertions.push(`Assert.NotEmpty(result.${csField});`);\n    }\n    extraCount++;\n  }\n\n  return assertions;\n}\n\n/** Escape a JS string for use as a C# verbatim-friendly string literal. */\nfunction csStringLiteral(s: string): string {\n  return `\"${s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r')}\"`;\n}\n","import type { ApiSpec, EmitterContext, OperationsMap } from '@workos/oagen';\nimport { resolveMethodName } from './naming.js';\nimport { buildServiceAccessPaths } from './client.js';\nimport { buildResolvedLookup, lookupResolved, getMountTarget } from '../shared/resolved-ops.js';\n\n/**\n * Build operation-to-SDK-method mapping for the manifest.\n */\nexport function buildOperationsMap(spec: ApiSpec, ctx: EmitterContext): OperationsMap {\n  const manifest: OperationsMap = {};\n  const accessPaths = buildServiceAccessPaths(spec.services, ctx);\n  const resolvedLookup = buildResolvedLookup(ctx);\n\n  for (const service of spec.services) {\n    let serviceProp = accessPaths.get(service.name);\n    if (!serviceProp) {\n      const mountTarget = getMountTarget(service, ctx);\n      serviceProp = accessPaths.get(mountTarget);\n    }\n    if (!serviceProp) {\n      throw new Error(`Missing public client access path for service ${service.name}`);\n    }\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const method = resolveMethodName(op, service, ctx);\n\n      // Use per-operation mountOn when it differs from the service default\n      const resolved = lookupResolved(op, resolvedLookup);\n      const propName = (resolved && accessPaths.get(resolved.mountOn)) ?? serviceProp;\n\n      manifest[httpKey] = { sdkMethod: method, service: propName };\n    }\n  }\n\n  return manifest;\n}\n","import type {\n  Emitter,\n  EmitterContext,\n  FormatCommand,\n  GeneratedFile,\n  ApiSpec,\n  Model,\n  Enum,\n  Service,\n} from '@workos/oagen';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { generateModels, primeModelAliases, type DiscriminatorContext } from './models.js';\nimport { enrichModelsFromSpec, getSyntheticEnums } from '../shared/model-utils.js';\nimport { generateEnums, primeEnumAliases } from './enums.js';\nimport { generateResources } from './resources.js';\nimport { generateClient } from './client.js';\nimport { generateTests } from './tests.js';\nimport { buildOperationsMap } from './manifest.js';\nimport { generateWrapperOptionsClasses } from './wrappers.js';\nimport { groupByMount, isModelInScope, fileExistsAfterRun } from '../shared/resolved-ops.js';\nimport { AUTOGEN_NOTICE } from '../shared/file-header.js';\nimport { discriminatedUnions, resolveModelName } from './type-map.js';\nimport { modelClassName } from './naming.js';\n\n/**\n * Fix the namespace for C#. The CLI passes `--namespace workos` which gives\n * namespacePascal = \"Workos\", but C# needs \"WorkOS\" (preserving the brand casing).\n */\nfunction fixNamespace(ctx: EmitterContext): EmitterContext {\n  if (ctx.namespace === 'workos' || ctx.namespacePascal === 'Workos') {\n    return { ...ctx, namespacePascal: 'WorkOS' };\n  }\n  return ctx;\n}\n\n/** Ensure every generated file's content ends with a trailing newline. */\nfunction ensureTrailingNewlines(files: GeneratedFile[]): GeneratedFile[] {\n  for (const f of files) {\n    if (f.content && !f.content.endsWith('\\n')) {\n      f.content += '\\n';\n    }\n  }\n  return files;\n}\n\n/** Prefix for source files so they land under the .csproj directory. */\nconst SRC_PREFIX = 'src/WorkOS.net/';\n/** Prefix for test files so they land under the test project directory. */\nconst TEST_PREFIX = 'test/WorkOSTests/';\n\n/** Prefix generated source file paths to match the .NET project layout. */\nfunction prefixSourcePaths(files: GeneratedFile[]): GeneratedFile[] {\n  for (const f of files) {\n    f.path = `${SRC_PREFIX}${f.path}`;\n  }\n  return files;\n}\n\n/** Prefix generated test/fixture paths to match the .NET test project layout. */\nfunction prefixTestPaths(files: GeneratedFile[]): GeneratedFile[] {\n  for (const f of files) {\n    f.path = `${TEST_PREFIX}${f.path}`;\n  }\n  return files;\n}\n\n/**\n * Scoped-run gate for a discriminated-union variant referenced by a generated\n * converter (the event-registry / polymorphic dispatch aggregate). A converter\n * may only name a variant whose per-model `Entities/<Class>.cs` file will exist\n * on disk after the run — otherwise the `new <Class>()` / `ToObject<<Class>>`\n * arm references a type whose file is never emitted (CS0246). The set that\n * exists after the run is: in-scope variants (emitted this run) ∪ variants\n * already on disk from a prior manifest (scoped runs never prune), so a\n * renamed/removed-but-still-on-disk variant is RETAINED while a brand-new\n * out-of-scope variant is EXCLUDED. A full run includes everything.\n *\n * The variant name is resolved through the model-alias map first, exactly as\n * the converter emits it (`modelClassName(resolveModelName(name))`), and the\n * candidate path carries the `src/WorkOS.net/` prefix so it matches the\n * prefixed paths recorded in `priorTargetManifestPaths`.\n */\nfunction variantFileExistsAfterRun(variantModelName: string, ctx: EmitterContext): boolean {\n  const canonical = resolveModelName(variantModelName);\n  const relPath = `${SRC_PREFIX}Entities/${modelClassName(canonical)}.cs`;\n  return fileExistsAfterRun(relPath, isModelInScope(canonical, ctx), ctx);\n}\n\nexport const dotnetEmitter: Emitter = {\n  language: 'dotnet',\n\n  generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n    const c = fixNamespace(ctx);\n    primeEnumAliases(c.spec.enums);\n    const enriched = enrichModelsFromSpec(models);\n    // Re-prime after enrichment so synthetic enums from oneOf branches are\n    // included in the alias map used by mapTypeRef during model emission.\n    const synEnumsForModels = getSyntheticEnums();\n    if (synEnumsForModels.length > 0) {\n      primeEnumAliases([...c.spec.enums, ...synEnumsForModels]);\n    }\n\n    // Restore fields on discriminated base models. enrichModelsFromSpec clears\n    // fields for dispatcher-capable languages; C# uses inheritance instead:\n    // the base class keeps its common fields and variant classes extend it.\n    const originalByName = new Map(models.map((m) => [m.name, m]));\n    const discriminatorBases = new Set<string>();\n    const variantToBase = new Map<string, string>();\n    const modelDiscriminators = new Map<string, { property: string; mapping: Record<string, string> }>();\n\n    const dotnetModels = enriched.map((m) => {\n      const disc = (m as any).discriminator;\n      if (disc && m.fields.length === 0) {\n        const original = originalByName.get(m.name);\n        if (original && original.fields.length > 0) {\n          discriminatorBases.add(m.name);\n          modelDiscriminators.set(m.name, disc);\n          for (const variantName of Object.values(disc.mapping) as string[]) {\n            variantToBase.set(variantName, m.name);\n          }\n          return { ...m, fields: original.fields };\n        }\n      }\n      return m;\n    });\n\n    // Build a map of base model name → discriminator wire-property name so the\n    // model emitter can mark the discriminator field as internal-set.\n    const discriminatorProperties = new Map<string, string>();\n    for (const [baseName, disc] of modelDiscriminators) {\n      discriminatorProperties.set(baseName, disc.property);\n    }\n\n    const discCtx: DiscriminatorContext = { discriminatorBases, variantToBase, discriminatorProperties };\n    const files = generateModels(dotnetModels, c, discCtx);\n\n    // Generate discriminator converters for oneOf unions with discriminator\n    // (union-type references, e.g. a field typed as oneOf with discriminator)\n    if (discriminatedUnions.size > 0) {\n      for (const [baseName, disc] of discriminatedUnions) {\n        const converterName = `${baseName}DiscriminatorConverter`;\n        const lines: string[] = [];\n        lines.push(`namespace ${c.namespacePascal}`);\n        lines.push('{');\n        lines.push('    using System;');\n        lines.push('    using Newtonsoft.Json;');\n        lines.push('    using Newtonsoft.Json.Linq;');\n        lines.push('');\n        lines.push(`    /// <summary>`);\n        lines.push(`    /// JSON converter that deserializes discriminated union variants`);\n        lines.push(`    /// based on the \"${disc.property}\" property.`);\n        lines.push(`    /// </summary>`);\n        lines.push(`    public class ${converterName} : Newtonsoft.Json.JsonConverter`);\n        lines.push('    {');\n        lines.push('        public override bool CanConvert(Type objectType) => objectType == typeof(object);');\n        lines.push('');\n        // Override returns `object?` to match Newtonsoft.Json 13+'s nullable\n        // signature; `JToken.ToObject<T>` is itself `T?`, so a non-nullable\n        // override would trigger CS8603 under <Nullable>enable</Nullable>.\n        lines.push(\n          '        public override object? ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object? existingValue, Newtonsoft.Json.JsonSerializer serializer)',\n        );\n        lines.push('        {');\n        lines.push('            var jObject = JObject.Load(reader);');\n        lines.push(`            var discriminatorValue = jObject[\"${disc.property}\"]?.ToString();`);\n        lines.push('            switch (discriminatorValue)');\n        lines.push('            {');\n        for (const [value, modelName] of Object.entries(disc.mapping)) {\n          // Scoped-run gate: only dispatch to a variant whose `Entities/*.cs`\n          // file will exist after the run. A brand-new out-of-scope variant is\n          // skipped (its `.cs` is never emitted ⇒ CS0246); unmatched discriminator\n          // values fall through to the `default` arm below.\n          if (!variantFileExistsAfterRun(modelName, c)) continue;\n          const csName = modelClassName(resolveModelName(modelName));\n          lines.push(`                case \"${value}\": return jObject.ToObject<${csName}>(serializer);`);\n        }\n        lines.push('                default: return jObject.ToObject<object>(serializer);');\n        lines.push('            }');\n        lines.push('        }');\n        lines.push('');\n        lines.push(\n          '        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object? value, Newtonsoft.Json.JsonSerializer serializer)',\n        );\n        lines.push('        {');\n        lines.push('            serializer.Serialize(writer, value);');\n        lines.push('        }');\n        lines.push('    }');\n        lines.push('}');\n\n        files.push({\n          path: `Client/Utilities/${converterName}.cs`,\n          content: lines.join('\\n'),\n          overwriteExisting: true,\n        });\n      }\n    }\n\n    // Generate converters for discriminated base models (model-level\n    // discriminators detected by enrichModelsFromSpec, e.g. EventSchema).\n    // ReadJson uses Populate (not Deserialize) to avoid infinite recursion\n    // with the [JsonConverter] attribute applied to the base class.\n    // CanWrite is false so serialization uses the default path and never\n    // re-enters WriteJson.\n    for (const [baseName, disc] of modelDiscriminators) {\n      // Skip the converter entirely when the base model's own `Entities/*.cs`\n      // won't exist after a scoped run (brand-new out-of-scope base): its\n      // `new <baseClass>()` default arm and `[JsonConverter]` attribute would\n      // both dangle. When the base is already on disk we still emit it — the\n      // untouched base class references this converter by name.\n      if (!variantFileExistsAfterRun(baseName, c)) continue;\n      const baseClass = modelClassName(baseName);\n      const converterName = `${baseClass}DiscriminatorConverter`;\n      const lines: string[] = [];\n      lines.push(`namespace ${c.namespacePascal}`);\n      lines.push('{');\n      lines.push('    using System;');\n      lines.push('    using Newtonsoft.Json;');\n      lines.push('    using Newtonsoft.Json.Linq;');\n      lines.push('');\n      lines.push(`    /// <summary>`);\n      lines.push(`    /// JSON converter that deserializes <see cref=\"${baseClass}\"/> into the`);\n      lines.push(`    /// correct variant subclass based on the \"${disc.property}\" property.`);\n      lines.push(`    /// </summary>`);\n      lines.push(`    public class ${converterName} : Newtonsoft.Json.JsonConverter`);\n      lines.push('    {');\n      lines.push('        public override bool CanWrite => false;');\n      lines.push('');\n      lines.push(\n        `        public override bool CanConvert(Type objectType) => typeof(${baseClass}).IsAssignableFrom(objectType);`,\n      );\n      lines.push('');\n      // See first converter — `object?` matches Newtonsoft 13+ to avoid CS8603.\n      lines.push(\n        '        public override object? ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object? existingValue, Newtonsoft.Json.JsonSerializer serializer)',\n      );\n      lines.push('        {');\n      lines.push('            var jObject = JObject.Load(reader);');\n      lines.push(`            var discriminatorValue = jObject[\"${disc.property}\"]?.ToString();`);\n      lines.push('');\n      lines.push('            object target;');\n      lines.push('            switch (discriminatorValue)');\n      lines.push('            {');\n      for (const [value, variantModelName] of Object.entries(disc.mapping)) {\n        // Scoped-run gate: only construct a variant whose `Entities/*.cs` file\n        // will exist after the run. This is the event-registry aggregate\n        // (`EventSchema` enumerates every event payload model): a brand-new\n        // out-of-scope event type is skipped (its `.cs` is never emitted ⇒\n        // CS0246), while a renamed/removed-but-still-on-disk one is retained.\n        // Unmatched discriminator values fall through to the `default` arm,\n        // which deserializes into the base class.\n        if (!variantFileExistsAfterRun(variantModelName, c)) continue;\n        const csName = modelClassName(variantModelName);\n        lines.push(`                case \"${value}\": target = new ${csName}(); break;`);\n      }\n      lines.push(`                default: target = new ${baseClass}(); break;`);\n      lines.push('            }');\n      lines.push('');\n      lines.push('            serializer.Populate(jObject.CreateReader(), target);');\n      lines.push('            return target;');\n      lines.push('        }');\n      lines.push('');\n      lines.push(\n        '        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object? value, Newtonsoft.Json.JsonSerializer serializer)',\n      );\n      lines.push('        {');\n      lines.push(\n        '            throw new NotImplementedException(\"Serialization is handled by the default serializer.\");',\n      );\n      lines.push('        }');\n      lines.push('    }');\n      lines.push('}');\n\n      files.push({\n        path: `Client/Utilities/${converterName}.cs`,\n        content: lines.join('\\n'),\n        overwriteExisting: true,\n      });\n    }\n\n    return prefixSourcePaths(ensureTrailingNewlines(files));\n  },\n\n  generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n    const c = fixNamespace(ctx);\n    // Ensure synthetic enums are populated regardless of method execution order.\n    // enrichModelsFromSpec is idempotent (cached raw spec) and populates the\n    // module-level synthetic-enum store consumed by getSyntheticEnums().\n    enrichModelsFromSpec(c.spec.models);\n    const syntheticEnums = getSyntheticEnums();\n    const allEnums = syntheticEnums.length > 0 ? [...enums, ...syntheticEnums] : enums;\n    return prefixSourcePaths(ensureTrailingNewlines(generateEnums(allEnums, c)));\n  },\n\n  generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n    const c = fixNamespace(ctx);\n    const synEnums = getSyntheticEnums();\n    primeEnumAliases(synEnums.length > 0 ? [...c.spec.enums, ...synEnums] : c.spec.enums);\n    primeModelAliases(enrichModelsFromSpec(c.spec.models));\n    const files = generateResources(services, c);\n\n    // Also generate wrapper options classes\n    const mountGroups = groupByMount(c);\n    for (const [, group] of mountGroups) {\n      for (const resolvedOp of group.resolvedOps) {\n        if (resolvedOp.wrappers && resolvedOp.wrappers.length > 0) {\n          const wrapperOptionsLines = generateWrapperOptionsClasses(resolvedOp, c);\n          if (wrapperOptionsLines.length > 0) {\n            const mountName = resolvedOp.mountOn;\n            const optionsPath = `Services/${mountName}/_interfaces/${mountName}WrapperOptions.cs`;\n            const content = [\n              `namespace ${c.namespacePascal}`,\n              '{',\n              '    using System.Collections.Generic;',\n              '    using Newtonsoft.Json;',\n              '    using STJS = System.Text.Json.Serialization;',\n              ...wrapperOptionsLines,\n              '}',\n            ].join('\\n');\n            files.push({\n              path: optionsPath,\n              content,\n              overwriteExisting: true,\n            });\n          }\n        }\n      }\n    }\n\n    return prefixSourcePaths(ensureTrailingNewlines(files));\n  },\n\n  generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    const c = fixNamespace(ctx);\n    return prefixSourcePaths(ensureTrailingNewlines(generateClient(spec, c)));\n  },\n\n  generateErrors(): GeneratedFile[] {\n    return [];\n  },\n\n  generateTypeSignatures(): GeneratedFile[] {\n    return [];\n  },\n\n  generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    const c = fixNamespace(ctx);\n    const synEnumsForTests = getSyntheticEnums();\n    primeEnumAliases(synEnumsForTests.length > 0 ? [...spec.enums, ...synEnumsForTests] : spec.enums);\n    primeModelAliases(enrichModelsFromSpec(c.spec.models));\n    return prefixTestPaths(ensureTrailingNewlines(generateTests(spec, c)));\n  },\n\n  buildOperationsMap(spec: ApiSpec, ctx: EmitterContext) {\n    return buildOperationsMap(spec, fixNamespace(ctx));\n  },\n\n  fileHeader(): string {\n    return `// ${AUTOGEN_NOTICE}`;\n  },\n\n  formatCommand(targetDir: string): FormatCommand | null {\n    // `dotnet format` applies both whitespace rules and analyzer code fixes\n    // (StyleCop, etc.) to the generated files, matching the target project's\n    // conventions. We prefer a .sln/.slnx/.csproj workspace so MSBuild loads\n    // the analyzer ruleset correctly.\n    const workspace = findDotnetWorkspace(targetDir);\n    if (!workspace) return null;\n\n    // `dotnet format` expects `--include` paths relative to the workspace\n    // (or absolute). Our harness appends absolute paths, which is fine.\n    // Run `--no-restore` so formatting doesn't trigger a package restore on\n    // every codegen run.\n    return {\n      cmd: 'dotnet',\n      args: ['format', workspace, '--no-restore', '--include'],\n      // Keep batches small enough to stay under argv length limits while\n      // still amortizing MSBuild startup across many files.\n      batchSize: 500,\n    };\n  },\n};\n\n/** Locate a .sln/.slnx/.csproj file in the target directory for `dotnet format`. */\nfunction findDotnetWorkspace(targetDir: string): string | null {\n  if (!fs.existsSync(targetDir)) return null;\n  const entries = fs.readdirSync(targetDir);\n  const sln = entries.find((e) => e.endsWith('.sln') || e.endsWith('.slnx'));\n  if (sln) return path.resolve(targetDir, sln);\n  const csproj = entries.find((e) => e.endsWith('.csproj'));\n  if (csproj) return path.resolve(targetDir, csproj);\n  return null;\n}\n","import type { Operation, Service, EmitterContext, TypeRef } from '@workos/oagen';\nimport {\n  buildExportedClassNameSet as buildExportedClassNameSetShared,\n  resolveServiceTarget as resolveServiceTargetShared,\n} from '../shared/service-name-collision.js';\nimport { toPascalCase, toCamelCase, toSnakeCase } from '@workos/oagen';\nimport { buildResolvedLookup, lookupMethodName, getMountTarget } from '../shared/resolved-ops.js';\nimport { stripUrnPrefix } from '../shared/naming-utils.js';\n\n/**\n * Acronyms that should appear fully uppercase in PascalCase identifiers.\n * `toPascalCase` would otherwise titlecase them (e.g. `Sso`, `Pkce`, `Mfa`).\n * Both [className] and [apiClassName] consult this list so model and service\n * class names stay consistent (e.g. `SsoConnection` -> `SSOConnection`).\n */\nconst PASCAL_ACRONYMS = ['SSO', 'PKCE', 'MFA'];\n\nfunction uppercaseAcronyms(pascal: string): string {\n  let result = pascal;\n  for (const acronym of PASCAL_ACRONYMS) {\n    // Match the titlecased form (e.g. `Sso`) at any position where it stands\n    // as a complete word (followed by an uppercase letter, digit, or end).\n    const titled = acronym.charAt(0) + acronym.slice(1).toLowerCase();\n    const re = new RegExp(`${titled}(?=[A-Z0-9]|$)`, 'g');\n    result = result.replace(re, acronym);\n  }\n  return result;\n}\n\n/** PascalCase class/type name. */\nexport function className(name: string): string {\n  return uppercaseAcronyms(toPascalCase(stripUrnPrefix(name)));\n}\n\n/** PascalCase file name (matches the primary class). */\nexport function fileName(name: string): string {\n  return uppercaseAcronyms(toPascalCase(stripUrnPrefix(name)));\n}\n\n/** snake_case file name for fixtures/test data. */\nexport function fixtureFileName(name: string): string {\n  return toSnakeCase(stripUrnPrefix(name));\n}\n\n/** camelCase method name. */\nexport function methodName(name: string): string {\n  return toCamelCase(name);\n}\n\n/** camelCase Kotlin property / local variable name. */\nexport function propertyName(name: string): string {\n  const camel = toCamelCase(name);\n  // `object` is a Kotlin reserved word. Instead of backtick-escaping it\n  // (forcing callers to write `event.\\`object\\``), rename to `objectType`\n  // and rely on @JsonProperty(\"object\") for wire mapping.\n  if (camel === 'object') return 'objectType';\n  return escapeReserved(camel);\n}\n\n/**\n * camelCase domain property name for a MODEL field, honoring a `domainName`\n * override (set via the `fieldHints` config) so a wire field can surface under\n * a friendlier name. The wire key (the `@JsonProperty(\"...\")` argument) still\n * derives from `field.name`. No-op when `domainName` is unset, so it is also\n * safe on params. Only apply to model fields.\n */\nexport function domainPropertyName(field: { name: string; domainName?: string }): string {\n  return propertyName(field.domainName ?? field.name);\n}\n\n/** camelCase alias (kept for parity with other emitters). */\nexport const fieldName = propertyName;\nexport const localName = propertyName;\n\n/** PascalCase directory segment for a service / mount group. */\nexport function moduleName(name: string): string {\n  return toPascalCase(name);\n}\n\n/** Lower-case Kotlin package segment for a service / mount group. */\nexport function packageSegment(name: string): string {\n  // Kotlin package convention: all-lowercase, no separators.\n  return toPascalCase(name).toLowerCase();\n}\n\n/** Kotlin service class name for a mount group (e.g., `Organizations`). */\nexport function apiClassName(name: string): string {\n  return className(name);\n}\n\n/**\n * Resolve the Kotlin service class name with the collision suffix applied\n * when needed. Wraps `apiClassName` so callers don't need to thread the\n * exported-classes set through unrelated emission logic.\n */\nexport function resolveApiClassName(name: string, exportedClasses: Set<string>): string {\n  return apiClassName(resolveServiceTarget(name, exportedClasses));\n}\n\n/**\n * Build the set of model + enum class names exported by the SDK. Used to\n * detect collisions with operation-client class names — a colliding service\n * gets a `Service` suffix appended.\n */\nexport function buildExportedClassNameSet(ctx: EmitterContext): Set<string> {\n  return buildExportedClassNameSetShared(ctx, className);\n}\n\n/**\n * Resolve a service's mount-target identifier, appending `Service` on\n * collision with an exported model/enum class. Kotlin sees the collision\n * when a service class shares a simple name with an imported model class\n * (e.g. `com.workos.models.OrganizationMembership` vs\n * `com.workos.organizationmembership.OrganizationMembership`) — the file's\n * local declaration shadows the import for unqualified references.\n */\nexport function resolveServiceTarget(target: string, exportedClasses: Set<string>): string {\n  return resolveServiceTargetShared(target, exportedClasses, className);\n}\n\n/** Accessor property exposed on the WorkOS client (camelCase). */\nexport function servicePropertyName(name: string): string {\n  return toCamelCase(name);\n}\n\n/** Resolve the effective service (mount target) name. */\nexport function resolveServiceName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n/** Build a map from IR service name -> resolved mount-target name (PascalCase). */\nexport function buildServiceNameMap(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of services) {\n    map.set(service.name, resolveServiceName(service, ctx));\n  }\n  return map;\n}\n\n/** Resolve the SDK method name (camelCase) for an operation. */\nexport function resolveMethodName(op: Operation, service: Service, ctx: EmitterContext): string {\n  const lookup = buildResolvedLookup(ctx);\n  const resolved = lookupMethodName(op, lookup);\n  if (resolved) {\n    return trimMountedResourceFromMethod(methodName(resolved), resolveClassName(service, ctx));\n  }\n  const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const existing = ctx.overlayLookup?.methodByOperation?.get(httpKey);\n  if (existing) {\n    return trimMountedResourceFromMethod(methodName(existing.methodName), resolveClassName(service, ctx));\n  }\n  return trimMountedResourceFromMethod(methodName(op.name), resolveClassName(service, ctx));\n}\n\n/** Resolve the SDK class name (PascalCase) for a service. */\nexport function resolveClassName(service: Service, ctx: EmitterContext): string {\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (r.service.name === service.name) return className(r.mountOn);\n  }\n  if (ctx.overlayLookup?.methodByOperation) {\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const existing = ctx.overlayLookup.methodByOperation.get(httpKey);\n      if (existing) return className(existing.className);\n    }\n  }\n  return className(service.name);\n}\n\n/** Build a map from IR service name -> mount-target directory (PascalCase). */\nexport function buildMountDirMap(ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of ctx.spec.services) {\n    const target = getMountTarget(service, ctx);\n    map.set(service.name, moduleName(target));\n  }\n  return map;\n}\n\nfunction splitPascalWords(name: string): string[] {\n  return name.match(/[A-Z]+(?:[a-z]+|(?=[A-Z]|$))|[A-Z]?[a-z]+|[0-9]+/g) ?? [name];\n}\n\nfunction singularize(word: string): string {\n  if (word.endsWith('ies') && word.length > 3) {\n    return `${word.slice(0, -3)}y`;\n  }\n  if (word.endsWith('s') && !word.endsWith('ss')) {\n    return word.slice(0, -1);\n  }\n  return word;\n}\n\nfunction wordsMatch(left: string, right: string): boolean {\n  return singularize(left.toLowerCase()) === singularize(right.toLowerCase());\n}\n\n/**\n * Trim the mount-target resource words from the start of a method name.\n * E.g. `listOrganizations` on OrganizationsApi becomes `list`.\n */\nfunction trimMountedResourceFromMethod(method: string, mountName: string): string {\n  const methodWords = splitPascalWords(method);\n  if (methodWords.length < 2) return method;\n\n  const mountWords = splitPascalWords(className(mountName));\n  if (mountWords.length === 0) return method;\n\n  let matched = 0;\n  while (\n    matched < mountWords.length &&\n    matched + 1 < methodWords.length &&\n    wordsMatch(methodWords[matched + 1], mountWords[matched])\n  ) {\n    matched++;\n  }\n\n  if (matched === 0) return method;\n\n  return [methodWords[0], ...methodWords.slice(matched + 1)].join('');\n}\n\n/** Kotlin hard/soft keywords that must be back-ticked when used as identifiers. */\nconst KOTLIN_RESERVED = new Set([\n  'as',\n  'break',\n  'class',\n  'continue',\n  'do',\n  'else',\n  'false',\n  'for',\n  'fun',\n  'if',\n  'in',\n  'interface',\n  'is',\n  'null',\n  'object',\n  'package',\n  'return',\n  'super',\n  'this',\n  'throw',\n  'true',\n  'try',\n  'typealias',\n  'typeof',\n  'val',\n  'var',\n  'when',\n  'while',\n]);\n\n/** Escape a Kotlin identifier if it collides with a reserved word. */\nexport function escapeReserved(name: string): string {\n  return KOTLIN_RESERVED.has(name) ? `\\`${name}\\`` : name;\n}\n\n/** Escape a string literal for Kotlin source. */\nexport function ktStringLiteral(value: string): string {\n  return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r')}\"`;\n}\n\n/** Escape any scalar as a Kotlin literal expression. */\nexport function ktLiteral(value: string | number | boolean): string {\n  if (typeof value === 'string') return ktStringLiteral(value);\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  return String(value);\n}\n\n/**\n * Map a wire field name to the expression that reads it off a WorkOS client\n * instance (used for inferFromClient fields).\n */\nexport function clientFieldExpression(field: string): string {\n  switch (field) {\n    case 'client_id':\n      return 'clientId';\n    case 'client_secret':\n      return 'apiKey';\n    default:\n      return propertyName(field);\n  }\n}\n\n/** Convert snake_case / camelCase to a human-readable lowercase phrase for docs. */\nexport function humanize(name: string): string {\n  return name\n    .replace(/_/g, ' ')\n    .replace(/([a-z])([A-Z])/g, '$1 $2')\n    .toLowerCase();\n}\n\n/**\n * If the parameter is typed as an enum and its description is long enough\n * that repeating it across every method's KDoc adds noise, return a short\n * description that defers to the enum's own KDoc with a `See [EnumName].`\n * reference. Otherwise return null and the caller keeps the spec text.\n *\n * Currently only `PaginationOrder` is shortened — the SSO/MFA/etc. enums\n * have brief descriptions already. Generalize when other long-description\n * enums appear in the spec.\n */\nconst LONG_ENUM_DESC_THRESHOLD = 120;\n\nexport function maybeShortenEnumParamDescription(\n  type: TypeRef | undefined,\n  description: string | undefined,\n): { description: string; enumRef: string } | null {\n  if (!type || !description) return null;\n  const enumName = extractEnumName(type);\n  if (!enumName) return null;\n  if (description.length <= LONG_ENUM_DESC_THRESHOLD) return null;\n  // Only special-case PaginationOrder for now; other enums keep their\n  // descriptions verbatim so we don't over-trim until a pattern emerges.\n  if (className(enumName) !== 'PaginationOrder') return null;\n  return {\n    description: `the order to return records in. See [${className(enumName)}].`,\n    enumRef: className(enumName),\n  };\n}\n\nfunction extractEnumName(type: TypeRef): string | null {\n  if (type.kind === 'enum') return type.name;\n  if (type.kind === 'nullable') return extractEnumName(type.inner);\n  return null;\n}\n","import type { Enum, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { className, ktStringLiteral } from './naming.js';\nimport { isEnumInScope } from '../shared/resolved-ops.js';\n\nconst KOTLIN_SRC_PREFIX = 'src/main/kotlin/';\nconst ENUMS_PACKAGE = 'com.workos.types';\nconst ENUMS_DIR = 'com/workos/types';\n\n/**\n * Mapping from an IR enum name to its canonical enum name. When two enums\n * share identical sorted wire values the shorter-named one is canonical and\n * the others become `typealias` files. Downstream consumers (type-map,\n * resources) use this map to resolve references to the canonical class.\n */\nexport const enumCanonicalMap = new Map<string, string>();\n\n/**\n * Generate Kotlin `enum class` types from the IR enums. Each enum is emitted\n * to its own file under `com.workos.types`, annotated with Jackson\n * `@JsonValue` on the wire value. An `Unknown` sentinel is always the first\n * constant so that responses with new variants still deserialize instead of\n * throwing.\n *\n * Enums with identical sets of wire values are deduplicated: the one with the\n * shortest PascalCase name becomes canonical and the rest emit `typealias`\n * files pointing at the canonical class.\n */\nexport function generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n  if (enums.length === 0) return [];\n\n  // Reset the canonical map on every generation run (guards against re-entry).\n  enumCanonicalMap.clear();\n\n  // --- Dedup: group enums by a hash of their sorted wire values. ---\n  const hashGroups = new Map<string, Enum[]>();\n  for (const enumDef of enums) {\n    if (enumDef.values.length === 0) continue;\n    const hash = enumWireHash(enumDef);\n    if (!hashGroups.has(hash)) hashGroups.set(hash, []);\n    hashGroups.get(hash)!.push(enumDef);\n  }\n\n  // Within each group, pick the shortest className as canonical.\n  const aliasOf = new Map<string, string>(); // enum name → canonical enum name\n  const sharedSortEmitters = new Set<string>();\n  for (const [, group] of hashGroups) {\n    if (group.length <= 1) {\n      if (group.length === 1 && isSharedSortOrderEnum(group[0])) {\n        enumCanonicalMap.set(group[0].name, 'SortOrder');\n        sharedSortEmitters.add(group[0].name);\n      }\n      continue;\n    }\n    if (group.every(isSharedSortOrderEnum)) {\n      const [canonical, ...rest] = [...group].sort((a, b) => a.name.localeCompare(b.name));\n      sharedSortEmitters.add(canonical.name);\n      for (const enumDef of [canonical, ...rest]) enumCanonicalMap.set(enumDef.name, 'SortOrder');\n      continue;\n    }\n    const sorted = [...group].sort(\n      (a, b) =>\n        className(a.name).length - className(b.name).length || className(a.name).localeCompare(className(b.name)),\n    );\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      aliasOf.set(sorted[i].name, canonical.name);\n      enumCanonicalMap.set(sorted[i].name, canonical.name);\n    }\n  }\n\n  const files: GeneratedFile[] = [];\n\n  for (const enumDef of enums) {\n    if (enumDef.values.length === 0) continue;\n\n    const typeName = canonicalEnumTypeName(enumDef);\n\n    // FR-1.4: write per-enum FILES only when in scope. Each enum is its own\n    // `.kt` file (no barrel), so an out-of-scope enum left untouched on disk\n    // stays importable.\n    const enumInScope = isEnumInScope(enumDef.name, ctx);\n\n    // Non-canonical enum: emit a typealias instead of a full enum class.\n    const sharedSortEmitter = sharedSortEmitters.has(enumDef.name);\n    const canonicalName = sharedSortEmitter\n      ? undefined\n      : (aliasOf.get(enumDef.name) ?? enumCanonicalMap.get(enumDef.name));\n    if (canonicalName) {\n      const canonicalType = className(canonicalName);\n      // Skip when different IR names collapse to the same output name\n      if (typeName === canonicalType) continue;\n      const aliasLine = `typealias ${typeName} = ${canonicalType}`;\n      // ktlint enforces a 140-char max line length. When the typealias\n      // exceeds that, add a @file:Suppress to avoid an unfixable violation.\n      const suppressLine = aliasLine.length > 140 ? `@file:Suppress(\"ktlint:standard:max-line-length\")\\n\\n` : '';\n      const aliasContent = [\n        `${suppressLine}package ${ENUMS_PACKAGE}`,\n        '',\n        `/** Alias for [${canonicalType}]. */`,\n        aliasLine,\n        '',\n      ].join('\\n');\n      if (enumInScope) {\n        files.push({\n          path: `${KOTLIN_SRC_PREFIX}${ENUMS_DIR}/${typeName}.kt`,\n          content: aliasContent,\n          overwriteExisting: true,\n        });\n      }\n      continue;\n    }\n\n    const lines: string[] = [];\n    lines.push(`package ${ENUMS_PACKAGE}`);\n    lines.push('');\n    lines.push('import com.fasterxml.jackson.annotation.JsonEnumDefaultValue');\n    lines.push('import com.fasterxml.jackson.annotation.JsonValue');\n    lines.push('');\n    // Replace the tautological \"Foo enum.\" docstring with a slightly more\n    // informative summary. `Unknown` is emitted as the forward-compatibility\n    // sentinel for values the server introduces after this SDK was built.\n    lines.push(`/** Enumeration of valid ${typeName} values returned or accepted by the API. */`);\n    lines.push(`enum class ${typeName}(`);\n    lines.push('  /** The wire value sent to and received from the API. */');\n    lines.push('  @JsonValue val value: String');\n    lines.push(') {');\n    // `@JsonEnumDefaultValue` makes Jackson's\n    // READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE feature map unrecognized\n    // wire values onto `Unknown` instead of throwing — required for forward\n    // compatibility when the API introduces new variants.\n    lines.push('  @JsonEnumDefaultValue');\n    lines.push(`  Unknown(${ktStringLiteral('unknown')}),`);\n\n    const seenNames = new Set<string>(['Unknown']);\n    const seenWire = new Set<string>(['unknown']);\n    const members: string[] = [];\n\n    for (const v of enumDef.values) {\n      const wire = String(v.value);\n      if (seenWire.has(wire)) continue;\n      seenWire.add(wire);\n\n      let memberName = className(wire);\n      if (!memberName || /^[0-9]/.test(memberName)) memberName = `Value${memberName || wire}`;\n      if (memberName === typeName || seenNames.has(memberName)) {\n        let suffix = 2;\n        while (seenNames.has(`${memberName}${suffix}`)) suffix += 1;\n        memberName = `${memberName}${suffix}`;\n      }\n      seenNames.add(memberName);\n\n      if (v.description?.trim()) {\n        members.push(`  /** ${escapeKdoc(v.description.split('\\n')[0].trim())} */`);\n      }\n      if (v.deprecated) {\n        members.push('  @Deprecated(\"Deprecated enum value\")');\n      }\n      members.push(`  ${memberName}(${ktStringLiteral(wire)})`);\n    }\n\n    // Track whether we are currently in a doc block leading up to the next\n    // enum value declaration. When the upcoming case has KDoc, insert a blank\n    // line before the doc comment for visual separation (skip for the very\n    // first case so we don't open the block with a blank).\n    let firstValueEmitted = false;\n    for (let i = 0; i < members.length; i++) {\n      const isLast = i === members.length - 1;\n      const line = members[i];\n      const trimmedStart = line.trimStart();\n      const isDocStart = trimmedStart.startsWith('/**');\n      const isAnnotation = trimmedStart.startsWith('@');\n      if (isDocStart && firstValueEmitted) {\n        lines.push('');\n      }\n      if (isDocStart || isAnnotation) {\n        lines.push(line);\n        continue;\n      }\n      lines.push(isLast ? line : `${line},`);\n      firstValueEmitted = true;\n    }\n\n    lines.push('}');\n    lines.push('');\n\n    if (enumInScope) {\n      files.push({\n        path: `${KOTLIN_SRC_PREFIX}${ENUMS_DIR}/${typeName}.kt`,\n        content: lines.join('\\n'),\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n\nfunction canonicalEnumTypeName(enumDef: Enum): string {\n  return isSharedSortOrderEnum(enumDef) ? 'SortOrder' : className(enumDef.name);\n}\n\nfunction isSharedSortOrderEnum(enumDef: Enum): boolean {\n  const wireValues = [...new Set(enumDef.values.map((value) => String(value.value).toLowerCase()))].sort();\n  return wireValues.length === 2 && wireValues[0] === 'asc' && wireValues[1] === 'desc';\n}\n\n/** Hash an enum by its sorted wire values so identical enums collide. */\nfunction enumWireHash(enumDef: Enum): string {\n  return [...enumDef.values]\n    .map((v) => String(v.value))\n    .sort()\n    .join('|');\n}\n\nfunction escapeKdoc(s: string): string {\n  return s.replace(/\\*\\//g, '*\\u200b/');\n}\n","import type { TypeRef, PrimitiveType, UnionType } from '@workos/oagen';\nimport { mapTypeRef as irMapTypeRef } from '@workos/oagen';\nimport { className } from './naming.js';\nimport { enumCanonicalMap } from './enums.js';\n\n/** Resolve an enum name through the canonical map (identity when no alias). */\nfunction resolveEnumName(name: string): string {\n  return className(enumCanonicalMap.get(name) ?? name);\n}\n\n/**\n * Map an IR TypeRef to a non-nullable Kotlin type expression.\n *\n * Kotlin's type system marks nullability at use-sites (`T?`). Optional fields\n * on generated models append `?` to the output of this function.\n */\nexport function mapTypeRef(ref: TypeRef): string {\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (_ref, items) => `List<${items}>`,\n    model: (r) => className(r.name),\n    enum: (r) => resolveEnumName(r.name),\n    union: (r, variants) => joinUnionVariants(r, variants),\n    nullable: (_ref, inner) => (inner.endsWith('?') ? inner : `${inner}?`),\n    literal: (r) => {\n      if (r.value === null) return 'Any?';\n      if (typeof r.value === 'string') return 'String';\n      if (typeof r.value === 'number') return Number.isInteger(r.value) ? 'Long' : 'Double';\n      if (typeof r.value === 'boolean') return 'Boolean';\n      return 'Any';\n    },\n    map: (_ref, value) => `Map<String, ${value}>`,\n  });\n}\n\n/**\n * Map an IR TypeRef to a nullable Kotlin type expression (always appends `?`).\n * Useful for optional fields on models / request options.\n */\nexport function mapTypeRefOptional(ref: TypeRef): string {\n  const baseType = mapTypeRef(ref);\n  return baseType.endsWith('?') ? baseType : `${baseType}?`;\n}\n\n/**\n * Is the given IR TypeRef a primitive value? Useful when deciding whether a\n * nullable field needs an explicit `= null` default.\n */\nexport function isValueTypeRef(ref: TypeRef): boolean {\n  if (ref.kind === 'enum') return true;\n  if (ref.kind === 'primitive') {\n    if (ref.format === 'date-time') return true;\n    switch (ref.type) {\n      case 'integer':\n      case 'number':\n      case 'boolean':\n        return true;\n      default:\n        return false;\n    }\n  }\n  return false;\n}\n\nfunction mapPrimitive(ref: PrimitiveType): string {\n  if (ref.format === 'binary') return 'ByteArray';\n  if (ref.format === 'int32') return 'Int';\n  if (ref.format === 'int64') return 'Long';\n  if (ref.format === 'date-time') return 'OffsetDateTime';\n  switch (ref.type) {\n    case 'string':\n      return 'String';\n    case 'integer':\n      return 'Long';\n    case 'number':\n      return 'Double';\n    case 'boolean':\n      return 'Boolean';\n    case 'unknown':\n      return 'Any';\n  }\n}\n\n/**\n * Track discriminated unions so the model generator can emit the appropriate\n * Jackson `@JsonTypeInfo` / `@JsonSubTypes` annotations on the sealed parent.\n */\nexport const discriminatedUnions = new Map<\n  string,\n  { property: string; mapping: Record<string, string>; variantTypes: string[] }\n>();\n\nfunction joinUnionVariants(ref: UnionType, variants: string[]): string {\n  if (ref.compositionKind === 'allOf') {\n    return variants[0] ?? 'Any';\n  }\n  const unique = [...new Set(variants)];\n\n  // Register discriminated unions BEFORE the single-unique collapse so we\n  // don't lose the dispatcher when every variant aliases to the same canonical\n  // type. The base type used at the call site is the IR variant name, which\n  // matches how the dispatcher infrastructure looks up registered unions.\n  if (ref.discriminator && ref.discriminator.mapping) {\n    const irVariantNames = ref.variants\n      .filter((v) => v.kind === 'model')\n      .map((v) => (v.kind === 'model' ? v.name : ''))\n      .filter(Boolean);\n    const baseName = irVariantNames[0] ?? unique[0];\n    discriminatedUnions.set(baseName, {\n      property: ref.discriminator.property,\n      mapping: ref.discriminator.mapping,\n      variantTypes: unique,\n    });\n    // Use the base sealed type; Jackson @JsonTypeInfo handles variant selection.\n    return baseName;\n  }\n\n  if (unique.length === 1) return unique[0];\n\n  // Non-discriminated unions fall back to the Kotlin top type. A generic\n  // AnyOf<> is planned for a future phase if emitter tests prove it necessary.\n  return 'Any';\n}\n\n/** Kotlin imports implied by a given type expression. Caller collects into a set. */\nexport function implicitImportsFor(kotlinType: string): string[] {\n  const imports: string[] = [];\n  if (/\\bOffsetDateTime\\b/.test(kotlinType)) {\n    imports.push('java.time.OffsetDateTime');\n  }\n  return imports;\n}\n","import type { Model, EmitterContext, GeneratedFile, TypeRef, Field } from '@workos/oagen';\nimport { mapTypeRef, discriminatedUnions } from './type-map.js';\nimport { className, domainPropertyName, ktStringLiteral, humanize } from './naming.js';\nimport { enumCanonicalMap } from './enums.js';\nimport {\n  isListWrapperModel,\n  isListMetadataModel,\n  collectNonPaginatedResponseModelNames,\n  collectReferencedListMetadataModels,\n} from '../shared/model-utils.js';\nimport { isModelInScope, fileExistsAfterRun } from '../shared/resolved-ops.js';\n\nconst KOTLIN_SRC_PREFIX = 'src/main/kotlin/';\nconst MODELS_PACKAGE = 'com.workos.models';\nconst MODELS_DIR = 'com/workos/models';\n\n/**\n * The relative path (target-root-relative, matching the prior manifest) of the\n * per-model `.kt` FILE the emitter writes for a model. The aggregate gate\n * ({@link fileExistsAfterRun}) checks this exact path against the freshly-emitted\n * in-scope set and the prior manifest. Must stay in sync with the path used in\n * {@link emitDataClass} / {@link emitSealedUnion} / the typealias branch.\n */\nfunction modelFilePath(modelName: string): string {\n  return `${KOTLIN_SRC_PREFIX}${MODELS_DIR}/${className(modelName)}.kt`;\n}\n\n/**\n * Some specs leave string fields without `format: date-time` even though the\n * description (or the example) makes clear they carry an ISO-8601 timestamp.\n * Detect that here so we can promote the type to `OffsetDateTime` in the\n * Kotlin output.\n */\nconst ISO_8601_DESCRIPTION_RE = /\\bISO[-_ ]?8601\\b/i;\n\nfunction looksLikeIso8601String(description: string | undefined): boolean {\n  if (!description) return false;\n  return ISO_8601_DESCRIPTION_RE.test(description);\n}\n\nfunction promoteIso8601TypeRef(type: TypeRef, description: string | undefined): TypeRef {\n  if (!looksLikeIso8601String(description)) return type;\n  const promote = (t: TypeRef): TypeRef => {\n    if (t.kind === 'primitive' && t.type === 'string' && !t.format) {\n      return { kind: 'primitive', type: 'string', format: 'date-time' };\n    }\n    if (t.kind === 'nullable') return { kind: 'nullable', inner: promote(t.inner) };\n    return t;\n  };\n  return promote(type);\n}\n\nfunction promoteFieldType(f: Field): Field {\n  const promoted = promoteIso8601TypeRef(f.type, f.description);\n  return promoted === f.type ? f : { ...f, type: promoted };\n}\n\n/**\n * Generate Kotlin `data class` models. Each model becomes a separate `.kt`\n * file under `com.workos.models`. Discriminated unions emit a sealed class\n * with Jackson `@JsonTypeInfo` / `@JsonSubTypes` annotations so the base type\n * picks the right variant at deserialization time.\n *\n * List wrappers (`{ data, list_metadata }`) and the shared `ListMetadata`\n * model are skipped — the hand-maintained runtime provides [Page]/[ListMetadata].\n */\nexport function generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n  if (models.length === 0) return [];\n\n  // First pass: call mapTypeRef on every model field so discriminator info is\n  // registered before we start emitting parents.\n  for (const model of models) {\n    for (const field of model.fields) mapTypeRef(field.type);\n  }\n\n  const files: GeneratedFile[] = [];\n\n  // Wrappers referenced as a non-paginated response (e.g. `VersionListResponse`\n  // for `GET /vault/v1/kv/{id}/versions`) must still be emitted — the resource\n  // code references them by name and pagination iterators don't unwrap them.\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(ctx.spec.services);\n  const skipAsListWrapper = (m: Model): boolean => isListWrapperModel(m) && !nonPaginatedRefs.has(m.name);\n  // A `ListMetadata`-shape model referenced by a surviving non-paginated\n  // wrapper (e.g. vault's `VersionListResponse`) must still emit a data class\n  // — otherwise the wrapper's class references a type that was never declared.\n  const listMetadataNeeded = collectReferencedListMetadataModels(models, nonPaginatedRefs);\n  const skipAsListMetadata = (m: Model): boolean => isListMetadataModel(m) && !listMetadataNeeded.has(m.name);\n\n  // Deduplication: identical structures become typealiases.\n  // Pass 1: hash without nested-alias resolution.\n  modelAliasMap = null;\n  const hashGroupsPass1 = new Map<string, string[]>();\n  for (const model of models) {\n    if (skipAsListWrapper(model) || skipAsListMetadata(model)) continue;\n    if (model.fields.length === 0 && discriminatedUnions.has(className(model.name))) continue;\n    const hash = structuralHash(model);\n    if (!hashGroupsPass1.has(hash)) hashGroupsPass1.set(hash, []);\n    hashGroupsPass1.get(hash)!.push(model.name);\n  }\n\n  const aliasOf = new Map<string, string>();\n  for (const [hash, names] of hashGroupsPass1) {\n    if (names.length <= 1 || hash === '') continue;\n    const sorted = [...names].sort(preferShorterCanonical);\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      if (hasRequestSuffix(sorted[i]) !== hasRequestSuffix(canonical)) continue;\n      aliasOf.set(sorted[i], canonical);\n    }\n  }\n\n  // Pass 2: re-hash with the alias map so models whose only difference was\n  // referencing aliased vs canonical nested types now collide.\n  modelAliasMap = aliasOf;\n  const hashGroupsPass2 = new Map<string, string[]>();\n  for (const model of models) {\n    if (skipAsListWrapper(model) || skipAsListMetadata(model)) continue;\n    if (model.fields.length === 0 && discriminatedUnions.has(className(model.name))) continue;\n    if (aliasOf.has(model.name)) continue; // already aliased in pass 1\n    const hash = structuralHash(model);\n    if (!hashGroupsPass2.has(hash)) hashGroupsPass2.set(hash, []);\n    hashGroupsPass2.get(hash)!.push(model.name);\n  }\n  for (const [hash, names] of hashGroupsPass2) {\n    if (names.length <= 1 || hash === '') continue;\n    const sorted = [...names].sort(preferShorterCanonical);\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) {\n      if (aliasOf.has(sorted[i])) continue;\n      if (hasRequestSuffix(sorted[i]) !== hasRequestSuffix(canonical)) continue;\n      aliasOf.set(sorted[i], canonical);\n    }\n  }\n\n  for (const model of models) {\n    if (skipAsListWrapper(model) || skipAsListMetadata(model)) continue;\n    const typeName = className(model.name);\n    // FR-1.4: write per-model FILES only when in scope. Each model is its own\n    // `.kt` file (no barrel), so an out-of-scope model left untouched on disk\n    // stays importable. The WorkOSEvent sealed interface below is an aggregate\n    // built from many event models, so it is NOT gated.\n    const modelInScope = isModelInScope(model.name, ctx);\n\n    // Parent of a discriminated union: emit a sealed class.\n    if (model.fields.length === 0 && discriminatedUnions.has(typeName)) {\n      if (modelInScope) {\n        files.push(emitSealedUnion(typeName, discriminatedUnions.get(typeName)!, ctx));\n      }\n      continue;\n    }\n\n    const canonical = aliasOf.get(model.name);\n    if (canonical) {\n      const canonicalType = className(canonical);\n      // Skip when different IR names collapse to the same output name\n      if (typeName === canonicalType) continue;\n      const aliasContent = [\n        `package ${MODELS_PACKAGE}`,\n        '',\n        `/** Alias for [${canonicalType}]. */`,\n        `typealias ${typeName} = ${canonicalType}`,\n        '',\n      ].join('\\n');\n      if (modelInScope) {\n        files.push({\n          path: `${KOTLIN_SRC_PREFIX}${MODELS_DIR}/${typeName}.kt`,\n          content: aliasContent,\n          overwriteExisting: true,\n        });\n      }\n      continue;\n    }\n\n    if (modelInScope) {\n      files.push(emitDataClass(model));\n    }\n  }\n\n  // Generate the sealed WorkOSEvent interface. Collect all event envelope\n  // models that have a literal `event` field and build the @JsonSubTypes\n  // mapping so Jackson can deserialize directly to the correct concrete type.\n  //\n  // This is an AGGREGATE: it enumerates many event models by name. A scoped\n  // (`--services`) run emits per-model `.kt` files only for in-scope models, so\n  // listing a brand-new OUT-OF-SCOPE event model here would reference a\n  // `ModelName::class` whose file is never written → \"Unresolved reference\"\n  // (the WorkOSEvent.kt build break). Gate each entry so it appears only if its\n  // model file will EXIST on disk after the run = in-scope (emitted now) ∪\n  // already-on-disk (prior manifest; scoped runs never prune). Renamed/\n  // removed-but-on-disk models still present under the same name in the spec are\n  // retained; full runs include everything (gate is inert).\n  const eventMapping: Array<{ wireValue: string; modelName: string }> = [];\n  for (const model of models) {\n    if (skipAsListWrapper(model) || skipAsListMetadata(model)) continue;\n    if (aliasOf.has(model.name)) continue;\n    if (!isEventEnvelopeModel(model)) continue;\n    if (!fileExistsAfterRun(modelFilePath(model.name), isModelInScope(model.name, ctx), ctx)) continue;\n    const eventField = model.fields.find((f) => f.name === 'event');\n    if (eventField && eventField.type.kind === 'literal' && typeof eventField.type.value === 'string') {\n      eventMapping.push({ wireValue: eventField.type.value, modelName: model.name });\n    }\n  }\n  if (eventMapping.length > 0) {\n    files.push(emitWorkOSEvent(eventMapping));\n  }\n\n  return files;\n}\n\n/**\n * Detect whether a model follows the webhook event envelope pattern:\n * has required `id`, `event`, `created_at` fields plus a `data` field.\n */\nfunction isEventEnvelopeModel(model: Model): boolean {\n  const fieldNames = new Set(model.fields.map((f) => f.name));\n  return fieldNames.has('id') && fieldNames.has('event') && fieldNames.has('created_at') && fieldNames.has('data');\n}\n\nfunction emitDataClass(model: Model): GeneratedFile {\n  const typeName = className(model.name);\n  const imports = collectImports(model.fields);\n  const implementsEvent = isEventEnvelopeModel(model);\n  // WorkOSEvent sealed interface is generated in the same package — no import needed.\n  const lines: string[] = [];\n  lines.push(`package ${MODELS_PACKAGE}`);\n  lines.push('');\n  for (const imp of [...imports].sort()) lines.push(`import ${imp}`);\n  if (imports.size > 0) lines.push('');\n\n  appendKdoc(lines, model.description ?? `${typeName} model.`, 0);\n\n  if (model.fields.length === 0) {\n    // Kotlin data classes require at least one primary constructor param.\n    // Use a regular empty class instead.\n    lines.push(`class ${typeName}`);\n    lines.push('');\n  } else {\n    const implClause = implementsEvent ? ' : WorkOSEvent' : '';\n    lines.push(`data class ${typeName}(`);\n\n    // Emit non-defaulted params first, then defaulted — Kotlin requires\n    // non-defaulted params before defaulted ones. Literal-typed fields always\n    // receive a default, so they sort after plain required fields.\n    const hasDefault = (f: Field): boolean => !f.required || f.type.kind === 'literal';\n    const ordered = [...model.fields].sort((a, b) => {\n      const aDef = hasDefault(a);\n      const bDef = hasDefault(b);\n      if (aDef === bDef) return 0;\n      return aDef ? 1 : -1;\n    });\n    // When implementing WorkOSEvent, matching fields need `override`.\n    const overrideFields = implementsEvent ? new Set(['id', 'event', 'createdAt']) : new Set<string>();\n    const rendered = renderFields(ordered, overrideFields);\n    for (let i = 0; i < rendered.length; i++) {\n      const suffix = i === rendered.length - 1 ? '' : ',';\n      lines.push(`${rendered[i]}${suffix}`);\n      // Visually separate properties: KDoc + annotations for the next field\n      // get their own paragraph. Kotlin requires the comma to come *before*\n      // the blank line; we already appended it above.\n      if (i < rendered.length - 1) {\n        lines.push('');\n      }\n    }\n\n    lines.push(`)${implClause}`);\n    lines.push('');\n  }\n\n  return {\n    path: `${KOTLIN_SRC_PREFIX}${MODELS_DIR}/${typeName}.kt`,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\nfunction emitSealedUnion(\n  typeName: string,\n  disc: { property: string; mapping: Record<string, string>; variantTypes: string[] },\n  ctx: EmitterContext,\n): GeneratedFile {\n  const lines: string[] = [];\n  lines.push(`package ${MODELS_PACKAGE}`);\n  lines.push('');\n  lines.push('import com.fasterxml.jackson.annotation.JsonSubTypes');\n  lines.push('import com.fasterxml.jackson.annotation.JsonTypeInfo');\n  lines.push('');\n  // AGGREGATE gate: @JsonSubTypes enumerates each variant model by name\n  // (`VariantClass::class`). The sealed parent itself is in scope here, but a\n  // scoped run may not emit a brand-new OUT-OF-SCOPE variant's `.kt` file — so\n  // only list variants whose model file will exist on disk after the run\n  // (in-scope ∪ prior manifest). A full run keeps every variant (gate is inert).\n  const entries = Object.entries(disc.mapping).filter(([, modelName]) =>\n    fileExistsAfterRun(modelFilePath(modelName), isModelInScope(modelName, ctx), ctx),\n  );\n  // KDoc with worked Kotlin + Java consumption examples. These unions are\n  // returned by Jackson; callers branch on the concrete subtype to access\n  // variant-specific data. Use a surviving variant so the example never names a\n  // class whose file the scoped run skipped.\n  const exampleVariantType = entries.length > 0 ? className(entries[0][1]) : null;\n  lines.push('/**');\n  lines.push(` * Discriminated union over ${typeName} variants. Selected by \\`${disc.property}\\`.`);\n  if (exampleVariantType) {\n    lines.push(' *');\n    lines.push(' * Usage from Kotlin:');\n    lines.push(' * ```kotlin');\n    lines.push(` * when (val v: ${typeName} = receivedFromApi()) {`);\n    lines.push(` *   is ${exampleVariantType} -> handle(v)`);\n    lines.push(' *   else -> handleOther(v)');\n    lines.push(' * }');\n    lines.push(' * ```');\n    lines.push(' *');\n    lines.push(' * Usage from Java:');\n    lines.push(' * ```java');\n    lines.push(` * ${typeName} v = receivedFromApi();`);\n    lines.push(` * if (v instanceof ${exampleVariantType}) {`);\n    lines.push(` *     handle((${exampleVariantType}) v);`);\n    lines.push(' * }');\n    lines.push(' * ```');\n  }\n  lines.push(' */');\n  lines.push('@JsonTypeInfo(');\n  lines.push('  use = JsonTypeInfo.Id.NAME,');\n  lines.push('  include = JsonTypeInfo.As.EXISTING_PROPERTY,');\n  lines.push(`  property = ${ktStringLiteral(disc.property)},`);\n  lines.push('  visible = true');\n  lines.push(')');\n  lines.push('@JsonSubTypes(');\n  for (let i = 0; i < entries.length; i++) {\n    const [wireValue, modelName] = entries[i];\n    const variantType = className(modelName);\n    const suffix = i === entries.length - 1 ? '' : ',';\n    lines.push(`  JsonSubTypes.Type(value = ${variantType}::class, name = ${ktStringLiteral(wireValue)})${suffix}`);\n  }\n  lines.push(')');\n  lines.push(`sealed class ${typeName}`);\n  lines.push('');\n\n  return {\n    path: `${KOTLIN_SRC_PREFIX}${MODELS_DIR}/${typeName}.kt`,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\n/**\n * Emit the sealed `WorkOSEvent` interface with Jackson discriminated\n * deserialization. Each concrete event model (UserCreated, DsyncUserUpdated,\n * etc.) already extends this interface. The `@JsonSubTypes` annotation lets\n * Jackson pick the right subclass when deserializing JSON with an `event`\n * discriminator field. `EventSchema` is the fallback for unknown event types.\n */\nfunction emitWorkOSEvent(eventMapping: Array<{ wireValue: string; modelName: string }>): GeneratedFile {\n  const lines: string[] = [];\n  lines.push(`package ${MODELS_PACKAGE}`);\n  lines.push('');\n  lines.push('import com.fasterxml.jackson.annotation.JsonSubTypes');\n  lines.push('import com.fasterxml.jackson.annotation.JsonTypeInfo');\n  lines.push('import java.time.OffsetDateTime');\n  lines.push('');\n\n  lines.push('/**');\n  lines.push(' * Sealed interface for all webhook/event envelope models.');\n  lines.push(' *');\n  lines.push(' * Jackson deserializes incoming event JSON to the correct concrete type');\n  lines.push(' * based on the `event` discriminator field. Unknown event types fall back');\n  lines.push(' * to [EventSchema] with untyped `data: Map<String, Any>`.');\n  lines.push(' *');\n  lines.push(' * ```kotlin');\n  lines.push(' * val event: WorkOSEvent = objectMapper.readValue(json, WorkOSEvent::class.java)');\n  lines.push(' * when (event) {');\n  lines.push(' *   is UserCreated -> println(\"User created: ${event.data.id}\")');\n  lines.push(' *   is EventSchema -> println(\"Unknown event: ${event.event}\")');\n  lines.push(' * }');\n  lines.push(' * ```');\n  lines.push(' */');\n\n  lines.push('@JsonTypeInfo(');\n  lines.push('  use = JsonTypeInfo.Id.NAME,');\n  lines.push('  include = JsonTypeInfo.As.EXISTING_PROPERTY,');\n  lines.push('  property = \"event\",');\n  lines.push('  visible = true,');\n  lines.push('  defaultImpl = EventSchema::class');\n  lines.push(')');\n  lines.push('@JsonSubTypes(');\n  // Sort entries for stable output\n  const sorted = [...eventMapping].sort((a, b) => a.wireValue.localeCompare(b.wireValue));\n  for (let i = 0; i < sorted.length; i++) {\n    const { wireValue, modelName } = sorted[i];\n    const typeName = className(modelName);\n    const suffix = i === sorted.length - 1 ? '' : ',';\n    lines.push(`  JsonSubTypes.Type(value = ${typeName}::class, name = ${ktStringLiteral(wireValue)})${suffix}`);\n  }\n  lines.push(')');\n  lines.push('sealed interface WorkOSEvent {');\n  lines.push('  /** Unique identifier for this event. */');\n  lines.push('  val id: String');\n  lines.push('');\n  lines.push('  /** The event type identifier. */');\n  lines.push('  val event: String');\n  lines.push('');\n  lines.push('  /** Timestamp when the event was created. */');\n  lines.push('  val createdAt: OffsetDateTime');\n  lines.push('}');\n  lines.push('');\n\n  return {\n    path: `${KOTLIN_SRC_PREFIX}${MODELS_DIR}/WorkOSEvent.kt`,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\nfunction renderFields(fields: Field[], overrideFields: Set<string> = new Set()): string[] {\n  const seen = new Set<string>();\n  const lines: string[] = [];\n\n  for (const rawField of fields) {\n    const field = promoteFieldType(rawField);\n    // DOMAIN identifier: the data class property name. Honors a `domainName`\n    // override (e.g. connection_type -> type); the `@JsonProperty(...)` wire\n    // key below still derives from `field.name`.\n    const kotlinName = domainPropertyName(field);\n    if (seen.has(kotlinName)) continue;\n    seen.add(kotlinName);\n\n    const baseType = mapTypeRef(field.type);\n    let kotlinType: string;\n    let defaultExpr: string | null = null;\n\n    // Const literal fields: emit a hardcoded default matching the literal\n    // value so callers don't have to pass it — but only when the field is\n    // required. Optional literal fields must default to null so that absent\n    // keys round-trip correctly.\n    const literalDefault = literalDefaultExpr(field.type);\n\n    if (literalDefault !== null && field.required) {\n      kotlinType = baseType;\n      defaultExpr = literalDefault;\n    } else if (!field.required) {\n      kotlinType = baseType.endsWith('?') ? baseType : `${baseType}?`;\n      defaultExpr = 'null';\n    } else if (baseType.endsWith('?')) {\n      // Required field whose underlying type is already nullable.\n      kotlinType = baseType;\n    } else {\n      kotlinType = baseType;\n    }\n\n    const isOverride = overrideFields.has(kotlinName);\n    const annotations: string[] = [];\n    // Omit @JvmField so Kotlin generates proper getter methods (getId(),\n    // isEmailVerified(), etc.) for Java callers — matching the accessor\n    // convention used by Stripe, AWS SDK v2, and Twilio.\n    annotations.push(`@JsonProperty(${ktStringLiteral(field.name)})`);\n    if (field.deprecated) annotations.push(buildDeprecatedAnnotation(field.description));\n\n    const paramParts: string[] = [];\n    if (field.description?.trim()) {\n      const line = field.description.split('\\n').find((l) => l.trim()) ?? '';\n      lines.push(`  /** ${escapeKdoc(line.trim())} */`);\n    } else if (literalDefault !== null) {\n      lines.push(`  /** Always \\`${literalDefault}\\`. */`);\n    } else {\n      lines.push(`  /** The ${humanize(field.name)}. */`);\n    }\n    for (const anno of annotations) lines.push(`  ${anno}`);\n\n    const overridePrefix = isOverride ? 'override ' : '';\n    const rendered = `  ${overridePrefix}val ${kotlinName}: ${kotlinType}`;\n    paramParts.push(rendered);\n    if (defaultExpr !== null) paramParts[0] = `${paramParts[0]} = ${defaultExpr}`;\n    lines.push(paramParts[0]);\n  }\n  // Collapse annotation + val pairs into a list where each contiguous block\n  // becomes one field entry, preserving order.\n  return collapseFieldEntries(lines);\n}\n\nfunction collapseFieldEntries(rawLines: string[]): string[] {\n  // `rawLines` intermixes kdoc comments, annotations, and `val` declarations.\n  // Group them so each field is a single multi-line entry, so the caller can\n  // append a trailing comma at the right spot.\n  const entries: string[] = [];\n  let current: string[] = [];\n  for (const line of rawLines) {\n    const trimmed = line.trimStart();\n    const isDeclaration = trimmed.startsWith('val ') || trimmed.startsWith('override val ');\n    current.push(line);\n    if (isDeclaration) {\n      entries.push(current.join('\\n'));\n      current = [];\n    }\n  }\n  if (current.length > 0) entries.push(current.join('\\n'));\n  return entries;\n}\n\n/**\n * Pull the most useful free-form deprecation hint out of a field description\n * and lift it into the `@Deprecated(...)` message argument. Most WorkOS\n * deprecations are written as a description that begins with \"Deprecated\"\n * (e.g. \"Deprecated. Use `domain_data` instead.\"). When the description\n * doesn't carry a hint we fall back to a short, self-explanatory message\n * rather than the generic \"Deprecated field\" placeholder.\n */\nfunction deprecationMessageFromDescription(description: string | undefined): string {\n  if (!description) return 'Deprecated.';\n  const firstLine = description\n    .split('\\n')\n    .map((l) => l.trim())\n    .find((l) => l.length > 0);\n  if (!firstLine) return 'Deprecated.';\n  // Trim trailing whitespace and collapse internal whitespace runs so the\n  // annotation argument stays on one line.\n  const collapsed = firstLine.replace(/\\s+/g, ' ').trim();\n  if (collapsed.length === 0) return 'Deprecated.';\n  // Only lift the description when it actually carries a deprecation hint\n  // (e.g. \"Deprecated. Use `domain_data` instead.\") — many fields keep their\n  // forward-looking description verbatim, which would be misleading inside\n  // an `@Deprecated(...)` argument.\n  if (/\\bdeprecat/i.test(collapsed)) return collapsed;\n  return 'Deprecated.';\n}\n\nfunction buildDeprecatedAnnotation(description: string | undefined): string {\n  const message = deprecationMessageFromDescription(description);\n  return `@Deprecated(${ktStringLiteral(message)})`;\n}\n\n/**\n * If the TypeRef is a literal (const) with a string, number, or boolean value,\n * return the Kotlin expression for that default. Otherwise return null.\n */\nfunction literalDefaultExpr(ref: TypeRef): string | null {\n  if (ref.kind !== 'literal' || ref.value === null) return null;\n  if (typeof ref.value === 'string') return ktStringLiteral(ref.value);\n  if (typeof ref.value === 'number') return Number.isInteger(ref.value) ? `${ref.value}L` : String(ref.value);\n  if (typeof ref.value === 'boolean') return ref.value ? 'true' : 'false';\n  return null;\n}\n\nfunction collectImports(fields: Field[]): Set<string> {\n  const imports = new Set<string>();\n  if (fields.length === 0) return imports;\n  imports.add('com.fasterxml.jackson.annotation.JsonProperty');\n  for (const rawField of fields) {\n    const field = promoteFieldType(rawField);\n    const mapped = mapTypeRef(field.type);\n    if (/\\bOffsetDateTime\\b/.test(mapped)) imports.add('java.time.OffsetDateTime');\n    for (const enumName of collectEnumNames(field.type)) {\n      // Resolve through the canonical map so imports point at the actual\n      // enum class, not an alias that may not have its own file.\n      const canonical = enumCanonicalMap.get(enumName) ?? enumName;\n      imports.add(`com.workos.types.${className(canonical)}`);\n    }\n  }\n  return imports;\n}\n\nfunction collectEnumNames(ref: TypeRef, acc: Set<string> = new Set()): Set<string> {\n  if (ref.kind === 'enum') acc.add(ref.name);\n  else if (ref.kind === 'array') collectEnumNames(ref.items, acc);\n  else if (ref.kind === 'map') collectEnumNames(ref.valueType, acc);\n  else if (ref.kind === 'nullable') collectEnumNames(ref.inner, acc);\n  else if (ref.kind === 'union') for (const v of ref.variants) collectEnumNames(v, acc);\n  return acc;\n}\n\nfunction appendKdoc(lines: string[], text: string, indent: number): void {\n  const pad = ' '.repeat(indent);\n  const firstLine = text.split('\\n').find((l) => l.trim()) ?? '';\n  lines.push(`${pad}/** ${escapeKdoc(firstLine.trim())} */`);\n}\n\nfunction escapeKdoc(s: string): string {\n  return s.replace(/\\*\\//g, '*\\u200b/');\n}\n\n// Re-exported so downstream emitters (resources, tests) can filter wrapper models.\nexport { isListWrapperModel, isListMetadataModel };\n\n// --- Canonical name selection ---\n\n/**\n * When picking which model name should be the concrete class (canonical) vs.\n * a typealias, prefer shorter names first (they tend to be the public-facing\n * names like `User`, `Role`), then fall back to alphabetical order for\n * stability. This avoids situations where `User = EmailChangeConfirmationUser`\n * or `SlimRole = AddRolePermission`.\n */\nfunction preferShorterCanonical(a: string, b: string): number {\n  const aName = className(a);\n  const bName = className(b);\n  if (aName.length !== bName.length) return aName.length - bName.length;\n  return aName.localeCompare(bName);\n}\n\n// --- Unsafe typealias guard ---\n\n/** Suffixes that indicate a request / mutation DTO. */\nconst REQUEST_SUFFIXES = /(?:Dto|Request|Create|Update|Add|Remove|Set)$/i;\n\n/**\n * Returns true when [name] looks like a request DTO based on its suffix.\n * Used to prevent aliasing request DTOs to response models that happen to\n * share the same field shapes today.\n */\nfunction hasRequestSuffix(name: string): boolean {\n  return REQUEST_SUFFIXES.test(className(name));\n}\n\n// --- Structural dedup ---\n\n/**\n * Resolve a model name through the alias map so that two models referencing\n * aliased nested types produce the same structural hash. Called after the\n * first alias pass to catch transitive matches.\n */\nlet modelAliasMap: Map<string, string> | null = null;\n\nfunction normalizeTypeForHash(ref: TypeRef): unknown {\n  if (ref.kind === 'enum') {\n    const vals = ref.values ? [...ref.values].sort() : [];\n    return { kind: 'enum', values: vals };\n  }\n  if (ref.kind === 'model') {\n    // Resolve through the alias map so `FooData` and `BarData` (aliased to\n    // FooData) produce the same hash when referenced as nested types.\n    const resolved = modelAliasMap?.get(ref.name) ?? ref.name;\n    return { kind: 'model', name: resolved };\n  }\n  if (ref.kind === 'nullable') return { kind: 'nullable', inner: normalizeTypeForHash(ref.inner) };\n  if (ref.kind === 'array') return { kind: 'array', items: normalizeTypeForHash(ref.items) };\n  if (ref.kind === 'union') return { kind: 'union', variants: ref.variants.map(normalizeTypeForHash) };\n  if (ref.kind === 'map') return { kind: 'map', valueType: normalizeTypeForHash(ref.valueType) };\n  return ref;\n}\n\nfunction structuralHash(model: Model): string {\n  return model.fields\n    .map((f) => `${f.name}:${JSON.stringify(normalizeTypeForHash(f.type))}:${f.required}`)\n    .sort()\n    .join('|');\n}\n","import { parsePathTemplate, hasPathParams } from '../shared/path-template.js';\nimport { ktLiteral, propertyName } from './naming.js';\n\n/**\n * The fully-qualified runtime helper that the generated code calls. Kotlin\n * doesn't ship a path-segment URL encoder out of the box (java.net.URLEncoder\n * is form-encoding — it encodes space as \"+\", which is wrong for path\n * segments). The runtime helper lives in workos-kotlin at\n * com.workos.common.http.encodePathSegment.\n */\nexport const KOTLIN_PATH_ENCODE_IMPORT = 'com.workos.common.http.encodePathSegment';\n\nexport interface KotlinPathExpression {\n  /** The Kotlin expression to splice in as the `path = ...` argument. */\n  expression: string;\n  /** Whether the caller must add `KOTLIN_PATH_ENCODE_IMPORT` to its import set. */\n  requiresEncodeImport: boolean;\n}\n\n/**\n * Build the Kotlin string-template that the SDK passes as the request path.\n *\n * Every {paramName} placeholder is wrapped in `encodePathSegment(...)` so a\n * caller-supplied id containing \"../\" cannot be normalized by the underlying\n * HTTP transport into a different endpoint of the WorkOS API while still\n * authenticated with the application's API key.\n *\n *   \"/orgs\"            → `\"orgs\"`\n *   \"/orgs/{id}\"       → `\"orgs/${encodePathSegment(id)}\"`\n *   \"/orgs/{id}/foo\"   → `\"orgs/${encodePathSegment(id)}/foo\"`\n */\nexport function buildKotlinPathExpression(rawPath: string): KotlinPathExpression {\n  const segments = parsePathTemplate(rawPath);\n  if (!hasPathParams(segments)) {\n    return { expression: ktLiteral(rawPath), requiresEncodeImport: false };\n  }\n\n  let body = '';\n  for (const seg of segments) {\n    if (seg.kind === 'literal') {\n      body += escapeKotlinStringLiteral(seg.value);\n    } else {\n      body += `\\${encodePathSegment(${propertyName(seg.name)})}`;\n    }\n  }\n  return { expression: `\"${body}\"`, requiresEncodeImport: true };\n}\n\nfunction escapeKotlinStringLiteral(literal: string): string {\n  return literal.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\$/g, '\\\\$');\n}\n","/**\n * Helpers for emitting `suspend` overloads alongside every generated\n * blocking SDK method. The suspend variant simply delegates to the blocking\n * implementation under `withContext(Dispatchers.IO)`, so callers can invoke\n * any operation from a coroutine context without blocking the calling\n * dispatcher.\n *\n * Naming: the suspend variant uses a `Suspend`-suffixed Kotlin source name\n * (e.g. `deleteEndpointSuspend`). This matters because Kotlin does not let\n * a `suspend` function and a non-`suspend` function with the same name and\n * identical value parameters coexist in the same scope — they are not\n * distinguishable at call sites, even with `@JvmName`. (`@JvmName` only\n * disambiguates JVM signatures, not Kotlin source names.) Naming the suspend\n * variant explicitly sidesteps the conflict and makes the choice between\n * blocking and suspending callable obvious at the call site. The matching\n * `@JvmName(\"...Suspend\")` is now technically redundant but kept for\n * explicit clarity in Java interop / tooling.\n */\n\nimport { escapeReserved } from './naming.js';\n\nexport interface SuspendParam {\n  /** Already-rendered \"name: Type\" or \"name: Type = default\" Kotlin declaration. */\n  decl: string;\n  /** Bare parameter name to forward to the blocking version. */\n  name: string;\n}\n\n/**\n * Emit a suspend overload that delegates to a blocking method.\n *\n * The emitted lines preserve the parameter declarations (including default\n * values) so callers can invoke the suspend variant with named arguments and\n * skip optional parameters, just as they do with the blocking version.\n *\n * The emitted suspend method is named `${methodName}Suspend` (a distinct\n * Kotlin source name from the blocking method) — see the file-level KDoc for\n * why this is required.\n */\nexport function emitSuspendVariant(opts: {\n  methodName: string;\n  params: SuspendParam[];\n  returnType: string;\n  deprecated?: boolean;\n}): string[] {\n  const { methodName, params, returnType, deprecated } = opts;\n  const suspendName = `${methodName}Suspend`;\n  const lines: string[] = [];\n\n  lines.push('  /**');\n  lines.push(`   * Coroutine-aware variant of [${escapeReserved(methodName)}]. Use this from`);\n  lines.push('   * a `suspend` function or coroutine scope.');\n  lines.push('   *');\n  lines.push(`   * Delegates to the blocking [${escapeReserved(methodName)}] under`);\n  lines.push('   * `withContext(Dispatchers.IO)`, so this is safe to call from any');\n  lines.push('   * coroutine dispatcher (including `Dispatchers.Main`).');\n  lines.push('   */');\n  if (deprecated) lines.push('  @Deprecated(\"Deprecated operation\")');\n  lines.push(`  @JvmName(${jvmNameLiteral(suspendName)})`);\n\n  const returnClause = returnType === 'Unit' ? '' : `: ${returnType}`;\n  const callArgs = params.map((p) => p.name).join(', ');\n\n  if (params.length === 0) {\n    lines.push(`  suspend fun ${escapeReserved(suspendName)}()${returnClause} = withContext(Dispatchers.IO) {`);\n    lines.push(`    ${escapeReserved(methodName)}()`);\n    lines.push('  }');\n    return lines;\n  }\n\n  if (params.length === 1) {\n    const single = params[0].decl.replace(/^\\s+/, '');\n    lines.push(\n      `  suspend fun ${escapeReserved(suspendName)}(${single})${returnClause} = withContext(Dispatchers.IO) {`,\n    );\n  } else {\n    lines.push(`  suspend fun ${escapeReserved(suspendName)}(`);\n    for (let i = 0; i < params.length; i++) {\n      const suffix = i === params.length - 1 ? '' : ',';\n      lines.push(`${params[i].decl}${suffix}`);\n    }\n    lines.push(`  )${returnClause} = withContext(Dispatchers.IO) {`);\n  }\n  lines.push(`    ${escapeReserved(methodName)}(${callArgs})`);\n  lines.push('  }');\n  return lines;\n}\n\n/**\n * Imports a service file needs to declare any suspend overloads.\n */\nexport const SUSPEND_IMPORTS: readonly string[] = ['kotlinx.coroutines.Dispatchers', 'kotlinx.coroutines.withContext'];\n\nfunction jvmNameLiteral(name: string): string {\n  return JSON.stringify(name);\n}\n","import type { EmitterContext, ResolvedOperation, ResolvedWrapper } from '@workos/oagen';\nimport {\n  className,\n  propertyName,\n  ktLiteral,\n  clientFieldExpression,\n  escapeReserved,\n  humanize,\n  maybeShortenEnumParamDescription,\n} from './naming.js';\nimport { mapTypeRef, mapTypeRefOptional } from './type-map.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { sortPathParamsByTemplateOrder } from './resources.js';\nimport { buildKotlinPathExpression } from './path-expression.js';\nimport { emitSuspendVariant, type SuspendParam } from './suspend.js';\n\n/**\n * Emit Kotlin wrapper methods for a union-split operation. Each wrapper\n * method takes only the fields it needs for its variant, fills in the\n * operation-level defaults and client-inferred values, and posts to the\n * underlying operation.\n *\n * Returns a list of lines (with leading indentation suitable for inclusion\n * inside the service class body).\n */\nexport function generateWrapperMethods(resolvedOp: ResolvedOperation, ctx: EmitterContext): string[] {\n  if (!resolvedOp.wrappers || resolvedOp.wrappers.length === 0) return [];\n\n  const out: string[] = [];\n  for (const wrapper of resolvedOp.wrappers) {\n    if (out.length > 0) out.push('');\n    for (const line of emitWrapperMethod(resolvedOp, wrapper, ctx)) out.push(line);\n  }\n  return out;\n}\n\nfunction emitWrapperMethod(resolvedOp: ResolvedOperation, wrapper: ResolvedWrapper, ctx: EmitterContext): string[] {\n  const op = resolvedOp.operation;\n  const method = propertyName(wrapper.name);\n  const resolvedParams = resolveWrapperParams(wrapper, ctx);\n  const responseClass = wrapper.responseModelName ? className(wrapper.responseModelName) : null;\n\n  const pathParams = sortPathParamsByTemplateOrder(op);\n\n  const lines: string[] = [];\n\n  // Build KDoc: operation description + a `@param` line for *every* parameter\n  // (Dokka does not flag missing @param blocks, so coverage has to be enforced\n  // at emit time) + `@return` when there's a response model. Spec-provided\n  // descriptions are preferred; the fallback is templated from the parameter\n  // name so the SDK still compiles cleanly under failOnWarning.\n  const kdocLines: string[] = [];\n  const opDesc = (op.description ?? '').trim();\n  const wrapperHumanName = method.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();\n  if (opDesc) {\n    kdocLines.push(opDesc.split('\\n')[0]);\n  } else {\n    kdocLines.push(`${wrapperHumanName.charAt(0).toUpperCase()}${wrapperHumanName.slice(1)}.`);\n  }\n  const paramDocs: string[] = [];\n  const pushParamDoc = (\n    kotlinName: string,\n    sourceName: string,\n    description: string | undefined,\n    type?: import('@workos/oagen').TypeRef,\n  ) => {\n    const firstLine =\n      description\n        ?.split('\\n')\n        .find((l) => l.trim())\n        ?.trim() ?? '';\n    const fallback = `the ${humanize(sourceName)} of the request.`;\n    let text = firstLine || fallback;\n    const shortened = maybeShortenEnumParamDescription(type, text);\n    if (shortened) text = shortened.description;\n    paramDocs.push(`@param ${kotlinName} ${escapeKdoc(text)}`);\n  };\n  for (const pp of pathParams) {\n    pushParamDoc(propertyName(pp.name), pp.name, pp.description, pp.type);\n  }\n  for (const rp of resolvedParams) {\n    pushParamDoc(propertyName(rp.paramName), rp.paramName, rp.field?.description, rp.field?.type);\n  }\n  // Trailing `requestOptions` parameter — stable canned phrasing.\n  pushParamDoc(\n    'requestOptions',\n    'request_options',\n    'per-request overrides (idempotency key, API key, headers, timeout)',\n  );\n  if (responseClass) {\n    paramDocs.push(`@return the ${responseClass}`);\n  }\n  lines.push('  /**');\n  for (const l of kdocLines) lines.push(`   * ${escapeKdoc(l)}`);\n  lines.push('   *');\n  for (const p of paramDocs) lines.push(`   * ${p}`);\n  lines.push('   */');\n\n  lines.push('  @JvmOverloads');\n\n  // Build the method parameter list: path params, wrapper params, requestOptions.\n  // `suspendParams` mirrors `params` but tracks the bare parameter name so the\n  // suspend overload (emitted at the end of this function) can forward each\n  // argument to the blocking implementation.\n  const params: string[] = [];\n  const suspendParams: SuspendParam[] = [];\n  for (const pp of pathParams) {\n    const decl = `    ${propertyName(pp.name)}: String`;\n    params.push(decl);\n    suspendParams.push({ decl, name: propertyName(pp.name) });\n  }\n  for (const rp of resolvedParams) {\n    const paramName = propertyName(rp.paramName);\n    const kotlinType = rp.field\n      ? rp.isOptional\n        ? mapTypeRefOptional(rp.field.type)\n        : mapTypeRef(rp.field.type)\n      : rp.isOptional\n        ? 'String?'\n        : 'String';\n    const trailer = rp.isOptional ? ' = null' : '';\n    const decl = `    ${paramName}: ${kotlinType}${trailer}`;\n    params.push(decl);\n    suspendParams.push({ decl, name: paramName });\n  }\n  params.push('    requestOptions: RequestOptions? = null');\n  suspendParams.push({ decl: '    requestOptions: RequestOptions? = null', name: 'requestOptions' });\n\n  const returnClause = responseClass ? `: ${responseClass}` : '';\n  if (params.length === 1) {\n    const single = params[0].replace(/^\\s+/, '');\n    lines.push(`  fun ${escapeReserved(method)}(${single})${returnClause} {`);\n  } else {\n    lines.push(`  fun ${escapeReserved(method)}(`);\n    for (let i = 0; i < params.length; i++) {\n      const suffix = i === params.length - 1 ? '' : ',';\n      lines.push(`${params[i]}${suffix}`);\n    }\n    lines.push(`  )${returnClause} {`);\n  }\n\n  // The /user_management/authenticate endpoint is union-split into one\n  // wrapper per grant_type. Every variant posts the same shape (caller\n  // params + grant_type + client_id + client_secret) to the same path with\n  // the same response model, so we route through a single `authenticate(...)`\n  // private helper instead of duplicating the request boilerplate per grant.\n  const inferred = wrapper.inferFromClient ?? [];\n  const usesStandardClientCreds = inferred.includes('client_id') && inferred.includes('client_secret');\n  if (\n    op.path === '/user_management/authenticate' &&\n    op.httpMethod.toUpperCase() === 'POST' &&\n    responseClass === 'AuthenticateResponse' &&\n    typeof wrapper.defaults?.grant_type === 'string' &&\n    usesStandardClientCreds\n  ) {\n    const grantType = wrapper.defaults.grant_type;\n    lines.push(`    return authenticate(`);\n    lines.push(`      grantType = ${ktLiteral(grantType)},`);\n    lines.push(`      requestOptions = requestOptions,`);\n    const entryLines = resolvedParams.map((rp) => {\n      const paramName = propertyName(rp.paramName);\n      return `      ${ktLiteral(rp.paramName)} to ${paramName}`;\n    });\n    for (let i = 0; i < entryLines.length; i++) {\n      const sep = i === entryLines.length - 1 ? '' : ',';\n      lines.push(`${entryLines[i]}${sep}`);\n    }\n    lines.push(`    )`);\n    lines.push('  }');\n    appendSuspendVariant(lines, method, suspendParams, responseClass ?? 'Unit');\n    return lines;\n  }\n\n  // Build body using bodyOf() — consistent with non-wrapper methods.\n  // bodyOf() automatically drops null optional values.\n  const bodyEntries: string[] = [];\n  for (const rp of resolvedParams) {\n    const paramName = propertyName(rp.paramName);\n    bodyEntries.push(`      ${ktLiteral(rp.paramName)} to ${paramName}`);\n  }\n  for (const [k, v] of Object.entries(wrapper.defaults ?? {})) {\n    bodyEntries.push(`      ${ktLiteral(k)} to ${ktLiteral(v)}`);\n  }\n  for (const k of wrapper.inferFromClient ?? []) {\n    bodyEntries.push(`      ${ktLiteral(k)} to workos.${clientFieldExpression(k)}`);\n  }\n  if (bodyEntries.length > 0) {\n    lines.push(`    val body =`);\n    lines.push(`      bodyOf(`);\n    for (let i = 0; i < bodyEntries.length; i++) {\n      const sep = i === bodyEntries.length - 1 ? '' : ',';\n      lines.push(`  ${bodyEntries[i]}${sep}`);\n    }\n    lines.push(`      )`);\n  } else {\n    lines.push(`    val body = linkedMapOf<String, Any?>()`);\n  }\n\n  const pathExpr = buildKotlinPathExpression(op.path).expression;\n  const httpMethod = op.httpMethod.toUpperCase();\n\n  lines.push(`    val config =`);\n  lines.push(`      RequestConfig(`);\n  lines.push(`        method = ${ktLiteral(httpMethod)},`);\n  lines.push(`        path = ${pathExpr},`);\n  lines.push(`        body = body,`);\n  if (op.requestBodyEncoding === 'form-urlencoded') {\n    // Some ops (SSO token, User Management authenticate) are form-encoded.\n    // Rewrite as formBody mapping string→string instead of JSON body.\n    // Fallback: leave body as JSON — the API accepts JSON for these too.\n  }\n  lines.push(`        requestOptions = requestOptions`);\n  lines.push(`      )`);\n\n  if (responseClass) {\n    lines.push(`    return workos.baseClient.request(config, ${responseClass}::class.java)`);\n  } else {\n    lines.push(`    workos.baseClient.requestVoid(config)`);\n  }\n\n  lines.push('  }');\n  appendSuspendVariant(lines, method, suspendParams, responseClass ?? 'Unit');\n  return lines;\n}\n\nfunction appendSuspendVariant(\n  lines: string[],\n  method: string,\n  suspendParams: SuspendParam[],\n  returnType: string,\n): void {\n  lines.push('');\n  for (const ln of emitSuspendVariant({ methodName: method, params: suspendParams, returnType })) {\n    lines.push(ln);\n  }\n}\n\nfunction escapeKdoc(s: string): string {\n  return s.replace(/\\*\\//g, '*\\u200b/');\n}\n","import type { Operation } from '@workos/oagen';\n\n/**\n * Operations whose generated implementation would be wrong (URL builders\n * served as HTTP calls). Hand-maintained code in `workos-kotlin` owns these\n * method names instead; the emitter must skip resources, tests, and the\n * smoke manifest for any operation in this set.\n *\n * Keys are `\"METHOD path\"` in the same form used by the smoke manifest.\n */\nexport const HANDWRITTEN_OVERRIDE_OPS: ReadonlySet<string> = new Set([\n  // AuthKit authorization URL (H09 / H10 are hand-built).\n  'GET /user_management/authorize',\n  // AuthKit logout URL (H17 — URL, not HTTP call).\n  'GET /user_management/sessions/logout',\n  // SSO authorization URL (H14 / H15 are hand-built).\n  'GET /sso/authorize',\n  // SSO logout URL (H17 — URL, not HTTP call).\n  'GET /sso/logout',\n]);\n\n/** True if the operation is owned by a hand-maintained override. */\nexport function isHandwrittenOverride(op: Operation): boolean {\n  return HANDWRITTEN_OVERRIDE_OPS.has(`${op.httpMethod.toUpperCase()} ${op.path}`);\n}\n","import type {\n  Service,\n  Operation,\n  Parameter,\n  EmitterContext,\n  GeneratedFile,\n  ResolvedOperation,\n  Model,\n  TypeRef,\n  Field,\n} from '@workos/oagen';\nimport { planOperation } from '@workos/oagen';\nimport { mapTypeRef, mapTypeRefOptional, implicitImportsFor } from './type-map.js';\nimport {\n  isListWrapperModel,\n  isListMetadataModel,\n  collectNonPaginatedResponseModelNames,\n  collectReferencedListMetadataModels,\n} from '../shared/model-utils.js';\nimport { enumCanonicalMap } from './enums.js';\nimport {\n  className,\n  propertyName,\n  resolveApiClassName,\n  packageSegment,\n  resolveMethodName,\n  ktLiteral,\n  clientFieldExpression,\n  escapeReserved,\n  humanize,\n  maybeShortenEnumParamDescription,\n  buildExportedClassNameSet,\n} from './naming.js';\nimport {\n  buildResolvedLookup,\n  lookupResolved,\n  scopedMountGroups,\n  buildHiddenParams,\n  getOpDefaults,\n  getOpInferFromClient,\n  collectGroupedParamNames,\n  collectBodyFieldTypes,\n} from '../shared/resolved-ops.js';\nimport { generateWrapperMethods } from './wrappers.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { isHandwrittenOverride } from './overrides.js';\nimport { buildKotlinPathExpression, KOTLIN_PATH_ENCODE_IMPORT } from './path-expression.js';\nimport { emitSuspendVariant, SUSPEND_IMPORTS, type SuspendParam } from './suspend.js';\n\nconst KOTLIN_SRC_PREFIX = 'src/main/kotlin/';\n\n/**\n * Some specs leave query params / fields typed as plain `string` even though\n * the description (or the field name) makes clear they carry an ISO-8601\n * timestamp. Detecting that here lets us emit `OffsetDateTime` so callers\n * don't have to format the wire string themselves.\n */\nconst ISO_8601_DESCRIPTION_RE = /\\bISO[-_ ]?8601\\b/i;\n\nfunction looksLikeIso8601String(description: string | undefined): boolean {\n  if (!description) return false;\n  return ISO_8601_DESCRIPTION_RE.test(description);\n}\n\n/**\n * Promote a string `TypeRef` to a `format: date-time` primitive when the\n * accompanying description identifies it as an ISO-8601 timestamp. Leaves\n * non-string types untouched.\n */\nfunction promoteIso8601TypeRef(type: TypeRef, description: string | undefined): TypeRef {\n  if (!looksLikeIso8601String(description)) return type;\n  const promote = (t: TypeRef): TypeRef => {\n    if (t.kind === 'primitive' && t.type === 'string' && !t.format) {\n      return { kind: 'primitive', type: 'string', format: 'date-time' };\n    }\n    if (t.kind === 'nullable') return { kind: 'nullable', inner: promote(t.inner) };\n    return t;\n  };\n  return promote(type);\n}\n\nfunction promoteParameterType(p: Parameter): Parameter {\n  const promoted = promoteIso8601TypeRef(p.type, p.description);\n  return promoted === p.type ? p : { ...p, type: promoted };\n}\n\nfunction promoteFieldType(f: Field): Field {\n  const promoted = promoteIso8601TypeRef(f.type, f.description);\n  return promoted === f.type ? f : { ...f, type: promoted };\n}\n\n/**\n * Generate one API class per mount group. Methods map 1:1 to IR operations.\n * Path params, query params, and body fields are flattened into the method\n * signature so callers never need to construct an intermediate options object.\n */\nexport function generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n  if (services.length === 0) return [];\n\n  const mountGroups = scopedMountGroups(ctx);\n  if (mountGroups.size === 0) return [];\n\n  const files: GeneratedFile[] = [];\n  const resolvedLookup = buildResolvedLookup(ctx);\n  const exportedClasses = buildExportedClassNameSet(ctx);\n\n  for (const [mountName, group] of mountGroups) {\n    const classCode = generateApiClass(mountName, group.operations, ctx, resolvedLookup);\n    if (!classCode) continue;\n    const pkg = packageSegment(mountName);\n    files.push({\n      path: `${KOTLIN_SRC_PREFIX}com/workos/${pkg}/${resolveApiClassName(mountName, exportedClasses)}.kt`,\n      content: classCode,\n      overwriteExisting: true,\n    });\n  }\n\n  return files;\n}\n\nfunction generateApiClass(\n  mountName: string,\n  operations: Operation[],\n  ctx: EmitterContext,\n  resolvedLookup: Map<string, ResolvedOperation>,\n): string | null {\n  if (operations.length === 0) return null;\n  const apiClass = resolveApiClassName(mountName, buildExportedClassNameSet(ctx));\n  const pkg = `com.workos.${packageSegment(mountName)}`;\n\n  const imports = new Set<string>();\n  imports.add('com.workos.WorkOS');\n  imports.add('com.workos.common.http.Page');\n  imports.add('com.workos.common.http.RequestConfig');\n  imports.add('com.workos.common.http.RequestOptions');\n  // Every emitted method gains a `suspend` overload that delegates to the\n  // blocking version under `withContext(Dispatchers.IO)`.\n  for (const imp of SUSPEND_IMPORTS) imports.add(imp);\n\n  const body: string[] = [];\n  const seenMethods = new Set<string>();\n  const hasAuthenticateHelper = operations.some(\n    (op) => op.path === '/user_management/authenticate' && op.httpMethod.toUpperCase() === 'POST',\n  );\n\n  if (hasAuthenticateHelper) {\n    imports.add('com.workos.common.http.bodyOf');\n    imports.add('com.workos.models.AuthenticateResponse');\n    body.push(...generateAuthenticateHelper());\n  }\n\n  for (const op of operations) {\n    if (isHandwrittenOverride(op)) continue;\n    const resolvedOp = lookupResolved(op, resolvedLookup);\n    if ((resolvedOp?.wrappers?.length ?? 0) > 0) {\n      // Emit one method per wrapper instead of the raw union-split operation.\n      for (const wrapper of resolvedOp!.wrappers!) {\n        if (wrapper.responseModelName) {\n          imports.add(`com.workos.models.${className(wrapper.responseModelName)}`);\n        }\n        // Register imports for wrapper param field types\n        const resolvedParams = resolveWrapperParams(wrapper, ctx);\n        for (const rp of resolvedParams) {\n          if (rp.field) registerTypeImports(rp.field.type, imports, ctx);\n        }\n      }\n      // Wrapper methods use bodyOf() for request body construction.\n      imports.add('com.workos.common.http.bodyOf');\n      // Wrappers share the operation's path; if it has any {param}, the\n      // wrapper emits encodePathSegment(...) and needs the import.\n      if (/\\{[^{}]+\\}/.test(resolvedOp!.operation.path)) {\n        imports.add(KOTLIN_PATH_ENCODE_IMPORT);\n      }\n      const wrapperLines = generateWrapperMethods(resolvedOp!, ctx);\n      if (body.length > 0) body.push('');\n      for (const line of wrapperLines) body.push(line);\n      continue;\n    }\n\n    const method = resolveMethodName(op, findService(ctx, op) ?? ({} as Service), ctx);\n    if (seenMethods.has(method)) continue;\n    seenMethods.add(method);\n\n    const rendered = renderMethod(mountName, method, op, ctx, resolvedOp, imports);\n    if (body.length > 0) body.push('');\n    body.push(rendered);\n  }\n\n  if (body.length === 0) return null;\n\n  // Emit sealed classes for parameter groups before the API class.\n  // Parameter-group IR can lose body field type fidelity; prefer the request\n  // body model's field type when available.\n  const bodyFieldTypes = new Map<string, TypeRef>();\n  for (const op of operations) {\n    for (const [name, type] of collectBodyFieldTypes(op, ctx.spec.models)) {\n      bodyFieldTypes.set(name, type);\n    }\n  }\n  const sealedLines: string[] = [];\n  const emittedSealedClasses = new Set<string>();\n  for (const op of operations) {\n    if ((op.parameterGroups?.length ?? 0) > 0) {\n      for (const group of op.parameterGroups ?? []) {\n        // Register imports for types used in parameter group sealed classes.\n        // The body field type override may introduce enum/model types that\n        // the original IR parameter didn't reference.\n        for (const variant of group.variants) {\n          for (const p of variant.parameters) {\n            const effectiveType = bodyFieldTypes.get(p.name) ?? p.type;\n            registerTypeImports(effectiveType, imports, ctx);\n          }\n        }\n        if (emittedSealedClasses.has(group.name)) continue;\n        emittedSealedClasses.add(group.name);\n        for (const line of generateSealedClass(group, bodyFieldTypes)) sealedLines.push(line);\n      }\n    }\n  }\n\n  // Drop unused imports by peeking at the body text and sealed class text.\n  const allText = body.join('\\n') + '\\n' + sealedLines.join('\\n');\n  const filteredImports = [...imports].filter((imp) => {\n    const simple = imp.slice(imp.lastIndexOf('.') + 1);\n    // Skip the import if the class body never references the simple name.\n    if (simple === 'WorkOS' || simple === 'RequestOptions') return true;\n    return new RegExp(`\\\\b${simple}\\\\b`).test(allText);\n  });\n\n  const lines: string[] = [];\n  lines.push(`package ${pkg}`);\n  lines.push('');\n  for (const imp of filteredImports.sort()) lines.push(`import ${imp}`);\n  lines.push('');\n  for (const line of sealedLines) lines.push(line);\n\n  const serviceDescription = resolveServiceDescription(ctx, mountName, operations);\n  // Every blocking method on this class also has a `suspend` overload — the\n  // suspend variant delegates to the blocking one via\n  // `withContext(Dispatchers.IO)` and is safe to call from any coroutine\n  // dispatcher. The service-level KDoc surfaces this so callers don't have to\n  // discover it per-method.\n  const suspendNote =\n    'Every operation on this class is available in two flavors: a blocking variant ' +\n    '(`<methodName>`) and a coroutine-aware variant (`<methodName>Suspend`). ' +\n    'The `Suspend` variants delegate to the blocking ones under `withContext(Dispatchers.IO)`, ' +\n    'so they are safe to call from any coroutine dispatcher (including `Dispatchers.Main`).';\n  if (serviceDescription) {\n    const docLines = serviceDescription.trim().split('\\n');\n    lines.push('/**');\n    for (const l of docLines) lines.push(l ? ` * ${escapeKdoc(l)}` : ' *');\n    lines.push(' *');\n    lines.push(` * ${escapeKdoc(suspendNote)}`);\n    lines.push(' */');\n  } else {\n    lines.push('/**');\n    lines.push(` * API accessor for ${mountName}.`);\n    lines.push(' *');\n    lines.push(` * ${escapeKdoc(suspendNote)}`);\n    lines.push(' */');\n  }\n  // ktlint requires constructor-property parameters on their own line.\n  // The property is `internal` so hand-maintained extension files in the\n  // same module can reach the underlying [WorkOS] client (e.g. to build\n  // URLs that are not HTTP calls).\n  lines.push(`class ${apiClass}(`);\n  lines.push('  internal val workos: WorkOS');\n  lines.push(`) {`);\n  for (const line of body) lines.push(line);\n  lines.push('}');\n  lines.push('');\n  return lines.join('\\n');\n}\n\nfunction findService(ctx: EmitterContext, op: Operation): Service | undefined {\n  for (const service of ctx.spec.services) {\n    if (service.operations.includes(op)) return service;\n  }\n  return undefined;\n}\n\n/**\n * Resolve a human-friendly description for a generated API class. Walks the\n * operations in the mount group, picks the first service whose description\n * is populated, and falls back to `null` when nothing meaningful is\n * available (the caller uses a generic fallback).\n */\nfunction resolveServiceDescription(ctx: EmitterContext, _mountName: string, operations: Operation[]): string | null {\n  for (const op of operations) {\n    const svc = findService(ctx, op);\n    if (svc?.description?.trim()) return svc.description;\n  }\n  return null;\n}\n\n/**\n * Render a single SDK method for an operation.\n */\nfunction renderMethod(\n  _mountName: string,\n  method: string,\n  op: Operation,\n  ctx: EmitterContext,\n  resolvedOp: ResolvedOperation | undefined,\n  imports: Set<string>,\n): string {\n  const plan = planOperation(op);\n  const hidden = buildHiddenParams(resolvedOp);\n  const defaults = getOpDefaults(resolvedOp);\n  const inferFromClient = getOpInferFromClient(resolvedOp);\n\n  const httpMethod = op.httpMethod.toUpperCase();\n  const pathParams = sortPathParamsByTemplateOrder(op);\n  const groupedParamNames = collectGroupedParamNames(op);\n  const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n  const queryParams = op.queryParams\n    .filter((p) => !hidden.has(p.name) && !groupedParamNames.has(p.name))\n    .map(promoteParameterType);\n  const bodyModel = resolveBodyModel(op, ctx);\n  const bodyFields = bodyModel\n    ? bodyModel.fields.filter((f) => !hidden.has(f.name) && !groupedParamNames.has(f.name)).map(promoteFieldType)\n    : [];\n\n  // Track imports we need\n  for (const p of [...pathParams, ...queryParams]) registerTypeImports(p.type, imports, ctx);\n  for (const f of bodyFields) registerTypeImports(f.type, imports, ctx);\n  const paginatedItemName = resolvePaginatedItemName(plan.paginatedItemModelName, ctx);\n  if (plan.responseModelName && !plan.isPaginated) {\n    imports.add(`com.workos.models.${className(plan.responseModelName)}`);\n  }\n  if (paginatedItemName) {\n    imports.add(`com.workos.models.${className(paginatedItemName)}`);\n    imports.add('com.fasterxml.jackson.core.type.TypeReference');\n  }\n\n  // Deduplicate: path params take precedence; query params second; body last.\n  // If a body field collides with a path/query param, rename the body field's\n  // Kotlin parameter (e.g. `slug` → `bodySlug`) so callers can pass both\n  // values. The wire name on the body map still uses the original field name.\n  const paramNames = new Set<string>();\n  for (const pp of pathParams) paramNames.add(propertyName(pp.name));\n  const uniqueQuery = queryParams.filter((qp) => !paramNames.has(propertyName(qp.name)));\n  for (const qp of uniqueQuery) paramNames.add(propertyName(qp.name));\n\n  const sharedQueryBodyParams = new Set(\n    uniqueQuery\n      .filter((qp) => bodyFields.some((bf) => bf.name === qp.name && mapTypeRef(qp.type) === mapTypeRef(bf.type)))\n      .map((qp) => qp.name),\n  );\n\n  // Map body field wire name → Kotlin parameter name. When the natural name\n  // collides with a path/query, prefix with `body` (e.g. slug → bodySlug).\n  const bodyParamNames = new Map<string, string>();\n  for (const bf of bodyFields) {\n    const natural = propertyName(bf.name);\n    if (sharedQueryBodyParams.has(bf.name)) {\n      bodyParamNames.set(bf.name, natural);\n      continue;\n    }\n    if (paramNames.has(natural)) {\n      const renamed = `body${natural.charAt(0).toUpperCase()}${natural.slice(1)}`;\n      bodyParamNames.set(bf.name, renamed);\n      paramNames.add(renamed);\n    } else {\n      bodyParamNames.set(bf.name, natural);\n      paramNames.add(natural);\n    }\n  }\n\n  const groupParamNames = assignGroupParameterNames(op, paramNames);\n\n  const params: string[] = [];\n  // Mirrors `params` but tracks the bare Kotlin parameter name so the suspend\n  // overload (emitted alongside the blocking version) can forward arguments.\n  const suspendParams: SuspendParam[] = [];\n  const pushParam = (decl: string, name: string) => {\n    params.push(decl);\n    suspendParams.push({ decl, name });\n  };\n  for (const pp of pathParams) pushParam(`    ${propertyName(pp.name)}: String`, propertyName(pp.name));\n\n  const sortedQuery = [...uniqueQuery].sort((a, b) => (a.required === b.required ? 0 : a.required ? -1 : 1));\n  for (const qp of sortedQuery) {\n    pushParam(\n      renderParam(qp.name, qp.type, qp.required, method.startsWith('list') && qp.name === 'limit'),\n      propertyName(qp.name),\n    );\n  }\n\n  // Parameter group params (sealed class types)\n  for (const group of op.parameterGroups ?? []) {\n    const sealedName = sealedGroupName(group.name);\n    const prop = groupParamNames.get(group.name)!;\n    if (group.optional) {\n      pushParam(`    ${prop}: ${sealedName}? = null`, prop);\n    } else {\n      pushParam(`    ${prop}: ${sealedName}`, prop);\n    }\n  }\n\n  // PATCH operations use PatchField<T> for optional body fields so callers\n  // can distinguish \"omit\" (Absent) from \"clear\" (Present(null)).\n  const isPatch = httpMethod === 'PATCH';\n\n  const sortedBodyFields = [...bodyFields].sort((a, b) => (a.required === b.required ? 0 : a.required ? -1 : 1));\n  for (const bf of sortedBodyFields) {\n    if (sharedQueryBodyParams.has(bf.name)) continue;\n    if (isPatch && !bf.required) {\n      const baseType = mapTypeRef(bf.type);\n      imports.add('com.workos.common.http.PatchField');\n      pushParam(\n        `    ${bodyParamNames.get(bf.name)!}: PatchField<${baseType}> = PatchField.Absent`,\n        bodyParamNames.get(bf.name)!,\n      );\n    } else {\n      pushParam(renderParamNamed(bodyParamNames.get(bf.name)!, bf.type, bf.required), bodyParamNames.get(bf.name)!);\n    }\n  }\n\n  // Per-request options trailer (always optional)\n  pushParam('    requestOptions: RequestOptions? = null', 'requestOptions');\n\n  const returnType = resolveReturnType(plan, imports, ctx);\n  const isPaginated = plan.isPaginated && paginatedItemName !== null;\n\n  const lines: string[] = [];\n  const kdocLines = buildMethodKdoc(op, pathParams, sortedQuery, sortedBodyFields, bodyParamNames, plan);\n  for (const ln of kdocLines) lines.push(ln);\n  if (op.deprecated) lines.push('  @Deprecated(\"Deprecated operation\")');\n  lines.push('  @JvmOverloads');\n  // Omit explicit `: Unit` to keep ktlint happy.\n  const returnClause = returnType === 'Unit' ? '' : `: ${returnType}`;\n  if (params.length === 1) {\n    // Single param fits on one line; ktlint enforces inline form.\n    const singleParam = params[0].replace(/^\\s+/, '');\n    lines.push(`  fun ${escapeReserved(method)}(${singleParam})${returnClause} {`);\n  } else {\n    lines.push(`  fun ${escapeReserved(method)}(`);\n    for (let i = 0; i < params.length; i++) {\n      const suffix = i === params.length - 1 ? '' : ',';\n      lines.push(`${params[i]}${suffix}`);\n    }\n    lines.push(`  )${returnClause} {`);\n  }\n\n  // Build body / query config\n  //\n  // POST/PUT/PATCH always need a request body — OkHttp rejects them otherwise.\n  // DELETE and GET only emit a body when the spec explicitly declares one\n  // (OpenAPI allows DELETE-with-body; GET-with-body is uncommon but legal).\n  // GET never carries defaults/inferFromClient in the body — those fall back\n  // to the query string for GET.\n  const methodAlwaysHasBody = ['POST', 'PUT', 'PATCH'].includes(httpMethod);\n  const specDeclaresBody = op.requestBody !== undefined;\n  const hasBody =\n    methodAlwaysHasBody ||\n    (specDeclaresBody && httpMethod !== 'GET') ||\n    ((httpMethod === 'PUT' || httpMethod === 'PATCH' || httpMethod === 'POST' || httpMethod === 'DELETE') &&\n      (Object.keys(defaults).length > 0 || inferFromClient.length > 0) &&\n      specDeclaresBody);\n  const appendDefaultsAsQuery = !hasBody && (Object.keys(defaults).length > 0 || inferFromClient.length > 0);\n  const pathBuilt = buildKotlinPathExpression(op.path);\n  const pathExpr = pathBuilt.expression;\n  if (pathBuilt.requiresEncodeImport) imports.add(KOTLIN_PATH_ENCODE_IMPORT);\n\n  if (\n    op.path === '/user_management/authenticate' &&\n    httpMethod === 'POST' &&\n    plan.responseModelName === 'AuthenticateResponse'\n  ) {\n    imports.add('com.workos.models.AuthenticateResponse');\n    const grantType = defaults.grant_type ?? 'authorization_code';\n    const entryLines = sortedBodyFields\n      .filter((bf) => bf.name !== 'grant_type' && bf.name !== 'client_id' && bf.name !== 'client_secret')\n      .map((bf) => `      ${ktLiteral(bf.name)} to ${bodyParamNames.get(bf.name)!}`);\n    lines.push(`    return authenticate(`);\n    lines.push(`      grantType = ${ktLiteral(grantType)},`);\n    lines.push(`      requestOptions = requestOptions,`);\n    for (let i = 0; i < entryLines.length; i++) {\n      const suffix = i === entryLines.length - 1 ? '' : ',';\n      lines.push(`${entryLines[i]}${suffix}`);\n    }\n    lines.push(`    )`);\n    lines.push('  }');\n    appendSuspendVariantLines(lines, method, suspendParams, returnType, op.deprecated);\n    return lines.join('\\n');\n  }\n\n  if (isPaginated) {\n    // Nested helper function + requestPage call; 'after' is owned by the\n    // cursor logic so we skip it in the generic query loop.\n    // 'after' and 'before' are owned by the cursor logic. 'before' is only\n    // included on the first page — re-sending it on follow-up pages (where\n    // afterCursor is set by the pagination engine) is nonsensical and can\n    // cause empty or looping results from the server.\n    imports.add('com.workos.common.http.addIfNotNull');\n    imports.add('com.workos.common.http.addJoinedIfNotNull');\n    imports.add('com.workos.common.http.addEach');\n    const itemClass = className(paginatedItemName!);\n    lines.push(`    val itemType = object : TypeReference<${itemClass}>() {}`);\n    lines.push(`    return workos.baseClient.requestPage(`);\n    lines.push(`      method = ${ktLiteral(httpMethod)},`);\n    lines.push(`      path = ${pathExpr},`);\n    lines.push(`      itemType = itemType,`);\n    lines.push(`      requestOptions = requestOptions,`);\n    lines.push(`      before = ${pickNamedQueryParam(sortedQuery, 'before')},`);\n    lines.push(`      after = ${pickNamedQueryParam(sortedQuery, 'after')}`);\n    lines.push(`    ) {`);\n    for (const qp of sortedQuery.filter((p) => p.name !== 'after' && p.name !== 'before')) {\n      for (const ln of emitQueryParam(qp, '      ', true)) lines.push(ln);\n    }\n    for (const group of op.parameterGroups ?? []) {\n      for (const ln of emitGroupQueryDispatch(group, groupParamNames.get(group.name)!, '      ', true)) {\n        lines.push(ln);\n      }\n    }\n    lines.push(`    }`);\n  } else {\n    // Only emit the `params` local when the method actually contributes\n    // query parameters (spec-declared query, or defaults/inferFromClient\n    // for GET/DELETE without a body). `RequestConfig.queryParams` defaults\n    // to `emptyList()` when omitted, so we avoid dead local declarations.\n    // Groups go to the body for POST/PUT/PATCH (hasBody), query otherwise.\n    const groupsGoToQuery = hasGroups && !hasBody;\n    const emitsQueryParams = sortedQuery.length > 0 || appendDefaultsAsQuery || groupsGoToQuery;\n    if (emitsQueryParams) {\n      imports.add('com.workos.common.http.addIfNotNull');\n      imports.add('com.workos.common.http.addJoinedIfNotNull');\n      imports.add('com.workos.common.http.addEach');\n      lines.push(`    val params = mutableListOf<Pair<String, String>>()`);\n      for (const qp of sortedQuery) for (const ln of emitQueryParam(qp, '    ')) lines.push(ln);\n      if (groupsGoToQuery) {\n        for (const group of op.parameterGroups ?? []) {\n          for (const ln of emitGroupQueryDispatch(group, groupParamNames.get(group.name)!, '    ')) lines.push(ln);\n        }\n      }\n      if (appendDefaultsAsQuery) {\n        for (const [k, v] of Object.entries(defaults)) lines.push(`    params += ${ktLiteral(k)} to ${ktLiteral(v)}`);\n        // Client-inferred fields may be nullable (e.g. clientId). Skip when\n        // null rather than serializing \"null\" into the URL.\n        for (const k of inferFromClient) {\n          lines.push(`    workos.${clientFieldExpression(k)}?.let { params += ${ktLiteral(k)} to it }`);\n        }\n      }\n    }\n\n    if (hasBody) {\n      // Use bodyOf() / patchBodyOf() helpers to build the request body in a\n      // single expression. This drops null optional values automatically\n      // instead of repeating `if (x != null) body[\"x\"] = x` per field.\n      const helperFn = isPatch ? 'patchBodyOf' : 'bodyOf';\n      imports.add(`com.workos.common.http.${helperFn}`);\n      const bodyEntries: string[] = [];\n      for (const bf of sortedBodyFields) {\n        const prop = bodyParamNames.get(bf.name)!;\n        bodyEntries.push(`      ${ktLiteral(bf.name)} to ${prop}`);\n      }\n      for (const [k, v] of Object.entries(defaults)) {\n        bodyEntries.push(`      ${ktLiteral(k)} to ${ktLiteral(v)}`);\n      }\n      for (const k of inferFromClient) {\n        bodyEntries.push(`      ${ktLiteral(k)} to workos.${clientFieldExpression(k)}`);\n      }\n      if (bodyEntries.length > 0) {\n        // ktlint: \"A multiline expression should start on a new line\"\n        lines.push(`    val body =`);\n        lines.push(`      ${helperFn}(`);\n        for (let i = 0; i < bodyEntries.length; i++) {\n          const sep = i === bodyEntries.length - 1 ? '' : ',';\n          lines.push(`  ${bodyEntries[i]}${sep}`);\n        }\n        lines.push(`      )`);\n      } else {\n        // Empty body (POST/PUT/PATCH still require one for OkHttp).\n        lines.push(`    val body = linkedMapOf<String, Any?>()`);\n      }\n      // Parameter group values go into the body for POST/PUT/PATCH so\n      // sensitive fields (passwords, role slugs) never leak into the URL.\n      if (hasGroups) {\n        for (const group of op.parameterGroups ?? []) {\n          for (const ln of emitGroupBodyDispatch(group, groupParamNames.get(group.name)!, '    ')) {\n            lines.push(ln);\n          }\n        }\n      }\n      lines.push(`    val config =`);\n      lines.push(`      RequestConfig(`);\n      lines.push(`        method = ${ktLiteral(httpMethod)},`);\n      lines.push(`        path = ${pathExpr},`);\n      if (emitsQueryParams) lines.push(`        queryParams = params,`);\n      lines.push(`        body = body,`);\n      lines.push(`        requestOptions = requestOptions`);\n      lines.push(`      )`);\n    } else {\n      lines.push(`    val config =`);\n      lines.push(`      RequestConfig(`);\n      lines.push(`        method = ${ktLiteral(httpMethod)},`);\n      lines.push(`        path = ${pathExpr},`);\n      if (emitsQueryParams) lines.push(`        queryParams = params,`);\n      lines.push(`        requestOptions = requestOptions`);\n      lines.push(`      )`);\n    }\n\n    if (plan.responseModelName && plan.isArrayResponse) {\n      // `type: array` response — deserialize as List<T> via TypeReference.\n      const itemClass = className(plan.responseModelName);\n      imports.add('com.fasterxml.jackson.core.type.TypeReference');\n      lines.push(`    val responseType = object : TypeReference<List<${itemClass}>>() {}`);\n      lines.push(`    return workos.baseClient.request(config, responseType)`);\n    } else if (plan.responseModelName) {\n      const responseClass = className(plan.responseModelName);\n      lines.push(`    return workos.baseClient.request(config, ${responseClass}::class.java)`);\n    } else if (plan.isDelete || !plan.isModelResponse) {\n      lines.push(`    workos.baseClient.requestVoid(config)`);\n    } else {\n      lines.push(`    workos.baseClient.requestVoid(config)`);\n    }\n  }\n\n  lines.push('  }');\n  appendSuspendVariantLines(lines, method, suspendParams, returnType, op.deprecated);\n\n  // Java-friendly overloads: for each variant of every sealed-class parameter\n  // group, emit an additional overload that accepts the variant's flat fields\n  // directly (no `new ResourceTarget.ById(...)` boilerplate from Java).\n  appendJavaFriendlyVariantOverloads(lines, {\n    method,\n    op,\n    canonicalParams: suspendParams,\n    groupParamNames,\n    returnType,\n    deprecated: op.deprecated,\n  });\n\n  return lines.join('\\n');\n}\n\ninterface JavaOverloadCtx {\n  method: string;\n  op: Operation;\n  /**\n   * The exact parameter declarations of the canonical method, in order. The\n   * Java-friendly overload reuses these verbatim for non-variant params so\n   * type/nullability/default exactly match the canonical method (avoiding\n   * subtle drift like `Long?` vs `Int?` or `String?` vs `String`).\n   */\n  canonicalParams: SuspendParam[];\n  groupParamNames: Map<string, string>;\n  returnType: string;\n  deprecated: boolean | undefined;\n}\n\n/**\n * For each variant of every sealed-class parameter group on `op`, append a\n * Java-discoverable overload that takes the variant's flat fields directly\n * and forwards to the canonical (sealed-class) method.\n *\n * Implementation scope: when an operation has multiple parameter groups, we\n * emit overloads for each variant of each group while keeping the *other*\n * groups' sealed-class params unchanged. This avoids combinatorial explosion\n * for ops with several groups while still flattening the common case.\n *\n * Method-name derivation handles the most common variant shapes (`ById`,\n * `ByExternalId`, etc.). Other shapes (e.g. `Plaintext`, `Imported`) are\n * skipped with a comment so unusual unions don't compile-fail the SDK; if\n * one becomes important we can add an explicit case here.\n */\nfunction appendJavaFriendlyVariantOverloads(lines: string[], ctx: JavaOverloadCtx): void {\n  const groups = ctx.op.parameterGroups ?? [];\n  if (groups.length === 0) return;\n\n  for (const group of groups) {\n    for (const variant of group.variants) {\n      const overloadMethodName = deriveOverloadMethodName(ctx.method, variant.name);\n      if (overloadMethodName === null) {\n        // Variant shape doesn't fit a clean Java-friendly method name; skip.\n        // TODO: extend deriveOverloadMethodName for less-common shapes\n        // (e.g. password variants) once we have a need for them.\n        continue;\n      }\n      emitOneJavaOverload(lines, ctx, group, variant, overloadMethodName);\n    }\n  }\n}\n\nfunction deriveOverloadMethodName(baseMethod: string, variantName: string): string | null {\n  const v = className(variantName);\n  if (v === 'ById') return baseMethod;\n  if (/^By[A-Z]/.test(v)) {\n    // Don't double-stack a By-suffix: if the operation method already ends\n    // with the variant suffix (case-insensitive), reuse it as-is. This keeps\n    // names like `updateResourceByExternalId` from becoming\n    // `updateResourceByExternalIdByExternalId`.\n    if (baseMethod.toLowerCase().endsWith(v.toLowerCase())) {\n      return baseMethod;\n    }\n    return `${baseMethod}${v}`;\n  }\n  return null;\n}\n\nfunction emitOneJavaOverload(\n  lines: string[],\n  ctx: JavaOverloadCtx,\n  group: import('@workos/oagen').ParameterGroup,\n  variant: import('@workos/oagen').ParameterGroup['variants'][number],\n  overloadMethodName: string,\n): void {\n  const sealedName = sealedGroupName(group.name);\n  const variantClass = className(variant.name);\n  const targetGroupProp = ctx.groupParamNames.get(group.name)!;\n\n  // Reuse the canonical method's exact parameter decls. We swap out only the\n  // target group's slot (replacing the sealed param with variant fields) and\n  // leave path/query/body params untouched so types/nullability/defaults\n  // line up exactly with what the canonical method accepts.\n  type ParamSpec = { decl: string; name: string };\n  const decls: ParamSpec[] = [];\n\n  // Track names already in use so variant field names that collide with\n  // existing op params can be deterministically disambiguated.\n  const existingNames = new Set<string>();\n  for (const cp of ctx.canonicalParams) {\n    if (cp.name !== targetGroupProp) existingNames.add(cp.name);\n  }\n\n  // Compute variant field decls (with collision-aware names). For a colliding\n  // field, prefix it with the group's property name (e.g. `externalId` →\n  // `parentResourceExternalId`) so the overload signature is unambiguous and\n  // doesn't shadow the operation's own path/query/body params.\n  const variantFieldDecls: ParamSpec[] = [];\n  const variantArgPairs: { sealedField: string; localName: string }[] = [];\n  for (const p of variant.parameters) {\n    const sealedField = deriveShortPropertyName(p.name, group.name);\n    let localName = sealedField;\n    if (existingNames.has(localName)) {\n      const groupPrefix = propertyName(group.name);\n      const camel = `${groupPrefix}${localName.charAt(0).toUpperCase()}${localName.slice(1)}`;\n      localName = camel;\n    }\n    existingNames.add(localName);\n    // Variant fields are always required when their variant is selected — the\n    // sealed-class data class declares them non-nullable (see\n    // [generateSealedClass]). Mirror that here so the overload's flat\n    // parameter types match the variant-constructor argument types exactly.\n    // Also: prefer the body model's field type via [bodyFieldTypes] when the\n    // parameter-group IR has lost type fidelity. Inside this scope we don't\n    // have bodyFieldTypes; the canonical method's type rendering for variant\n    // fields hasn't been needed elsewhere, so fall back to p.type — which is\n    // correct for non-body groups (path/query) and for body groups whose\n    // types weren't degraded.\n    const decl = renderParamNamed(localName, p.type, true);\n    variantFieldDecls.push({ decl, name: localName });\n    variantArgPairs.push({ sealedField, localName });\n  }\n\n  // Walk canonical params; substitute the target group slot with the variant's\n  // flat fields, copy everything else unchanged.\n  for (const cp of ctx.canonicalParams) {\n    if (cp.name === targetGroupProp) {\n      for (const v of variantFieldDecls) decls.push(v);\n    } else {\n      decls.push({ decl: cp.decl, name: cp.name });\n    }\n  }\n\n  const returnClause = ctx.returnType === 'Unit' ? '' : `: ${ctx.returnType}`;\n  const variantArgs = variantArgPairs.map((p) => `${p.sealedField} = ${p.localName}`).join(', ');\n  const sealedConstruct = `${sealedName}.${variantClass}(${variantArgs})`;\n\n  // Build the call to the canonical method by walking canonical params again:\n  // the target group slot is set to the inline-constructed variant; everything\n  // else passes through by its canonical name.\n  const forwardArgs: string[] = [];\n  for (const cp of ctx.canonicalParams) {\n    if (cp.name === targetGroupProp) {\n      forwardArgs.push(`${cp.name} = ${sealedConstruct}`);\n    } else {\n      forwardArgs.push(`${cp.name} = ${cp.name}`);\n    }\n  }\n\n  // KDoc.\n  lines.push('');\n  lines.push('  /**');\n  lines.push(`   * Java-friendly overload — equivalent to`);\n  lines.push(`   * \\`${ctx.method}(${sealedName}.${variantClass}(...))\\` from Kotlin.`);\n  lines.push(`   *`);\n  lines.push(`   * Accepts the discriminating fields directly so Java callers don't`);\n  lines.push(`   * need to construct \\`${sealedName}.${variantClass}\\` explicitly.`);\n  lines.push('   */');\n  if (ctx.deprecated) lines.push('  @Deprecated(\"Deprecated operation\")');\n  // Note: no `@JvmOverloads` here. The synthetic Java overloads `@JvmOverloads`\n  // generates (one per trailing optional, with the optional dropped) collide\n  // with the canonical method's `@JvmOverloads` permutations whenever the\n  // overload reuses the canonical method name (e.g. `ById` variants).\n  // Java callers pay a small ergonomic cost — they must pass `null` for\n  // optional trailing params (typically just `requestOptions`) — but the\n  // overload's main purpose (no sealed-class construction) still applies.\n\n  // Emit the function signature.\n  if (decls.length === 1) {\n    const single = decls[0].decl.replace(/^\\s+/, '');\n    lines.push(`  fun ${escapeReserved(overloadMethodName)}(${single})${returnClause} = ${ctx.method}(`);\n  } else {\n    lines.push(`  fun ${escapeReserved(overloadMethodName)}(`);\n    for (let i = 0; i < decls.length; i++) {\n      const sep = i === decls.length - 1 ? '' : ',';\n      lines.push(`${decls[i].decl}${sep}`);\n    }\n    lines.push(`  )${returnClause} = ${ctx.method}(`);\n  }\n  for (let i = 0; i < forwardArgs.length; i++) {\n    const sep = i === forwardArgs.length - 1 ? '' : ',';\n    lines.push(`    ${forwardArgs[i]}${sep}`);\n  }\n  lines.push('  )');\n\n  // Emit a coroutine-friendly suspend variant of the overload too.\n  appendSuspendVariantLines(\n    lines,\n    overloadMethodName,\n    decls.map((d) => ({ decl: d.decl, name: d.name })),\n    ctx.returnType,\n    ctx.deprecated,\n  );\n}\n\nfunction appendSuspendVariantLines(\n  lines: string[],\n  method: string,\n  suspendParams: SuspendParam[],\n  returnType: string,\n  deprecated: boolean | undefined,\n): void {\n  lines.push('');\n  for (const ln of emitSuspendVariant({ methodName: method, params: suspendParams, returnType, deprecated })) {\n    lines.push(ln);\n  }\n}\n\nfunction resolveReturnType(plan: ReturnType<typeof planOperation>, imports: Set<string>, ctx?: EmitterContext): string {\n  const itemName = plan.isPaginated\n    ? (resolvePaginatedItemName(plan.paginatedItemModelName, ctx) ?? plan.paginatedItemModelName)\n    : null;\n  if (plan.isPaginated && itemName) {\n    const item = className(itemName);\n    imports.add(`com.workos.models.${item}`);\n    return `Page<${item}>`;\n  }\n  if (plan.responseModelName && plan.isArrayResponse) {\n    const cls = className(plan.responseModelName);\n    imports.add(`com.workos.models.${cls}`);\n    return `List<${cls}>`;\n  }\n  if (plan.responseModelName) {\n    const cls = className(plan.responseModelName);\n    imports.add(`com.workos.models.${cls}`);\n    return cls;\n  }\n  return 'Unit';\n}\n\n/**\n * If [paginatedItemModelName] points to a list wrapper (`{ data, list_metadata }`),\n * unwrap it and return the actual item model name. Otherwise return as-is.\n */\nfunction resolvePaginatedItemName(name: string | null, ctx?: EmitterContext): string | null {\n  if (!name || !ctx) return name;\n  const model = ctx.spec.models.find((m) => m.name === name);\n  if (!model) return name;\n  const dataField = model.fields.find((f) => f.name === 'data');\n  if (!dataField || dataField.type.kind !== 'array') return name;\n  const items = dataField.type.items;\n  if (items.kind === 'model') return items.name;\n  return name;\n}\n\nfunction renderParam(name: string, type: TypeRef, required: boolean, forceInt = false): string {\n  return renderParamNamed(propertyName(name), type, required, forceInt);\n}\n\nfunction renderParamNamed(kotlinName: string, type: TypeRef, required: boolean, forceInt = false): string {\n  const mapped = forceInt ? (required ? 'Int' : 'Int?') : required ? mapTypeRef(type) : mapTypeRefOptional(type);\n  return required ? `    ${kotlinName}: ${mapped}` : `    ${kotlinName}: ${mapped} = null`;\n}\n\n/**\n * Build the KDoc block preceding an SDK method.  Combines the operation's\n * summary/description with `@param` docs for every parameter that has a\n * description in the spec, `@return` when a response model is known, and\n * `@throws` for the standard error types.\n */\nfunction buildMethodKdoc(\n  op: Operation,\n  pathParams: Parameter[],\n  queryParams: Parameter[],\n  bodyFields: Field[],\n  bodyParamNames: Map<string, string>,\n  plan: ReturnType<typeof planOperation>,\n): string[] {\n  // Use the operation's description as the KDoc body, split by newline.\n  // Escape `*/` sequences to keep KDoc valid.\n  const descriptionRaw = (op.description ?? '').trim();\n  const textLines: string[] = [];\n  if (descriptionRaw) {\n    for (const l of descriptionRaw.split('\\n')) textLines.push(escapeKdoc(l));\n  }\n\n  // @param lines. Use the Kotlin-visible parameter name (body collisions get\n  // renamed, e.g. slug → bodySlug). Every parameter gets an `@param` line —\n  // Dokka does not flag missing `@param` blocks (only fully undocumented\n  // declarations), so we have to enforce coverage at emit time. Spec-provided\n  // descriptions are preferred; missing descriptions get a templated fallback\n  // derived from the parameter name. The fallback is intentionally a little\n  // ugly — it nudges callers to add real descriptions to the spec.\n  const paramDocs: string[] = [];\n  const seenParamDocs = new Set<string>();\n  const pushParamDoc = (\n    name: string,\n    sourceName: string,\n    description: string | undefined,\n    deprecated?: boolean,\n    type?: TypeRef,\n  ) => {\n    if (seenParamDocs.has(name)) return;\n    seenParamDocs.add(name);\n    paramDocs.push(formatParamDoc(name, description, deprecated, sourceName, type));\n  };\n  for (const pp of pathParams) {\n    pushParamDoc(propertyName(pp.name), pp.name, pp.description, pp.deprecated, pp.type);\n  }\n  for (const qp of queryParams) {\n    pushParamDoc(propertyName(qp.name), qp.name, qp.description, qp.deprecated, qp.type);\n  }\n  for (const bf of bodyFields) {\n    pushParamDoc(bodyParamNames.get(bf.name)!, bf.name, bf.description, bf.deprecated, bf.type);\n  }\n  // Always document the trailing `requestOptions` parameter with a stable,\n  // canned phrasing so generated SDKs are consistent and Dokka's coverage\n  // reporting has nothing to flag.\n  pushParamDoc('requestOptions', 'request_options', REQUEST_OPTIONS_PARAM_DESCRIPTION);\n\n  const returnDoc = plan.isPaginated\n    ? '@return a [com.workos.common.http.Page] of results'\n    : plan.responseModelName\n      ? `@return the ${plan.isArrayResponse ? `list of ${className(plan.responseModelName)}` : className(plan.responseModelName)}`\n      : null;\n\n  const hasAnyContent = textLines.length > 0 || paramDocs.length > 0 || returnDoc !== null;\n  if (!hasAnyContent) return [];\n\n  const out: string[] = ['  /**'];\n  for (const l of textLines) out.push(l ? `   * ${l}` : '   *');\n  const hasBodyText = textLines.length > 0;\n  const needsSpacer = hasBodyText && (paramDocs.length > 0 || returnDoc !== null);\n  if (needsSpacer) out.push('   *');\n  for (const p of paramDocs) out.push(`   * ${p}`);\n  if (returnDoc) {\n    if (paramDocs.length > 0) out.push('   *');\n    out.push(`   * ${returnDoc}`);\n  }\n  out.push('   */');\n  return out;\n}\n\n/**\n * Stable, canned description for the trailing `requestOptions` parameter that\n * every generated method exposes. Kept as a constant so the same phrasing\n * appears across resource methods, wrapper methods, and union-split helpers.\n */\nconst REQUEST_OPTIONS_PARAM_DESCRIPTION = 'per-request overrides (idempotency key, API key, headers, timeout)';\n\nfunction formatParamDoc(\n  kotlinName: string,\n  description: string | undefined,\n  deprecated?: boolean,\n  sourceName?: string,\n  type?: TypeRef,\n): string {\n  const firstLine = description?.split('\\n').find((l) => l.trim()) ?? '';\n  const specText = firstLine.trim();\n  const deprecationNote = deprecated ? '**Deprecated.**' : '';\n  // Fall back to a templated description derived from the parameter name when\n  // the spec didn't provide one. Dokka has no `-Xdoclint:missing` analogue,\n  // so emitting a placeholder is the only way to guarantee `@param` coverage.\n  const fallback = `the ${humanize(sourceName ?? kotlinName)} of the request.`;\n  let text = specText || fallback;\n  // For long enum-typed parameter descriptions (notably PaginationOrder),\n  // replace the verbose per-method copy with a short summary that defers to\n  // the enum's own KDoc — see [maybeShortenEnumParamDescription].\n  const shortened = maybeShortenEnumParamDescription(type, text);\n  if (shortened) text = shortened.description;\n  const parts = [deprecationNote, text].filter(Boolean).join(' ');\n  return `@param ${kotlinName} ${escapeKdoc(parts)}`;\n}\n\n/**\n * Unwrap a possibly-nullable type to check if the inner type is an array,\n * and return the array's item type for downstream serialization decisions.\n */\nfunction unwrapArray(t: TypeRef): TypeRef | null {\n  if (t.kind === 'array') return t.items;\n  if (t.kind === 'nullable' && t.inner.kind === 'array') return t.inner.items;\n  return null;\n}\n\n/**\n * Serialize a single value expression for a query parameter.  For enums we\n * use `.value` so the wire name is used; for strings the value is already\n * the right type; for everything else `.toString()`.\n */\nfunction valueExprForQuery(type: TypeRef): string {\n  const inner = type.kind === 'nullable' ? type.inner : type;\n  if (inner.kind === 'enum') return 'it.value';\n  if (inner.kind === 'primitive' && inner.type === 'string') {\n    return inner.format === 'date-time' ? 'it.toString()' : 'it';\n  }\n  return 'it.toString()';\n}\n\nfunction emitQueryParam(p: Parameter, indent: string, receiverMode = false): string[] {\n  const prop = propertyName(p.name);\n  const rendered = queryParamToString(p.type, prop);\n  const inner = p.type.kind === 'nullable' ? p.type.inner : p.type;\n  const arrayItem = unwrapArray(p.type);\n  // In receiver-lambda mode (`requestPage { ... }`) the surrounding closure is\n  // an extension on `MutableList<Pair<String, String>>`, so we elide the\n  // explicit `params.` qualifier (extension functions resolve via implicit\n  // receiver) and route `+=` through `add(pair)` to keep ktlint happy.\n  const callPrefix = receiverMode ? '' : 'params.';\n  const addPair = (pair: string) => (receiverMode ? `add(${pair})` : `params += ${pair}`);\n  if (arrayItem) {\n    // Honor `style: form, explode: false` → comma-joined. Default (explode:true\n    // or unspecified for form) → repeated keys.  `p.explode ?? true` matches\n    // the OpenAPI default for query parameters when `style` is form.\n    const explode = p.explode ?? true;\n    const itemExpr = valueExprForQuery(arrayItem);\n    // `it` is the loop variable in the trivial mapping case — `xs.map { it }`\n    // is the identity function, so emit the collection directly when the per-\n    // item expression doesn't transform the value.\n    const isIdentity = itemExpr === 'it';\n    if (!explode) {\n      if (p.required) {\n        const arg = isIdentity ? prop : `${prop}.map { ${itemExpr} }`;\n        return [`${indent}${callPrefix}addJoinedIfNotNull(${ktLiteral(p.name)}, ${arg})`];\n      }\n      const arg = isIdentity ? prop : `${prop}?.map { ${itemExpr} }`;\n      return [`${indent}${callPrefix}addJoinedIfNotNull(${ktLiteral(p.name)}, ${arg})`];\n    }\n    if (p.required) {\n      const arg = isIdentity ? prop : `${prop}.map { ${itemExpr} }`;\n      return [`${indent}${callPrefix}addEach(${ktLiteral(p.name)}, ${arg})`];\n    }\n    if (isIdentity) {\n      return [`${indent}${prop}?.let { ${callPrefix}addEach(${ktLiteral(p.name)}, it) }`];\n    }\n    return [`${indent}${prop}?.let { ${callPrefix}addEach(${ktLiteral(p.name)}, it.map { ${itemExpr} }) }`];\n  }\n  if (p.required) return [`${indent}${addPair(`${ktLiteral(p.name)} to ${rendered}`)}`];\n  if (inner.kind === 'primitive' && inner.type === 'string' && inner.format !== 'date-time') {\n    return [`${indent}${callPrefix}addIfNotNull(${ktLiteral(p.name)}, ${prop})`];\n  }\n  return [`${indent}${prop}?.let { ${addPair(`${ktLiteral(p.name)} to ${queryParamToString(inner, 'it')}`)} }`];\n}\n\nfunction queryParamToString(type: TypeRef, varName: string): string {\n  if (type.kind === 'enum') return `${varName}.value`;\n  if (type.kind === 'nullable') return queryParamToString(type.inner, varName);\n  // Plain `string` is already the wire type. ISO-8601 strings get promoted to\n  // `OffsetDateTime`, so we need an explicit `.toString()` to serialize them\n  // as the spec-required ISO-8601 representation.\n  if (type.kind === 'primitive' && type.type === 'string') {\n    return type.format === 'date-time' ? `${varName}.toString()` : varName;\n  }\n  return `${varName}.toString()`;\n}\n\nfunction _emitBodyField(field: Field, kotlinParamName: string, isPatch: boolean): string[] {\n  const prop = kotlinParamName;\n  if (field.required) return [`    body[${ktLiteral(field.name)}] = ${prop}`];\n  // PATCH: PatchField<T> — serialize Present(value) including explicit null;\n  // skip Absent entirely so the server preserves the field's current value.\n  if (isPatch) {\n    return [`    if (${prop} is PatchField.Present) body[${ktLiteral(field.name)}] = ${prop}.value`];\n  }\n  return [`    if (${prop} != null) body[${ktLiteral(field.name)}] = ${prop}`];\n}\n\nfunction pickNamedQueryParam(sorted: Parameter[], name: string): string {\n  const match = sorted.find((p) => p.name === name);\n  return match ? propertyName(match.name) : 'null';\n}\n\nfunction generateAuthenticateHelper(): string[] {\n  return [\n    '  private fun authenticate(',\n    '    grantType: String,',\n    '    requestOptions: RequestOptions?,',\n    '    vararg entries: Pair<String, Any?>',\n    '  ): AuthenticateResponse {',\n    '    val body =',\n    '      bodyOf(',\n    '        *entries,',\n    '        \"grant_type\" to grantType,',\n    '        \"client_id\" to workos.clientId,',\n    '        \"client_secret\" to workos.apiKey',\n    '      )',\n    '    val config =',\n    '      RequestConfig(',\n    '        method = \"POST\",',\n    '        path = \"/user_management/authenticate\",',\n    '        body = body,',\n    '        requestOptions = requestOptions',\n    '      )',\n    '    return workos.baseClient.request(config, AuthenticateResponse::class.java)',\n    '  }',\n  ];\n}\n\nfunction resolveBodyModel(op: Operation, ctx: EmitterContext): Model | null {\n  const body = op.requestBody;\n  if (!body) return null;\n  if (body.kind !== 'model') return null;\n  return ctx.spec.models.find((m) => m.name === body.name) ?? null;\n}\n\nfunction registerTypeImports(ref: TypeRef, imports: Set<string>, ctx: EmitterContext): void {\n  const mapped = mapTypeRef(ref);\n  for (const imp of implicitImportsFor(mapped)) imports.add(imp);\n\n  // Match the model-emission gate: a `ListMetadata`-shape model that survives\n  // emission (because a non-paginated wrapper still references it) needs its\n  // import here too.\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(ctx.spec.services);\n  const listMetadataNeeded = collectReferencedListMetadataModels(ctx.spec.models, nonPaginatedRefs);\n\n  walk(ref, (r) => {\n    if (r.kind === 'enum') {\n      // When an enum is aliased, import the canonical class instead of the alias.\n      const canonicalName = enumCanonicalMap.get(r.name) ?? r.name;\n      imports.add(`com.workos.types.${className(canonicalName)}`);\n    }\n    if (r.kind === 'model') {\n      const referenced = ctx.spec.models.find((m) => m.name === r.name);\n      if (referenced) {\n        const skipWrapper = isListWrapperModel(referenced) && !nonPaginatedRefs.has(referenced.name);\n        const skipMetadata = isListMetadataModel(referenced) && !listMetadataNeeded.has(referenced.name);\n        if (skipWrapper || skipMetadata) return;\n      }\n      imports.add(`com.workos.models.${className(r.name)}`);\n    }\n  });\n}\n\nfunction walk(ref: TypeRef, fn: (r: TypeRef) => void): void {\n  fn(ref);\n  if (ref.kind === 'array') walk(ref.items, fn);\n  else if (ref.kind === 'map') walk(ref.valueType, fn);\n  else if (ref.kind === 'nullable') walk(ref.inner, fn);\n  else if (ref.kind === 'union') for (const v of ref.variants) walk(v, fn);\n}\n\n/** Sort operation path parameters by their first appearance in the URL template. */\nexport function sortPathParamsByTemplateOrder(op: Operation): Parameter[] {\n  return [...op.pathParams].sort((a, b) => {\n    const posA = op.path.indexOf(`{${a.name}}`);\n    const posB = op.path.indexOf(`{${b.name}}`);\n    return posA - posB;\n  });\n}\n\nfunction escapeKdoc(s: string): string {\n  return s.replace(/\\*\\//g, '*\\u200b/');\n}\n\n// ---------------------------------------------------------------------------\n// Mutually-exclusive parameter group support\n// ---------------------------------------------------------------------------\n\n/**\n * Derive a short Kotlin property name for a parameter within a variant,\n * stripping the group name prefix to avoid stuttering.\n */\nfunction deriveShortPropertyName(paramName: string, groupName: string): string {\n  const prefix = groupName + '_';\n  const stripped = paramName.startsWith(prefix) ? paramName.slice(prefix.length) : paramName;\n  return propertyName(stripped);\n}\n\n/**\n * Generate sealed class definitions for all parameter groups in an operation.\n *\n * [bodyFieldTypes] is a fallback map from wire field name → TypeRef built from\n * the body model. When the oagen core resolves parameter group variants it\n * sometimes loses array/object types, falling back to a primitive string.\n * Cross-referencing the body model corrects that.\n */\nfunction generateSealedClass(\n  group: import('@workos/oagen').ParameterGroup,\n  bodyFieldTypes?: Map<string, TypeRef>,\n): string[] {\n  const lines: string[] = [];\n  const sealedName = sealedGroupName(group.name);\n\n  // KDoc with Kotlin + Java construction examples. Pick the first variant as\n  // a worked example so callers see the variant constructor in both languages\n  // without us having to enumerate every shape.\n  const example = group.variants[0];\n  if (example) {\n    const exampleVariant = className(example.name);\n    const exampleArgs = example.parameters\n      .map((p) => `${deriveShortPropertyName(p.name, group.name)} = \"...\"`)\n      .join(', ');\n    lines.push('/**');\n    lines.push(` * Mutually exclusive ${humanize(group.name)} parameter variants.`);\n    lines.push(' *');\n    lines.push(' * Usage from Kotlin:');\n    lines.push(' * ```kotlin');\n    lines.push(` * val target: ${sealedName} = ${sealedName}.${exampleVariant}(${exampleArgs})`);\n    lines.push(' * ```');\n    lines.push(' *');\n    lines.push(' * Usage from Java:');\n    lines.push(' * ```java');\n    lines.push(\n      ` * ${sealedName} target = new ${sealedName}.${exampleVariant}(${example.parameters.map(() => '\"...\"').join(', ')});`,\n    );\n    lines.push(' * ```');\n    lines.push(' *');\n    lines.push(\n      ` * Java callers may also use the per-variant overloads on the surrounding API class to skip variant construction entirely.`,\n    );\n    lines.push(' */');\n  } else {\n    lines.push(`/** Mutually exclusive ${humanize(group.name)} parameter variants. */`);\n  }\n  lines.push(`sealed class ${sealedName} {`);\n  for (let vi = 0; vi < group.variants.length; vi++) {\n    const variant = group.variants[vi];\n    const variantName = className(variant.name);\n    const fields = variant.parameters.map((p) => {\n      const prop = deriveShortPropertyName(p.name, group.name);\n      // Prefer the body model's field type when available — the IR parameter\n      // group may have lost array/object type info for body fields.\n      const effectiveType = bodyFieldTypes?.get(p.name) ?? p.type;\n      return { decl: `val ${prop}: ${mapTypeRef(effectiveType)}`, name: p.name };\n    });\n    // ktlint requires blank line before each declaration inside a sealed class\n    if (vi > 0) lines.push('');\n    // ktlint class-signature rule requires multi-line constructors\n    lines.push(`  /** Variant: ${humanize(variant.name)}. */`);\n    lines.push(`  data class ${variantName}(`);\n    for (let i = 0; i < fields.length; i++) {\n      const comma = i < fields.length - 1 ? ',' : '';\n      lines.push(`    /** The ${humanize(fields[i].name)}. */`);\n      lines.push(`    ${fields[i].decl}${comma}`);\n    }\n    lines.push(`  ) : ${sealedName}()`);\n  }\n  lines.push('}');\n  lines.push('');\n  return lines;\n}\n\n/** Emit `when` dispatch that serializes a parameter group into query params. */\nfunction emitGroupQueryDispatch(\n  group: import('@workos/oagen').ParameterGroup,\n  prop: string,\n  indent: string,\n  receiverMode = false,\n): string[] {\n  const sealedName = sealedGroupName(group.name);\n  const lines: string[] = [];\n\n  if (group.optional) {\n    lines.push(`${indent}if (${prop} != null) {`);\n    emitWhenBlock(lines, group, sealedName, prop, `${indent}  `, receiverMode);\n    lines.push(`${indent}}`);\n  } else {\n    emitWhenBlock(lines, group, sealedName, prop, indent, receiverMode);\n  }\n  return lines;\n}\n\nfunction assignGroupParameterNames(op: Operation, occupiedNames: Set<string>): Map<string, string> {\n  const names = new Map<string, string>();\n  for (const group of op.parameterGroups ?? []) {\n    const natural = propertyName(sealedGroupName(group.name));\n    const assigned = reserveUniqueGroupParameterName(natural, occupiedNames);\n    names.set(group.name, assigned);\n  }\n  return names;\n}\n\nfunction reserveUniqueGroupParameterName(base: string, occupiedNames: Set<string>): string {\n  if (!occupiedNames.has(base)) {\n    occupiedNames.add(base);\n    return base;\n  }\n\n  const capitalized = `${base.charAt(0).toUpperCase()}${base.slice(1)}`;\n  const prefixed = `group${capitalized}`;\n  if (!occupiedNames.has(prefixed)) {\n    occupiedNames.add(prefixed);\n    return prefixed;\n  }\n\n  let index = 2;\n  while (occupiedNames.has(`${prefixed}${index}`)) index += 1;\n  const fallback = `${prefixed}${index}`;\n  occupiedNames.add(fallback);\n  return fallback;\n}\n\nfunction emitWhenBlock(\n  lines: string[],\n  group: import('@workos/oagen').ParameterGroup,\n  sealedName: string,\n  prop: string,\n  indent: string,\n  receiverMode = false,\n): void {\n  lines.push(`${indent}when (${prop}) {`);\n  for (const variant of group.variants) {\n    const variantName = className(variant.name);\n    const entries = variant.parameters.map((p) => {\n      const fieldProp = deriveShortPropertyName(p.name, group.name);\n      const pair = `${ktLiteral(p.name)} to ${prop}.${fieldProp}`;\n      return receiverMode ? `add(${pair})` : `params += ${pair}`;\n    });\n    if (entries.length === 1) {\n      lines.push(`${indent}  is ${sealedName}.${variantName} -> ${entries[0]}`);\n    } else {\n      lines.push(`${indent}  is ${sealedName}.${variantName} -> {`);\n      for (const e of entries) lines.push(`${indent}    ${e}`);\n      lines.push(`${indent}  }`);\n    }\n  }\n  lines.push(`${indent}}`);\n}\n\n/** Emit `when` dispatch that serializes a parameter group into the request body map. */\nfunction emitGroupBodyDispatch(group: import('@workos/oagen').ParameterGroup, prop: string, indent: string): string[] {\n  const sealedName = sealedGroupName(group.name);\n  const lines: string[] = [];\n\n  if (group.optional) {\n    lines.push(`${indent}if (${prop} != null) {`);\n    emitBodyWhenBlock(lines, group, sealedName, prop, `${indent}  `);\n    lines.push(`${indent}}`);\n  } else {\n    emitBodyWhenBlock(lines, group, sealedName, prop, indent);\n  }\n  return lines;\n}\n\nfunction sealedGroupName(name: string): string {\n  const resolved = className(name);\n  if (resolved === 'Password') return 'CreateUserPassword';\n  if (resolved === 'Role') return 'CreateUserRole';\n  return resolved;\n}\n\nfunction emitBodyWhenBlock(\n  lines: string[],\n  group: import('@workos/oagen').ParameterGroup,\n  sealedName: string,\n  prop: string,\n  indent: string,\n): void {\n  lines.push(`${indent}when (${prop}) {`);\n  for (const variant of group.variants) {\n    const variantName = className(variant.name);\n    const entries = variant.parameters.map((p) => {\n      const fieldProp = deriveShortPropertyName(p.name, group.name);\n      return `body[${ktLiteral(p.name)}] = ${prop}.${fieldProp}`;\n    });\n    if (entries.length === 1) {\n      lines.push(`${indent}  is ${sealedName}.${variantName} -> ${entries[0]}`);\n    } else {\n      lines.push(`${indent}  is ${sealedName}.${variantName} -> {`);\n      for (const e of entries) lines.push(`${indent}    ${e}`);\n      lines.push(`${indent}  }`);\n    }\n  }\n  lines.push(`${indent}}`);\n}\n","import type { ApiSpec, EmitterContext, GeneratedFile, Service } from '@workos/oagen';\nimport { resolveApiClassName, packageSegment, servicePropertyName, buildExportedClassNameSet } from './naming.js';\nimport { getMountTarget } from '../shared/resolved-ops.js';\n\nconst KOTLIN_SRC_PREFIX = 'src/main/kotlin/';\n\n/**\n * Generate service accessor properties for the hand-maintained `WorkOS` class.\n *\n * Each accessor is a `val` property with a custom getter that delegates to\n * `WorkOS.service(...)` for lazy, cached construction. The generated file\n * contains a `WorkOS` class stub with only these properties — the oagen\n * merger deep-merges them into the existing hand-written `WorkOS.kt`.\n *\n * Each referenced service class is hoisted into a top-level `import` so the\n * accessor bodies use the short class name. The live `WorkOS.kt` is marked\n * `@oagen-ignore-file` and won't be regenerated, but the emitter still emits\n * the cleaner shape so future regenerations don't reintroduce the FQN noise.\n */\nexport function generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const targets = deduplicateByMount(spec.services, ctx);\n  if (targets.length === 0) return [];\n\n  const imports = new Set<string>();\n  const accessorLines: string[] = [];\n  const exportedClasses = buildExportedClassNameSet(ctx);\n  for (const mount of targets) {\n    const apiCls = resolveApiClassName(mount, exportedClasses);\n    const fqn = `com.workos.${packageSegment(mount)}.${apiCls}`;\n    imports.add(fqn);\n    const prop = servicePropertyName(mount);\n    accessorLines.push('');\n    accessorLines.push(`  /** Lazily-constructed [${apiCls}] accessor for this [WorkOS] client. */`);\n    accessorLines.push(`  val ${prop}: ${apiCls}`);\n    accessorLines.push('    get() =');\n    accessorLines.push('      service(');\n    accessorLines.push(`        ${apiCls}::class`);\n    accessorLines.push('      ) {');\n    accessorLines.push(`        ${apiCls}(this)`);\n    accessorLines.push('      }');\n  }\n\n  const lines: string[] = [];\n  lines.push('package com.workos');\n  lines.push('');\n  for (const imp of [...imports].sort()) lines.push(`import ${imp}`);\n  if (imports.size > 0) lines.push('');\n  lines.push('open class WorkOS {');\n  for (const line of accessorLines) lines.push(line);\n  lines.push('}');\n  lines.push('');\n\n  return [\n    {\n      path: `${KOTLIN_SRC_PREFIX}com/workos/WorkOS.kt`,\n      content: lines.join('\\n'),\n    },\n  ];\n}\n\nfunction deduplicateByMount(services: Service[], ctx: EmitterContext): string[] {\n  const targets = new Set<string>();\n  for (const s of services) targets.add(getMountTarget(s, ctx));\n  return [...targets].sort();\n}\n","import type {\n  ApiSpec,\n  EmitterContext,\n  GeneratedFile,\n  Operation,\n  Service,\n  Model,\n  TypeRef,\n  ResolvedOperation,\n  ResolvedWrapper,\n} from '@workos/oagen';\nimport { planOperation } from '@workos/oagen';\nimport {\n  resolveApiClassName,\n  packageSegment,\n  resolveMethodName,\n  ktStringLiteral,\n  className,\n  propertyName,\n  domainPropertyName,\n  buildExportedClassNameSet,\n} from './naming.js';\nimport { mapTypeRef } from './type-map.js';\nimport {\n  scopedMountGroups,\n  lookupResolved,\n  buildResolvedLookup,\n  buildHiddenParams,\n  collectGroupedParamNames,\n  isModelInScope,\n  isEnumInScope,\n  fileExistsAfterRun,\n} from '../shared/resolved-ops.js';\nimport { isListWrapperModel, isListMetadataModel } from '../shared/model-utils.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { isHandwrittenOverride } from './overrides.js';\n\nconst TEST_PREFIX = 'src/test/kotlin/';\n\n// Per-item FILE paths (target-root-relative, matching the prior manifest) the\n// model/enum emitters write. The whole-suite test aggregates below reference\n// these classes by name, so they may only list an item whose file will EXIST\n// on disk after the run (in-scope ∪ prior manifest) — otherwise a scoped\n// (`--services`) run references a `Class::class.java` whose `.kt` was never\n// emitted. Must stay in sync with the paths in `models.ts` / `enums.ts`.\nconst MODELS_FILE_PREFIX = 'src/main/kotlin/com/workos/models/';\nconst ENUMS_FILE_PREFIX = 'src/main/kotlin/com/workos/types/';\n\nfunction modelFilePath(modelName: string): string {\n  return `${MODELS_FILE_PREFIX}${className(modelName)}.kt`;\n}\n\nfunction enumFilePath(enumName: string): string {\n  return `${ENUMS_FILE_PREFIX}${className(enumName)}.kt`;\n}\n\n/**\n * Mirror the ISO-8601 hint promotion the resource/model emitters use so tests\n * synthesize values whose Kotlin type matches the generated method signature.\n * Kept in sync with the helpers in `resources.ts` / `models.ts`; if the\n * detection rule changes, update all three.\n */\nconst ISO_8601_DESCRIPTION_RE = /\\bISO[-_ ]?8601\\b/i;\n\nfunction looksLikeIso8601String(description: string | undefined): boolean {\n  if (!description) return false;\n  return ISO_8601_DESCRIPTION_RE.test(description);\n}\n\nfunction promoteIso8601TypeRef(type: TypeRef, description: string | undefined): TypeRef {\n  if (!looksLikeIso8601String(description)) return type;\n  const promote = (t: TypeRef): TypeRef => {\n    if (t.kind === 'primitive' && t.type === 'string' && !t.format) {\n      return { kind: 'primitive', type: 'string', format: 'date-time' };\n    }\n    if (t.kind === 'nullable') return { kind: 'nullable', inner: promote(t.inner) };\n    return t;\n  };\n  return promote(type);\n}\n\n/**\n * Generate one JUnit 5 + WireMock test class per API mount group, plus a\n * cross-cutting model round-trip test.\n *\n * Per mount group the emitter produces:\n *  - A happy-path test for every operation whose required arguments can be\n *    synthesized (primitives, enums, arrays, maps). Deserializes a minimal\n *    JSON response and asserts a non-null result.\n *  - 401/404/429/500 error-mapping tests against one representative operation\n *    in the group.\n *\n * Operations with required arguments we can't synthesize (e.g. a required\n * model object in the request body) fall back to error-only coverage using\n * the representative operation.\n */\nexport function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const mountGroups = scopedMountGroups(ctx);\n  const resolvedLookup = buildResolvedLookup(ctx);\n\n  const exportedClasses = buildExportedClassNameSet(ctx);\n  for (const [mountName, group] of mountGroups) {\n    const content = generateServiceTestClass(mountName, group.operations, ctx, resolvedLookup);\n    if (!content) continue;\n    const pkg = packageSegment(mountName);\n    files.push({\n      path: `${TEST_PREFIX}com/workos/${pkg}/${resolveApiClassName(mountName, exportedClasses)}Test.kt`,\n      content,\n      overwriteExisting: true,\n    });\n  }\n\n  const roundTripFile = generateModelRoundTripTest(spec, ctx);\n  if (roundTripFile) files.push(roundTripFile);\n\n  const forwardCompatFile = generateForwardCompatTest(spec, ctx);\n  if (forwardCompatFile) files.push(forwardCompatFile);\n\n  return files;\n}\n\ninterface OpTest {\n  method: string;\n  httpMethod: string; // lowercase for WireMock\n  pathForWireMock: string;\n  callArgs: string;\n  responseClass: string | null;\n  minimalResponseBody: string;\n  canEmitHappyPath: boolean;\n  imports: Set<string>;\n  /** Wire field names required in the request body — asserted via matchingJsonPath. */\n  requiredBodyPaths: string[];\n  /** `name=value` pairs required on the query string — asserted via matchingRegex. */\n  requiredQueryAssertions: { name: string; valueRegex: string }[];\n  /** Wire field names that must NOT appear as query params (e.g. password on POST). */\n  forbiddenQueryParams: string[];\n  /** Assertions on response fields: { kotlinAccessor, expectedExpr }. */\n  responseAssertions: { accessor: string; expectedExpr: string }[];\n}\n\nfunction generateServiceTestClass(\n  mountName: string,\n  operations: Operation[],\n  ctx: EmitterContext,\n  resolvedLookup: Map<string, ResolvedOperation>,\n): string | null {\n  const imports = new Set<string>();\n  // Base JUnit/exception imports — always present.\n  imports.add('com.workos.common.exceptions.GenericServerException');\n  imports.add('com.workos.common.exceptions.NotFoundException');\n  imports.add('com.workos.common.exceptions.RateLimitException');\n  imports.add('com.workos.common.exceptions.UnauthorizedException');\n  imports.add('com.workos.test.TestBase');\n  imports.add('org.junit.jupiter.api.Assertions.assertNotNull');\n  imports.add('org.junit.jupiter.api.Assertions.assertThrows');\n  imports.add('org.junit.jupiter.api.Test');\n\n  const opTests: OpTest[] = [];\n\n  for (const op of operations) {\n    if (isHandwrittenOverride(op)) continue;\n    const resolved = lookupResolved(op, resolvedLookup);\n    const wrappers = resolved?.wrappers ?? [];\n    if (wrappers.length > 0) {\n      // Union-split operation — emit one test per wrapper.\n      for (const wrapper of wrappers) {\n        const test = buildWrapperTest(op, wrapper, ctx);\n        if (test) opTests.push(test);\n      }\n      continue;\n    }\n\n    const test = buildOperationTest(op, resolved, ctx);\n    if (test) opTests.push(test);\n  }\n\n  if (opTests.length === 0) return null;\n\n  // Deduplicate by method name (split operations map to distinct methods;\n  // non-wrapper operations already have unique names).\n  const seen = new Set<string>();\n  const uniqueTests = opTests.filter((t) => {\n    if (seen.has(t.method)) return false;\n    seen.add(t.method);\n    return true;\n  });\n\n  // Pick a \"representative\" op for error-mapping tests. Prefer the first op\n  // that has no path params (simplest URL to stub). Fall back to the first.\n  const repOp = uniqueTests.find((t) => !t.pathForWireMock.includes('sample-arg')) ?? uniqueTests[0];\n\n  // Only register per-op imports for tests that will actually emit a body.\n  // Ops that can't synthesize a happy path don't contribute to the file, so\n  // their imports (HTTP methods, payload types) would be unused.\n  const httpMethodsUsed = new Set<string>();\n  for (const t of uniqueTests) {\n    if (!t.canEmitHappyPath) continue;\n    t.imports.forEach((i) => imports.add(i));\n    httpMethodsUsed.add(t.httpMethod);\n  }\n  // The representative op is used for error-mapping tests regardless of its\n  // happy-path status, so its type imports are always needed.\n  repOp.imports.forEach((i) => imports.add(i));\n  httpMethodsUsed.add(repOp.httpMethod);\n\n  // Register request-verification imports only for operations that actually\n  // emit verify() calls (i.e., have body/query assertions). This avoids\n  // unused `*RequestedFor` and `urlPathMatching` imports in test files where\n  // no happy-path test has scalar required params.\n  const verifyMethods = new Set<string>();\n  for (const t of uniqueTests) {\n    if (!t.canEmitHappyPath) continue;\n    if (t.requiredBodyPaths.length > 0 || t.requiredQueryAssertions.length > 0 || t.forbiddenQueryParams.length > 0) {\n      verifyMethods.add(t.httpMethod);\n    }\n  }\n  if (verifyMethods.size > 0) {\n    imports.add('com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching');\n    for (const m of verifyMethods) {\n      imports.add(`com.github.tomakehurst.wiremock.client.WireMock.${m}RequestedFor`);\n    }\n  }\n  const anyBody = uniqueTests.some((t) => t.canEmitHappyPath && t.requiredBodyPaths.length > 0);\n  const anyQuery = uniqueTests.some((t) => t.canEmitHappyPath && t.requiredQueryAssertions.length > 0);\n  const anyForbidden = uniqueTests.some((t) => t.canEmitHappyPath && t.forbiddenQueryParams.length > 0);\n  if (anyBody) imports.add('com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath');\n  if (anyQuery) imports.add('com.github.tomakehurst.wiremock.client.WireMock.matching');\n  if (anyForbidden) imports.add('com.github.tomakehurst.wiremock.client.WireMock.absent');\n  // assertEquals is needed when any test has response field assertions.\n  if (uniqueTests.some((t) => t.canEmitHappyPath && t.responseAssertions.length > 0)) {\n    imports.add('org.junit.jupiter.api.Assertions.assertEquals');\n  }\n\n  const pkg = packageSegment(mountName);\n  const apiCls = resolveApiClassName(mountName, buildExportedClassNameSet(ctx));\n\n  // If any operation would emit a disabled placeholder test, preregister\n  // the `Disabled` import before we serialize the header.\n  if (uniqueTests.some((t) => !t.canEmitHappyPath)) {\n    imports.add('org.junit.jupiter.api.Disabled');\n  }\n\n  const lines: string[] = [];\n  lines.push(`package com.workos.${pkg}`);\n  lines.push('');\n  for (const imp of [...imports].sort()) {\n    lines.push(`import ${imp}`);\n  }\n  lines.push('');\n  lines.push(`class ${apiCls}Test : TestBase() {`);\n  lines.push(`  private fun api() = ${apiCls}(createWorkOSClient())`);\n\n  for (const t of uniqueTests) {\n    if (t.canEmitHappyPath) {\n      emitHappyPathTest(lines, t);\n    } else {\n      // Previously these were silently dropped.  Emitting a disabled test\n      // keeps the method visible in test reports so contributors know there\n      // is intentionally no synthesized coverage, rather than being surprised\n      // that the method has zero tests.\n      emitDisabledHappyPathTest(lines, t);\n    }\n  }\n\n  emitErrorTest(lines, '401', 'UnauthorizedException', repOp);\n  emitErrorTest(lines, '404', 'NotFoundException', repOp);\n  emitErrorTest(lines, '429', 'RateLimitException', repOp);\n  emitErrorTest(lines, '500', 'GenericServerException', repOp);\n\n  lines.push('}');\n  lines.push('');\n  return lines.join('\\n');\n}\n\nfunction buildOperationTest(\n  op: Operation,\n  resolved: ResolvedOperation | undefined,\n  ctx: EmitterContext,\n): OpTest | null {\n  const svc = findService(ctx, op);\n  if (!svc) return null;\n  const method = resolveMethodName(op, svc, ctx);\n  const plan = planOperation(op);\n  const mountPackage = packageSegment(resolved?.mountOn ?? svc.name);\n\n  const hidden = buildHiddenParams(resolved);\n\n  // Build call args in the order expected by the generated method signature:\n  //   pathParams ++ requiredQuery ++ requiredBodyFields\n  const imports = new Set<string>();\n  const argParts: string[] = [];\n  const requiredBodyPaths: string[] = [];\n  const requiredQueryAssertions: { name: string; valueRegex: string }[] = [];\n\n  for (const _pp of op.pathParams) argParts.push(ktStringLiteral('sample-arg'));\n\n  const groupedParamNames = collectGroupedParamNames(op);\n\n  const queryFields = op.queryParams.filter((p) => !hidden.has(p.name) && !groupedParamNames.has(p.name));\n  const sortedQuery = [...queryFields].sort((a, b) => (a.required === b.required ? 0 : a.required ? -1 : 1));\n  const sharedQueryBodyParams = new Set<string>();\n  const bodyModel = resolveBodyModel(op, ctx);\n  for (const qp of queryFields) {\n    const matchingBodyField = bodyModel?.fields.find((field) => field.name === qp.name);\n    if (matchingBodyField && mapTypeRef(qp.type) === mapTypeRef(matchingBodyField.type)) {\n      sharedQueryBodyParams.add(qp.name);\n    }\n  }\n  for (const qp of sortedQuery) {\n    if (!qp.required) break;\n    const promotedType = promoteIso8601TypeRef(qp.type, qp.description);\n    const val = synthValue(promotedType, ctx, imports);\n    if (val === null) return null;\n    argParts.push(val);\n    // Best-effort wire assertion: for primitives/strings we know the synthesized\n    // value so we can assert equality; otherwise just assert presence.\n    const regex = queryValueRegexFor(promotedType);\n    if (regex !== null) requiredQueryAssertions.push({ name: qp.name, valueRegex: regex });\n  }\n\n  // Parameter group args — emit as named args (they appear after optionals in the signature)\n  const groupParamNames = assignGroupParameterNames(op, hidden, queryFields, bodyModel, groupedParamNames);\n  for (const group of op.parameterGroups ?? []) {\n    const variant = group.variants[0];\n    const sealedName = sealedGroupName(group.name);\n    const variantName = className(variant.name);\n    const variantArgs = variant.parameters.map((_p) => ktStringLiteral('sample-arg')).join(', ');\n    imports.add(`com.workos.${mountPackage}.${sealedName}`);\n    argParts.push(`${groupParamNames.get(group.name)!} = ${sealedName}.${variantName}(${variantArgs})`);\n  }\n\n  if (bodyModel) {\n    // Body fields always pass; colliding names are renamed (e.g. slug →\n    // bodySlug) by the resources emitter, so every required body field still\n    // needs a test argument here.\n    const bodyFields = bodyModel.fields.filter((f) => !hidden.has(f.name) && !groupedParamNames.has(f.name));\n    const sortedBody = [...bodyFields].sort((a, b) => (a.required === b.required ? 0 : a.required ? -1 : 1));\n    for (const bf of sortedBody) {\n      if (sharedQueryBodyParams.has(bf.name)) continue;\n      if (!bf.required) break;\n      const promotedType = promoteIso8601TypeRef(bf.type, bf.description);\n      const val = synthValue(promotedType, ctx, imports);\n      if (val === null) return null;\n      argParts.push(val);\n      // matchingJsonPath on an array/map body field fails on empty\n      // synthesized collections because JsonPath returns an empty result\n      // set.  Scalar fields always materialize with a concrete value, so\n      // we only assert those paths.\n      if (isScalarBodyField(promotedType)) requiredBodyPaths.push(bf.name);\n    }\n  }\n\n  const plan2 = plan;\n  const responseClass = plan2.isPaginated\n    ? 'Page'\n    : plan2.responseModelName\n      ? className(plan2.responseModelName)\n      : null;\n\n  const minimalBody = buildResponseBody(plan2, ctx);\n\n  // Void/delete methods don't need a response class or body — they succeed\n  // when the call completes without throwing. We can emit a happy-path test\n  // as long as we were able to synthesize all required arguments.\n  const isVoidMethod = responseClass === null;\n  const canEmitHappyPath = isVoidMethod || (responseClass !== null && minimalBody !== null);\n\n  // Build response field assertions for non-paginated, non-array model responses.\n  // Array responses return List<T>, so `result.field` doesn't compile.\n  const responseAssertions =\n    !plan2.isPaginated && !plan2.isArrayResponse && plan2.responseModelName\n      ? buildResponseAssertions(plan2.responseModelName, ctx)\n      : [];\n\n  // For POST/PUT/PATCH with parameter groups, collect all wire field names\n  // from the groups — these must NOT appear as query parameters.\n  const forbiddenQueryParams: string[] = [];\n  const httpUpper = op.httpMethod.toUpperCase();\n  if (['POST', 'PUT', 'PATCH'].includes(httpUpper) && (op.parameterGroups?.length ?? 0) > 0) {\n    for (const group of op.parameterGroups!) {\n      for (const variant of group.variants) {\n        for (const p of variant.parameters) {\n          if (!forbiddenQueryParams.includes(p.name)) forbiddenQueryParams.push(p.name);\n        }\n      }\n    }\n  }\n\n  return {\n    method,\n    httpMethod: op.httpMethod.toLowerCase(),\n    pathForWireMock: op.path.replace(/\\{[^}]+\\}/g, 'sample-arg'),\n    callArgs: argParts.join(', '),\n    responseClass,\n    minimalResponseBody: minimalBody ?? '{}',\n    canEmitHappyPath,\n    imports,\n    requiredBodyPaths,\n    requiredQueryAssertions,\n    forbiddenQueryParams,\n    responseAssertions,\n  };\n}\n\nfunction assignGroupParameterNames(\n  op: Operation,\n  hidden: Set<string>,\n  queryFields: Operation['queryParams'],\n  bodyModel: Model | null,\n  groupedParamNames: Set<string> = new Set(),\n): Map<string, string> {\n  const occupiedNames = new Set<string>();\n\n  for (const pp of op.pathParams) occupiedNames.add(propertyName(pp.name));\n  for (const qp of queryFields) occupiedNames.add(propertyName(qp.name));\n\n  for (const bf of bodyModel?.fields ?? []) {\n    if (hidden.has(bf.name) || groupedParamNames.has(bf.name)) continue;\n    const natural = propertyName(bf.name);\n    if (occupiedNames.has(natural)) {\n      occupiedNames.add(`body${natural.charAt(0).toUpperCase()}${natural.slice(1)}`);\n    } else {\n      occupiedNames.add(natural);\n    }\n  }\n\n  const names = new Map<string, string>();\n  for (const group of op.parameterGroups ?? []) {\n    const natural = propertyName(sealedGroupName(group.name));\n    const assigned = reserveUniqueGroupParameterName(natural, occupiedNames);\n    names.set(group.name, assigned);\n  }\n  return names;\n}\n\nfunction sealedGroupName(name: string): string {\n  const resolved = className(name);\n  if (resolved === 'Password') return 'CreateUserPassword';\n  if (resolved === 'Role') return 'CreateUserRole';\n  return resolved;\n}\n\nfunction reserveUniqueGroupParameterName(base: string, occupiedNames: Set<string>): string {\n  if (!occupiedNames.has(base)) {\n    occupiedNames.add(base);\n    return base;\n  }\n\n  const capitalized = `${base.charAt(0).toUpperCase()}${base.slice(1)}`;\n  const prefixed = `group${capitalized}`;\n  if (!occupiedNames.has(prefixed)) {\n    occupiedNames.add(prefixed);\n    return prefixed;\n  }\n\n  let index = 2;\n  while (occupiedNames.has(`${prefixed}${index}`)) index += 1;\n  const fallback = `${prefixed}${index}`;\n  occupiedNames.add(fallback);\n  return fallback;\n}\n\n/** True if the synthesized body value serializes to a concrete JSON scalar. */\nfunction isScalarBodyField(type: TypeRef): boolean {\n  const inner = type.kind === 'nullable' ? type.inner : type;\n  if (inner.kind === 'primitive') return inner.format !== 'binary';\n  if (inner.kind === 'enum') return true;\n  if (inner.kind === 'literal') return true;\n  return false;\n}\n\n/**\n * When we can recognize the synthesized test value for a query param,\n * return a regex that matches the expected serialized form. Returns null\n * when the value is too complex to assert (e.g. arrays, models).\n */\nfunction queryValueRegexFor(type: TypeRef): string | null {\n  const inner = type.kind === 'nullable' ? type.inner : type;\n  if (inner.kind === 'primitive') {\n    if (inner.format === 'date-time') return null; // OffsetDateTime.now() — not reproducible\n    switch (inner.type) {\n      case 'string':\n        return 'sample-arg';\n      case 'integer':\n        return '0';\n      case 'number':\n        return '0\\\\.0';\n      case 'boolean':\n        return 'false';\n    }\n    return null;\n  }\n  return null;\n}\n\nfunction buildResponseBody(plan: ReturnType<typeof planOperation>, ctx: EmitterContext): string | null {\n  if (plan.isPaginated) {\n    return `{\"data\": [], \"list_metadata\": {\"before\": null, \"after\": null}}`;\n  }\n  if (!plan.responseModelName) return null;\n  const itemJson = synthJsonForModelName(plan.responseModelName, ctx, new Set());\n  if (itemJson === null) return null;\n  // For `type: array` responses, the Kotlin method returns `List<T>` and\n  // Jackson expects a JSON array on the wire, not a single object.\n  if (plan.isArrayResponse) return `[${itemJson}]`;\n  return itemJson;\n}\n\nfunction buildWrapperTest(op: Operation, wrapper: ResolvedWrapper, ctx: EmitterContext): OpTest | null {\n  const method = propertyName(wrapper.name);\n  const imports = new Set<string>();\n  const argParts: string[] = [];\n\n  for (const _pp of op.pathParams) argParts.push(ktStringLiteral('sample-arg'));\n\n  const resolved = resolveWrapperParams(wrapper, ctx);\n  for (const rp of resolved) {\n    if (rp.isOptional) continue;\n    if (!rp.field) {\n      argParts.push(ktStringLiteral('sample-arg'));\n      continue;\n    }\n    const promotedType = promoteIso8601TypeRef(rp.field.type, rp.field.description);\n    const val = synthValue(promotedType, ctx, imports);\n    if (val === null) return null;\n    argParts.push(val);\n  }\n\n  const responseClass = wrapper.responseModelName ? className(wrapper.responseModelName) : null;\n  const minimalBody = wrapper.responseModelName\n    ? synthJsonForModelName(wrapper.responseModelName, ctx, new Set())\n    : null;\n  const isVoidMethod = responseClass === null;\n  const canEmitHappyPath = isVoidMethod || (responseClass !== null && minimalBody !== null);\n  const responseAssertions = wrapper.responseModelName ? buildResponseAssertions(wrapper.responseModelName, ctx) : [];\n\n  return {\n    method,\n    httpMethod: op.httpMethod.toLowerCase(),\n    pathForWireMock: op.path.replace(/\\{[^}]+\\}/g, 'sample-arg'),\n    callArgs: argParts.join(', '),\n    responseClass,\n    minimalResponseBody: minimalBody ?? '{}',\n    canEmitHappyPath,\n    imports,\n    requiredBodyPaths: [],\n    requiredQueryAssertions: [],\n    forbiddenQueryParams: [],\n    responseAssertions,\n  };\n}\n\n/** Synthesize a Kotlin expression for a typed value. Returns null if we cannot. */\nfunction synthValue(type: TypeRef, ctx: EmitterContext, imports: Set<string>): string | null {\n  if (type.kind === 'nullable') {\n    return 'null';\n  }\n  if (type.kind === 'primitive') {\n    if (type.format === 'binary') return 'ByteArray(0)';\n    if (type.format === 'date-time') {\n      imports.add('java.time.OffsetDateTime');\n      return 'OffsetDateTime.now()';\n    }\n    switch (type.type) {\n      case 'string':\n        return '\"sample-arg\"';\n      case 'integer':\n        if (type.format === 'int64') return '0L';\n        return '0';\n      case 'number':\n        return '0.0';\n      case 'boolean':\n        return 'false';\n    }\n    return null;\n  }\n  if (type.kind === 'enum') {\n    const cls = className(type.name);\n    imports.add(`com.workos.types.${cls}`);\n    // Skip `Unknown` (index 0) — serializing the Unknown sentinel throws\n    // because it exists only for forward-compat deserialization. Pick the\n    // first concrete variant instead.\n    return `${cls}.values().first { it != ${cls}.Unknown }`;\n  }\n  if (type.kind === 'array') {\n    // Empty list of the right item type. Kotlin's List<T> is invariant.\n    const itemType = renderTypeForSynthesis(type.items, ctx, imports);\n    if (itemType === null) return null;\n    return `emptyList<${itemType}>()`;\n  }\n  if (type.kind === 'map') {\n    const valueType = renderTypeForSynthesis(type.valueType, ctx, imports);\n    if (valueType === null) return null;\n    return `emptyMap<String, ${valueType}>()`;\n  }\n  if (type.kind === 'literal') {\n    if (typeof type.value === 'string') return ktStringLiteral(type.value);\n    if (typeof type.value === 'number') return String(type.value);\n    if (typeof type.value === 'boolean') return String(type.value);\n    return 'null';\n  }\n  // model / union — too complex to synthesize generically.\n  return null;\n}\n\n/**\n * Render a Kotlin type string for use as a generic type parameter in a\n * synthesized empty collection. Registers any required imports (enums,\n * models). Returns null when the type can't be reduced to a concrete\n * Kotlin class.\n */\nfunction renderTypeForSynthesis(type: TypeRef, ctx: EmitterContext, imports: Set<string>): string | null {\n  if (type.kind === 'model') {\n    const cls = className(type.name);\n    imports.add(`com.workos.models.${cls}`);\n    return cls;\n  }\n  if (type.kind === 'enum') {\n    const cls = className(type.name);\n    imports.add(`com.workos.types.${cls}`);\n    return cls;\n  }\n  if (type.kind === 'union') {\n    // Unions render as Any; an empty list is still valid.\n    return 'Any';\n  }\n  // For everything else (primitives, arrays, maps, literals) the IR mapping\n  // produces a self-contained Kotlin type expression.\n  return mapTypeRef(type);\n}\n\nfunction resolveBodyModel(op: Operation, ctx: EmitterContext): Model | null {\n  const body = op.requestBody;\n  if (!body) return null;\n  if (body.kind !== 'model') return null;\n  return ctx.spec.models.find((m) => m.name === body.name) ?? null;\n}\n\n/**\n * Build a minimal JSON string whose required fields satisfy the model's\n * contract. Nested model references are resolved recursively. Returns null\n * if a required field has a type we can't synthesize (e.g. open union).\n */\nfunction synthJsonForModelName(name: string, ctx: EmitterContext, visited: Set<string>): string | null {\n  if (visited.has(name)) return null;\n  visited.add(name);\n  const model = ctx.spec.models.find((m) => m.name === name);\n  if (!model) return null;\n\n  const entries: string[] = [];\n  for (const field of model.fields) {\n    if (!field.required) continue;\n    const val = synthJsonValue(field.type, ctx, visited);\n    if (val === null) {\n      visited.delete(name);\n      return null;\n    }\n    entries.push(`${JSON.stringify(field.name)}: ${val}`);\n  }\n  visited.delete(name);\n  return `{${entries.join(', ')}}`;\n}\n\n/** Produce a JSON literal (string) for a given IR TypeRef, or null. */\nfunction synthJsonValue(type: TypeRef, ctx: EmitterContext, visited: Set<string>): string | null {\n  if (type.kind === 'nullable') return 'null';\n  if (type.kind === 'primitive') {\n    if (type.format === 'binary') return '\"\"';\n    if (type.format === 'date-time') return '\"2024-01-01T00:00:00Z\"';\n    if (type.format === 'date') return '\"2024-01-01\"';\n    switch (type.type) {\n      case 'string':\n        return '\"sample\"';\n      case 'integer':\n      case 'number':\n        return '0';\n      case 'boolean':\n        return 'false';\n    }\n    return null;\n  }\n  if (type.kind === 'enum') {\n    const em = ctx.spec.enums.find((e) => e.name === type.name);\n    if (em && em.values.length > 0) {\n      return JSON.stringify(String(em.values[0].value));\n    }\n    return '\"unknown\"';\n  }\n  if (type.kind === 'array') return '[]';\n  if (type.kind === 'map') return '{}';\n  if (type.kind === 'literal') {\n    if (typeof type.value === 'string') return JSON.stringify(type.value);\n    if (typeof type.value === 'number') return String(type.value);\n    if (typeof type.value === 'boolean') return String(type.value);\n    return 'null';\n  }\n  if (type.kind === 'model') {\n    return synthJsonForModelName(type.name, ctx, visited);\n  }\n  if (type.kind === 'union') {\n    // Try to pick a synthesizable variant.\n    for (const v of type.variants) {\n      const syn = synthJsonValue(v, ctx, visited);\n      if (syn !== null) return syn;\n    }\n    return null;\n  }\n  return null;\n}\n\n/**\n * Build assertEquals assertions for required scalar fields on a response model.\n * Returns `{ accessor, expectedExpr }` pairs for fields whose JSON value we\n * synthesize and whose Kotlin type we can assert against.\n *\n * Only asserts fields present on ALL structurally-identical models in the\n * dedup group. This avoids broken assertions when the Kotlin class is a\n * typealias pointing at a canonical model with a different field set.\n * As a practical heuristic we restrict to fields that appear on the\n * response model itself (models that get deduplicated share the same fields).\n */\nconst MAX_RESPONSE_ASSERTIONS = 5;\n\nfunction buildResponseAssertions(\n  responseModelName: string | null,\n  ctx: EmitterContext,\n): { accessor: string; expectedExpr: string }[] {\n  if (!responseModelName) return [];\n  const model = ctx.spec.models.find((m) => m.name === responseModelName);\n  if (!model) return [];\n\n  const assertions: { accessor: string; expectedExpr: string }[] = [];\n  for (const field of model.fields) {\n    if (!field.required) continue;\n    if (assertions.length >= MAX_RESPONSE_ASSERTIONS) break;\n    // DOMAIN identifier: the property accessor on the deserialized model.\n    // Honors a `domainName` override; the synthesized JSON above keys off\n    // `field.name` (the wire key).\n    const ktProp = domainPropertyName(field);\n    const type = field.type;\n    if (type.kind === 'primitive') {\n      if (type.format === 'date-time') continue;\n      switch (type.type) {\n        case 'string':\n          assertions.push({ accessor: ktProp, expectedExpr: '\"sample\"' });\n          break;\n        case 'integer':\n          assertions.push({ accessor: ktProp, expectedExpr: type.format === 'int32' ? '0' : '0L' });\n          break;\n        case 'number':\n          assertions.push({ accessor: ktProp, expectedExpr: '0.0' });\n          break;\n        case 'boolean':\n          assertions.push({ accessor: ktProp, expectedExpr: 'false' });\n          break;\n      }\n    } else if (type.kind === 'literal') {\n      if (typeof type.value === 'string') {\n        assertions.push({ accessor: ktProp, expectedExpr: ktStringLiteral(type.value) });\n      } else if (typeof type.value === 'number') {\n        assertions.push({ accessor: ktProp, expectedExpr: String(type.value) });\n      } else if (typeof type.value === 'boolean') {\n        assertions.push({ accessor: ktProp, expectedExpr: String(type.value) });\n      }\n    }\n  }\n  return assertions;\n}\n\nfunction emitHappyPathTest(lines: string[], t: OpTest): void {\n  lines.push('');\n  lines.push(`  @Test`);\n  const isVoid = t.responseClass === null;\n  const testLabel = isVoid ? `${t.method} completes without throwing` : `${t.method} returns a typed response`;\n  lines.push(`  fun \\`${testLabel}\\`() {`);\n\n  // Void/delete methods don't return a body — stub with 200 and empty body.\n  const statusCode = isVoid ? (t.httpMethod === 'delete' ? 204 : 200) : 200;\n  if (isVoid) {\n    lines.push(\n      `    stubResponse(${ktStringLiteral(t.httpMethod.toUpperCase())}, ${ktStringLiteral(t.pathForWireMock)}, ${statusCode})`,\n    );\n  } else {\n    const bodyString = ktStringLiteral(t.minimalResponseBody);\n    const stubLine = `    stubResponse(${ktStringLiteral(t.httpMethod.toUpperCase())}, ${ktStringLiteral(t.pathForWireMock)}, ${statusCode}, ${bodyString})`;\n    if (stubLine.length <= KTLINT_MAX_LINE_LENGTH) {\n      lines.push(stubLine);\n    } else {\n      lines.push('    stubResponse(');\n      lines.push(`      ${ktStringLiteral(t.httpMethod.toUpperCase())},`);\n      lines.push(`      ${ktStringLiteral(t.pathForWireMock)},`);\n      lines.push(`      ${statusCode},`);\n      emitStubResponseBody(lines, '      ', t.minimalResponseBody);\n      lines.push('    )');\n    }\n  }\n\n  if (isVoid) {\n    emitCall(lines, '    ', `api().${t.method}`, t.callArgs);\n  } else {\n    emitCall(lines, '    ', `val result = api().${t.method}`, t.callArgs);\n    lines.push('    assertNotNull(result)');\n    // Emit exact-value assertions for required scalar fields in the response.\n    for (const a of t.responseAssertions) {\n      lines.push(`    assertEquals(${a.expectedExpr}, result.${a.accessor})`);\n    }\n  }\n\n  // Verify the outbound request shape.  Body fields and query assertions\n  // live on the `OpTest` and are only emitted when we know the synthesized\n  // arguments produce a deterministic wire representation.\n  if (t.requiredBodyPaths.length > 0 || t.requiredQueryAssertions.length > 0 || t.forbiddenQueryParams.length > 0) {\n    lines.push('    wireMockRule.verify(');\n    lines.push(`      ${t.httpMethod}RequestedFor(urlPathMatching(${ktStringLiteral(t.pathForWireMock)}))`);\n    for (const path of t.requiredBodyPaths) {\n      lines.push(`        .withRequestBody(matchingJsonPath(${ktStringLiteral(`$.${path}`)}))`);\n    }\n    for (const qa of t.requiredQueryAssertions) {\n      lines.push(`        .withQueryParam(${ktStringLiteral(qa.name)}, matching(${ktStringLiteral(qa.valueRegex)}))`);\n    }\n    // Assert sensitive fields from parameter groups never leak into the URL.\n    for (const name of t.forbiddenQueryParams) {\n      lines.push(`        .withQueryParam(${ktStringLiteral(name)}, absent())`);\n    }\n    lines.push('    )');\n  }\n  lines.push('  }');\n}\n\n/**\n * Emit a `@Disabled` placeholder for operations whose happy-path arguments\n * could not be synthesized (for example, a required body union that the\n * test generator cannot construct).  The disabled test keeps the method in\n * the test report so CI surfaces the coverage gap.\n */\nfunction emitDisabledHappyPathTest(lines: string[], t: OpTest): void {\n  lines.push('');\n  lines.push(`  @Test`);\n  lines.push(`  @Disabled(\"generator: could not synthesize required arguments for ${t.method}\")`);\n  lines.push(`  fun \\`${t.method} returns a typed response\\`() {`);\n  lines.push(`    // Intentionally empty: the generator could not synthesize required arguments.`);\n  lines.push('  }');\n}\n\nfunction emitErrorTest(lines: string[], status: string, exceptionName: string, t: OpTest): void {\n  lines.push('');\n  lines.push(`  @Test`);\n  lines.push(`  fun \\`${t.method} translates ${status} to ${exceptionName}\\`() {`);\n  lines.push(\n    `    stubResponse(${ktStringLiteral(t.httpMethod.toUpperCase())}, ${ktStringLiteral(t.pathForWireMock)}, ${status})`,\n  );\n  lines.push(`    assertThrows(${exceptionName}::class.java) {`);\n  emitCall(lines, '      ', `api().${t.method}`, t.callArgs);\n  lines.push('    }');\n  lines.push('  }');\n}\n\n/**\n * Emit `val json = \"...\"` on a single line when it fits within KTLINT_MAX_LINE_LENGTH,\n * otherwise split the string literal across lines joined with `+`.\n */\nfunction emitJsonVal(lines: string[], indent: string, rawJson: string): void {\n  const encoded = ktStringLiteral(rawJson);\n  const singleLine = `${indent}val json = ${encoded}`;\n  if (singleLine.length <= KTLINT_MAX_LINE_LENGTH) {\n    lines.push(singleLine);\n    return;\n  }\n  // ktlint: \"A multiline expression should start on a new line\"\n  lines.push(`${indent}val json =`);\n  // ktlint indent rules (with indent_size=2, continuation_indent=2):\n  //   first continuation after `=`:  indent + 2  (e.g. 6 spaces)\n  //   subsequent `+` continuations:  indent + 4  (e.g. 8 spaces)\n  const firstIndent = `${indent}  `;\n  const restIndent = `${indent}    `;\n  // Budget for the widest indent so every chunk fits.\n  const maxChunkLineLen = KTLINT_MAX_LINE_LENGTH - restIndent.length - 2; // 2 for \" +\"\n  const chunks = splitEscapedStringLiteral(encoded, maxChunkLineLen);\n  for (let i = 0; i < chunks.length; i++) {\n    const suffix = i === chunks.length - 1 ? '' : ' +';\n    const lineIndent = i === 0 ? firstIndent : restIndent;\n    lines.push(`${lineIndent}${chunks[i]}${suffix}`);\n  }\n}\n\n/**\n * Emit the body argument for a multi-line `stubResponse(...)` call. When the\n * encoded literal fits on one line it is emitted directly; otherwise it is\n * broken into string-plus-string chunks joined with `+`.\n */\nfunction emitStubResponseBody(lines: string[], indent: string, body: string): void {\n  const encoded = ktStringLiteral(body);\n  if (`${indent}${encoded}`.length <= KTLINT_MAX_LINE_LENGTH) {\n    lines.push(`${indent}${encoded}`);\n    return;\n  }\n  const continuationIndent = indent.length + 2;\n  const maxChunkLineLen = KTLINT_MAX_LINE_LENGTH - continuationIndent - 2;\n  const chunks = splitEscapedStringLiteral(encoded, maxChunkLineLen);\n  for (let i = 0; i < chunks.length; i++) {\n    const suffix = i === chunks.length - 1 ? '' : ' +';\n    const prefix = i === 0 ? '' : '  ';\n    lines.push(`${indent}${prefix}${chunks[i]}${suffix}`);\n  }\n}\n\n/**\n * Split a Kotlin string literal (including its wrapping quotes) into\n * smaller literals such that each one is <= [maxChunkLen] characters. Splits\n * preferentially after commas or spaces, and never inside a `\\X` escape\n * sequence.\n */\nfunction splitEscapedStringLiteral(literal: string, maxChunkLen: number): string[] {\n  // Strip the outer wrapping quotes.\n  const inner = literal.slice(1, -1);\n  const chunks: string[] = [];\n  // Reserve 2 chars for the wrapping quotes of each output chunk.\n  const target = Math.max(20, maxChunkLen - 2);\n  let i = 0;\n  while (i < inner.length) {\n    if (inner.length - i <= target) {\n      chunks.push(`\"${inner.slice(i)}\"`);\n      break;\n    }\n    // Prefer a split right after a comma or space within the window. The\n    // window is `[i, i + target - 1]` so `safeEnd = j + 1 <= i + target`,\n    // keeping the emitted chunk content <= `target` characters long.\n    const windowEnd = i + target - 1;\n    let safeEnd = -1;\n    for (let j = windowEnd; j > i; j--) {\n      const ch = inner[j];\n      if ((ch === ',' || ch === ' ') && !endsWithOddBackslash(inner, i, j)) {\n        safeEnd = j + 1;\n        break;\n      }\n    }\n    if (safeEnd === -1) {\n      // No comma/space — back up over any trailing backslash pair.\n      let end = i + target;\n      while (end > i && endsWithOddBackslash(inner, i, end)) end--;\n      safeEnd = end;\n    }\n    chunks.push(`\"${inner.slice(i, safeEnd)}\"`);\n    i = safeEnd;\n  }\n  return chunks;\n}\n\n/** True if the number of trailing `\\` chars in `inner[start..pos-1]` is odd. */\nfunction endsWithOddBackslash(inner: string, start: number, pos: number): boolean {\n  let count = 0;\n  for (let k = pos - 1; k >= start && inner[k] === '\\\\'; k--) count++;\n  return count % 2 === 1;\n}\n\n/**\n * Emit `<prefix>(<args>)` either on a single line or, if that would exceed\n * ktlint's 140-char limit, broken across multiple lines with one argument\n * per line. [indent] is the leading whitespace on the expression line.\n *\n * When splitting a `val name = call.expr(...)` form, the assignment's RHS is\n * moved to its own line (ktlint: \"A multiline expression should start on a\n * new line\").\n */\nfunction emitCall(lines: string[], indent: string, prefix: string, args: string): void {\n  const single = `${indent}${prefix}(${args})`;\n  if (single.length <= KTLINT_MAX_LINE_LENGTH) {\n    lines.push(single);\n    return;\n  }\n  // If the prefix is an assignment (`val x = expr.call`), split the assignment\n  // so the expression starts on its own line with an extra indent level.\n  const assignMatch = /^((?:val|var) [^=]+=)\\s*(.+)$/.exec(prefix);\n  const exprPrefix = assignMatch ? assignMatch[2] : prefix;\n  const exprIndent = assignMatch ? `${indent}  ` : indent;\n  if (assignMatch) lines.push(`${indent}${assignMatch[1]}`);\n  lines.push(`${exprIndent}${exprPrefix}(`);\n  const argIndent = `${exprIndent}  `;\n  const parts = splitTopLevelArgs(args);\n  for (let i = 0; i < parts.length; i++) {\n    const suffix = i === parts.length - 1 ? '' : ',';\n    lines.push(`${argIndent}${parts[i]}${suffix}`);\n  }\n  lines.push(`${exprIndent})`);\n}\n\nconst KTLINT_MAX_LINE_LENGTH = 140;\n\n/** Split a call-argument string on top-level commas (ignoring nested parens/quotes). */\nfunction splitTopLevelArgs(args: string): string[] {\n  const out: string[] = [];\n  let depth = 0;\n  let inString = false;\n  let buf = '';\n  for (let i = 0; i < args.length; i++) {\n    const ch = args[i];\n    if (inString) {\n      buf += ch;\n      if (ch === '\\\\' && i + 1 < args.length) {\n        buf += args[++i];\n      } else if (ch === '\"') {\n        inString = false;\n      }\n      continue;\n    }\n    if (ch === '\"') {\n      inString = true;\n      buf += ch;\n      continue;\n    }\n    if (ch === '(' || ch === '<' || ch === '[' || ch === '{') depth++;\n    else if (ch === ')' || ch === '>' || ch === ']' || ch === '}') depth--;\n    if (ch === ',' && depth === 0) {\n      out.push(buf.trim());\n      buf = '';\n      continue;\n    }\n    buf += ch;\n  }\n  if (buf.trim()) out.push(buf.trim());\n  return out;\n}\n\n/**\n * True when a TypeRef is safe for JSON round-trip testing: primitives,\n * nullable wrappers around primitives, literals, and empty arrays/maps.\n * Nested model and enum references are excluded because Jackson\n * reserializes them with additional optional-field defaults that weren't\n * in the original fixture JSON.\n */\nfunction isRoundTripSafeType(ref: TypeRef): boolean {\n  if (ref.kind === 'primitive') return true;\n  if (ref.kind === 'literal') return true;\n  if (ref.kind === 'nullable') return isRoundTripSafeType(ref.inner);\n  if (ref.kind === 'array') return isRoundTripSafeType(ref.items);\n  if (ref.kind === 'map') return isRoundTripSafeType(ref.valueType);\n  return false;\n}\n\nfunction generateModelRoundTripTest(spec: ApiSpec, ctx: EmitterContext): GeneratedFile | null {\n  // Collect round-trippable models: non-list-wrapper data classes for which\n  // we can synthesize a complete JSON fixture (required fields only).\n  // Uses synthJsonForModelName which handles primitives, enums, nested\n  // models, arrays, maps, and literals — much broader than the old\n  // primitives-only filter.\n  const targets: { model: Model; json: string }[] = [];\n  const seenModelClassNames = new Set<string>();\n  for (const m of spec.models) {\n    if (isListWrapperModel(m) || isListMetadataModel(m)) continue;\n    if (m.fields.length === 0) continue;\n    // AGGREGATE gate: this whole-suite test references `${cls}::class.java`. In a\n    // scoped run only in-scope model files are emitted, so skip a brand-new\n    // OUT-OF-SCOPE model whose `.kt` won't exist on disk. In-scope ∪ prior\n    // manifest is retained; a full run keeps everything (gate is inert).\n    if (!fileExistsAfterRun(modelFilePath(m.name), isModelInScope(m.name, ctx), ctx)) continue;\n    const cls = className(m.name);\n    if (seenModelClassNames.has(cls)) continue;\n    seenModelClassNames.add(cls);\n    // Only include models where ALL fields are required AND all types are\n    // round-trip safe (primitives, nullable, literals, simple arrays/maps).\n    // Nested model/enum references break round-trip because Jackson\n    // reserializes with additional default fields not in the original JSON.\n    if (!m.fields.every((f) => f.required && isRoundTripSafeType(f.type))) continue;\n    const json = synthJsonForModelName(m.name, ctx, new Set());\n    if (json !== null) targets.push({ model: m, json });\n  }\n  if (targets.length === 0) return null;\n\n  const lines: string[] = [\n    'package com.workos.models',\n    '',\n    'import com.workos.common.json.ObjectMapperFactory',\n    'import org.junit.jupiter.api.Assertions.assertEquals',\n    'import org.junit.jupiter.api.Test',\n    '',\n    'class GeneratedModelRoundTripTest {',\n    '  private val mapper = ObjectMapperFactory.create()',\n  ];\n\n  for (const { model, json } of targets) {\n    const cls = className(model.name);\n    lines.push('', '  @Test', `  fun \\`${cls} round-trips through Jackson\\`() {`);\n    emitJsonVal(lines, '    ', json);\n    lines.push(\n      `    val parsed = mapper.readValue(json, ${cls}::class.java)`,\n      '    val reserialized = mapper.writeValueAsString(parsed)',\n      '    val tree1 = mapper.readTree(json)',\n      '    val tree2 = mapper.readTree(reserialized)',\n      '    assertEquals(tree1, tree2)',\n      '  }',\n    );\n  }\n\n  lines.push('}', '');\n\n  return {\n    path: `${TEST_PREFIX}com/workos/models/GeneratedModelRoundTripTest.kt`,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\n/**\n * Emit a forward-compatibility suite that proves:\n *  - unrecognized enum wire values map to the `Unknown` sentinel rather\n *    than throwing (covers the Jackson @JsonEnumDefaultValue wiring);\n *  - unknown top-level JSON fields on a model do not fail deserialization\n *    (FAIL_ON_UNKNOWN_PROPERTIES=false);\n *  - ISO-8601 timestamps round-trip through `OffsetDateTime` without\n *    precision loss.\n *\n * Tests a representative set of enums (up to MAX_ENUM_FORWARD_COMPAT) and\n * the first synthesizable model.\n */\nconst MAX_ENUM_FORWARD_COMPAT = 15;\n\nfunction generateForwardCompatTest(spec: ApiSpec, ctx: EmitterContext): GeneratedFile | null {\n  // Select multiple enums for forward-compat testing, not just the first.\n  // AGGREGATE gate: each selected enum is imported as `com.workos.types.X`. In a\n  // scoped run only in-scope enum files are emitted, so skip a brand-new\n  // OUT-OF-SCOPE enum whose `.kt` won't exist on disk (in-scope ∪ prior manifest\n  // retained; full run keeps everything).\n  const enumTargets = spec.enums\n    .filter((e) => e.values.length > 0)\n    .filter((e) => fileExistsAfterRun(enumFilePath(e.name), isEnumInScope(e.name, ctx), ctx))\n    .slice(0, MAX_ENUM_FORWARD_COMPAT);\n  const modelTarget = spec.models.find((m) => {\n    if (isListWrapperModel(m) || isListMetadataModel(m)) return false;\n    if (m.fields.length === 0) return false;\n    // Same aggregate gate as the round-trip test: the model is referenced as\n    // `${cls}::class.java`, so it must exist on disk after the run.\n    if (!fileExistsAfterRun(modelFilePath(m.name), isModelInScope(m.name, ctx), ctx)) return false;\n    return synthJsonForModelName(m.name, ctx, new Set()) !== null;\n  });\n  if (enumTargets.length === 0 && !modelTarget) return null;\n\n  const enumImports = new Set<string>();\n  for (const e of enumTargets) enumImports.add(`com.workos.types.${className(e.name)}`);\n\n  const lines: string[] = [\n    'package com.workos.models',\n    '',\n    'import com.fasterxml.jackson.core.type.TypeReference',\n    'import com.workos.common.json.ObjectMapperFactory',\n  ];\n  for (const imp of [...enumImports].sort()) lines.push(`import ${imp}`);\n  lines.push(\n    'import org.junit.jupiter.api.Assertions.assertEquals',\n    'import org.junit.jupiter.api.Assertions.assertNotNull',\n    'import org.junit.jupiter.api.Test',\n    '',\n    'class GeneratedForwardCompatTest {',\n    '  private val mapper = ObjectMapperFactory.create()',\n  );\n\n  for (const enumTarget of enumTargets) {\n    const enumCls = className(enumTarget.name);\n    lines.push(\n      '',\n      `  @Test`,\n      `  fun \\`unknown ${enumCls} wire values deserialize to Unknown\\`() {`,\n      '    // Simulates a future server release that introduces a new enum variant.',\n      `    val parsed = mapper.readValue(${ktStringLiteral('\"__oagen_new_variant__\"')}, ${enumCls}::class.java)`,\n      `    assertEquals(${enumCls}.Unknown, parsed)`,\n      '  }',\n    );\n  }\n\n  if (modelTarget) {\n    const modelCls = className(modelTarget.name);\n    const jsonLiteral = synthJsonForModelName(modelTarget.name, ctx, new Set())!;\n    const jsonWithExtra = jsonLiteral.replace('{', '{\"__oagen_future_field__\": \"ignored\", ');\n    lines.push('', `  @Test`, `  fun \\`${modelCls} ignores unknown JSON fields\\`() {`);\n    emitJsonVal(lines, '    ', jsonWithExtra);\n    lines.push(`    val parsed = mapper.readValue(json, ${modelCls}::class.java)`, '    assertNotNull(parsed)', '  }');\n  }\n\n  lines.push(\n    '',\n    '  @Test',\n    '  fun `OffsetDateTime round-trips through the configured mapper`() {',\n    '    val jsonIn = \"\\\\\"2024-01-15T12:34:56.789Z\\\\\"\"',\n    '    val parsed = mapper.readValue(jsonIn, object : TypeReference<java.time.OffsetDateTime>() {})',\n    '    val reserialized = mapper.writeValueAsString(parsed)',\n    '    // Jackson serializes OffsetDateTime as an ISO-8601 string when',\n    '    // WRITE_DATES_AS_TIMESTAMPS is disabled. The wire form may choose a',\n    '    // different offset representation (e.g. \"+00:00\" vs \"Z\") so compare',\n    '    // logical equality of the parsed value rather than the raw string.',\n    '    val reparsed = mapper.readValue(reserialized, object : TypeReference<java.time.OffsetDateTime>() {})',\n    '    assertEquals(parsed.toInstant(), reparsed.toInstant())',\n    '  }',\n    '}',\n    '',\n  );\n\n  return {\n    path: `${TEST_PREFIX}com/workos/models/GeneratedForwardCompatTest.kt`,\n    content: lines.join('\\n'),\n    overwriteExisting: true,\n  };\n}\n\nfunction findService(ctx: EmitterContext, op: Operation): Service | undefined {\n  for (const service of ctx.spec.services) {\n    if (service.operations.includes(op)) return service;\n  }\n  return undefined;\n}\n","import type { ApiSpec, EmitterContext, OperationsMap } from '@workos/oagen';\nimport { resolveMethodName, servicePropertyName, resolveClassName } from './naming.js';\nimport { buildResolvedLookup, lookupResolved, getMountTarget } from '../shared/resolved-ops.js';\nimport { propertyName } from './naming.js';\nimport { isHandwrittenOverride } from './overrides.js';\n\n/**\n * Build the operation-to-SDK-method mapping for the manifest.\n *\n * The `service` is the camelCase accessor property on the main `WorkOS`\n * client (e.g., `organizations`).\n *\n * For polymorphic/split operations (e.g., authenticate -> 8 methods), the\n * manifest emits an array of methods so each variant is addressable.\n */\nexport function buildOperationsMap(spec: ApiSpec, ctx: EmitterContext): OperationsMap {\n  const manifest: OperationsMap = {};\n  const resolvedLookup = buildResolvedLookup(ctx);\n\n  for (const service of spec.services) {\n    const mountTarget = getMountTarget(service, ctx);\n    const prop = servicePropertyName(resolveClassName(service, ctx) || mountTarget);\n    for (const op of service.operations) {\n      if (isHandwrittenOverride(op)) continue;\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n\n      // Check if this operation is split into wrapper methods\n      const resolved = lookupResolved(op, resolvedLookup);\n      const wrappers = resolved?.wrappers ?? [];\n\n      // Use the resolved mount target for correct service attribution\n      const resolvedProp = resolved ? servicePropertyName(resolved.mountOn) : prop;\n\n      if (wrappers.length > 0) {\n        // Polymorphic operation: emit an array of methods\n        const methods = wrappers.map((w) => ({\n          sdkMethod: propertyName(w.name),\n          service: resolvedProp,\n        }));\n        manifest[httpKey] = methods;\n      } else {\n        const method = resolveMethodName(op, service, ctx);\n        manifest[httpKey] = { sdkMethod: method, service: resolvedProp };\n      }\n    }\n  }\n\n  return manifest;\n}\n","import type {\n  Emitter,\n  EmitterContext,\n  FormatCommand,\n  GeneratedFile,\n  ApiSpec,\n  Model,\n  Enum,\n  Service,\n} from '@workos/oagen';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { generateModels } from './models.js';\nimport { generateEnums } from './enums.js';\nimport { generateResources } from './resources.js';\nimport { generateClient } from './client.js';\nimport { generateTests } from './tests.js';\nimport { buildOperationsMap } from './manifest.js';\nimport { enrichModelsFromSpec, getSyntheticEnums } from '../shared/model-utils.js';\nimport { flattenDiscriminatedUnionFields } from '../shared/union-flatten.js';\nimport { AUTOGEN_NOTICE } from '../shared/file-header.js';\n\n/** Ensure every generated file ends with a trailing newline. */\nfunction ensureTrailingNewlines(files: GeneratedFile[]): GeneratedFile[] {\n  for (const f of files) {\n    if (f.content && !f.content.endsWith('\\n')) {\n      f.content += '\\n';\n    }\n  }\n  return files;\n}\n\nexport const kotlinEmitter: Emitter = {\n  language: 'kotlin',\n\n  generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n    const enriched = enrichModelsFromSpec(models);\n    // Kotlin uses sealed interfaces (WorkOSEvent) for event dispatch rather\n    // than class inheritance, so discriminated base models like EventSchema\n    // need their fields restored to be emitted as proper data classes.\n    // enrichModelsFromSpec clears fields for dispatcher-capable languages;\n    // restore the originals here so Kotlin emits a full data class.\n    const originalByName = new Map(models.map((m) => [m.name, m]));\n    const kotlinModels = enriched.map((m) => {\n      if ((m as any).discriminator && m.fields.length === 0) {\n        const original = originalByName.get(m.name);\n        if (original && original.fields.length > 0) {\n          return { ...m, fields: original.fields };\n        }\n      }\n      return m;\n    });\n    // Kotlin renders a discriminated-union field as its first variant's data\n    // class, so fields unique to later variants (organization_id on the user\n    // owner) are lost. Flatten such unions into one superset data class so\n    // every variant field is reachable.\n    return ensureTrailingNewlines(generateModels(flattenDiscriminatedUnionFields(kotlinModels), ctx));\n  },\n\n  generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n    // Merge synthetic enums produced during model enrichment (inline oneOf\n    // definitions) so they get proper enum class files.\n    const syntheticEnums = getSyntheticEnums();\n    return ensureTrailingNewlines(generateEnums([...enums, ...syntheticEnums], ctx));\n  },\n\n  generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateResources(services, ctx));\n  },\n\n  generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateClient(spec, ctx));\n  },\n\n  generateErrors(_ctx: EmitterContext): GeneratedFile[] {\n    // Exception hierarchy is hand-maintained in workos-kotlin (see Phase 2).\n    return [];\n  },\n\n  generateTypeSignatures(): GeneratedFile[] {\n    return [];\n  },\n\n  generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    // Pass enriched models so round-trip tests see the full field set\n    // (including optional oneOf-enriched fields and flattened discriminated-\n    // union owner fields) and can filter accurately.\n    const enrichedModels = flattenDiscriminatedUnionFields(enrichModelsFromSpec(spec.models));\n    const enrichedSpec: ApiSpec = { ...spec, models: enrichedModels };\n    return ensureTrailingNewlines(generateTests(enrichedSpec, { ...ctx, spec: enrichedSpec }));\n  },\n\n  buildOperationsMap(spec: ApiSpec, ctx: EmitterContext) {\n    return buildOperationsMap(spec, ctx);\n  },\n\n  fileHeader(): string {\n    return `// ${AUTOGEN_NOTICE}`;\n  },\n\n  formatCommand(targetDir: string): FormatCommand | null {\n    // `./gradlew ktlintFormat` fixes whitespace, import ordering, and most\n    // wrapping/line-length violations across the whole source set. The file\n    // list appended by oagen is ignored — Gradle reformats every Kotlin\n    // file. oagen's writer already runs the spawned process with\n    // `cwd: targetDir`, so we don't `cd` again (an additional `cd` re-resolves\n    // a relative `targetDir` against itself and silently lands in a missing\n    // directory, which is what was causing this command to no-op in practice).\n    if (!fs.existsSync(path.join(targetDir, 'gradlew'))) return null;\n    return {\n      cmd: 'bash',\n      args: ['-c', './gradlew ktlintFormat --quiet >/dev/null 2>&1; true'],\n    };\n  },\n};\n","import type { Operation, Service, EmitterContext } from '@workos/oagen';\nimport { toPascalCase, toSnakeCase } from '@workos/oagen';\nimport { buildResolvedLookup, lookupMethodName, getMountTarget } from '../shared/resolved-ops.js';\nimport { stripUrnPrefix, applyAcronymFixes } from '../shared/naming-utils.js';\nimport {\n  buildExportedClassNameSet as buildExportedClassNameSetShared,\n  resolveServiceTarget as resolveServiceTargetShared,\n} from '../shared/service-name-collision.js';\n\n/**\n * Ruby class names that collide with core classes. When a model name resolves\n * to one of these, suffix with \"Model\".\n */\nconst RUBY_RESERVED_CLASS_NAMES = new Set([\n  'Array',\n  'Hash',\n  'String',\n  'Integer',\n  'Float',\n  'Object',\n  'Module',\n  'Class',\n  'Comparable',\n  'Enumerable',\n  'Range',\n  'Proc',\n  'Method',\n  'Regexp',\n  'Symbol',\n  'File',\n  'Dir',\n  'IO',\n  'Data',\n]);\n\n/** PascalCase class name with acronym preservation. */\nexport function className(name: string): string {\n  let result = applyAcronymFixes(toPascalCase(stripUrnPrefix(name)));\n  if (RUBY_RESERVED_CLASS_NAMES.has(result)) {\n    result += 'Model';\n  }\n  return result;\n}\n\n/** snake_case file name (without extension). */\nexport function fileName(name: string): string {\n  return toSnakeCase(stripUrnPrefix(name));\n}\n\n/** snake_case method name. */\nexport function methodName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/** snake_case field name. */\nexport function fieldName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/**\n * snake_case domain field name for a model field, honoring a `domainName`\n * override (set via the `fieldHints` config) so a wire field can surface under\n * a friendlier name. The wire key (still derived from `field.name`) is what\n * gets sent/received over the wire — only the domain attr/accessor name changes.\n */\nexport function domainFieldName(field: { name: string; domainName?: string }): string {\n  return toSnakeCase(field.domainName ?? field.name);\n}\n\n/**\n * Ruby reserved words that cannot be used as parameter names.\n * When a path/query param name collides, suffix with underscore.\n */\nconst RUBY_RESERVED_WORDS = new Set([\n  'BEGIN',\n  'END',\n  'alias',\n  'and',\n  'begin',\n  'break',\n  'case',\n  'class',\n  'def',\n  'defined?',\n  'do',\n  'else',\n  'elsif',\n  'end',\n  'ensure',\n  'false',\n  'for',\n  'if',\n  'in',\n  'module',\n  'next',\n  'nil',\n  'not',\n  'or',\n  'redo',\n  'rescue',\n  'retry',\n  'return',\n  'self',\n  'super',\n  'then',\n  'true',\n  'undef',\n  'unless',\n  'until',\n  'when',\n  'while',\n  'yield',\n  // Common methods on Object/Kernel that shouldn't be shadowed\n  'hash',\n  'send',\n  'class',\n  'method',\n  'tap',\n]);\n\n/**\n * Safe parameter name for path/query params that avoids shadowing Ruby reserved words.\n */\nexport function safeParamName(name: string): string {\n  const snake = toSnakeCase(name);\n  return RUBY_RESERVED_WORDS.has(snake) ? `${snake}_` : snake;\n}\n\n/** snake_case module/directory name. */\nexport function moduleName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/**\n * Build the set of model + enum Ruby class names that the SDK exposes under\n * `WorkOS::`. Used to detect collisions with operation-client class names —\n * a colliding service gets a `Service` suffix (`OrganizationMembershipService`)\n * so it doesn't shadow the model class under Zeitwerk's collapsed namespace.\n */\nexport function buildExportedClassNameSet(ctx: EmitterContext): Set<string> {\n  return buildExportedClassNameSetShared(ctx, className);\n}\n\n/**\n * Resolve a service's mount-target identifier, appending `Service` on\n * collision with an exported model/enum class name. The returned PascalCase\n * value feeds `className`/`fileName` to derive matching class + file names\n * (e.g. `OrganizationMembershipService` / `organization_membership_service`).\n *\n * Accessor names (`servicePropertyName`) intentionally use the RAW target —\n * `client.organization_membership` is more readable than the suffixed form.\n *\n * The directory used by `loader.collapse` (the model home) likewise uses the\n * raw target.\n */\nexport function resolveServiceTarget(target: string, exportedClasses: Set<string>): string {\n  return resolveServiceTargetShared(target, exportedClasses, className);\n}\n\n/**\n * PascalCase class name for a parameter-group variant. Mirrors the Python\n * convention: group \"password\" + variant \"plaintext\" → `PasswordPlaintext`.\n * Used as the Ruby constant under the WorkOS module.\n */\nexport function groupVariantClassName(groupName: string, variantName: string): string {\n  return className(`${groupName}_${variantName}`);\n}\n\n/** snake_case Zeitwerk-compatible filename for a parameter-group variant. */\nexport function groupVariantFileName(groupName: string, variantName: string): string {\n  return fileName(`${groupName}_${variantName}`);\n}\n\n/**\n * Fully-qualified Ruby constant for a parameter-group variant scoped under\n * its owning resource module — e.g. \"WorkOS::UserManagement::PasswordPlaintext\".\n * Mirrors Python's `workos.user_management.PasswordPlaintext` namespacing.\n */\nexport function scopedGroupVariantClassName(mountTarget: string, groupName: string, variantName: string): string {\n  return `WorkOS::${className(mountTarget)}::${groupVariantClassName(groupName, variantName)}`;\n}\n\n/** snake_case property name for service accessors on the client. */\nexport function servicePropertyName(name: string): string {\n  return toSnakeCase(name);\n}\n\n/**\n * Resolve the effective service name, using the overlay-resolved class name\n * when available.\n */\nexport function resolveServiceName(service: Service, ctx: EmitterContext): string {\n  return resolveClassName(service, ctx);\n}\n\n/**\n * Build a map from IR service name to resolved service name.\n */\nexport function buildServiceNameMap(services: Service[], ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of services) {\n    map.set(service.name, resolveServiceName(service, ctx));\n  }\n  return map;\n}\n\n/** Resolve the SDK method name for an operation, using resolved operations first. */\nexport function resolveMethodName(op: Operation, _service: Service, ctx: EmitterContext): string {\n  const lookup = buildResolvedLookup(ctx);\n  const resolved = lookupMethodName(op, lookup);\n  if (resolved) return resolved;\n  const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const existing = ctx.overlayLookup?.methodByOperation?.get(httpKey);\n  if (existing) return toSnakeCase(existing.methodName);\n  return toSnakeCase(op.name);\n}\n\n/** Resolve the SDK class name for a service, using resolved operations' mountOn. */\nexport function resolveClassName(service: Service, ctx: EmitterContext): string {\n  for (const r of ctx.resolvedOperations ?? []) {\n    if (r.service.name === service.name) return r.mountOn;\n  }\n  if (ctx.overlayLookup?.methodByOperation) {\n    for (const op of service.operations) {\n      const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const existing = ctx.overlayLookup.methodByOperation.get(httpKey);\n      if (existing) return existing.className;\n    }\n  }\n  return toPascalCase(service.name);\n}\n\n/** Resolve the type name for a model, checking overlay first. */\nexport function resolveTypeName(name: string, ctx: EmitterContext): string {\n  const existing = ctx.overlayLookup?.interfaceByName?.get(name);\n  if (existing) return existing;\n  return toPascalCase(stripUrnPrefix(name));\n}\n\n/**\n * Build a map from IR service name to mount-target directory name.\n */\nexport function buildMountDirMap(ctx: EmitterContext): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const service of ctx.spec.services) {\n    const target = getMountTarget(service, ctx);\n    map.set(service.name, moduleName(target));\n  }\n  return map;\n}\n","import type { Model, EmitterContext, GeneratedFile, TypeRef, Field } from '@workos/oagen';\nimport { walkTypeRef, assignModelsToServices } from '@workos/oagen';\nimport { className, domainFieldName, fileName, buildMountDirMap } from './naming.js';\nimport {\n  isListWrapperModel,\n  isListMetadataModel,\n  collectNonPaginatedResponseModelNames,\n} from '../shared/model-utils.js';\nimport { isModelInScope } from '../shared/resolved-ops.js';\n\n/** Folder under lib/workos/ for models not owned by any service. */\nexport const SHARED_MODEL_DIR = 'shared';\n\n/**\n * Prefix → mount-target-dir map for models that `assignModelsToServices` can't\n * place (mostly webhook event payloads whose types aren't directly returned by\n * any API operation). The prefix is the PascalCase model-name prefix.\n *\n * Order matters: longest prefix wins (checked first). Prefixes not in this map\n * land in `shared/`.\n */\nexport const EVENT_MODEL_DIR_BY_PREFIX: ReadonlyArray<readonly [string, string]> = [\n  // Longer prefixes first — prefix matching is first-hit wins.\n  ['ApiKey', 'api_keys'],\n  ['OrganizationDomain', 'organization_domains'],\n  ['Organization', 'organizations'],\n  ['Authentication', 'user_management'],\n  ['Invitation', 'user_management'],\n  ['MagicAuth', 'user_management'],\n  ['Magic', 'user_management'],\n  ['Password', 'user_management'],\n  ['Email', 'user_management'],\n  ['Session', 'user_management'],\n  ['Action', 'user_management'],\n  ['User', 'user_management'],\n  ['Connection', 'sso'],\n  ['Dsync', 'directory_sync'],\n  ['Directory', 'directory_sync'],\n  ['Flag', 'feature_flags'],\n  ['Role', 'authorization'],\n  ['Permission', 'authorization'],\n  // Vault has no generated resource class (service is hand-maintained in the\n  // Ruby SDK), but the webhook payload models ship from the spec — group them\n  // under vault/ so the folder tree matches the hand-written client.\n  ['Vault', 'vault'],\n];\n\n/** Pick a subfolder for a model not assigned to any service. */\nexport function classifyUnassignedModel(modelName: string): string {\n  for (const [prefix, dir] of EVENT_MODEL_DIR_BY_PREFIX) {\n    if (modelName.startsWith(prefix)) return dir;\n  }\n  return SHARED_MODEL_DIR;\n}\n\n/**\n * Generate Ruby model classes from IR Model definitions.\n *\n * Each model becomes a file at `lib/workos/{snake_name}.rb` containing\n * a class under `WorkOS::` with:\n *   - attr_accessor for all fields\n *   - initialize(json) that parses JSON\n *   - to_json(*) that returns a hash\n */\nexport function generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n  if (models.length === 0) return [];\n\n  // Enum name set — used to detect enum-typed fields (treated as plain strings in Ruby).\n  const enumNames = new Set(ctx.spec.enums.map((e) => e.name));\n  const modelNames = new Set(models.map((m) => m.name));\n\n  // Model → mount target directory. Each model is assigned to the first service\n  // that references it (transitively). Orphans land in `shared/`. Zeitwerk is\n  // told to collapse each subfolder (in client.ts) so the namespace stays flat.\n  const modelToService = assignModelsToServices(models, ctx.spec.services, ctx.modelHints);\n  const mountDirMap = buildMountDirMap(ctx);\n  const dirFor = (modelName: string): string => {\n    const service = modelToService.get(modelName);\n    if (!service) return classifyUnassignedModel(modelName);\n    return mountDirMap.get(service) ?? classifyUnassignedModel(modelName);\n  };\n\n  const files: GeneratedFile[] = [];\n\n  // Wrappers referenced as a non-paginated response (e.g. `VersionListResponse`\n  // for `GET /vault/v1/kv/{id}/versions`) must still be emitted — the resource\n  // code references them by name and the pagination iterator doesn't unwrap them.\n  const nonPaginatedRefs = collectNonPaginatedResponseModelNames(ctx.spec.services);\n  const skipAsListWrapper = (m: Model): boolean => isListWrapperModel(m) && !nonPaginatedRefs.has(m.name);\n\n  // Dedup identical models (by recursive structural hash).\n  const recursiveHashes = buildRecursiveHashMap(models, enumNames);\n  const hashGroups = new Map<string, string[]>();\n  for (const m of models) {\n    if (skipAsListWrapper(m) || isListMetadataModel(m)) continue;\n    const h = recursiveHashes.get(m.name) ?? '';\n    if (!hashGroups.has(h)) hashGroups.set(h, []);\n    hashGroups.get(h)!.push(m.name);\n  }\n  const aliasOf = new Map<string, string>();\n  for (const names of hashGroups.values()) {\n    if (names.length <= 1) continue;\n    const sorted = [...names].sort();\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) aliasOf.set(sorted[i], canonical);\n  }\n\n  for (const model of models) {\n    if (skipAsListWrapper(model) || isListMetadataModel(model)) continue;\n\n    const cls = className(model.name);\n    const file = fileName(model.name);\n\n    // Ruby constant alias for duplicate models. Zeitwerk resolves the\n    // canonical on reference; the alias file just assigns the constant.\n    const canonical = aliasOf.get(model.name);\n    if (canonical) {\n      const canonCls = className(canonical);\n      const lines: string[] = [];\n      lines.push('module WorkOS');\n      lines.push(`  ${cls} = ${canonCls}`);\n      lines.push('end');\n      // FR-1.4: write the per-model file only when in scope. Zeitwerk autoloads\n      // by path, so there is no barrel to keep in sync; out-of-scope alias files\n      // are left untouched on disk.\n      if (isModelInScope(model.name, ctx)) {\n        files.push({\n          path: `lib/workos/${dirFor(model.name)}/${file}.rb`,\n          content: lines.join('\\n'),\n          integrateTarget: true,\n          overwriteExisting: true,\n        });\n      }\n      continue;\n    }\n\n    // Deduplicate field names that collide after snake_case.\n    const seenFieldNames = new Set<string>();\n    const fields = model.fields.filter((f) => {\n      // Dedup on the DOMAIN accessor name (honors fieldHints override).\n      const n = domainFieldName(f);\n      if (seenFieldNames.has(n)) return false;\n      seenFieldNames.add(n);\n      return true;\n    });\n\n    const lines: string[] = [];\n    lines.push('module WorkOS');\n    lines.push(`  class ${cls} < WorkOS::Types::BaseModel`);\n    lines.push('');\n\n    // Split fields into non-deprecated (attr_accessor) and deprecated (explicit accessors with warn).\n    const accessorFields = fields.filter((f) => !f.deprecated);\n    const deprecatedFields = fields.filter((f) => f.deprecated);\n\n    // HASH_ATTRS maps wire names (symbols) to Ruby attribute names (symbols).\n    // HashProvider uses this for to_h, to_json, and inspect.\n    lines.push('    HASH_ATTRS = {');\n    for (let i = 0; i < fields.length; i++) {\n      const field = fields[i];\n      // DOMAIN attr symbol (honors fieldHints); the key below is the WIRE name.\n      const fname = domainFieldName(field);\n      const sep = i === fields.length - 1 ? '' : ',';\n      lines.push(`      ${rubyHashLiteralKey(field.name)} :${fname}${sep}`);\n    }\n    lines.push('    }.freeze');\n    lines.push('');\n\n    // Emit @deprecated YARD tags for any deprecated fields before the accessor block.\n    if (deprecatedFields.length > 0) {\n      for (const f of deprecatedFields) {\n        const desc = f.description ? ` ${f.description.split('\\n')[0].trim()}` : '';\n        lines.push(`    # @!attribute ${domainFieldName(f)}`);\n        lines.push(`    #   @deprecated${desc}`);\n      }\n      lines.push('');\n    }\n\n    if (accessorFields.length > 0) {\n      const attrs = accessorFields.map((f) => `:${domainFieldName(f)}`);\n      if (attrs.length === 1) {\n        lines.push(`    attr_accessor ${attrs[0]}`);\n      } else {\n        lines.push(`    attr_accessor \\\\`);\n        for (let i = 0; i < attrs.length; i++) {\n          const sep = i === attrs.length - 1 ? '' : ',';\n          lines.push(`      ${attrs[i]}${sep}`);\n        }\n      }\n      lines.push('');\n    }\n\n    // Emit deprecated field accessors with runtime warnings.\n    for (const f of deprecatedFields) {\n      const fname = domainFieldName(f);\n      lines.push(`    def ${fname}`);\n      lines.push(\n        `      warn \"[DEPRECATION] \\\\\\`${fname}\\\\\\` is deprecated and will be removed in a future version.\", uplevel: 1`,\n      );\n      lines.push(`      @${fname}`);\n      lines.push('    end');\n      lines.push('');\n      lines.push(`    def ${fname}=(value)`);\n      lines.push(`      @${fname} = value`);\n      lines.push('    end');\n      lines.push('');\n    }\n\n    // initialize(json)\n    lines.push('    def initialize(json)');\n    lines.push('      hash = self.class.normalize(json)');\n    for (const field of fields) {\n      // DOMAIN ivar name (honors fieldHints); rawKey is the WIRE key read from the hash.\n      const fname = domainFieldName(field);\n      const rawKey = field.name;\n      lines.push(`      ${deserializeAssignment(fname, rawKey, field.type, field.required, enumNames, modelNames)}`);\n    }\n    lines.push('    end');\n\n    lines.push('  end');\n    lines.push('end');\n\n    // FR-1.4: write the per-model file only when in scope. Zeitwerk autoloads by\n    // path, so there is no barrel to keep in sync; out-of-scope model files are\n    // left untouched on disk.\n    if (isModelInScope(model.name, ctx)) {\n      files.push({\n        path: `lib/workos/${dirFor(model.name)}/${file}.rb`,\n        content: lines.join('\\n'),\n        integrateTarget: true,\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n\n/**\n * Produce a Ruby assignment line like `@foo = hash[:foo]` or the appropriate\n * nested-model construction for the field's type.\n */\nfunction deserializeAssignment(\n  rubyFieldName: string,\n  rawKey: string,\n  ref: TypeRef,\n  required: boolean,\n  enumNames: Set<string>,\n  modelNames: Set<string>,\n): string {\n  const accessor = rubyHashAccessor('hash', rawKey);\n  const expr = deserializeExpression(accessor, ref, required, enumNames, modelNames);\n  return `@${rubyFieldName} = ${expr}`;\n}\n\n/** Build an expression that deserializes a TypeRef from the given accessor. */\nfunction deserializeExpression(\n  accessor: string,\n  ref: TypeRef,\n  required: boolean,\n  enumNames: Set<string>,\n  modelNames: Set<string>,\n): string {\n  void enumNames;\n  // Unwrap nullable — nullable behaves like optional at the value level.\n  if (ref.kind === 'nullable') {\n    return deserializeExpression(accessor, ref.inner, false, enumNames, modelNames);\n  }\n\n  if (ref.kind === 'array') {\n    const inner = ref.items;\n    const itemDeser = deserializeExpression('item', inner, true, enumNames, modelNames);\n    if (itemDeser === 'item') {\n      return `(${accessor} || [])`;\n    }\n    return `(${accessor} || []).map { |item| ${itemDeser} }`;\n  }\n\n  if (ref.kind === 'map') {\n    return `${accessor} || {}`;\n  }\n\n  if (ref.kind === 'model' && modelNames.has(ref.name)) {\n    const cls = `WorkOS::${className(ref.name)}`;\n    if (required) {\n      return `${accessor} ? ${cls}.new(${accessor}) : nil`;\n    }\n    return `${accessor} ? ${cls}.new(${accessor}) : nil`;\n  }\n\n  if (ref.kind === 'enum' && enumNames.has(ref.name)) {\n    return accessor; // enums are plain strings in Ruby (values match server)\n  }\n\n  if (ref.kind === 'union') {\n    // Discriminated union: dispatch on the discriminator property to construct\n    // the matching variant. Unknown values fall back to the raw hash so callers\n    // can still introspect (rather than crashing on an unmapped discriminator).\n    if (ref.discriminator && ref.discriminator.mapping) {\n      const entries = Object.entries(ref.discriminator.mapping).filter(([, name]) => modelNames.has(name));\n      if (entries.length > 0) {\n        const propAccess = rubyHashAccessor(accessor, ref.discriminator.property);\n        const branches = entries\n          .map(([value, modelName]) => {\n            const cls = `WorkOS::${className(modelName)}`;\n            return `when ${JSON.stringify(value)} then ${cls}.new(${accessor})`;\n          })\n          .join(' ');\n        const dispatcher = `(case ${propAccess} ${branches} else ${accessor} end)`;\n        return `${accessor} ? ${dispatcher} : nil`;\n      }\n    }\n    // Non-discriminated union of models: pick the first variant as a best-\n    // effort typed wrapper. Preserves the pre-discriminator behavior of\n    // wrapping inline-variant unions whose owner used to be a single model.\n    const firstModelVariant = ref.variants.find((v) => v.kind === 'model' && modelNames.has(v.name));\n    if (firstModelVariant && firstModelVariant.kind === 'model') {\n      const cls = `WorkOS::${className(firstModelVariant.name)}`;\n      return `${accessor} ? ${cls}.new(${accessor}) : nil`;\n    }\n    return accessor;\n  }\n\n  if (ref.kind === 'literal') {\n    return accessor;\n  }\n\n  // primitive\n  return accessor;\n}\n\n/** Produce a Ruby accessor expression `hash[:foo]` or `hash[:\"weird#name\"]` for a raw field name. */\nfunction rubyHashAccessor(accessor: string, name: string): string {\n  if (/^[a-z_][a-zA-Z0-9_]*$/.test(name)) {\n    return `${accessor}[:${name}]`;\n  }\n  // Non-simple identifier: quoted symbol literal.\n  return `${accessor}[:\"${name.replace(/\"/g, '\\\\\"')}\"]`;\n}\n\n/** Produce a Ruby hash key literal (e.g., `foo:` shorthand or `\"foo#bar\" =>`).\n *  Simple identifiers (including camelCase) use symbol shorthand; names with\n *  special characters fall back to string-key `=>` syntax. */\nfunction rubyHashLiteralKey(name: string): string {\n  if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {\n    return `${name}:`;\n  }\n  return `\"${name.replace(/\"/g, '\\\\\"')}\" =>`;\n}\n\n/** Build a recursive structural hash map for model deduplication. */\nfunction buildRecursiveHashMap(models: Model[], enumNames: Set<string>): Map<string, string> {\n  const modelByName = new Map(models.map((m) => [m.name, m]));\n  const memo = new Map<string, string>();\n\n  const hashTypeRef = (ref: TypeRef, visiting: Set<string>): string => {\n    switch (ref.kind) {\n      case 'primitive':\n        return `P:${ref.type}${ref.format ?? ''}`;\n      case 'array':\n        return `A[${hashTypeRef(ref.items, visiting)}]`;\n      case 'nullable':\n        return `N[${hashTypeRef(ref.inner, visiting)}]`;\n      case 'map':\n        return `M[${hashTypeRef(ref.valueType, visiting)}]`;\n      case 'literal':\n        return `L:${String(ref.value)}`;\n      case 'enum':\n        return `E:${ref.name}`;\n      case 'model': {\n        if (visiting.has(ref.name)) return `R:${ref.name}`; // cycle\n        return `Ref[${hashModel(ref.name, visiting)}]`;\n      }\n      case 'union':\n        return `U[${ref.variants.map((v) => hashTypeRef(v, visiting)).join(',')}]`;\n    }\n    return 'unknown';\n  };\n\n  const hashField = (f: Field, visiting: Set<string>): string => {\n    return `${f.name}:${f.required ? 'R' : 'O'}:${hashTypeRef(f.type, visiting)}`;\n  };\n\n  const hashModel = (name: string, visiting: Set<string>): string => {\n    if (memo.has(name)) return memo.get(name)!;\n    const m = modelByName.get(name);\n    if (!m) return `?:${name}`;\n    visiting.add(name);\n    const fieldsSorted = [...m.fields].sort((a, b) => a.name.localeCompare(b.name));\n    const h = fieldsSorted.map((f) => hashField(f, visiting)).join('|');\n    visiting.delete(name);\n    memo.set(name, h);\n    return h;\n  };\n\n  void enumNames;\n  void walkTypeRef;\n  const out = new Map<string, string>();\n  for (const m of models) {\n    out.set(m.name, hashModel(m.name, new Set()));\n  }\n  return out;\n}\n","import type { Enum, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { toUpperSnakeCase } from '@workos/oagen';\nimport { className, fileName } from './naming.js';\nimport { isEnumInScope } from '../shared/resolved-ops.js';\n\n/**\n * Generate Ruby enum class files.\n *\n * Each enum becomes a class under `WorkOS::Types::` with uppercase constants\n * and a frozen `ALL` array of all values.\n */\nexport function generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n  if (enums.length === 0) return [];\n\n  const files: GeneratedFile[] = [];\n  const aliasOf = collectEnumAliasOf(enums);\n\n  for (const enumDef of enums) {\n    const cls = className(enumDef.name);\n    // FR-1.4: write the per-enum file only when in scope. Out-of-scope enum\n    // files are left untouched on disk; Zeitwerk autoloads them by path.\n    const enumInScope = isEnumInScope(enumDef.name, ctx);\n\n    // If this enum duplicates another (by value set), emit a Ruby constant\n    // alias. Zeitwerk autoloads the canonical when the alias is first\n    // referenced.\n    const canonicalName = aliasOf.get(enumDef.name);\n    if (canonicalName) {\n      const canonicalCls = className(canonicalName);\n      const lines: string[] = [];\n      lines.push('module WorkOS');\n      lines.push('  module Types');\n      lines.push(`    ${cls} = ${canonicalCls}`);\n      lines.push('  end');\n      lines.push('end');\n      if (enumInScope) {\n        files.push({\n          path: `lib/workos/types/${fileName(enumDef.name)}.rb`,\n          content: lines.join('\\n'),\n          integrateTarget: true,\n          overwriteExisting: true,\n        });\n      }\n      continue;\n    }\n\n    // Deduplicate repeated string values.\n    const seen = new Set<string>();\n    const uniqueValues: typeof enumDef.values = [];\n    for (const v of enumDef.values) {\n      const str = String(v.value);\n      if (!seen.has(str)) {\n        seen.add(str);\n        uniqueValues.push({ ...v, value: str });\n      }\n    }\n\n    if (uniqueValues.length === 0) {\n      // No values — emit a placeholder string-alias class.\n      const lines: string[] = [];\n      lines.push('module WorkOS');\n      lines.push('  module Types');\n      lines.push(`    class ${cls}`);\n      lines.push('      ALL = [].freeze');\n      lines.push('    end');\n      lines.push('  end');\n      lines.push('end');\n      if (enumInScope) {\n        files.push({\n          path: `lib/workos/types/${fileName(enumDef.name)}.rb`,\n          content: lines.join('\\n'),\n          integrateTarget: true,\n          overwriteExisting: true,\n        });\n      }\n      continue;\n    }\n\n    // Determine string vs integer enum.\n    const allIntegers = uniqueValues.every((v) => typeof v.value === 'number' && Number.isInteger(v.value));\n\n    // Reserve ALL for the frozen list constant at the bottom; any enum value\n    // whose upper-snake form collides gets a VALUE_ prefix.\n    const RESERVED_MEMBER_NAMES = new Set(['ALL']);\n    const usedNames = new Set<string>();\n    const memberLines: string[] = [];\n    const allEntries: string[] = [];\n\n    for (const v of uniqueValues) {\n      let member = toUpperSnakeCase(String(v.value));\n      // Ruby constants must start with an uppercase letter.\n      if (!/^[A-Z]/.test(member)) member = `VALUE_${member}`;\n      if (RESERVED_MEMBER_NAMES.has(member)) member = `VALUE_${member}`;\n      if (usedNames.has(member)) {\n        let suffix = 2;\n        while (usedNames.has(`${member}_${suffix}`)) suffix++;\n        member = `${member}_${suffix}`;\n      }\n      usedNames.add(member);\n      const valueLit = allIntegers ? String(v.value) : `'${String(v.value).replace(/'/g, \"\\\\'\")}'`;\n      if (v.deprecated) {\n        memberLines.push(`      # @deprecated`);\n      }\n      memberLines.push(`      ${member} = ${valueLit}`);\n      allEntries.push(member);\n    }\n\n    const lines: string[] = [];\n    lines.push('module WorkOS');\n    lines.push('  module Types');\n    lines.push(`    class ${cls}`);\n    lines.push(...memberLines);\n    lines.push(`      ALL = [${allEntries.join(', ')}].freeze`);\n    lines.push('    end');\n    lines.push('  end');\n    lines.push('end');\n\n    if (enumInScope) {\n      files.push({\n        path: `lib/workos/types/${fileName(enumDef.name)}.rb`,\n        content: lines.join('\\n'),\n        integrateTarget: true,\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  return files;\n}\n\n/**\n * Detect when two or more enums have the same value set — pick the lexicographically\n * first as canonical and return a map of aliasName -> canonicalName for the rest.\n */\nfunction collectEnumAliasOf(enums: Enum[]): Map<string, string> {\n  const hashGroups = new Map<string, string[]>();\n  for (const e of enums) {\n    const hash = [...e.values]\n      .map((v) => String(v.value))\n      .sort()\n      .join('|');\n    if (!hashGroups.has(hash)) hashGroups.set(hash, []);\n    hashGroups.get(hash)!.push(e.name);\n  }\n  const aliasOf = new Map<string, string>();\n  for (const names of hashGroups.values()) {\n    if (names.length <= 1) continue;\n    const sorted = [...names].sort();\n    const canonical = sorted[0];\n    for (let i = 1; i < sorted.length; i++) aliasOf.set(sorted[i], canonical);\n  }\n  return aliasOf;\n}\n\n/** Collect the set of enum names that were emitted. */\nexport function collectEnumSymbols(enums: Enum[]): string[] {\n  return enums.map((e) => e.name);\n}\n","import type { TypeRef, PrimitiveType, UnionType } from '@workos/oagen';\nimport { mapTypeRef as irMapTypeRef } from '@workos/oagen';\nimport { className } from './naming.js';\n\n/**\n * Map an IR TypeRef to a Ruby YARD doc type string.\n * Ruby is dynamically typed, so these are used only in YARD comments.\n */\nexport function mapTypeRef(ref: TypeRef): string {\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (ref, items) => {\n      void ref;\n      return `Array<${items}>`;\n    },\n    model: (r) => `WorkOS::${className(r.name)}`,\n    enum: (r) => `WorkOS::Types::${className(r.name)}`,\n    union: (r, variants) => joinUnionVariants(r, variants),\n    nullable: (ref, inner) => {\n      void ref;\n      return inner;\n    },\n    literal: (r) => (typeof r.value === 'string' ? 'String' : r.value === null ? 'nil' : typeof r.value),\n    map: (ref, value) => {\n      void ref;\n      return `Hash{String => ${value}}`;\n    },\n  });\n}\n\n/**\n * Map an IR TypeRef to a more verbose Ruby-compatible type string for documentation.\n * Includes `nil` for nullable types (YARD convention: `[Foo, nil]`).\n */\nexport function mapTypeRefForYard(ref: TypeRef): string {\n  return irMapTypeRef<string>(ref, {\n    primitive: mapPrimitive,\n    array: (ref, items) => {\n      void ref;\n      return `Array<${items}>`;\n    },\n    model: (r) => `WorkOS::${className(r.name)}`,\n    enum: (r) => `WorkOS::Types::${className(r.name)}`,\n    union: (r, variants) => joinUnionVariantsYard(r, variants),\n    nullable: (ref, inner) => {\n      void ref;\n      // Avoid duplicate nil when inner already contains nil (e.g. from a union with a null literal).\n      const parts = inner.split(', ');\n      if (parts.includes('nil')) return inner;\n      return `${inner}, nil`;\n    },\n    literal: (r) => (typeof r.value === 'string' ? 'String' : r.value === null ? 'nil' : typeof r.value),\n    map: (ref, value) => {\n      void ref;\n      return `Hash{String => ${value}}`;\n    },\n  });\n}\n\nfunction mapPrimitive(ref: PrimitiveType): string {\n  if (ref.format) {\n    switch (ref.format) {\n      case 'binary':\n        return 'String';\n    }\n  }\n  switch (ref.type) {\n    case 'string':\n      return 'String';\n    case 'integer':\n      return 'Integer';\n    case 'number':\n      return 'Float';\n    case 'boolean':\n      return 'Boolean';\n    case 'unknown':\n      return 'Object';\n  }\n}\n\nfunction joinUnionVariants(ref: UnionType, variants: string[]): string {\n  if (ref.compositionKind === 'allOf') {\n    return variants[0] ?? 'Object';\n  }\n  const unique = [...new Set(variants)];\n  if (unique.length === 1) return unique[0];\n  return unique.join(', ');\n}\n\nfunction joinUnionVariantsYard(ref: UnionType, variants: string[]): string {\n  if (ref.compositionKind === 'allOf') {\n    return variants[0] ?? 'Object';\n  }\n  const unique = [...new Set(variants)];\n  if (unique.length === 1) return unique[0];\n  return unique.join(', ');\n}\n","import type { EmitterContext, Operation, ResolvedOperation, ResolvedWrapper } from '@workos/oagen';\nimport { className, fieldName, safeParamName } from './naming.js';\nimport { resolveWrapperParams, formatWrapperDescription } from '../shared/wrapper-utils.js';\nimport { mapTypeRefForYard } from './type-map.js';\n\n/**\n * Generate Ruby wrapper method lines for union split operations.\n *\n * Each wrapper is a typed convenience method that:\n * - Accepts only the exposed params (keyword args)\n * - Injects constant defaults (e.g., grant_type)\n * - Reads inferred fields from client config (e.g., client_id)\n * - Delegates to the same HTTP runtime as the main method\n */\nexport function generateWrapperMethods(\n  resolvedOp: ResolvedOperation,\n  ctx: EmitterContext,\n  modelNames: Set<string>,\n  requires: Set<string>,\n): string[] {\n  if (!resolvedOp.wrappers || resolvedOp.wrappers.length === 0) return [];\n  const out: string[] = [];\n  for (const wrapper of resolvedOp.wrappers) {\n    const body = emitWrapperMethod(resolvedOp.operation, wrapper, ctx, modelNames, requires);\n    out.push(body);\n  }\n  return out;\n}\n\n/** Collect response model filenames needed for wrapper imports. */\nexport function collectWrapperResponseModels(resolvedOp: ResolvedOperation): Set<string> {\n  const models = new Set<string>();\n  for (const w of resolvedOp.wrappers ?? []) {\n    if (w.responseModelName) models.add(w.responseModelName);\n  }\n  return models;\n}\n\nfunction emitWrapperMethod(\n  op: Operation,\n  wrapper: ResolvedWrapper,\n  ctx: EmitterContext,\n  modelNames: Set<string>,\n  requires: Set<string>,\n): string {\n  void requires;\n  const method = wrapper.name; // already snake_case\n  const wrapperParams = resolveWrapperParams(wrapper, ctx);\n  const lines: string[] = [];\n\n  // YARD doc\n  lines.push(`    # ${formatWrapperDescription(wrapper.name)}.`);\n  for (const p of op.pathParams ?? []) {\n    const pyType = mapTypeRefForYard(p.type);\n    lines.push(`    # @param ${safeParamName(p.name)} [${pyType}]`);\n  }\n  for (const wp of wrapperParams) {\n    const type = wp.field ? mapTypeRefForYard(wp.field.type) : 'String';\n    const alreadyNilable = type.split(', ').includes('nil');\n    const suffix = wp.isOptional && !alreadyNilable ? ', nil' : '';\n    lines.push(`    # @param ${fieldName(wp.paramName)} [${type}${suffix}]`);\n  }\n  lines.push(`    # @param request_options [Hash] Per-request overrides.`);\n  if (wrapper.responseModelName) {\n    lines.push(`    # @return [WorkOS::${className(wrapper.responseModelName)}]`);\n  } else {\n    lines.push(`    # @return [nil]`);\n  }\n\n  // Signature\n  const sigParts: string[] = [];\n  const seen = new Set<string>();\n  for (const p of op.pathParams ?? []) {\n    const n = safeParamName(p.name);\n    if (seen.has(n)) continue;\n    seen.add(n);\n    sigParts.push(`${n}:`);\n  }\n  // Required first, then optional\n  for (const wp of wrapperParams) {\n    if (wp.isOptional) continue;\n    const n = fieldName(wp.paramName);\n    if (seen.has(n)) continue;\n    seen.add(n);\n    sigParts.push(`${n}:`);\n  }\n  for (const wp of wrapperParams) {\n    if (!wp.isOptional) continue;\n    const n = fieldName(wp.paramName);\n    if (seen.has(n)) continue;\n    seen.add(n);\n    sigParts.push(`${n}: nil`);\n  }\n  sigParts.push('request_options: {}');\n\n  if (sigParts.length === 1 && sigParts[0].length < 60) {\n    lines.push(`    def ${method}(${sigParts[0]})`);\n  } else {\n    lines.push(`    def ${method}(`);\n    for (let i = 0; i < sigParts.length; i++) {\n      const sep = i === sigParts.length - 1 ? '' : ',';\n      lines.push(`      ${sigParts[i]}${sep}`);\n    }\n    lines.push('    )');\n  }\n\n  // Body hash\n  const bodyEntries: string[] = [];\n  for (const [k, v] of Object.entries(wrapper.defaults)) {\n    const lit = typeof v === 'string' ? rubyStringLit(v) : String(v);\n    bodyEntries.push(`${rubyStringLit(k)} => ${lit}`);\n  }\n  for (const fc of wrapper.inferFromClient) {\n    const clientProp = fc === 'client_secret' ? 'api_key' : fc;\n    bodyEntries.push(`${rubyStringLit(fc)} => @client.${clientProp}`);\n  }\n  for (const wp of wrapperParams) {\n    bodyEntries.push(`${rubyStringLit(wp.paramName)} => ${fieldName(wp.paramName)}`);\n  }\n  lines.push('      body = {');\n  for (let i = 0; i < bodyEntries.length; i++) {\n    const sep = i === bodyEntries.length - 1 ? '' : ',';\n    lines.push(`        ${bodyEntries[i]}${sep}`);\n  }\n  lines.push('      }.compact');\n\n  // Path string — use the unified @client.request helper.\n  const rubyPath = interpolateRubyPath(op.path, op.pathParams ?? []);\n  const verbSym = op.httpMethod.toLowerCase();\n  lines.push('      response = @client.request(');\n  lines.push(`        method: :${verbSym},`);\n  lines.push(`        path: ${rubyPath},`);\n  lines.push('        auth: true,');\n  lines.push('        body: body,');\n  lines.push('        request_options: request_options');\n  lines.push('      )');\n\n  // Response handling\n  if (wrapper.responseModelName && modelNames.has(wrapper.responseModelName)) {\n    lines.push(`      WorkOS::${className(wrapper.responseModelName)}.new(response.body)`);\n  } else {\n    lines.push('      JSON.parse(response.body)');\n  }\n\n  lines.push('    end');\n\n  return lines.join('\\n');\n}\n\nfunction interpolateRubyPath(path: string, pathParams: Operation['pathParams']): string {\n  if (!pathParams || pathParams.length === 0) return `'${path}'`;\n  let result = path;\n  for (const p of pathParams) {\n    result = result.split(`{${p.name}}`).join(`#{WorkOS::Util.encode_path(${safeParamName(p.name)})}`);\n  }\n  return `\"${result}\"`;\n}\n\nfunction rubyStringLit(s: string): string {\n  return `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n","import type { EmitterContext, TypeRef, Model } from '@workos/oagen';\nimport { className, fieldName, groupVariantClassName } from './naming.js';\nimport { mapTypeRefForYard } from './type-map.js';\nimport { collectBodyFieldTypes, groupByMount } from '../shared/resolved-ops.js';\n\n/**\n * Sorbet type string for a TypeRef. Mirrors `mapSorbetType` in rbi.ts but\n * lives here so the parameter-groups module is self-contained.\n */\nfunction mapSorbetType(ref: TypeRef): string {\n  switch (ref.kind) {\n    case 'primitive':\n      switch (ref.type) {\n        case 'string':\n          return 'String';\n        case 'integer':\n          return 'Integer';\n        case 'number':\n          return 'Float';\n        case 'boolean':\n          return 'T::Boolean';\n        case 'unknown':\n          return 'T.untyped';\n      }\n      break;\n    case 'array':\n      return `T::Array[${mapSorbetType(ref.items)}]`;\n    case 'model':\n      return `WorkOS::${className(ref.name)}`;\n    case 'enum':\n      return 'String';\n    case 'nullable': {\n      const inner = mapSorbetType(ref.inner);\n      return inner === 'T.untyped' ? inner : `T.nilable(${inner})`;\n    }\n    case 'literal':\n      if (typeof ref.value === 'string') return 'String';\n      if (ref.value === null) return 'NilClass';\n      if (typeof ref.value === 'number') return Number.isInteger(ref.value) ? 'Integer' : 'Float';\n      return 'T::Boolean';\n    case 'union': {\n      const variants = ref.variants.map((v) => mapSorbetType(v));\n      const unique = [...new Set(variants)];\n      if (unique.length === 1) return unique[0];\n      return `T.any(${unique.join(', ')})`;\n    }\n    case 'map':\n      return `T::Hash[String, ${mapSorbetType(ref.valueType)}]`;\n  }\n  return 'T.untyped';\n}\n\nexport interface CollectedVariant {\n  className: string;\n  groupName: string;\n  variantName: string;\n  /** PascalCase mount target this variant is scoped under (e.g. \"UserManagement\"). */\n  mountTarget: string;\n  parameters: { name: string; type: TypeRef }[];\n}\n\n/**\n * Build a stable groupName -> mountTarget map. Each parameter group is owned\n * by exactly one resource module — Ruby variant classes are inlined into\n * `WorkOS::<MountTarget>::<Variant>` (matching Python's per-resource layout),\n * so a dispatcher in another resource that references the same group still\n * resolves to a single canonical class.\n *\n * Mount targets are visited in alphabetical order so first-wins is\n * deterministic across runs. In the current spec no group is shared across\n * mount targets; if one ever is, the alphabetically-first owner gets the\n * class and other dispatchers reference it by full path.\n */\nexport function buildGroupOwnerMap(ctx: EmitterContext): Map<string, string> {\n  const owner = new Map<string, string>();\n  const groups = groupByMount(ctx);\n  const sortedTargets = [...groups.keys()].sort();\n  for (const target of sortedTargets) {\n    const g = groups.get(target);\n    if (!g) continue;\n    for (const op of g.operations) {\n      for (const grp of op.parameterGroups ?? []) {\n        if (!owner.has(grp.name)) owner.set(grp.name, target);\n      }\n    }\n  }\n  return owner;\n}\n\n/**\n * Collect all variant classes a given mount target owns. Variants are\n * inlined into the resource file (and its RBI counterpart) — Zeitwerk's\n * collapse convention means subdirectories under `lib/workos/<service>/`\n * don't add a namespace level, so files there can't define\n * `WorkOS::<Service>::<Variant>`. Inline definitions sidestep that.\n *\n * Variant parameter types are taken from the IR's leaf type. When the IR's\n * leaf is a bare primitive but the request body model has a richer type\n * (array/enum/model/map), we fall back to the body type to recover fidelity\n * the IR drops. Body nullability is stripped — when a parameter group is\n * optional, the body field for the group becomes nullable, but within a\n * variant the leaf is always required (selecting the variant means passing it).\n */\nexport function collectVariantsForMountTarget(\n  ctx: EmitterContext,\n  models: Model[],\n  mountTarget: string,\n): CollectedVariant[] {\n  const owner = buildGroupOwnerMap(ctx);\n  const seen = new Set<string>();\n  const out: CollectedVariant[] = [];\n  const groups = groupByMount(ctx);\n  const g = groups.get(mountTarget);\n  if (!g) return out;\n  for (const op of g.operations) {\n    const bodyFieldTypes = collectBodyFieldTypes(op, models);\n    for (const group of op.parameterGroups ?? []) {\n      if (owner.get(group.name) !== mountTarget) continue;\n      for (const variant of group.variants) {\n        const cls = groupVariantClassName(group.name, variant.name);\n        if (seen.has(cls)) continue;\n        seen.add(cls);\n        out.push({\n          className: cls,\n          groupName: group.name,\n          variantName: variant.name,\n          mountTarget,\n          parameters: variant.parameters.map((p) => ({\n            name: p.name,\n            type: pickVariantParamType(p.type, bodyFieldTypes.get(p.name)),\n          })),\n        });\n      }\n    }\n  }\n  return out;\n}\n\n/**\n * Pick the type for a variant leaf parameter.\n *\n * Prefer the IR's leaf type. Use the body model's type only when the IR is a\n * bare primitive but the body has a structured type — that's the original\n * fidelity-recovery case the body fallback was added for. Strip any outer\n * nullable from the body type, since body nullability reflects the parent\n * group's optionality, not the leaf's required-ness within the variant.\n *\n * Exported so the test emitter can recover the same type the variant class\n * declares — IR primitives for fields like `role_slugs` would otherwise stub\n * as `\"stub\"` strings instead of the `[\"stub\"]` arrays the class accepts.\n */\nexport function pickVariantParamType(irType: TypeRef, bodyType: TypeRef | undefined): TypeRef {\n  if (!bodyType) return irType;\n  const unwrappedBody = bodyType.kind === 'nullable' ? bodyType.inner : bodyType;\n  const bodyIsStructured =\n    unwrappedBody.kind === 'array' ||\n    unwrappedBody.kind === 'enum' ||\n    unwrappedBody.kind === 'model' ||\n    unwrappedBody.kind === 'map';\n  if (irType.kind === 'primitive' && bodyIsStructured) return unwrappedBody;\n  return irType;\n}\n\nfunction readableName(name: string): string {\n  return name.replace(/_/g, ' ');\n}\n\n/**\n * Render the inline `Data.define` block for a single variant, indented for\n * inclusion inside a `class <Service>` body. Returns an array of lines with\n * 4-space indent (the resource file's class members are 4-space indented).\n */\nexport function emitInlineVariantClass(v: CollectedVariant): string[] {\n  const lines: string[] = [];\n  lines.push(`    # Identifies the ${readableName(v.groupName)} (${readableName(v.variantName)} variant).`);\n  lines.push('    #');\n  for (const p of v.parameters) {\n    const yardType = mapTypeRefForYard(p.type);\n    lines.push(`    # @!attribute [r] ${fieldName(p.name)}`);\n    lines.push(`    #   @return [${yardType}]`);\n  }\n  if (v.parameters.length === 0) {\n    lines.push(`    ${v.className} = Data.define`);\n  } else {\n    const fields = v.parameters.map((p) => `:${fieldName(p.name)}`).join(', ');\n    lines.push(`    ${v.className} = Data.define(${fields})`);\n  }\n  return lines;\n}\n\n/**\n * Render the inline RBI `class` block for a single variant, indented for\n * inclusion inside a `class <Service>` body in a service .rbi file. Returns\n * lines with 4-space indent.\n */\nexport function emitInlineVariantRbi(v: CollectedVariant): string[] {\n  const lines: string[] = [];\n  const fqcn = `WorkOS::${v.mountTarget}::${v.className}`;\n  lines.push(`    class ${v.className}`);\n  for (const p of v.parameters) {\n    lines.push(`      sig { returns(${mapSorbetType(p.type)}) }`);\n    lines.push(`      def ${fieldName(p.name)}; end`);\n    lines.push('');\n  }\n  if (v.parameters.length === 0) {\n    lines.push(`      sig { returns(${fqcn}) }`);\n    lines.push(`      def self.new; end`);\n  } else {\n    lines.push('      sig do');\n    lines.push('        params(');\n    for (let i = 0; i < v.parameters.length; i++) {\n      const p = v.parameters[i];\n      const sep = i === v.parameters.length - 1 ? '' : ',';\n      lines.push(`          ${fieldName(p.name)}: ${mapSorbetType(p.type)}${sep}`);\n    }\n    lines.push(`        ).returns(${fqcn})`);\n    lines.push('      end');\n    const kwargs = v.parameters.map((p) => `${fieldName(p.name)}:`).join(', ');\n    lines.push(`      def self.new(${kwargs}); end`);\n  }\n  lines.push('    end');\n  return lines;\n}\n","import type { Service, EmitterContext, GeneratedFile, Operation, TypeRef, Parameter, Model } from '@workos/oagen';\nimport { planOperation } from '@workos/oagen';\nimport {\n  className,\n  fieldName,\n  fileName,\n  methodName,\n  safeParamName,\n  resolveMethodName,\n  scopedGroupVariantClassName,\n  buildExportedClassNameSet,\n  resolveServiceTarget,\n} from './naming.js';\nimport { mapTypeRefForYard } from './type-map.js';\nimport {\n  buildResolvedLookup,\n  lookupResolved,\n  scopedMountGroups,\n  getOpDefaults,\n  getOpInferFromClient,\n  buildHiddenParams,\n  collectGroupedParamNames,\n} from '../shared/resolved-ops.js';\nimport { isListWrapperModel } from '../shared/model-utils.js';\nimport { generateWrapperMethods, collectWrapperResponseModels } from './wrappers.js';\nimport { buildGroupOwnerMap, collectVariantsForMountTarget, emitInlineVariantClass } from './parameter-groups.js';\n\n/**\n * Generate Ruby resource (service) classes from IR services.\n *\n * Produces one `.rb` file per mount target under `lib/workos/`.\n */\nexport function generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  const groups = scopedMountGroups(ctx);\n  const lookup = buildResolvedLookup(ctx);\n  const modelNames = new Set(ctx.spec.models.map((m) => m.name));\n  const enumNames = new Set(ctx.spec.enums.map((e) => e.name));\n  const modelByName = new Map<string, Model>();\n  for (const m of ctx.spec.models as Model[]) modelByName.set(m.name, m);\n\n  // Build a map of model.name -> isListWrapper to detect pagination.\n  const listWrapperModels = new Map<string, Model>();\n  for (const m of ctx.spec.models as Model[]) {\n    if (isListWrapperModel(m)) listWrapperModels.set(m.name, m);\n  }\n\n  // Resolve groupName -> owner mountTarget once per generation pass; every\n  // dispatcher and YARD `@param` reference resolves variant classes through\n  // this map so cross-resource references stay consistent.\n  const groupOwners = buildGroupOwnerMap(ctx);\n  const exportedClasses = buildExportedClassNameSet(ctx);\n\n  for (const [mountTarget, group] of groups) {\n    const resolvedTarget = resolveServiceTarget(mountTarget, exportedClasses);\n    const cls = className(resolvedTarget);\n    const file = fileName(resolvedTarget);\n\n    const operations = group.operations;\n    if (operations.length === 0) continue;\n\n    const requires = new Set<string>();\n    requires.add('json');\n\n    const lines: string[] = [];\n    const methodBodies: string[] = [];\n\n    const emittedMethodNames = new Set<string>();\n\n    // We look for each operation's \"home\" service within this group.\n    for (const op of operations) {\n      // Find the service that owns this op (via resolvedOps -> service mapping).\n      const ownerService =\n        group.resolvedOps.find((r) => r.operation === op)?.service ??\n        services.find((s) => s.operations.includes(op)) ??\n        services[0];\n      const method = resolveMethodName(op, ownerService, ctx);\n      if (emittedMethodNames.has(method)) continue;\n\n      const resolved = lookupResolved(op, lookup);\n      // Skip url-builder operations: these are spec-marked client-side URL\n      // constructors (no HTTP), and the Ruby SDK provides them via\n      // hand-maintained inline @oagen-ignore extensions on the relevant\n      // service class instead of generating an HTTP wrapper that would\n      // incorrectly hit the API.\n      if (resolved?.urlBuilder) {\n        emittedMethodNames.add(method);\n        continue;\n      }\n\n      emittedMethodNames.add(method);\n\n      const defaults = getOpDefaults(resolved);\n      const inferFromClient = new Set(getOpInferFromClient(resolved));\n      const hiddenParams = buildHiddenParams(resolved);\n\n      const body = emitMethod({\n        op,\n        method,\n        defaults,\n        inferFromClient,\n        hiddenParams,\n        enumNames,\n        modelNames,\n        modelByName,\n        listWrapperModels,\n        requires,\n        groupOwners,\n        exportedClasses,\n      });\n      methodBodies.push(body);\n\n      // Emit union split wrapper methods (e.g., authenticate_with_password).\n      if (resolved?.wrappers && resolved.wrappers.length > 0) {\n        const wrapperBodies = generateWrapperMethods(resolved, ctx, modelNames, requires);\n        for (let i = 0; i < resolved.wrappers.length; i++) {\n          const w = resolved.wrappers[i];\n          if (emittedMethodNames.has(w.name)) continue;\n          emittedMethodNames.add(w.name);\n          methodBodies.push(wrapperBodies[i]);\n          if (\n            w.responseModelName &&\n            modelNames.has(w.responseModelName) &&\n            !listWrapperModels.has(w.responseModelName)\n          ) {\n            requires.add(fileName(w.responseModelName));\n          }\n        }\n        // Also ensure any additional response models are added to requires set.\n        for (const m of collectWrapperResponseModels(resolved)) {\n          if (modelNames.has(m) && !listWrapperModels.has(m)) requires.add(fileName(m));\n        }\n      }\n    }\n\n    // Zeitwerk autoloads every WorkOS::* constant; only stdlib requires.\n    if (requires.has('json')) {\n      lines.push(`require 'json'`);\n      lines.push('');\n    }\n    lines.push('module WorkOS');\n    lines.push(`  class ${cls}`);\n\n    // Inline parameter-group variant classes owned by this mount target.\n    // Zeitwerk's `loader.collapse` flattens `lib/workos/<service>/` so files\n    // there can't define `WorkOS::<Service>::*` constants — variants must\n    // live inside the service's own file. Matches Python's per-resource\n    // dataclass layout.\n    const variants = collectVariantsForMountTarget(ctx, ctx.spec.models as Model[], mountTarget);\n    for (const v of variants) {\n      for (const line of emitInlineVariantClass(v)) lines.push(line);\n      lines.push('');\n    }\n\n    lines.push('    def initialize(client)');\n    lines.push('      @client = client');\n    lines.push('    end');\n    for (const body of methodBodies) {\n      lines.push('');\n      lines.push(body);\n    }\n    lines.push('  end');\n    lines.push('end');\n\n    files.push({\n      path: `lib/workos/${file}.rb`,\n      content: lines.join('\\n'),\n      integrateTarget: true,\n      overwriteExisting: true,\n    });\n  }\n\n  return files;\n}\n\n/** Build a single Ruby method from an Operation. */\nfunction emitMethod(args: {\n  op: Operation;\n  method: string;\n  defaults: Record<string, string | number | boolean>;\n  inferFromClient: Set<string>;\n  hiddenParams: Set<string>;\n  enumNames: Set<string>;\n  modelNames: Set<string>;\n  modelByName: Map<string, Model>;\n  listWrapperModels: Map<string, Model>;\n  requires: Set<string>;\n  groupOwners: Map<string, string>;\n  exportedClasses: Set<string>;\n}): string {\n  const {\n    op,\n    method,\n    defaults,\n    inferFromClient,\n    hiddenParams,\n    enumNames,\n    modelNames,\n    modelByName,\n    listWrapperModels,\n    requires,\n    groupOwners,\n    exportedClasses,\n  } = args;\n  void enumNames;\n\n  /** Fully-qualified Ruby constant for a variant (e.g. WorkOS::UserManagement::PasswordPlaintext). */\n  const variantClassRef = (group: { name: string }, variantName: string): string => {\n    const owner = groupOwners.get(group.name);\n    if (!owner) {\n      throw new Error(`No owner mount target found for parameter group '${group.name}'`);\n    }\n    return scopedGroupVariantClassName(resolveServiceTarget(owner, exportedClasses), group.name, variantName);\n  };\n\n  const plan = planOperation(op);\n  const lines: string[] = [];\n\n  // Collect params: path params positional, others keyword.\n  const pathParams = op.pathParams ?? [];\n  const groupedParamNames = collectGroupedParamNames(op);\n  const queryParams = (op.queryParams ?? []).filter((q) => !groupedParamNames.has(q.name));\n\n  // Request body params: if body is a model, expand its fields. Drop any field\n  // whose name is also a parameter-group name — those are dispatched by the\n  // group kwarg below, so emitting them as flat kwargs would shadow the group\n  // and cause `String#[Symbol]` TypeErrors when the dispatcher reads `:type`.\n  const bodyFields = getRequestBodyFields(op, hiddenParams, modelByName).filter((f) => !groupedParamNames.has(f.name));\n\n  // Detect path/body name collisions and build a rename map for body fields.\n  // When a body field's snake_case name matches a path param, prefix with \"body_\"\n  // so the Ruby method exposes distinct keyword args.\n  const pathParamNames = new Set(pathParams.map((p) => safeParamName(p.name)));\n  const bodyFieldRenames = new Map<string, string>();\n  for (const f of bodyFields) {\n    if (hiddenParams.has(f.name)) continue;\n    const n = fieldName(f.name);\n    if (pathParamNames.has(n)) {\n      bodyFieldRenames.set(f.name, `body_${n}`);\n    }\n  }\n\n  /** Resolve the Ruby kwarg name for a body field, applying renames if needed. */\n  const bodyKwargName = (wireName: string): string => {\n    return bodyFieldRenames.get(wireName) ?? fieldName(wireName);\n  };\n\n  // Method signature. Deduplicate param names across path/body/query.\n  const sigParts: string[] = [];\n  const seenParamNames = new Set<string>();\n\n  // Path params: always required, snake_case.\n  for (const p of pathParams) {\n    const n = safeParamName(p.name);\n    if (seenParamNames.has(n)) continue;\n    seenParamNames.add(n);\n    sigParts.push(`${n}:`);\n  }\n\n  // Required body/query params next.\n  for (const f of bodyFields) {\n    if (hiddenParams.has(f.name)) continue;\n    if (!f.required) continue;\n    const n = bodyKwargName(f.name);\n    if (seenParamNames.has(n)) continue;\n    seenParamNames.add(n);\n    sigParts.push(`${n}:`);\n  }\n  for (const q of queryParams) {\n    if (hiddenParams.has(q.name)) continue;\n    if (!q.required) continue;\n    const n = safeParamName(q.name);\n    if (seenParamNames.has(n)) continue;\n    seenParamNames.add(n);\n    sigParts.push(`${n}:`);\n  }\n\n  // Required parameter group kwargs.\n  for (const group of op.parameterGroups ?? []) {\n    if (group.optional) continue;\n    const n = fieldName(group.name);\n    if (seenParamNames.has(n)) continue;\n    seenParamNames.add(n);\n    sigParts.push(`${n}:`);\n  }\n\n  // Optional body/query params.\n  for (const f of bodyFields) {\n    if (hiddenParams.has(f.name)) continue;\n    if (f.required) continue;\n    const n = bodyKwargName(f.name);\n    if (seenParamNames.has(n)) continue;\n    seenParamNames.add(n);\n    sigParts.push(`${n}: nil`);\n  }\n  for (const q of queryParams) {\n    if (hiddenParams.has(q.name)) continue;\n    if (q.required) continue;\n    const n = safeParamName(q.name);\n    if (seenParamNames.has(n)) continue;\n    seenParamNames.add(n);\n    // Spec is the source of truth for defaults. If the OpenAPI parameter has\n    // a `default`, surface it in the Ruby keyword arg signature; otherwise\n    // default to nil so the param is omitted from the request unless set.\n    const defaultVal = q.default != null ? rubyDefaultLiteral(q.default) : 'nil';\n    sigParts.push(`${n}: ${defaultVal}`);\n  }\n\n  // Optional parameter group kwargs.\n  for (const group of op.parameterGroups ?? []) {\n    if (!group.optional) continue;\n    const n = fieldName(group.name);\n    if (seenParamNames.has(n)) continue;\n    seenParamNames.add(n);\n    sigParts.push(`${n}: nil`);\n  }\n\n  // Always accept request_options.\n  sigParts.push('request_options: {}');\n\n  // YARD docs.\n  const doc = buildYardDoc(\n    op,\n    pathParams,\n    queryParams,\n    bodyFields,\n    hiddenParams,\n    bodyFieldRenames,\n    listWrapperModels,\n    variantClassRef,\n  );\n  for (const line of doc) lines.push(`    ${line}`);\n\n  // Signature.\n  if (sigParts.length === 0) {\n    lines.push(`    def ${method}`);\n  } else if (sigParts.length === 1 && sigParts[0].length < 60) {\n    lines.push(`    def ${method}(${sigParts[0]})`);\n  } else {\n    lines.push(`    def ${method}(`);\n    for (let i = 0; i < sigParts.length; i++) {\n      const sep = i === sigParts.length - 1 ? '' : ',';\n      lines.push(`      ${sigParts[i]}${sep}`);\n    }\n    lines.push('    )');\n  }\n\n  // Emit deprecation warning for deprecated operations.\n  if (op.deprecated) {\n    lines.push(`      warn \"[DEPRECATION] \\\\\\`${method}\\\\\\` is deprecated.\", uplevel: 1`);\n  }\n\n  // Body: construct params / body / path\n  const rubyPath = interpolateRubyPath(op.path, pathParams);\n\n  // Query params hash.\n  // For methods with a request body (POST/PUT/PATCH), exclude query params\n  // that also appear as body fields — they belong in the body only.\n  const method_http = op.httpMethod.toLowerCase();\n  const hasBodyMethod = !['get', 'head', 'delete'].includes(method_http);\n  const bodyFieldNameSet = new Set(bodyFields.map((f) => f.name));\n  const qEntries = queryParams.filter(\n    (q) => !hiddenParams.has(q.name) && !(hasBodyMethod && bodyFieldNameSet.has(q.name)),\n  );\n  const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n  // Groups go to query only for operations without a request body (GET/DELETE).\n  // For POST/PUT/PATCH, groups are dispatched into the body below.\n  const groupsGoToQuery = hasGroups && !hasBodyMethod;\n  const hasQuery = qEntries.length > 0 || groupsGoToQuery;\n  if (hasQuery) {\n    // Skip `.compact` when no entry can be nil — required kwargs are always\n    // passed (Ruby raises ArgumentError otherwise), so the literal has no nil\n    // values to drop. Group dispatch happens after the literal is built and\n    // doesn't contribute potentially-nil entries either.\n    const queryHasNilable = qEntries.some((q) => !q.required);\n    const queryCompact = queryHasNilable ? '.compact' : '';\n    lines.push('      params = {');\n    for (let i = 0; i < qEntries.length; i++) {\n      const q = qEntries[i];\n      const sep = i === qEntries.length - 1 && !groupsGoToQuery ? '' : ',';\n      lines.push(`        ${rubyStringLit(q.name)} => ${safeParamName(q.name)}${sep}`);\n    }\n    lines.push(`      }${queryCompact}`);\n\n    if (groupsGoToQuery) {\n      // Parameter group dispatch: callers pass a typed variant class instance\n      // (e.g. `WorkOS::ParentResourceById`); we pattern-match on its class\n      // and forward its readers into the query hash.\n      for (const group of op.parameterGroups ?? []) {\n        const prop = fieldName(group.name);\n        if (group.optional) {\n          lines.push(`      if ${prop}`);\n          lines.push(`        case ${prop}`);\n        } else {\n          lines.push(`      case ${prop}`);\n        }\n        for (const variant of group.variants) {\n          const variantClass = variantClassRef(group, variant.name);\n          lines.push(`      when ${variantClass}`);\n          for (const p of variant.parameters) {\n            lines.push(`        params[${rubyStringLit(p.name)}] = ${prop}.${fieldName(p.name)}`);\n          }\n        }\n        lines.push(`      else`);\n        lines.push(`        raise ArgumentError, ${dispatchErrorLiteral(group, prop, variantClassRef)}`);\n        lines.push('      end');\n        if (group.optional) {\n          lines.push('      end');\n        }\n      }\n    }\n  }\n\n  // Request body. Emit when there are non-group body fields OR a parameter\n  // group dispatches into the body — the latter case matters when an\n  // operation's body is exclusively managed by a group (e.g.\n  // update_organization_membership's `role`), where filtering the group's\n  // leaves leaves bodyFields empty but the request still needs a payload.\n  const hasBody = (bodyFields.length > 0 && !['get', 'head'].includes(method_http)) || (hasGroups && hasBodyMethod);\n\n  if (hasBody) {\n    const bodyEntries: string[] = [];\n    for (const [k, v] of Object.entries(defaults)) {\n      const lit = typeof v === 'string' ? rubyStringLit(v) : String(v);\n      bodyEntries.push(`${rubyStringLit(k)} => ${lit}`);\n    }\n    for (const fc of inferFromClient) {\n      const clientProp = fc === 'client_secret' ? 'api_key' : fc;\n      const optKey = fc === 'client_secret' ? 'api_key' : fc;\n      bodyEntries.push(`${rubyStringLit(fc)} => (request_options[:${optKey}] || @client.${clientProp})`);\n    }\n    // Track whether any literal entry can be nil — defaults/inferFromClient\n    // resolve to non-nil values, so only optional body kwargs are nilable.\n    let bodyHasNilable = false;\n    for (const f of bodyFields) {\n      if (hiddenParams.has(f.name)) continue;\n      bodyEntries.push(`${rubyStringLit(f.name)} => ${bodyKwargName(f.name)}`);\n      if (!f.required) bodyHasNilable = true;\n    }\n    const bodyCompact = bodyHasNilable ? '.compact' : '';\n    lines.push('      body = {');\n    for (let i = 0; i < bodyEntries.length; i++) {\n      const sep = i === bodyEntries.length - 1 ? '' : ',';\n      lines.push(`        ${bodyEntries[i]}${sep}`);\n    }\n    lines.push(`      }${bodyCompact}`);\n\n    // Parameter group dispatch into body for POST/PUT/PATCH so sensitive\n    // fields (passwords, role slugs) never leak into the URL query string.\n    // DELETE groups are already handled via query above (groupsGoToQuery).\n    // Callers pass a typed variant class instance and we pattern-match on it.\n    if (hasGroups && hasBodyMethod) {\n      for (const group of op.parameterGroups ?? []) {\n        const prop = fieldName(group.name);\n        if (group.optional) {\n          lines.push(`      if ${prop}`);\n          lines.push(`        case ${prop}`);\n        } else {\n          lines.push(`      case ${prop}`);\n        }\n        for (const variant of group.variants) {\n          const variantClass = variantClassRef(group, variant.name);\n          lines.push(`      when ${variantClass}`);\n          for (const p of variant.parameters) {\n            lines.push(`        body[${rubyStringLit(p.name)}] = ${prop}.${fieldName(p.name)}`);\n          }\n        }\n        lines.push(`      else`);\n        lines.push(`        raise ArgumentError, ${dispatchErrorLiteral(group, prop, variantClassRef)}`);\n        lines.push('      end');\n        if (group.optional) {\n          lines.push('      end');\n        }\n      }\n    }\n  }\n\n  // Make the request via the unified @client.request helper.\n  const requestArgs: string[] = [];\n  requestArgs.push(`method: :${method_http}`);\n  requestArgs.push(`path: ${rubyPath}`);\n  requestArgs.push('auth: true');\n  if (hasQuery) requestArgs.push('params: params');\n  if (hasBody) requestArgs.push('body: body');\n  requestArgs.push('request_options: request_options');\n\n  lines.push('      response = @client.request(');\n  for (let i = 0; i < requestArgs.length; i++) {\n    const sep = i === requestArgs.length - 1 ? '' : ',';\n    lines.push(`        ${requestArgs[i]}${sep}`);\n  }\n  lines.push('      )');\n\n  // Response handling\n  void plan;\n  // Build the list of local kwarg names that should be forwarded when the\n  // method recursively calls itself for the next page (excluding the cursor\n  // param, which is overridden).\n  const forwardableParams: string[] = [];\n  const bodyNames = new Set(bodyFields.map((f) => bodyKwargName(f.name)));\n  for (const p of pathParams) forwardableParams.push(safeParamName(p.name));\n  for (const f of bodyFields) {\n    if (hiddenParams.has(f.name)) continue;\n    forwardableParams.push(bodyKwargName(f.name));\n  }\n  for (const q of queryParams) {\n    if (hiddenParams.has(q.name)) continue;\n    const name = safeParamName(q.name);\n    if (bodyNames.has(name) || forwardableParams.includes(name)) continue;\n    forwardableParams.push(name);\n  }\n  // Include parameter group kwargs so they are forwarded in pagination fetch_next.\n  for (const group of op.parameterGroups ?? []) {\n    const name = fieldName(group.name);\n    if (!forwardableParams.includes(name)) {\n      forwardableParams.push(name);\n    }\n  }\n  const responseLines = emitResponseHandling(op, listWrapperModels, modelNames, method, forwardableParams);\n  for (const line of responseLines) lines.push(`      ${line}`);\n\n  lines.push('    end');\n\n  // Ensure we require the response model file if needed.\n  // Skip list-wrapper models (they are not emitted as files).\n  const respModel = findPrimaryResponseModel(op.response);\n  if (respModel && modelNames.has(respModel) && !listWrapperModels.has(respModel)) {\n    requires.add(fileName(respModel));\n  }\n\n  return lines.join('\\n');\n}\n\n/** Build the response parsing expression(s). */\nfunction emitResponseHandling(\n  op: Operation,\n  listWrapperModels: Map<string, Model>,\n  modelNames: Set<string>,\n  currentMethod: string,\n  forwardableParams: string[],\n): string[] {\n  const ref = op.response;\n\n  // Build a filters hash from the forwarded params (excluding cursor).\n  const filterEntries = forwardableParams\n    .filter((p) => p !== 'after' && p !== 'request_options')\n    .map((p) => `${p}: ${p}`)\n    .join(', ');\n  const _filtersArg = filterEntries ? `, filters: { ${filterEntries} }` : '';\n\n  // Pagination / list wrapper: use ListStruct.from_response with auto-paging wired.\n  if (ref.kind === 'model' && listWrapperModels.has(ref.name)) {\n    const wrapper = listWrapperModels.get(ref.name)!;\n    const dataField = wrapper.fields.find((f) => f.name === 'data');\n    const itemCls =\n      dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model'\n        ? `WorkOS::${className(dataField.type.items.name)}`\n        : null;\n\n    const cursorLocal = safeParamName('after');\n    const hasCursorInSignature = forwardableParams.includes(cursorLocal);\n\n    const out: string[] = [];\n\n    if (hasCursorInSignature) {\n      // Build a fetch_next lambda that accepts a cursor string and replays\n      // the current call with the new cursor.\n      out.push(`fetch_next = ->(cursor) {`);\n      out.push(`  ${currentMethod}(`);\n      const allForwards = [...forwardableParams, 'request_options'];\n      for (let i = 0; i < allForwards.length; i++) {\n        const param = allForwards[i];\n        const sep = i === allForwards.length - 1 ? '' : ',';\n        const value = param === cursorLocal ? 'cursor' : param;\n        out.push(`    ${param}: ${value}${sep}`);\n      }\n      out.push(`  )`);\n      out.push(`}`);\n    }\n\n    const fromArgs: string[] = [];\n    fromArgs.push('response');\n    if (itemCls) fromArgs.push(`model: ${itemCls}`);\n    if (filterEntries) fromArgs.push(`filters: { ${filterEntries} }`);\n    if (hasCursorInSignature) fromArgs.push('fetch_next: fetch_next');\n\n    if (fromArgs.length <= 2) {\n      out.push(`WorkOS::Types::ListStruct.from_response(${fromArgs.join(', ')})`);\n    } else {\n      out.push(`WorkOS::Types::ListStruct.from_response(`);\n      for (let i = 0; i < fromArgs.length; i++) {\n        const sep = i === fromArgs.length - 1 ? '' : ',';\n        out.push(`  ${fromArgs[i]}${sep}`);\n      }\n      out.push(`)`);\n    }\n    return out;\n  }\n\n  if (ref.kind === 'model' && modelNames.has(ref.name)) {\n    const cls = `WorkOS::${className(ref.name)}`;\n    return [\n      `result = ${cls}.new(response.body)`,\n      `result.last_response = WorkOS::Types::ApiResponse.new(http_status: response.code.to_i, http_headers: response.each_header.to_h, request_id: response[\"x-request-id\"])`,\n      `result`,\n    ];\n  }\n\n  // Paginated endpoint whose IR response is typed as array (the IR lost the\n  // wrapper envelope). When op.pagination exists, the real HTTP response is\n  // { data: [...], list_metadata: {...} } — generate ListStruct handling.\n  if (ref.kind === 'array' && op.pagination) {\n    const itemCls =\n      ref.items.kind === 'model' && modelNames.has(ref.items.name) ? `WorkOS::${className(ref.items.name)}` : null;\n\n    const cursorLocal = safeParamName('after');\n    const hasCursorInSignature = forwardableParams.includes(cursorLocal);\n\n    const out: string[] = [];\n\n    if (hasCursorInSignature) {\n      out.push(`fetch_next = ->(cursor) {`);\n      out.push(`  ${currentMethod}(`);\n      const allForwards = [...forwardableParams, 'request_options'];\n      for (let i = 0; i < allForwards.length; i++) {\n        const param = allForwards[i];\n        const sep = i === allForwards.length - 1 ? '' : ',';\n        const value = param === cursorLocal ? 'cursor' : param;\n        out.push(`    ${param}: ${value}${sep}`);\n      }\n      out.push(`  )`);\n      out.push(`}`);\n    }\n\n    const fromArgs: string[] = [];\n    fromArgs.push('response');\n    if (itemCls) fromArgs.push(`model: ${itemCls}`);\n    if (filterEntries) fromArgs.push(`filters: { ${filterEntries} }`);\n    if (hasCursorInSignature) fromArgs.push('fetch_next: fetch_next');\n\n    if (fromArgs.length <= 2) {\n      out.push(`WorkOS::Types::ListStruct.from_response(${fromArgs.join(', ')})`);\n    } else {\n      out.push(`WorkOS::Types::ListStruct.from_response(`);\n      for (let i = 0; i < fromArgs.length; i++) {\n        const sep = i === fromArgs.length - 1 ? '' : ',';\n        out.push(`  ${fromArgs[i]}${sep}`);\n      }\n      out.push(`)`);\n    }\n    return out;\n  }\n\n  if (ref.kind === 'array' && ref.items.kind === 'model' && modelNames.has(ref.items.name)) {\n    const itemCls = `WorkOS::${className(ref.items.name)}`;\n    return [`parsed = JSON.parse(response.body)`, `(parsed || []).map { |item| ${itemCls}.new(item) }`];\n  }\n\n  if (ref.kind === 'nullable') {\n    return emitResponseHandling(\n      { ...op, response: ref.inner },\n      listWrapperModels,\n      modelNames,\n      currentMethod,\n      forwardableParams,\n    );\n  }\n\n  // Unknown/void response — return nil\n  if (ref.kind === 'primitive' && ref.type === 'unknown') {\n    return ['nil'];\n  }\n\n  // Default: return parsed JSON\n  return [`JSON.parse(response.body)`];\n}\n\n/** Find the primary model name (if any) in a response TypeRef. */\nfunction findPrimaryResponseModel(ref: TypeRef): string | null {\n  switch (ref.kind) {\n    case 'model':\n      return ref.name;\n    case 'nullable':\n      return findPrimaryResponseModel(ref.inner);\n    case 'array':\n      return findPrimaryResponseModel(ref.items);\n    case 'union': {\n      for (const v of ref.variants) {\n        const n = findPrimaryResponseModel(v);\n        if (n) return n;\n      }\n      return null;\n    }\n    default:\n      return null;\n  }\n}\n\n/** Get the body fields, expanded from model refs. Handles nested/model refs and unions. */\nfunction getRequestBodyFields(\n  op: Operation,\n  hiddenParams: Set<string>,\n  modelByName: Map<string, Model>,\n): { name: string; required: boolean; type: TypeRef; description?: string; deprecated?: boolean }[] {\n  void hiddenParams;\n  const ref = op.requestBody;\n  if (!ref) return [];\n\n  if (ref.kind === 'model') {\n    const model = modelByName.get(ref.name);\n    if (!model) return [];\n    return model.fields.map((f) => ({\n      name: f.name,\n      required: f.required,\n      type: f.type,\n      description: f.description,\n      deprecated: f.deprecated,\n    }));\n  }\n  if (ref.kind === 'nullable') {\n    return getRequestBodyFields({ ...op, requestBody: ref.inner }, hiddenParams, modelByName);\n  }\n  // Unions: merge fields from ALL model variants so every possible body param\n  // is exposed. Fields that appear in every variant keep their original\n  // requiredness; fields that appear in only some variants become optional.\n  if (ref.kind === 'union') {\n    const variantFieldSets: Map<\n      string,\n      { name: string; required: boolean; type: TypeRef; description?: string; deprecated?: boolean }\n    >[] = [];\n    for (const v of ref.variants) {\n      if (v.kind === 'model') {\n        const model = modelByName.get(v.name);\n        if (model) {\n          const fieldMap = new Map<\n            string,\n            { name: string; required: boolean; type: TypeRef; description?: string; deprecated?: boolean }\n          >();\n          for (const f of model.fields) {\n            fieldMap.set(f.name, {\n              name: f.name,\n              required: f.required,\n              type: f.type,\n              description: f.description,\n              deprecated: f.deprecated,\n            });\n          }\n          variantFieldSets.push(fieldMap);\n        }\n      }\n    }\n    if (variantFieldSets.length === 0) return [];\n\n    // Collect all field names in order (preserving first-seen order).\n    const allFieldNames: string[] = [];\n    const seen = new Set<string>();\n    for (const fieldMap of variantFieldSets) {\n      for (const name of fieldMap.keys()) {\n        if (!seen.has(name)) {\n          seen.add(name);\n          allFieldNames.push(name);\n        }\n      }\n    }\n\n    return allFieldNames.map((name) => {\n      // Use the first variant that has this field as the canonical source.\n      const canonical = variantFieldSets.find((fm) => fm.has(name))!.get(name)!;\n      // A field is required only if it appears and is required in EVERY variant.\n      const requiredInAll = variantFieldSets.every((fm) => {\n        const f = fm.get(name);\n        return f && f.required;\n      });\n      return { ...canonical, required: requiredInAll };\n    });\n  }\n  return [];\n}\n\n/** Convert an OpenAPI path like /orgs/{id}/users/{uid} to a Ruby interpolated string. */\nfunction interpolateRubyPath(path: string, pathParams: Parameter[]): string {\n  if (pathParams.length === 0) {\n    return `'${path}'`;\n  }\n  let result = path;\n  for (const p of pathParams) {\n    const placeholder = `{${p.name}}`;\n    result = result.split(placeholder).join(`#{WorkOS::Util.encode_path(${safeParamName(p.name)})}`);\n  }\n  return `\"${result}\"`;\n}\n\n/** Collapse multi-line description text into a single YARD-safe line. */\nfunction oneLine(desc: string | undefined): string {\n  if (!desc) return '';\n  return desc.replace(/\\r/g, ' ').replace(/\\n+/g, ' ').replace(/\\s+/g, ' ').trim();\n}\n\nfunction buildYardDoc(\n  op: Operation,\n  pathParams: Parameter[],\n  queryParams: Parameter[],\n  bodyFields: { name: string; required: boolean; type: TypeRef; description?: string; deprecated?: boolean }[],\n  hiddenParams: Set<string>,\n  bodyFieldRenames: Map<string, string> | undefined,\n  listWrapperModels: Map<string, Model> | undefined,\n  variantClassRef: (group: { name: string }, variantName: string) => string,\n): string[] {\n  const lines: string[] = [];\n  const summary = op.description ?? `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const firstLine = summary.split('\\n')[0] ?? '';\n  lines.push(`# ${firstLine}`);\n  if (op.deprecated) {\n    lines.push('# @deprecated');\n  }\n\n  // Track emitted param names to avoid duplicates (e.g. code in both body and query).\n  const emittedParamNames = new Set<string>();\n\n  for (const p of pathParams) {\n    const n = safeParamName(p.name);\n    if (emittedParamNames.has(n)) continue;\n    emittedParamNames.add(n);\n    const type = mapTypeRefForYard(p.type);\n    const deprecatedPrefix = p.deprecated ? '(deprecated) ' : '';\n    lines.push(`# @param ${n} [${type}] ${deprecatedPrefix}${oneLine(p.description)}`.trim());\n  }\n  for (const f of bodyFields) {\n    if (hiddenParams.has(f.name)) continue;\n    const paramName = bodyFieldRenames?.get(f.name) ?? fieldName(f.name);\n    if (emittedParamNames.has(paramName)) continue;\n    emittedParamNames.add(paramName);\n    const type = mapTypeRefForYard(f.type);\n    // Only append nil suffix for optional params whose type doesn't already include nil.\n    const alreadyNilable = type.split(', ').includes('nil');\n    const suffix = f.required || alreadyNilable ? '' : ', nil';\n    const deprecatedPrefix = f.deprecated ? '(deprecated) ' : '';\n    lines.push(`# @param ${paramName} [${type}${suffix}] ${deprecatedPrefix}${oneLine(f.description)}`.trim());\n  }\n  for (const q of queryParams) {\n    if (hiddenParams.has(q.name)) continue;\n    const n = safeParamName(q.name);\n    if (emittedParamNames.has(n)) continue;\n    emittedParamNames.add(n);\n    const type = mapTypeRefForYard(q.type);\n    const alreadyNilable = type.split(', ').includes('nil');\n    const suffix = q.required || alreadyNilable ? '' : ', nil';\n    const deprecatedPrefix = q.deprecated ? '(deprecated) ' : '';\n    lines.push(`# @param ${n} [${type}${suffix}] ${deprecatedPrefix}${oneLine(q.description)}`.trim());\n  }\n  // Parameter group kwargs: the type bracket lists the variant classes the\n  // caller may pass; no extra prose needed since YARD already renders them.\n  for (const group of op.parameterGroups ?? []) {\n    const n = fieldName(group.name);\n    if (emittedParamNames.has(n)) continue;\n    emittedParamNames.add(n);\n    const variantTypes = group.variants.map((v) => variantClassRef(group, v.name)).join(', ');\n    const suffix = group.optional ? ', nil' : '';\n    lines.push(`# @param ${n} [${variantTypes}${suffix}] Identifies the ${group.name.replace(/_/g, ' ')}.`);\n  }\n  lines.push(`# @param request_options [Hash] (see WorkOS::Types::RequestOptions)`);\n\n  // Return type: void for unknown-primitive, ListStruct for list wrappers and\n  // paginated array endpoints (with element type annotation).\n  const ref = op.response;\n  if (ref.kind === 'primitive' && ref.type === 'unknown') {\n    lines.push(`# @return [void]`);\n  } else if (ref.kind === 'model' && listWrapperModels?.has(ref.name)) {\n    const wrapper = listWrapperModels.get(ref.name)!;\n    const dataField = wrapper.fields.find((f: { name: string; type: TypeRef }) => f.name === 'data');\n    const elementType =\n      dataField && dataField.type.kind === 'array' && dataField.type.items.kind === 'model'\n        ? `WorkOS::${className(dataField.type.items.name)}`\n        : null;\n    const suffix = elementType ? `<${elementType}>` : '';\n    lines.push(`# @return [WorkOS::Types::ListStruct${suffix}]`);\n  } else if (ref.kind === 'array' && op.pagination) {\n    const elementType = ref.items.kind === 'model' ? `WorkOS::${className(ref.items.name)}` : null;\n    const suffix = elementType ? `<${elementType}>` : '';\n    lines.push(`# @return [WorkOS::Types::ListStruct${suffix}]`);\n  } else {\n    const retType = mapTypeRefForYard(ref);\n    lines.push(`# @return [${retType}]`);\n  }\n  return lines;\n}\n\nvoid methodName;\n\n/** Render a Ruby single-quoted string literal, escaping embedded quotes and backslashes. */\nfunction rubyStringLit(s: string): string {\n  return `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n}\n\n/** Render an arbitrary spec-default value as a Ruby literal for a method-arg default. */\nfunction rubyDefaultLiteral(value: unknown): string {\n  if (typeof value === 'string') return rubyStringLit(value);\n  if (typeof value === 'number') return Number.isFinite(value) ? String(value) : 'nil';\n  if (typeof value === 'boolean') return value ? 'true' : 'false';\n  if (value === null) return 'nil';\n  return 'nil';\n}\n\n/**\n * Build a Ruby double-quoted string expression for the `else raise ArgumentError`\n * arm of a parameter-group dispatcher. Lists the expected variant classes and\n * interpolates the actual class of the value the caller passed.\n */\nfunction dispatchErrorLiteral(\n  group: { name: string; variants: { name: string }[] },\n  prop: string,\n  variantClassRef: (group: { name: string }, variantName: string) => string,\n): string {\n  const expected = group.variants.map((v) => variantClassRef(group, v.name)).join(', ');\n  return `\"expected ${prop} to be one of: ${expected}, got #{${prop}.class}\"`;\n}\n","import type { ApiSpec, EmitterContext, GeneratedFile, Service, Model, Enum } from '@workos/oagen';\nimport { assignModelsToServices } from '@workos/oagen';\nimport {\n  servicePropertyName,\n  resolveClassName,\n  className,\n  fileName,\n  buildMountDirMap,\n  buildExportedClassNameSet,\n  resolveServiceTarget,\n} from './naming.js';\nimport { classifyUnassignedModel } from './models.js';\nimport { getMountTarget } from '../shared/resolved-ops.js';\nimport { isListWrapperModel, isListMetadataModel } from '../shared/model-utils.js';\nimport { NON_SPEC_SERVICES } from '../shared/non-spec-services.js';\n\n/**\n * Ruby `Client#accessor` wiring for each non-spec service id.\n *\n * Entries omitted from this map (e.g. `webhook_verification`) extend an\n * already-generated service class via `@oagen-ignore` blocks and need no\n * dedicated accessor.\n *\n * `ctorArg = 'self'` means the helper takes the client (`Foo.new(self)`).\n * `ctorArg = ''` means the accessor returns the constant directly (modules\n * with module-level functions, e.g. `WorkOS::PKCE`).\n */\nconst NON_SPEC_ACCESSORS: Record<string, { prop: string; className: string; ctorArg: 'self' | '' }> = {\n  passwordless: { prop: 'passwordless', className: 'Passwordless', ctorArg: 'self' },\n  actions: { prop: 'actions', className: 'Actions', ctorArg: 'self' },\n  session_manager: { prop: 'session_manager', className: 'SessionManager', ctorArg: 'self' },\n  pkce: { prop: 'pkce', className: 'PKCE', ctorArg: '' },\n};\n\n/**\n * Hand-maintained class names whose file basename does NOT camelCase to the\n * expected Ruby class name under Zeitwerk's default inflector. Each entry\n * adds an `inflect(\"file\" => \"Class\")` override so the autoloader can\n * resolve `WorkOS::PKCE` (rather than the default `WorkOS::Pkce`).\n */\nconst NON_SPEC_INFLECTIONS: ReadonlyArray<readonly [string, string]> = [['pkce', 'PKCE']];\n\n/**\n * Generate:\n *  - lib/workos.rb         — sets up a Zeitwerk loader for the gem\n *  - lib/workos/client.rb  — client class with service accessors\n *\n * The HTTP runtime (request execution, retries, error mapping, pagination)\n * lives in hand-maintained files flagged with `@oagen-ignore-file`:\n *  - lib/workos/base_client.rb\n *  - lib/workos/errors.rb\n *  - lib/workos/configuration.rb\n *  - lib/workos/hash_provider.rb\n *  - lib/workos/types/list_struct.rb\n */\nexport function generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  files.push(generateInflectionsFile(spec, ctx));\n  files.push(generateMainEntryFile(spec, ctx));\n  files.push(generateClientClass(spec, ctx));\n  return files;\n}\n\n/** Build map: top-level service -> resolved class name (deduplicated by mount target). */\nexport function buildTopLevelServices(spec: ApiSpec, ctx: EmitterContext): Service[] {\n  const seen = new Set<string>();\n  const out: Service[] = [];\n  for (const service of spec.services) {\n    const target = getMountTarget(service, ctx) || resolveClassName(service, ctx);\n    if (seen.has(target)) continue;\n    seen.add(target);\n    const canonical =\n      spec.services.find((s) => (getMountTarget(s, ctx) || resolveClassName(s, ctx)) === target && s.name === target) ??\n      service;\n    out.push(canonical);\n  }\n  return out;\n}\n\n/**\n * Simulate Zeitwerk::Inflector's default inflection so we can emit the minimal\n * set of overrides. Zeitwerk camelizes `foo_bar` -> `FooBar`; we only add\n * inflector entries when the emitter's canonical className disagrees.\n */\nfunction rubyCamelize(basename: string): string {\n  return basename\n    .split('_')\n    .filter((p) => p.length > 0)\n    .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n    .join('');\n}\n\n/** Build the inflection map: file basename -> class name for all generated constants. */\nfunction buildInflectionMap(spec: ApiSpec, ctx: EmitterContext): Map<string, string> {\n  const inflections = new Map<string, string>();\n\n  inflections.set('workos', 'WorkOS');\n\n  const exportedClasses = buildExportedClassNameSet(ctx);\n  for (const service of buildTopLevelServices(spec, ctx)) {\n    const target = resolveServiceTarget(\n      getMountTarget(service, ctx) || resolveClassName(service, ctx),\n      exportedClasses,\n    );\n    const cls = className(target);\n    const file = fileName(target);\n    if (rubyCamelize(file) !== cls) inflections.set(file, cls);\n  }\n\n  const seenClasses = new Set<string>();\n  for (const model of spec.models as Model[]) {\n    if (isListWrapperModel(model) || isListMetadataModel(model)) continue;\n    const cls = className(model.name);\n    if (seenClasses.has(cls)) continue;\n    seenClasses.add(cls);\n    const file = fileName(model.name);\n    if (rubyCamelize(file) !== cls) inflections.set(file, cls);\n  }\n\n  const seenEnums = new Set<string>();\n  for (const enumDef of spec.enums as Enum[]) {\n    const cls = className(enumDef.name);\n    if (seenEnums.has(cls)) continue;\n    seenEnums.add(cls);\n    const file = fileName(enumDef.name);\n    if (rubyCamelize(file) !== cls) inflections.set(file, cls);\n  }\n\n  for (const [file, cls] of NON_SPEC_INFLECTIONS) inflections.set(file, cls);\n\n  return inflections;\n}\n\n/** Generate lib/workos/inflections.rb — Zeitwerk inflection overrides (T40/C5). */\nfunction generateInflectionsFile(spec: ApiSpec, ctx: EmitterContext): GeneratedFile {\n  const inflections = buildInflectionMap(spec, ctx);\n  const inflectEntries = [...inflections.entries()]\n    .sort(([a], [b]) => a.localeCompare(b))\n    .map(([fileBase, cls]) => `  \"${fileBase}\" => \"${cls}\"`)\n    .join(',\\n');\n\n  const lines: string[] = [];\n  lines.push('# Zeitwerk inflection overrides for the WorkOS gem.');\n  lines.push('# Maps file basenames to class/module names where the default');\n  lines.push('# CamelCase inference disagrees with the canonical class name.');\n  lines.push('WORKOS_INFLECTIONS = {');\n  lines.push(inflectEntries);\n  lines.push('}.freeze');\n\n  return {\n    path: 'lib/workos/inflections.rb',\n    content: lines.join('\\n'),\n    integrateTarget: true,\n    overwriteExisting: true,\n  };\n}\n\n/** Generate lib/workos.rb — Zeitwerk bootstrap for the gem. */\nfunction generateMainEntryFile(spec: ApiSpec, ctx: EmitterContext): GeneratedFile {\n  const modelSubdirs = collectModelSubdirs(spec, ctx);\n\n  const lines: string[] = [];\n  lines.push(`require 'zeitwerk'`);\n  lines.push('');\n  lines.push('module WorkOS');\n  lines.push('end');\n  lines.push('');\n  lines.push('loader = Zeitwerk::Loader.for_gem');\n  lines.push(`require_relative 'workos/inflections'`);\n  lines.push('loader.inflector.inflect(WORKOS_INFLECTIONS)');\n  for (const dir of modelSubdirs) {\n    lines.push(`loader.collapse(\"#{__dir__}/workos/${dir}\")`);\n  }\n  lines.push(`loader.ignore(\"#{__dir__}/workos/errors.rb\")`);\n  lines.push(`loader.ignore(\"#{__dir__}/workos/inflections.rb\")`);\n  lines.push(`loader.ignore(\"#{__dir__}/workos/configuration.rb\")`);\n  lines.push('loader.setup');\n  lines.push('');\n  lines.push(`require 'workos/errors'`);\n  lines.push(`require 'workos/configuration'`);\n\n  return {\n    path: 'lib/workos.rb',\n    content: lines.join('\\n'),\n    integrateTarget: true,\n    overwriteExisting: true,\n  };\n}\n\n/**\n * Collect the set of mount-target subfolders that models.ts will populate.\n * Used by the Zeitwerk bootstrap to emit `loader.collapse` directives, which\n * keep the generated namespace flat while the filesystem is grouped.\n */\nfunction collectModelSubdirs(spec: ApiSpec, ctx: EmitterContext): string[] {\n  const modelToService = assignModelsToServices(spec.models as Model[], spec.services, ctx.modelHints);\n  const mountDirMap = buildMountDirMap(ctx);\n  const subdirs = new Set<string>();\n  for (const model of spec.models as Model[]) {\n    if (isListWrapperModel(model) || isListMetadataModel(model)) continue;\n    const service = modelToService.get(model.name);\n    const dir = service\n      ? (mountDirMap.get(service) ?? classifyUnassignedModel(model.name))\n      : classifyUnassignedModel(model.name);\n    subdirs.add(dir);\n  }\n  return [...subdirs].sort();\n}\n\n/** Generate lib/workos/client.rb — thin service-wiring client. */\nfunction generateClientClass(spec: ApiSpec, ctx: EmitterContext): GeneratedFile {\n  const lines: string[] = [];\n  lines.push('module WorkOS');\n  lines.push('  class Client < BaseClient');\n\n  const topLevelServices = buildTopLevelServices(spec, ctx);\n  const exportedClasses = buildExportedClassNameSet(ctx);\n  for (const service of topLevelServices) {\n    const rawTarget = getMountTarget(service, ctx) || resolveClassName(service, ctx);\n    const cls = className(resolveServiceTarget(rawTarget, exportedClasses));\n    const prop = servicePropertyName(rawTarget);\n    lines.push('');\n    lines.push(`    def ${prop}`);\n    lines.push(`      @${prop} ||= WorkOS::${cls}.new(self)`);\n    lines.push('    end');\n  }\n\n  // Non-spec service accessors. Emitted inside @oagen-ignore so user edits\n  // (added/removed accessors, renames) survive subsequent regenerations.\n  lines.push('');\n  lines.push('    # @oagen-ignore-start — non-spec service accessors (hand-maintained)');\n  for (const { id } of NON_SPEC_SERVICES) {\n    const wiring = NON_SPEC_ACCESSORS[id];\n    if (!wiring) continue;\n    const init = wiring.ctorArg ? `.new(${wiring.ctorArg})` : '';\n    lines.push('');\n    lines.push(`    def ${wiring.prop}`);\n    lines.push(`      @${wiring.prop} ||= WorkOS::${wiring.className}${init}`);\n    lines.push('    end');\n  }\n  lines.push('    # @oagen-ignore-end');\n\n  lines.push('  end');\n  lines.push('end');\n\n  return {\n    path: 'lib/workos/client.rb',\n    content: lines.join('\\n'),\n    integrateTarget: true,\n    overwriteExisting: true,\n  };\n}\n","import type { ApiSpec, EmitterContext, GeneratedFile, Model, Operation, ResolvedWrapper, TypeRef } from '@workos/oagen';\nimport { assignModelsToServices } from '@workos/oagen';\nimport {\n  className,\n  fileName,\n  fieldName,\n  domainFieldName,\n  safeParamName,\n  scopedGroupVariantClassName,\n  servicePropertyName,\n  resolveMethodName,\n  buildExportedClassNameSet,\n  resolveServiceTarget,\n  buildMountDirMap,\n} from './naming.js';\nimport {\n  buildResolvedLookup,\n  scopedMountGroups,\n  lookupResolved,\n  buildHiddenParams,\n  collectBodyFieldTypes,\n  isModelInScope,\n  fileExistsAfterRun,\n} from '../shared/resolved-ops.js';\nimport { isListWrapperModel, isListMetadataModel } from '../shared/model-utils.js';\nimport { classifyUnassignedModel } from './models.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { buildGroupOwnerMap, pickVariantParamType } from './parameter-groups.js';\n\n/**\n * Generate Ruby Minitest test files for each service and per-method.\n * Tests use WebMock to stub HTTP and fixtures from test/fixtures/*.fixture.json.\n *\n * For MVP, we produce:\n *  - test/test_helper.rb (if not present, via hand-maintained runtime)\n *  - test/workos/{service}_test.rb — per-service test class with basic assertions\n *  - test/fixtures/{op}.fixture.json — sample fixture for each operation\n */\nexport function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  const groups = scopedMountGroups(ctx);\n  const models = spec.models as Model[];\n  const modelByName = new Map<string, Model>();\n  for (const m of models) modelByName.set(m.name, m);\n\n  const lookup = buildResolvedLookup(ctx);\n  const groupOwners = buildGroupOwnerMap(ctx);\n  const exportedClasses = buildExportedClassNameSet(ctx);\n\n  for (const [mountTarget, group] of groups) {\n    const resolvedTarget = resolveServiceTarget(mountTarget, exportedClasses);\n    const cls = className(resolvedTarget);\n    const prop = servicePropertyName(mountTarget);\n    const file = fileName(resolvedTarget);\n\n    const lines: string[] = [];\n    lines.push(`require 'test_helper'`);\n    lines.push('');\n    lines.push(`class ${cls}Test < Minitest::Test`);\n    lines.push('  include FixtureHelper');\n    lines.push('');\n    lines.push('  def setup');\n    lines.push('    @client = WorkOS::Client.new(api_key: \"sk_test_123\")');\n    lines.push('  end');\n\n    const emittedTestMethods = new Set<string>();\n    const authMethodManifest: { method: string; httpMethodSym: string; stubUrl: string; callArgs: string }[] = [];\n\n    for (const op of group.operations) {\n      const ownerService = group.resolvedOps.find((r) => r.operation === op)?.service;\n      if (!ownerService) continue;\n      const method = resolveMethodName(op, ownerService, ctx);\n      // Skip url-builder ops: their generated wrappers are suppressed (handled\n      // in resources.ts) and their hand-maintained replacements live inside\n      // @oagen-ignore blocks with bespoke tests.\n      if (lookupResolved(op, lookup)?.urlBuilder) continue;\n      // Skip duplicate method names (two ops may resolve to the same name).\n      if (emittedTestMethods.has(method)) continue;\n      emittedTestMethods.add(method);\n      lines.push('');\n\n      // Build the exact stub URL with path params substituted.\n      const stubUrl = buildStubUrl(op);\n\n      const isList =\n        (op.response.kind === 'model' &&\n          modelByName.get(op.response.name) &&\n          (isListWrapperModel(modelByName.get(op.response.name)!) || false)) ||\n        // Also detect paginated endpoints whose IR response is typed as array\n        (op.response.kind === 'array' && !!op.pagination);\n\n      const _isDelete = op.httpMethod.toLowerCase() === 'delete';\n      const httpMethodSym = `:${op.httpMethod.toLowerCase()}`;\n\n      const resolved = lookupResolved(op, lookup);\n      const hiddenParams = buildHiddenParams(resolved);\n      const callArgs = buildCallArgsStub(op, modelByName, hiddenParams, groupOwners, models, exportedClasses);\n      const bodyMatcher = buildBodyMatcher(op, modelByName, hiddenParams, models);\n\n      // Collect method info for the parameterized 401 test (T20).\n      authMethodManifest.push({ method, httpMethodSym, stubUrl, callArgs });\n\n      const stubRegex = stubUrlRegex(stubUrl);\n      lines.push(`  def test_${method}_returns_expected_result`);\n      lines.push(`    stub_request(${httpMethodSym}, ${stubRegex})`);\n      if (bodyMatcher) lines.push(`      .with(body: ${bodyMatcher})`);\n      if (isList) {\n        lines.push(`      .to_return(body: '{\"data\": [], \"list_metadata\": {}}', status: 200)`);\n        lines.push(`    result = @client.${prop}.${method}(${callArgs})`);\n        lines.push('    assert_kind_of WorkOS::Types::ListStruct, result');\n      } else if (op.response.kind === 'primitive') {\n        lines.push(`      .to_return(body: \"{}\", status: 200)`);\n        lines.push(`    result = @client.${prop}.${method}(${callArgs})`);\n        lines.push('    assert_nil result');\n      } else {\n        lines.push(`      .to_return(body: \"{}\", status: 200)`);\n        lines.push(`    result = @client.${prop}.${method}(${callArgs})`);\n        lines.push('    refute_nil result');\n      }\n      lines.push('  end');\n\n      // Per-variant tests: for every parameter group with more than one\n      // variant, emit one extra test per non-first variant so the second/third\n      // arm of the dispatcher gets exercised. Without this, a wrong wire-name\n      // mapping in (e.g.) ResourceTargetByExternalId would slip through.\n      for (const group of op.parameterGroups ?? []) {\n        for (let vi = 1; vi < group.variants.length; vi++) {\n          const variant = group.variants[vi];\n          const overrides = new Map<string, number>([[group.name, vi]]);\n          const variantCallArgs = buildCallArgsStub(\n            op,\n            modelByName,\n            hiddenParams,\n            groupOwners,\n            models,\n            exportedClasses,\n            overrides,\n          );\n          const variantBodyMatcher = buildBodyMatcher(op, modelByName, hiddenParams, models, overrides);\n          const suffix = `with_${fieldName(group.name)}_${fieldName(variant.name)}`;\n          lines.push('');\n          lines.push(`  def test_${method}_${suffix}_returns_expected_result`);\n          lines.push(`    stub_request(${httpMethodSym}, ${stubRegex})`);\n          if (variantBodyMatcher) lines.push(`      .with(body: ${variantBodyMatcher})`);\n          if (isList) {\n            lines.push(`      .to_return(body: '{\"data\": [], \"list_metadata\": {}}', status: 200)`);\n            lines.push(`    result = @client.${prop}.${method}(${variantCallArgs})`);\n            lines.push('    assert_kind_of WorkOS::Types::ListStruct, result');\n          } else if (op.response.kind === 'primitive') {\n            lines.push(`      .to_return(body: \"{}\", status: 200)`);\n            lines.push(`    result = @client.${prop}.${method}(${variantCallArgs})`);\n            lines.push('    assert_nil result');\n          } else {\n            lines.push(`      .to_return(body: \"{}\", status: 200)`);\n            lines.push(`    result = @client.${prop}.${method}(${variantCallArgs})`);\n            lines.push('    refute_nil result');\n          }\n          lines.push('  end');\n        }\n      }\n\n      // Wrapper tests (union split variants).\n      if (resolved?.wrappers && resolved.wrappers.length > 0) {\n        for (const wrapper of resolved.wrappers) {\n          emitWrapperTests({\n            lines,\n            wrapper,\n            op,\n            prop,\n            stubUrl,\n            httpMethodSym,\n            ctx,\n          });\n        }\n      }\n    }\n\n    // T20: parameterized 401 test — one define_method per endpoint.\n    if (authMethodManifest.length > 0) {\n      lines.push('');\n      lines.push('  # Parameterized authentication error tests (one per endpoint).');\n      lines.push('  [');\n      for (const entry of authMethodManifest) {\n        const argsLit = entry.callArgs ? `, args: { ${entry.callArgs} }` : '';\n        lines.push(\n          `    { name: :${entry.method}, verb: ${entry.httpMethodSym}, url: ${stubUrlRegex(entry.stubUrl)}${argsLit} },`,\n        );\n      }\n      lines.push('  ].each do |spec|');\n      lines.push(`    define_method(\"test_#{spec[:name]}_raises_authentication_error_on_401\") do`);\n      lines.push(`      stub_request(spec[:verb], spec[:url])`);\n      lines.push(`        .to_return(body: '{\"message\": \"Unauthorized\"}', status: 401)`);\n      lines.push(`      assert_raises(WorkOS::AuthenticationError) do`);\n      lines.push(`        @client.${prop}.send(spec[:name], **(spec[:args] || {}))`);\n      lines.push('      end');\n      lines.push('    end');\n      lines.push('  end');\n    }\n\n    lines.push('end');\n\n    files.push({\n      path: `test/workos/test_${file}.rb`,\n      content: lines.join('\\n'),\n      integrateTarget: true,\n      overwriteExisting: true,\n    });\n  }\n\n  files.push(generateModelRoundTripTest(spec, ctx));\n\n  return files;\n}\n\n/**\n * Emit test/workos/model_round_trip_test.rb that round-trips every non-wrapper\n * model through `.new(json)` and `.to_json`, asserting the result is a Hash and\n * that required fields appear with the seeded values.\n *\n * This is a whole-suite AGGREGATE: it references `WorkOS::<Class>` for every\n * model. Under a scoped (`--services`) run only the selected services' per-model\n * `.rb` files are (re)written, so a test referencing a brand-new out-of-scope\n * model whose file was never emitted would raise `NameError: uninitialized\n * constant`. Each per-model test is therefore gated by {@link fileExistsAfterRun}\n * on the SAME path `models.ts` writes (`lib/workos/<dir>/<file>.rb`): emit only\n * when that file will exist on disk after the run — in-scope (emitted this run)\n * OR already present from a prior run (`priorTargetManifestPaths`). Brand-new\n * out-of-scope models are excluded; renamed/removed-but-on-disk models are\n * retained. A full run (scoping inert) keeps every model.\n */\nfunction generateModelRoundTripTest(spec: ApiSpec, ctx: EmitterContext): GeneratedFile {\n  const lines: string[] = [];\n  lines.push(`require 'test_helper'`);\n  lines.push('');\n  lines.push('class ModelRoundTripTest < Minitest::Test');\n\n  const models = (spec.models as Model[]).filter((m) => !isListWrapperModel(m) && !isListMetadataModel(m));\n  const enumNames = new Set(spec.enums.map((e) => e.name));\n  const emitted = new Set<string>();\n\n  // Resolve each model's per-model file path EXACTLY as models.ts does, so the\n  // scope gate keys on the same path the per-model FILE writer uses.\n  const modelToService = assignModelsToServices(models, ctx.spec.services, ctx.modelHints);\n  const mountDirMap = buildMountDirMap(ctx);\n  const dirFor = (modelName: string): string => {\n    const service = modelToService.get(modelName);\n    if (!service) return classifyUnassignedModel(modelName);\n    return mountDirMap.get(service) ?? classifyUnassignedModel(modelName);\n  };\n\n  for (const model of models) {\n    // Skip models whose per-model `.rb` file will NOT exist on disk after this\n    // run (brand-new + out-of-scope under `--services`). Without this gate the\n    // aggregate would reference an undefined constant. The path mirrors\n    // models.ts's `lib/workos/${dirFor}/${fileName}.rb`.\n    const modelFilePath = `lib/workos/${dirFor(model.name)}/${fileName(model.name)}.rb`;\n    if (!fileExistsAfterRun(modelFilePath, isModelInScope(model.name, ctx), ctx)) continue;\n\n    // Avoid duplicate test names when two IR model names collapse to the same\n    // snake_case file name (we use the file name as the test suffix).\n    const fileBase = fileName(model.name);\n    if (emitted.has(fileBase)) continue;\n    emitted.add(fileBase);\n\n    // Build a fixture hash with string keys and stub values for every field.\n    const fixtureEntries: string[] = [];\n    const assertions: string[] = [];\n    const dedupFields = new Set<string>();\n    for (const f of model.fields) {\n      const wireName = f.name;\n      // Dedup on the DOMAIN accessor name to mirror the model's field dedup\n      // (models.ts). The fixture/assertion keys below still use the WIRE name.\n      const rubyFieldName = domainFieldName(f);\n      if (dedupFields.has(rubyFieldName)) continue;\n      dedupFields.add(rubyFieldName);\n      const stub = roundTripStub(f.type, enumNames);\n      fixtureEntries.push(`    ${stringKeyLiteral(wireName)} => ${stub},`);\n      // For primitive required fields we can assert the value round-trips.\n      // The model's to_json uses `<wireName>:` shorthand (symbol keys) for\n      // valid Ruby identifiers and `\"wire#name\" =>` (string keys) otherwise.\n      // Note: the symbol key uses the original wire name, not the snake_cased\n      // Ruby field name.\n      void rubyFieldName;\n      if (f.required && isPrimitiveLike(f.type)) {\n        const accessorKey = /^[A-Za-z_][A-Za-z0-9_]*$/.test(wireName) ? `:${wireName}` : stringKeyLiteral(wireName);\n        const actualExpr = `json[${accessorKey}]`;\n        // Minitest 6 removed the `assert_equal nil, x` form — emit the\n        // correct assertion based on the stub the emitter chose above.\n        if (stub === 'nil') {\n          assertions.push(`    assert_nil ${actualExpr}`);\n        } else {\n          assertions.push(`    assert_equal fixture[${stringKeyLiteral(wireName)}], ${actualExpr}`);\n        }\n      }\n    }\n\n    lines.push('');\n    lines.push(`  def test_${fileBase}_round_trip`);\n    if (fixtureEntries.length === 0) {\n      lines.push(`    model = WorkOS::${className(model.name)}.new('{}')`);\n      lines.push('    json = model.to_h');\n      lines.push('    assert_kind_of Hash, json');\n    } else {\n      lines.push('    fixture = {');\n      for (const line of fixtureEntries) lines.push(line);\n      lines.push('    }');\n      lines.push(`    model = WorkOS::${className(model.name)}.new(fixture.to_json)`);\n      lines.push('    json = model.to_h');\n      lines.push('    assert_kind_of Hash, json');\n      for (const a of assertions) lines.push(a);\n      // T23: Assert every fixture key round-trips into to_h (handles both symbol and string keys).\n      lines.push(\n        '    fixture.each_key { |k| assert json.key?(k.to_sym) || json.key?(k), \"Expected to_h to include key #{k}\" }',\n      );\n    }\n    lines.push('  end');\n  }\n\n  lines.push('end');\n\n  return {\n    path: 'test/workos/test_model_round_trip.rb',\n    content: lines.join('\\n'),\n    integrateTarget: true,\n    overwriteExisting: true,\n  };\n}\n\n/** Produce a Ruby string literal for a raw (possibly non-identifier) key. */\nfunction stringKeyLiteral(name: string): string {\n  return `\"${name.replace(/\"/g, '\\\\\"')}\"`;\n}\n\nfunction isPrimitiveLike(ref: TypeRef): boolean {\n  if (ref.kind === 'primitive') return true;\n  if (ref.kind === 'nullable') return isPrimitiveLike(ref.inner);\n  return false;\n}\n\n/** Produce a Ruby literal value for seeding a model fixture. */\nfunction roundTripStub(ref: TypeRef, enumNames: Set<string>): string {\n  switch (ref.kind) {\n    case 'primitive':\n      switch (ref.type) {\n        case 'string':\n          return `\"stub\"`;\n        case 'integer':\n          return `1`;\n        case 'number':\n          return `1.0`;\n        case 'boolean':\n          return `true`;\n        default:\n          return `nil`;\n      }\n    case 'array':\n      return `[]`;\n    case 'map':\n      return `{}`;\n    case 'enum':\n      return enumNames.has(ref.name) ? `\"stub\"` : `\"stub\"`;\n    case 'literal':\n      if (typeof ref.value === 'string') return `\"${ref.value}\"`;\n      if (ref.value === null) return `nil`;\n      return String(ref.value);\n    case 'nullable':\n      return `nil`;\n    case 'model':\n      return `{}`;\n    case 'union':\n      return ref.variants.length > 0 ? roundTripStub(ref.variants[0], enumNames) : `nil`;\n    default:\n      return `nil`;\n  }\n}\n\n/** Build minimal placeholder arguments for calling the SDK method from a test.\n *  `variantOverrides` selects a non-zero variant index per group; absent groups\n *  default to variant 0. Used to emit per-variant test cases that exercise the\n *  second/third arm of each parameter-group dispatcher.\n */\nfunction buildCallArgsStub(\n  op: Operation,\n  modelByName: Map<string, Model>,\n  hiddenParams: Set<string>,\n  groupOwners: Map<string, string>,\n  models: Model[],\n  exportedClasses: Set<string>,\n  variantOverrides: Map<string, number> = new Map(),\n): string {\n  const parts: string[] = [];\n  const seen = new Set<string>();\n\n  // Path params (required).\n  const pathParamNames = new Set<string>();\n  for (const p of op.pathParams ?? []) {\n    const name = safeParamName(p.name);\n    pathParamNames.add(name);\n    if (seen.has(name)) continue;\n    seen.add(name);\n    parts.push(`${name}: ${stubValueFor(p.type)}`);\n  }\n\n  // Required body fields — expand from model if present.\n  // Apply path/body collision rename (body_ prefix) matching resources.ts.\n  const body = op.requestBody;\n  if (body) {\n    const bodyModel = resolveBodyModel(body, modelByName);\n    if (bodyModel) {\n      for (const f of bodyModel.fields) {\n        if (!f.required) continue;\n        if (hiddenParams.has(f.name)) continue;\n        let name = fieldName(f.name);\n        if (pathParamNames.has(name)) {\n          name = `body_${name}`;\n        }\n        if (seen.has(name)) continue;\n        seen.add(name);\n        parts.push(`${name}: ${stubValueFor(f.type)}`);\n      }\n    }\n  }\n\n  // Required query params.\n  for (const q of op.queryParams ?? []) {\n    if (!q.required) continue;\n    if (hiddenParams.has(q.name)) continue;\n    const name = safeParamName(q.name);\n    if (seen.has(name)) continue;\n    seen.add(name);\n    parts.push(`${name}: ${stubValueFor(q.type)}`);\n  }\n\n  // Parameter group kwargs (required and optional): instantiate the first\n  // variant's class. Optional groups are exercised too so the dispatcher\n  // code path is covered — passing nothing would skip the body block and\n  // hide silent-drop bugs (see workos/oagen-emitters#66).\n  //\n  // Variant param types are recovered from the body model: the IR's leaf type\n  // is often a bare primitive (`role_slugs: string`) even when the body model\n  // declares a richer shape (`Array<String>`). Stubbing without recovery would\n  // pass `\"stub\"` to `RoleMultiple.new(role_slugs:)` while the class signature\n  // declares `T::Array[String]` — the test passes locally but ships an invalid\n  // wire body the API rejects.\n  const bodyFieldTypes = collectBodyFieldTypes(op, models);\n  for (const group of op.parameterGroups ?? []) {\n    const name = fieldName(group.name);\n    if (seen.has(name)) continue;\n    seen.add(name);\n    const idx = variantOverrides.get(group.name) ?? 0;\n    const variant = group.variants[idx];\n    if (variant) {\n      const owner = groupOwners.get(group.name);\n      if (!owner) {\n        throw new Error(`No owner mount target found for parameter group '${group.name}'`);\n      }\n      const variantClass = scopedGroupVariantClassName(\n        resolveServiceTarget(owner, exportedClasses),\n        group.name,\n        variant.name,\n      );\n      const fieldStubs = variant.parameters\n        .map((p) => `${fieldName(p.name)}: ${stubValueFor(pickVariantParamType(p.type, bodyFieldTypes.get(p.name)))}`)\n        .join(', ');\n      parts.push(`${name}: ${variantClass}.new(${fieldStubs})`);\n    }\n  }\n\n  return parts.join(', ');\n}\n\n/**\n * Build a Ruby `hash_including(...)` matcher describing the wire body the\n * SDK should send for an operation whose body is constructed (in part) by a\n * parameter-group dispatcher. Returns `null` for operations without body\n * groups — those are still stubbed without a body matcher.\n *\n * The matcher includes every required non-group body field plus the first\n * variant's wire-name leaves for each group dispatched into the body. This\n * catches regressions where the dispatcher silently drops a passed group\n * (the original `update_organization_membership` regression).\n */\nfunction buildBodyMatcher(\n  op: Operation,\n  modelByName: Map<string, Model>,\n  hiddenParams: Set<string>,\n  models: Model[],\n  variantOverrides: Map<string, number> = new Map(),\n): string | null {\n  const httpMethod = op.httpMethod.toLowerCase();\n  const hasBodyMethod = !['get', 'head', 'delete'].includes(httpMethod);\n  const hasGroups = (op.parameterGroups?.length ?? 0) > 0;\n  if (!hasBodyMethod || !hasGroups) return null;\n\n  const groupedParamNames = new Set<string>();\n  for (const group of op.parameterGroups ?? []) {\n    for (const variant of group.variants) {\n      for (const p of variant.parameters) groupedParamNames.add(p.name);\n    }\n  }\n\n  const entries: string[] = [];\n\n  // Required non-group body fields, keyed by wire name.\n  if (op.requestBody) {\n    const bodyModel = resolveBodyModel(op.requestBody, modelByName);\n    if (bodyModel) {\n      for (const f of bodyModel.fields) {\n        if (!f.required) continue;\n        if (hiddenParams.has(f.name)) continue;\n        if (groupedParamNames.has(f.name)) continue;\n        entries.push(`\"${f.name}\" => ${stubValueFor(f.type)}`);\n      }\n    }\n  }\n\n  // Selected variant of each group: its leaves get pumped into the body. The\n  // matcher value must use the recovered (body-model) type, not the IR leaf —\n  // see buildCallArgsStub for the same reasoning. Without this, the matcher\n  // shape diverges from what the SDK actually sends.\n  const bodyFieldTypes = collectBodyFieldTypes(op, models);\n  for (const group of op.parameterGroups ?? []) {\n    const idx = variantOverrides.get(group.name) ?? 0;\n    const variant = group.variants[idx];\n    if (!variant) continue;\n    for (const p of variant.parameters) {\n      const recovered = pickVariantParamType(p.type, bodyFieldTypes.get(p.name));\n      entries.push(`\"${p.name}\" => ${stubValueFor(recovered)}`);\n    }\n  }\n\n  if (entries.length === 0) return null;\n  return `hash_including(${entries.join(', ')})`;\n}\n\nfunction resolveBodyModel(ref: TypeRef, modelByName: Map<string, Model>): Model | null {\n  if (ref.kind === 'model') return modelByName.get(ref.name) ?? null;\n  if (ref.kind === 'nullable') return resolveBodyModel(ref.inner, modelByName);\n  if (ref.kind === 'union') {\n    for (const v of ref.variants) {\n      if (v.kind === 'model') return modelByName.get(v.name) ?? null;\n    }\n  }\n  return null;\n}\n\nfunction emitWrapperTests(args: {\n  lines: string[];\n  wrapper: ResolvedWrapper;\n  op: Operation;\n  prop: string;\n  stubUrl: string;\n  httpMethodSym: string;\n  ctx: EmitterContext;\n}): void {\n  const { lines, wrapper, op, prop, stubUrl, httpMethodSym, ctx } = args;\n  const wrapperParams = resolveWrapperParams(wrapper, ctx);\n\n  // Build call args: path params + required exposed params only.\n  const parts: string[] = [];\n  const seen = new Set<string>();\n  for (const p of op.pathParams ?? []) {\n    const n = safeParamName(p.name);\n    if (seen.has(n)) continue;\n    seen.add(n);\n    parts.push(`${n}: ${stubValueFor(p.type)}`);\n  }\n  for (const wp of wrapperParams) {\n    if (wp.isOptional) continue;\n    const n = fieldName(wp.paramName);\n    if (seen.has(n)) continue;\n    seen.add(n);\n    parts.push(`${n}: ${wp.field ? stubValueFor(wp.field.type) : '\"stub\"'}`);\n  }\n  const callArgs = parts.join(', ');\n\n  const wrapperRegex = stubUrlRegex(stubUrl);\n  lines.push('');\n  lines.push(`  def test_${wrapper.name}_returns_expected_result`);\n  lines.push(`    stub_request(${httpMethodSym}, ${wrapperRegex})`);\n  lines.push(`      .to_return(body: \"{}\", status: 200)`);\n  lines.push(`    result = @client.${prop}.${wrapper.name}(${callArgs})`);\n  lines.push('    refute_nil result');\n  lines.push('  end');\n\n  lines.push('');\n  lines.push(`  def test_${wrapper.name}_raises_authentication_error_on_401`);\n  lines.push(`    stub_request(${httpMethodSym}, ${wrapperRegex})`);\n  lines.push(`      .to_return(body: '{\"message\": \"Unauthorized\"}', status: 401)`);\n  lines.push(`    assert_raises(WorkOS::AuthenticationError) do`);\n  lines.push(`      @client.${prop}.${wrapper.name}(${callArgs})`);\n  lines.push('    end');\n  lines.push('  end');\n}\n\nfunction stubValueFor(ref: TypeRef): string {\n  switch (ref.kind) {\n    case 'primitive':\n      switch (ref.type) {\n        case 'string':\n          return `\"stub\"`;\n        case 'integer':\n          return `1`;\n        case 'number':\n          return `1.0`;\n        case 'boolean':\n          return `true`;\n        default:\n          return `nil`;\n      }\n    case 'array':\n      // Single-element array — exercises the wire shape under hash_including\n      // matchers. An empty `[]` would match `\"role_slugs\": []` on the wire,\n      // hiding regressions where the SDK serializes the wrong type.\n      return `[${stubValueFor(ref.items)}]`;\n    case 'map':\n      return `{}`;\n    case 'enum':\n      return `\"stub\"`;\n    case 'literal':\n      if (typeof ref.value === 'string') return `\"${ref.value}\"`;\n      if (ref.value === null) return `nil`;\n      return String(ref.value);\n    case 'nullable':\n      return stubValueFor(ref.inner);\n    case 'model':\n      return `{}`;\n    case 'union':\n      return ref.variants.length > 0 ? stubValueFor(ref.variants[0]) : `nil`;\n    default:\n      return `nil`;\n  }\n}\n\n/**\n * Build a WebMock-compatible regex string that matches the exact API path\n * (with stub path params) plus an optional query string.\n *\n * Returns a Ruby Regexp literal like: %r{\\Ahttps://api\\.workos\\.com/organizations(\\?|\\z)}\n */\nfunction buildStubUrl(op: Operation): string {\n  let path = op.path;\n  for (const p of op.pathParams ?? []) {\n    path = path.replace(`{${p.name}}`, 'stub');\n  }\n  // Escape regex special chars in the URL path (dots, slashes, etc.)\n  const escaped = `https://api.workos.com${path}`.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n  return escaped;\n}\n\n/** Format the stub URL as a Ruby regex literal for WebMock. */\nfunction stubUrlRegex(escaped: string): string {\n  return `%r{\\\\A${escaped}(\\\\?|\\\\z)}`;\n}\n","import type { ApiSpec, EmitterContext, OperationsMap } from '@workos/oagen';\nimport { servicePropertyName } from './naming.js';\n\n/**\n * Build operation-to-SDK-method mapping for the manifest.\n *\n * Uses each resolved operation's actual mountOn (not the service default) so\n * operations remounted via operationHints land on the correct service prop.\n * Split operations emit one entry per wrapper (keyed by wrapper name + variant).\n *\n * The accessor (`service` field) uses the raw mountOn — accessor names stay\n * unsuffixed even when the underlying service class gets a `Service` suffix\n * on collision.\n */\nexport function buildOperationsMap(spec: ApiSpec, ctx: EmitterContext): OperationsMap {\n  void spec;\n  void ctx;\n  const manifest: OperationsMap = {};\n\n  for (const r of ctx.resolvedOperations ?? []) {\n    const op = r.operation;\n    const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n    const propName = servicePropertyName(r.mountOn);\n    manifest[httpKey] = { sdkMethod: r.methodName, service: propName };\n    if (r.wrappers && r.wrappers.length > 0) {\n      for (const w of r.wrappers) {\n        manifest[`${httpKey}#${w.targetVariant}`] = { sdkMethod: w.name, service: propName };\n      }\n    }\n  }\n\n  return manifest;\n}\n","import type { ApiSpec, EmitterContext, GeneratedFile, TypeRef, Model } from '@workos/oagen';\nimport { mapTypeRef as irMapTypeRef } from '@workos/oagen';\nimport {\n  className,\n  fieldName,\n  domainFieldName,\n  fileName,\n  safeParamName,\n  scopedGroupVariantClassName,\n  resolveMethodName,\n  servicePropertyName,\n  buildExportedClassNameSet,\n  resolveServiceTarget,\n} from './naming.js';\nimport {\n  buildResolvedLookup,\n  groupByMount,\n  isMountInScope,\n  isModelInScope,\n  lookupResolved,\n  buildHiddenParams,\n  collectGroupedParamNames,\n} from '../shared/resolved-ops.js';\nimport { isListWrapperModel, isListMetadataModel } from '../shared/model-utils.js';\nimport { buildGroupOwnerMap, collectVariantsForMountTarget, emitInlineVariantRbi } from './parameter-groups.js';\n\n/**\n * Map an IR TypeRef to a Sorbet type string for RBI files.\n */\nfunction mapSorbetType(ref: TypeRef): string {\n  return irMapTypeRef<string>(ref, {\n    primitive: (r) => {\n      switch (r.type) {\n        case 'string':\n          return 'String';\n        case 'integer':\n          return 'Integer';\n        case 'number':\n          return 'Float';\n        case 'boolean':\n          return 'T::Boolean';\n        case 'unknown':\n          return 'T.untyped';\n      }\n    },\n    array: (_ref, items) => `T::Array[${items}]`,\n    model: (r) => `WorkOS::${className(r.name)}`,\n    enum: () => 'String',\n    union: (r, variants) => {\n      if (r.compositionKind === 'allOf') return variants[0] ?? 'T.untyped';\n      const unique = [...new Set(variants)];\n      if (unique.length === 1) return unique[0];\n      return `T.any(${unique.join(', ')})`;\n    },\n    nullable: (_ref, inner) => wrapNilable(inner),\n    literal: (r) =>\n      typeof r.value === 'string'\n        ? 'String'\n        : r.value === null\n          ? 'NilClass'\n          : typeof r.value === 'number'\n            ? Number.isInteger(r.value)\n              ? 'Integer'\n              : 'Float'\n            : 'T::Boolean',\n    map: (_ref, value) => `T::Hash[String, ${value}]`,\n  });\n}\n\n/**\n * Generate .rbi files for Sorbet type checking.\n */\nexport function generateRbiFiles(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  const modelNames = new Set(spec.models.map((m) => m.name));\n  const _enumNames = new Set(spec.enums.map((e) => e.name));\n\n  // 1. Generate model RBI files\n  const models = (spec.models as Model[]).filter((m) => !isListWrapperModel(m) && !isListMetadataModel(m));\n\n  for (const model of models) {\n    const cls = className(model.name);\n    const lines: string[] = [];\n    lines.push('# typed: strong');\n    lines.push('');\n    lines.push('module WorkOS');\n    lines.push(`  class ${cls}`);\n\n    // Constructor\n    lines.push('    sig { params(json: T.any(String, T::Hash[Symbol, T.untyped])).void }');\n    lines.push('    def initialize(json); end');\n    lines.push('');\n\n    // Field accessors\n    const seenFieldNames = new Set<string>();\n    for (const f of model.fields) {\n      // DOMAIN accessor name in the .rbi (honors fieldHints override).\n      const fname = domainFieldName(f);\n      if (seenFieldNames.has(fname)) continue;\n      seenFieldNames.add(fname);\n      const sorbetType = f.required ? mapSorbetType(f.type) : wrapNilable(mapSorbetType(f.type));\n      lines.push(`    sig { returns(${sorbetType}) }`);\n      lines.push(`    def ${fname}; end`);\n      lines.push('');\n      lines.push(`    sig { params(value: ${sorbetType}).returns(${sorbetType}) }`);\n      lines.push(`    def ${fname}=(value); end`);\n      lines.push('');\n    }\n\n    // to_h and to_json\n    lines.push('    sig { returns(T::Hash[Symbol, T.untyped]) }');\n    lines.push('    def to_h; end');\n    lines.push('');\n    lines.push('    sig { params(args: T.untyped).returns(String) }');\n    lines.push('    def to_json(*args); end');\n\n    lines.push('  end');\n    lines.push('end');\n\n    // FR-1.4: write the per-model .rbi only when in scope. The client.rbi\n    // aggregate (section 3) stays on the full set so sigs for out-of-scope\n    // services whose .rb/.rbi still exist keep resolving.\n    if (isModelInScope(model.name, ctx)) {\n      files.push({\n        path: `rbi/workos/${fileName(model.name)}.rbi`,\n        content: lines.join('\\n'),\n        integrateTarget: true,\n        overwriteExisting: true,\n      });\n    }\n  }\n\n  // 2. Generate service RBI files\n  const groups = groupByMount(ctx);\n  const lookup = buildResolvedLookup(ctx);\n  const modelByName = new Map<string, Model>();\n  for (const m of spec.models as Model[]) modelByName.set(m.name, m);\n  const listWrapperModels = new Map<string, Model>();\n  for (const m of spec.models as Model[]) {\n    if (isListWrapperModel(m)) listWrapperModels.set(m.name, m);\n  }\n  const groupOwners = buildGroupOwnerMap(ctx);\n  const exportedClasses = buildExportedClassNameSet(ctx);\n\n  for (const [mountTarget, group] of groups) {\n    // Scoped run: emit per-service .rbi only for selected mount targets. The\n    // client.rbi aggregate loop below intentionally stays on the FULL `groups`\n    // set so it keeps emitting sigs for every service whose .rb still exists.\n    if (!isMountInScope(mountTarget, ctx)) continue;\n    const resolvedTarget = resolveServiceTarget(mountTarget, exportedClasses);\n    const cls = className(resolvedTarget);\n    const lines: string[] = [];\n    lines.push('# typed: strong');\n    lines.push('');\n    lines.push('module WorkOS');\n    lines.push(`  class ${cls}`);\n\n    // Inline parameter-group variant RBI blocks owned by this mount target.\n    // Mirrors the runtime `class ... PasswordPlaintext = Data.define(...) end`\n    // layout in lib/workos/<service>.rb.\n    const variants = collectVariantsForMountTarget(ctx, spec.models as Model[], mountTarget);\n    for (const v of variants) {\n      // Rewrite mountTarget to the (possibly pluralized) service class so the\n      // RBI's `WorkOS::<Service>::<Variant>` reference matches the runtime.\n      v.mountTarget = resolvedTarget;\n      for (const line of emitInlineVariantRbi(v)) lines.push(line);\n      lines.push('');\n    }\n\n    lines.push('    sig { params(client: WorkOS::BaseClient).void }');\n    lines.push('    def initialize(client); end');\n    lines.push('');\n\n    const emittedMethods = new Set<string>();\n\n    for (const op of group.operations) {\n      const ownerService =\n        group.resolvedOps.find((r) => r.operation === op)?.service ??\n        spec.services.find((s) => s.operations.includes(op)) ??\n        spec.services[0];\n      const method = resolveMethodName(op, ownerService, ctx);\n      if (emittedMethods.has(method)) continue;\n\n      const resolved = lookupResolved(op, lookup);\n      if (resolved?.urlBuilder) {\n        emittedMethods.add(method);\n        continue;\n      }\n      emittedMethods.add(method);\n\n      const hiddenParams = buildHiddenParams(resolved);\n      const groupedParamNames = collectGroupedParamNames(op);\n      const queryParams = (op.queryParams ?? []).filter((q) => !groupedParamNames.has(q.name));\n      // Drop body fields that collide with a parameter-group name; the group\n      // dispatcher kwarg handles them. See ruby/resources.ts for the matching\n      // filter on the runtime side.\n      const bodyFields = getRequestBodyFieldsFlat(op, hiddenParams, modelByName).filter(\n        (f) => !groupedParamNames.has(f.name),\n      );\n      const parameterGroups = op.parameterGroups ?? [];\n      const groupSorbetType = (group: (typeof parameterGroups)[number]): string => {\n        const owner = groupOwners.get(group.name);\n        if (!owner) {\n          throw new Error(`No owner mount target found for parameter group '${group.name}'`);\n        }\n        const resolvedOwner = resolveServiceTarget(owner, exportedClasses);\n        const variants = group.variants.map((v) => scopedGroupVariantClassName(resolvedOwner, group.name, v.name));\n        if (variants.length === 1) return variants[0];\n        return `T.any(${variants.join(', ')})`;\n      };\n\n      // Build parameter list for sig. Order mirrors the runtime emitter:\n      // path → required body → required query → required groups → optional\n      // body → optional query → optional groups → request_options.\n      const sigParams: string[] = [];\n      const seen = new Set<string>();\n\n      for (const p of op.pathParams ?? []) {\n        const n = safeParamName(p.name);\n        if (seen.has(n)) continue;\n        seen.add(n);\n        sigParams.push(`${n}: ${mapSorbetType(p.type)}`);\n      }\n      for (const f of bodyFields) {\n        if (hiddenParams.has(f.name)) continue;\n        if (!f.required) continue;\n        const n = fieldName(f.name);\n        if (seen.has(n)) continue;\n        seen.add(n);\n        sigParams.push(`${n}: ${mapSorbetType(f.type)}`);\n      }\n      for (const q of queryParams) {\n        if (hiddenParams.has(q.name)) continue;\n        if (!q.required) continue;\n        const n = safeParamName(q.name);\n        if (seen.has(n)) continue;\n        seen.add(n);\n        sigParams.push(`${n}: ${mapSorbetType(q.type)}`);\n      }\n      for (const group of parameterGroups) {\n        if (group.optional) continue;\n        const n = fieldName(group.name);\n        if (seen.has(n)) continue;\n        seen.add(n);\n        sigParams.push(`${n}: ${groupSorbetType(group)}`);\n      }\n      for (const f of bodyFields) {\n        if (hiddenParams.has(f.name)) continue;\n        if (f.required) continue;\n        const n = fieldName(f.name);\n        if (seen.has(n)) continue;\n        seen.add(n);\n        sigParams.push(`${n}: ${wrapNilable(mapSorbetType(f.type))}`);\n      }\n      for (const q of queryParams) {\n        if (hiddenParams.has(q.name)) continue;\n        if (q.required) continue;\n        const n = safeParamName(q.name);\n        if (seen.has(n)) continue;\n        seen.add(n);\n        sigParams.push(`${n}: ${wrapNilable(mapSorbetType(q.type))}`);\n      }\n      for (const group of parameterGroups) {\n        if (!group.optional) continue;\n        const n = fieldName(group.name);\n        if (seen.has(n)) continue;\n        seen.add(n);\n        sigParams.push(`${n}: ${wrapNilable(groupSorbetType(group))}`);\n      }\n      sigParams.push('request_options: T::Hash[Symbol, T.untyped]');\n\n      // Return type\n      const retType = mapSorbetReturnType(op.response, listWrapperModels, modelNames);\n\n      lines.push('    sig do');\n      lines.push('      params(');\n      for (let i = 0; i < sigParams.length; i++) {\n        const sep = i === sigParams.length - 1 ? '' : ',';\n        lines.push(`        ${sigParams[i]}${sep}`);\n      }\n      lines.push(`      ).returns(${retType})`);\n      lines.push('    end');\n      lines.push(`    def ${method}(${sigParams.map((p) => p.split(':')[0].trim() + ':').join(', ')}); end`);\n      lines.push('');\n    }\n\n    lines.push('  end');\n    lines.push('end');\n\n    files.push({\n      path: `rbi/workos/${fileName(resolvedTarget)}.rbi`,\n      content: lines.join('\\n'),\n      integrateTarget: true,\n      overwriteExisting: true,\n    });\n  }\n\n  // 3. Generate client RBI file\n  {\n    const lines: string[] = [];\n    lines.push('# typed: strong');\n    lines.push('');\n    lines.push('module WorkOS');\n    lines.push('  class Client < BaseClient');\n\n    for (const [mountTarget] of groups) {\n      const resolvedTarget = resolveServiceTarget(mountTarget, exportedClasses);\n      const cls = className(resolvedTarget);\n      const prop = servicePropertyName(mountTarget);\n      lines.push(`    sig { returns(WorkOS::${cls}) }`);\n      lines.push(`    def ${prop}; end`);\n      lines.push('');\n    }\n\n    lines.push('  end');\n    lines.push('end');\n\n    files.push({\n      path: 'rbi/workos/client.rbi',\n      content: lines.join('\\n'),\n      integrateTarget: true,\n      overwriteExisting: true,\n    });\n  }\n\n  return files;\n}\n\n/** Unwrap T.nilable(...) if already wrapped, to avoid double-wrapping. */\nfunction unwrapNilable(type: string): string {\n  if (type === 'T.untyped') return type;\n  const match = type.match(/^T\\.nilable\\((.+)\\)$/);\n  return match ? match[1] : type;\n}\n\n/** Wrap a type in T.nilable(), skipping T.untyped (which already includes nil) and avoiding double-wrapping. */\nfunction wrapNilable(type: string): string {\n  if (type === 'T.untyped') return type;\n  return `T.nilable(${unwrapNilable(type)})`;\n}\n\n/** Map a response TypeRef to a Sorbet return type. */\nfunction mapSorbetReturnType(ref: TypeRef, listWrapperModels: Map<string, Model>, modelNames: Set<string>): string {\n  if (ref.kind === 'model' && listWrapperModels.has(ref.name)) {\n    return 'WorkOS::Types::ListStruct';\n  }\n  if (ref.kind === 'model' && modelNames.has(ref.name)) {\n    return `WorkOS::${className(ref.name)}`;\n  }\n  if (ref.kind === 'array' && ref.items.kind === 'model' && modelNames.has(ref.items.name)) {\n    return `T::Array[WorkOS::${className(ref.items.name)}]`;\n  }\n  if (ref.kind === 'nullable') {\n    return wrapNilable(mapSorbetReturnType(ref.inner, listWrapperModels, modelNames));\n  }\n  if (ref.kind === 'primitive' && ref.type === 'unknown') {\n    return 'NilClass';\n  }\n  return mapSorbetType(ref);\n}\n\n/** Get body fields (flat) for RBI sig generation. */\nfunction getRequestBodyFieldsFlat(\n  op: { requestBody?: TypeRef },\n  hiddenParams: Set<string>,\n  modelByName: Map<string, Model>,\n): { name: string; required: boolean; type: TypeRef }[] {\n  void hiddenParams;\n  const ref = op.requestBody;\n  if (!ref) return [];\n  if (ref.kind === 'model') {\n    const model = modelByName.get(ref.name);\n    if (!model) return [];\n    return model.fields.map((f) => ({ name: f.name, required: f.required, type: f.type }));\n  }\n  if (ref.kind === 'nullable') {\n    return getRequestBodyFieldsFlat({ requestBody: ref.inner }, hiddenParams, modelByName);\n  }\n  if (ref.kind === 'union') {\n    for (const v of ref.variants) {\n      if (v.kind === 'model') {\n        const model = modelByName.get(v.name);\n        if (model) return model.fields.map((f) => ({ name: f.name, required: f.required, type: f.type }));\n      }\n    }\n  }\n  return [];\n}\n","import type {\n  Emitter,\n  EmitterContext,\n  FormatCommand,\n  GeneratedFile,\n  ApiSpec,\n  Model,\n  Enum,\n  Service,\n} from '@workos/oagen';\nimport { generateModels } from './models.js';\nimport { generateEnums } from './enums.js';\nimport { generateResources } from './resources.js';\nimport { generateClient } from './client.js';\nimport { generateTests } from './tests.js';\nimport { buildOperationsMap } from './manifest.js';\nimport { generateRbiFiles } from './rbi.js';\nimport { enrichModelsFromSpec, getSyntheticEnums } from '../shared/model-utils.js';\nimport { AUTOGEN_NOTICE } from '../shared/file-header.js';\n\n/** Ensure every generated file's content ends with a trailing newline. */\nfunction ensureTrailingNewlines(files: GeneratedFile[]): GeneratedFile[] {\n  for (const f of files) {\n    if (f.content && !f.content.endsWith('\\n')) {\n      f.content += '\\n';\n    }\n  }\n  return files;\n}\n\n/**\n * Flatten oneOf / allOf+oneOf variant fields onto each base model and pick\n * up the synthetic models / enums `enrichModelsFromSpec` produces for inline\n * variant shapes. Ruby emits flat hash-backed models, not sum types, so a\n * discriminated base whose IR fields were stripped (the new EventSchema-\n * style behaviour after the parser learned to walk allOf-wrapped variants)\n * has its original fields restored — otherwise `ConnectApplication`-style\n * bases would silently lose every variant field they had previously.\n */\nfunction enrichModelsForRuby(models: Model[], enums: Enum[]): Model[] {\n  const enriched = enrichModelsFromSpec(models, enums);\n  const originalByName = new Map(models.map((m) => [m.name, m]));\n  return enriched.map((m) => {\n    if ((m as { discriminator?: unknown }).discriminator && m.fields.length === 0) {\n      const original = originalByName.get(m.name);\n      if (original && original.fields.length > 0) {\n        return { ...m, fields: original.fields };\n      }\n    }\n    return m;\n  });\n}\n\nexport const rubyEmitter: Emitter = {\n  language: 'ruby',\n\n  generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n    const modelFiles = generateModels(enrichModelsForRuby(models, ctx.spec.enums), ctx);\n    return ensureTrailingNewlines(modelFiles);\n  },\n\n  generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n    const syntheticEnums = getSyntheticEnums();\n    return ensureTrailingNewlines(generateEnums([...enums, ...syntheticEnums], ctx));\n  },\n\n  generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateResources(services, ctx));\n  },\n\n  generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateClient(spec, ctx));\n  },\n\n  generateErrors(): GeneratedFile[] {\n    // Hand-maintained in the target SDK — base_client.rb, errors.rb,\n    // configuration.rb, hash_provider.rb, types/list_struct.rb,\n    // test/test_helper.rb, and version.rb all carry `@oagen-ignore-file`\n    // and are not regenerated.\n    return [];\n  },\n\n  generateTypeSignatures(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    const rbiFiles = generateRbiFiles(spec, ctx);\n    return ensureTrailingNewlines(rbiFiles);\n  },\n\n  generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateTests(spec, ctx));\n  },\n\n  buildOperationsMap(spec: ApiSpec, ctx: EmitterContext) {\n    return buildOperationsMap(spec, ctx);\n  },\n\n  fileHeader(): string {\n    return `# frozen_string_literal: true\\n\\n# ${AUTOGEN_NOTICE}`;\n  },\n\n  formatCommand(targetDir: string): FormatCommand | null {\n    void targetDir;\n    // The WorkOS Ruby SDK uses standardrb. oagen appends the list of written\n    // files as positional args after `args`; we filter to .rb files and pipe\n    // them to `bundle exec standardrb --fix`. cwd is set to targetDir by the\n    // harness so bundler picks up the SDK's Gemfile.\n    //\n    // Note: errors are NOT swallowed here — if standardrb fails (missing\n    // bundle, syntax error, etc.) the engine surfaces it. Silence only hides\n    // the fact that formatting never happened.\n    return {\n      cmd: 'bash',\n      args: [\n        '-c',\n        'RB_FILES=$(for f in \"$@\"; do case \"$f\" in *.rb) echo \"$f\";; esac; done); ' +\n          'if [ -n \"$RB_FILES\" ]; then printf \"%s\\\\n\" \"$RB_FILES\" | xargs bundle exec standardrb --fix --format quiet; fi',\n        '--',\n      ],\n      batchSize: 1000,\n    };\n  },\n};\n","import type { Operation, Service, EmitterContext } from '@workos/oagen';\nimport { toPascalCase, toSnakeCase, deriveMethodName } from '@workos/oagen';\nimport { stripUrnPrefix } from '../shared/naming-utils.js';\n\nconst RUST_KEYWORDS = new Set([\n  'as',\n  'break',\n  'const',\n  'continue',\n  'crate',\n  'else',\n  'enum',\n  'extern',\n  'false',\n  'fn',\n  'for',\n  'if',\n  'impl',\n  'in',\n  'let',\n  'loop',\n  'match',\n  'mod',\n  'move',\n  'mut',\n  'pub',\n  'ref',\n  'return',\n  'self',\n  'Self',\n  'static',\n  'struct',\n  'super',\n  'trait',\n  'true',\n  'type',\n  'unsafe',\n  'use',\n  'where',\n  'while',\n  'async',\n  'await',\n  'dyn',\n  'abstract',\n  'become',\n  'box',\n  'do',\n  'final',\n  'macro',\n  'override',\n  'priv',\n  'typeof',\n  'unsized',\n  'virtual',\n  'yield',\n  'try',\n  'union',\n]);\n\n/** PascalCase type name (for structs and enums). */\nexport function typeName(name: string): string {\n  return toPascalCase(stripUrnPrefix(name));\n}\n\n/** snake_case module/file basename (no extension). */\nexport function moduleName(name: string): string {\n  return escapeKeyword(toSnakeCase(stripUrnPrefix(name)));\n}\n\n/** snake_case method name. */\nexport function methodName(name: string): string {\n  return escapeKeyword(toSnakeCase(stripUrnPrefix(name)));\n}\n\n/** snake_case struct field. */\nexport function fieldName(name: string): string {\n  return escapeKeyword(toSnakeCase(name));\n}\n\n/**\n * snake_case domain field name for a model field, honoring a `domainName`\n * override (set via the `fieldHints` config) so a wire field can surface under\n * a friendlier identifier. The wire name (and thus the `#[serde(rename = ...)]`\n * key) still derives from `field.name`.\n */\nexport function domainFieldName(field: { name: string; domainName?: string }): string {\n  return escapeKeyword(toSnakeCase(field.domainName ?? field.name));\n}\n\n/** PascalCase enum variant. */\nexport function variantName(value: string | number): string {\n  const s = String(value);\n  // Numbers and values starting with a digit must be prefixed.\n  const pascal = toPascalCase(s);\n  if (/^[0-9]/.test(pascal)) return `V${pascal}`;\n  return pascal || 'Empty';\n}\n\n/** Resource handle struct name (e.g., `OrganizationsApi`). Suffix is chosen\n * to avoid collisions with API entity models (`AuthorizationResource`,\n * `Service`, etc.) that may share the singular noun. */\nexport function resourceStructName(serviceName: string): string {\n  const base = typeName(serviceName);\n  if (base.endsWith('Api')) return base;\n  // Drop a pre-existing `Resource` suffix; the conventional Rust handle name\n  // here is `…Api` regardless of the service's spec-side label.\n  const trimmed = base.endsWith('Resource') ? base.slice(0, -'Resource'.length) : base;\n  return `${trimmed}Api`;\n}\n\n/** Client accessor method name on `Client` (snake_case service name). */\nexport function resourceAccessorName(serviceName: string): string {\n  return moduleName(serviceName);\n}\n\n/** Rust file path for a resource module. */\nexport function resourceFileBasename(serviceName: string): string {\n  return moduleName(serviceName);\n}\n\n/** Resolve the SDK method name for an operation, honoring overlay hints. */\nexport function resolveMethodName(op: Operation, service: Service, ctx: EmitterContext): string {\n  const httpKey = `${op.httpMethod.toUpperCase()} ${op.path}`;\n  const overlayName = ctx.overlayLookup?.methodByOperation.get(httpKey)?.methodName;\n  if (overlayName) return methodName(overlayName);\n\n  const resolved = ctx.resolvedOperations?.find(\n    (r) => r.operation.path === op.path && r.operation.httpMethod === op.httpMethod,\n  );\n  if (resolved?.methodName) return methodName(resolved.methodName);\n\n  return methodName(deriveMethodName(op, service));\n}\n\n/** Suffix any Rust reserved word with `_` so it parses as an identifier. */\nfunction escapeKeyword(s: string): string {\n  if (s.length === 0) return '_';\n  if (RUST_KEYWORDS.has(s)) return `${s}_`;\n  if (/^[0-9]/.test(s)) return `_${s}`;\n  return s;\n}\n","import type { TypeRef, UnionType } from '@workos/oagen';\nimport { typeName } from './naming.js';\n\n/**\n * Lightweight registry that synthesises a named Rust enum for every IR union\n * encountered in field positions. Models reference the synthesised name; the\n * generator emits the enum bodies into a separate module so the crate stays\n * self-contained.\n */\nexport class UnionRegistry {\n  private byKey = new Map<\n    string,\n    { name: string; tag?: string; arms: { name: string; type: string; rename?: string }[] }\n  >();\n  private hintCounts = new Map<string, number>();\n\n  /** Total number of registered unions (used by callers to skip emit). */\n  size(): number {\n    return this.byKey.size;\n  }\n\n  /** Drop all collected unions. Call at the start of every emit run. */\n  reset(): void {\n    this.byKey.clear();\n    this.hintCounts.clear();\n  }\n\n  /**\n   * Register a union and return the Rust type name to reference.  Unions with\n   * identical structure (same variants + discriminator) are deduplicated.\n   */\n  register(union: UnionType, hint: string): string {\n    const variants = arms(union);\n\n    // Apply discriminator mapping (`{spec-value: '#/components/schemas/Foo'}`)\n    // as `#[serde(rename = \"spec-value\")]` on the matching variant. Without\n    // this, serde's tagged-union deserialization expects the discriminator\n    // value to literally equal the Rust variant name, which it never does\n    // when the OAS uses snake/kebab-case spec-side keys.\n    const mapping = union.discriminator?.mapping ?? {};\n    const inverseMapping = new Map<string, string>();\n    for (const [specKey, ref] of Object.entries(mapping)) {\n      const schemaName = ref.replace(/^#\\/components\\/schemas\\//, '');\n      // Last value wins — matches spec semantics where the final mapping for\n      // a schema is canonical.\n      inverseMapping.set(typeName(schemaName), specKey);\n    }\n    const armsWithRename: { name: string; type: string; rename?: string }[] = variants.map((v) => {\n      const rename = inverseMapping.get(v.name);\n      return rename !== undefined ? { ...v, rename } : v;\n    });\n\n    const key = JSON.stringify({\n      variants: armsWithRename.map((v) => ({ type: v.type, rename: v.rename ?? null })),\n      discriminator: union.discriminator?.property ?? null,\n      mapping: union.discriminator?.mapping ?? null,\n    });\n    const existing = this.byKey.get(key);\n    if (existing) return existing.name;\n\n    const name = this.uniqueName(`${typeName(hint)}OneOf`);\n    this.byKey.set(key, {\n      name,\n      tag: union.discriminator?.property,\n      arms: armsWithRename,\n    });\n    return name;\n  }\n\n  /**\n   * Render every registered union as a Rust source file (including a leading\n   * `use serde::...;` line).\n   */\n  render(): string {\n    if (this.byKey.size === 0) return '';\n    const blocks: string[] = [];\n    blocks.push('#[allow(unused_imports)]');\n    blocks.push('use super::*;');\n    blocks.push('#[allow(unused_imports)]');\n    blocks.push('use crate::enums::*;');\n    blocks.push('use serde::{Deserialize, Serialize};');\n    blocks.push('');\n\n    for (const u of this.byKey.values()) {\n      blocks.push('#[derive(Debug, Clone, Serialize, Deserialize)]');\n      if (u.tag) {\n        blocks.push(`#[serde(tag = ${JSON.stringify(u.tag)})]`);\n      } else {\n        blocks.push('#[serde(untagged)]');\n      }\n      blocks.push(`pub enum ${u.name} {`);\n      for (const a of u.arms) {\n        if (a.rename !== undefined) {\n          blocks.push(`    #[serde(rename = ${JSON.stringify(a.rename)})]`);\n        }\n        const single = `    ${a.name}(${a.type}),`;\n        if (single.length <= 100) {\n          blocks.push(single);\n        } else {\n          // Match rustfmt's break-shape for over-long tuple variants:\n          //   Variant(\n          //       LongType,\n          //   ),\n          blocks.push(`    ${a.name}(`);\n          blocks.push(`        ${a.type},`);\n          blocks.push('    ),');\n        }\n      }\n      blocks.push('}');\n      blocks.push('');\n    }\n\n    return blocks.join('\\n').replace(/\\n+$/g, '\\n');\n  }\n\n  private uniqueName(base: string): string {\n    const taken = new Set(Array.from(this.byKey.values()).map((u) => u.name));\n    if (!taken.has(base)) return base;\n    const n = (this.hintCounts.get(base) ?? 1) + 1;\n    this.hintCounts.set(base, n);\n    return `${base}${n}`;\n  }\n}\n\n/**\n * Map an IR `TypeRef` to a Rust type expression (e.g., `String`, `Vec<u32>`,\n * `Option<HashMap<String, serde_json::Value>>`).\n *\n * The caller decides whether to wrap the result in `Option<...>` based on the\n * field's `required` flag — `mapTypeRef` itself only emits `Option` for the\n * `nullable` IR variant.\n *\n * When `ctx.registry` is supplied, encountered unions are registered as\n * synthesised Rust enums (using `ctx.hint` to name the generated type); when\n * no registry is provided, unions degrade to `serde_json::Value`.\n */\nexport function mapTypeRef(ref: TypeRef, ctx?: { hint?: string; registry?: UnionRegistry }): string {\n  switch (ref.kind) {\n    case 'primitive':\n      return primitiveType(ref.type, ref.format);\n    case 'array':\n      return `Vec<${mapTypeRef(ref.items, ctx)}>`;\n    case 'model':\n      return typeName(ref.name);\n    case 'enum':\n      return typeName(ref.name);\n    case 'nullable':\n      return `Option<${mapTypeRef(ref.inner, ctx)}>`;\n    case 'literal':\n      return literalType(ref.value);\n    case 'map':\n      return `std::collections::HashMap<String, ${mapTypeRef(ref.valueType, ctx)}>`;\n    case 'union': {\n      const variants = ref.variants;\n      const mapped = variants.map((v) => mapTypeRef(v, ctx));\n      const unique = Array.from(new Set(mapped));\n      if (unique.length === 1) return unique[0]!;\n      if (ctx?.registry && ctx.hint) {\n        return ctx.registry.register(ref, ctx.hint);\n      }\n      return 'serde_json::Value';\n    }\n  }\n}\n\n/** Variants for the registry: each gets a Rust variant name + a payload type. */\nfunction arms(union: UnionType): { name: string; type: string }[] {\n  const seen = new Set<string>();\n  const out: { name: string; type: string }[] = [];\n  for (const v of union.variants) {\n    const t = mapTypeRef(v); // No registry — variants must already be named.\n    const armName = variantArmName(v, t);\n    let unique = armName;\n    let n = 1;\n    while (seen.has(unique)) {\n      n += 1;\n      unique = `${armName}${n}`;\n    }\n    seen.add(unique);\n    out.push({ name: unique, type: t });\n  }\n  return out;\n}\n\nfunction variantArmName(ref: TypeRef, mappedType: string): string {\n  if (ref.kind === 'model' || ref.kind === 'enum') return typeName(ref.name);\n  // Strip generics for arm naming and PascalCase.\n  const base = mappedType.replace(/[<>:,\\s]/g, '');\n  return typeName(base);\n}\n\n/**\n * Wrap a type in `Option<...>` if not already optional. Used for non-required\n * fields where the IR did not produce a `nullable` wrapper.\n */\nexport function makeOptional(rustType: string): string {\n  if (rustType.startsWith('Option<')) return rustType;\n  return `Option<${rustType}>`;\n}\n\nfunction primitiveType(type: 'string' | 'integer' | 'number' | 'boolean' | 'unknown', format?: string): string {\n  switch (type) {\n    case 'string':\n      if (format === 'binary') return 'Vec<u8>';\n      return 'String';\n    case 'integer':\n      if (format === 'int32') return 'i32';\n      return 'i64';\n    case 'number':\n      if (format === 'float') return 'f32';\n      return 'f64';\n    case 'boolean':\n      return 'bool';\n    case 'unknown':\n      return 'serde_json::Value';\n  }\n}\n\nfunction literalType(value: string | number | boolean | null): string {\n  if (value === null) return 'serde_json::Value';\n  if (typeof value === 'string') return 'String';\n  if (typeof value === 'number') return Number.isInteger(value) ? 'i64' : 'f64';\n  if (typeof value === 'boolean') return 'bool';\n  return 'serde_json::Value';\n}\n","/**\n * Heuristics for spotting fields that hold secrets. The Rust emitter wraps\n * such fields in `crate::SecretString` so their `Debug` representation does\n * not accidentally leak the value.\n *\n * The list is intentionally conservative — only fields whose names strongly\n * imply a credential or token are redacted. Generic names like `value` are\n * skipped; the cost of a leaked secret is high enough that we'd rather miss\n * the occasional secret than redact non-secret data and surprise users.\n */\nconst EXACT_NAMES = new Set<string>([\n  'password',\n  'new_password',\n  'old_password',\n  'password_hash',\n  'secret',\n  'client_secret',\n  'signing_secret',\n  'webhook_secret',\n  'token',\n  'access_token',\n  'refresh_token',\n  'id_token',\n  'session_token',\n  'authentication_token',\n  'pending_authentication_token',\n  'invitation_token',\n  'private_key',\n  'pem_private_key',\n  'data_key',\n  'encrypted_keys',\n  'encrypted_data_key',\n  'shared_secret',\n  'totp_secret',\n  'jwt',\n]);\n\n/** True when the field name strongly implies it holds a secret value. */\nexport function isSensitiveFieldName(name: string): boolean {\n  const norm = name.toLowerCase().replace(/-/g, '_');\n  if (EXACT_NAMES.has(norm)) return true;\n  // Common suffix forms: `*_token`, `*_secret`, `*_password`, `*_api_key`.\n  if (/_password(_hash)?$/.test(norm)) return true;\n  if (norm.endsWith('_secret')) return true;\n  if (norm.endsWith('_token') && norm !== 'csrf_token' && norm !== 'request_token') return true;\n  return false;\n}\n\n/**\n * If `rustType` is `String` or `Option<String>` and `fieldName` looks\n * sensitive, return the redacted equivalent (`crate::SecretString` or\n * `Option<crate::SecretString>`). Otherwise return `rustType` unchanged.\n */\nexport function applySecretRedaction(rustType: string, fieldName: string): string {\n  if (!isSensitiveFieldName(fieldName)) return rustType;\n  if (rustType === 'String') return 'crate::SecretString';\n  if (rustType === 'Option<String>') return 'Option<crate::SecretString>';\n  return rustType;\n}\n","import type { Model, EmitterContext, GeneratedFile, Field, TypeRef } from '@workos/oagen';\nimport { typeName, domainFieldName, moduleName } from './naming.js';\nimport { mapTypeRef, makeOptional, UnionRegistry } from './type-map.js';\nimport { applySecretRedaction } from './secret.js';\nimport { isModelInScope, fileExistsAfterRun, priorManifestBasenames } from '../shared/resolved-ops.js';\n\nconst HEADER_PLACEHOLDER = ''; // engine prepends fileHeader()\n\nconst UNIONS_MODULE = '_unions';\n\n/**\n * Generate one Rust source file per model under `src/models/`, plus a\n * `src/models/mod.rs` barrel that re-exports each module. Inline IR unions\n * encountered in field positions are synthesised into a single\n * `src/models/_unions.rs` module so the resulting Rust types are concrete.\n */\nexport function generateModels(models: Model[], ctx: EmitterContext, registry: UnionRegistry): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const moduleNames: string[] = [];\n  const seen = new Set<string>();\n\n  // Map of variant-model name -> discriminator wire-property for every model\n  // that appears as an arm of an internally-tagged (`#[serde(tag = ...)]`)\n  // union. serde consumes that property as the enum tag and strips it from the\n  // variant body during deserialization, so a *required* field of the same\n  // name can never be satisfied (\"missing field `type`\"). See renderField.\n  const taggedVariantFields = collectTaggedVariantFields(models);\n\n  for (const model of models) {\n    // Empty-field, non-discriminator models still need to be emitted as an\n    // empty struct so request bodies that reference them (e.g. an empty\n    // `CreateApplicationSecretDto`) compile.\n    const mod = moduleName(model.name);\n    if (seen.has(mod)) continue;\n    seen.add(mod);\n\n    // renderModel registers inline unions into `registry` as a side effect, and\n    // `_unions.rs` is rendered later (in generateClient) from that registry — so\n    // it MUST run for every model, even out-of-scope ones, or scoped runs drop\n    // unions. Compute content unconditionally; only the per-model `.rs` FILE write\n    // is scoped (FR-1.4) — an out-of-scope model's existing `.rs` file stays\n    // untouched on disk.\n    const inScope = isModelInScope(model.name, ctx);\n    const hintPath = ctx.overlayLookup?.fileBySymbol?.get(model.name);\n    const path = hintPath ?? `src/models/${mod}.rs`;\n    const content = renderModel(model, registry, taggedVariantFields.get(model.name));\n    if (inScope) {\n      files.push({\n        path,\n        content,\n        overwriteExisting: true,\n      });\n    }\n\n    // Declare the module only if its `.rs` file will exist on disk after this\n    // run: in-scope (emitted just now) or already present from a prior run. A\n    // scoped run must NOT declare a brand-new out-of-scope model whose file it\n    // never emits — that dangling `mod` is what broke the build. A full run\n    // declares every module (fileExistsAfterRun ⇒ true when scoping is inert).\n    if (fileExistsAfterRun(path, inScope, ctx)) {\n      moduleNames.push(mod);\n    }\n  }\n\n  // Scoped runs: retain barrel entries for model files still on disk (prior\n  // manifest) that the current spec no longer produces — e.g. a model renamed\n  // for another service. Out-of-scope code we did not regenerate may still\n  // reference them, so dropping the `mod` would break the build. De-duped\n  // against the modules declared above; a full run yields nothing here.\n  for (const base of priorManifestBasenames(ctx, 'src/models', '.rs', new Set([UNIONS_MODULE, 'mod']))) {\n    if (!seen.has(base)) {\n      seen.add(base);\n      moduleNames.push(base);\n    }\n  }\n\n  // Always include the unions module in the barrel so downstream stages\n  // (resources, etc.) that register additional unions don't need to mutate\n  // the barrel after the fact. The actual `_unions.rs` file is rendered in\n  // generateClient once every stage has finished registering.\n  moduleNames.push(UNIONS_MODULE);\n\n  files.push({\n    path: 'src/models/mod.rs',\n    content: renderModelsBarrel(moduleNames),\n    overwriteExisting: true,\n  });\n\n  return files;\n}\n\n/**\n * Walk every model field and record which models are arms of an\n * internally-tagged union, mapped to that union's discriminator property.\n */\nfunction collectTaggedVariantFields(models: Model[]): Map<string, string> {\n  const out = new Map<string, string>();\n  const visit = (ref: TypeRef): void => {\n    switch (ref.kind) {\n      case 'union':\n        if (ref.discriminator?.property) {\n          for (const variant of ref.variants) {\n            const name = variantModelName(variant);\n            if (name) out.set(name, ref.discriminator.property);\n          }\n        }\n        ref.variants.forEach(visit);\n        break;\n      case 'array':\n        visit(ref.items);\n        break;\n      case 'nullable':\n        visit(ref.inner);\n        break;\n      case 'map':\n        visit(ref.valueType);\n        break;\n      default:\n        break;\n    }\n  };\n  for (const model of models) for (const field of model.fields) visit(field.type);\n  return out;\n}\n\n/** Resolve the underlying model name of a union arm, unwrapping a nullable. */\nfunction variantModelName(ref: TypeRef): string | null {\n  if (ref.kind === 'model') return ref.name;\n  if (ref.kind === 'nullable') return variantModelName(ref.inner);\n  return null;\n}\n\nfunction renderModel(model: Model, registry: UnionRegistry, tagField?: string): string {\n  const lines: string[] = [];\n  lines.push(HEADER_PLACEHOLDER);\n  // Match rustfmt's canonical grouping: keyword-rooted paths (`super`,\n  // `crate`) sort before external-crate paths (`serde`). Pre-emit in that\n  // order so `cargo fmt --check` does not reshuffle the file.\n  lines.push('#[allow(unused_imports)]');\n  lines.push('use super::*;');\n  lines.push('#[allow(unused_imports)]');\n  lines.push('use crate::enums::*;');\n  lines.push('use serde::{Deserialize, Serialize};');\n  lines.push('');\n\n  if (model.description) lines.push(...docComment(model.description));\n\n  lines.push('#[derive(Debug, Clone, Serialize, Deserialize)]');\n\n  const resolvedNames = resolveFieldNames(model.fields);\n  const fieldLines = model.fields.map((f, i) => renderField(f, resolvedNames[i]!, model.name, registry, tagField));\n\n  // rustfmt collapses zero-field structs to `pub struct Foo {}` on a single\n  // line. Match that shape so `cargo fmt --check` passes.\n  if (fieldLines.length === 0) {\n    lines.push(`pub struct ${typeName(model.name)} {}`);\n  } else {\n    lines.push(`pub struct ${typeName(model.name)} {`);\n    lines.push(...fieldLines);\n    lines.push('}');\n  }\n  return lines.filter((l) => l !== HEADER_PLACEHOLDER).join('\\n') + '\\n';\n}\n\n/**\n * Resolve unique Rust identifiers for struct fields. The domain identifier\n * honors a `fieldHints` override (`domainName`, e.g. wire `connection_type` →\n * domain `type`); the wire name (and the `#[serde(rename = ...)]` key emitted\n * in `renderField`) still derives from `f.name`. Multiple names can collide\n * after snake-casing (e.g. `integration_type` and `integrationType` both\n * become `integration_type`). Subsequent collisions get a numeric suffix so\n * the struct compiles; serde `rename` preserves the original wire name in every\n * case.\n */\nfunction resolveFieldNames(fields: Field[]): string[] {\n  const used = new Set<string>();\n  const out: string[] = [];\n  for (const f of fields) {\n    const base = domainFieldName(f);\n    let candidate = base;\n    let suffix = 2;\n    while (used.has(candidate)) {\n      candidate = `${base}_${suffix}`;\n      suffix++;\n    }\n    used.add(candidate);\n    out.push(candidate);\n  }\n  return out;\n}\n\nfunction renderField(\n  field: Field,\n  rustField: string,\n  modelName: string,\n  registry: UnionRegistry,\n  tagField?: string,\n): string {\n  const lines: string[] = [];\n  const hasDescription = !!field.description;\n  if (hasDescription) {\n    for (const c of docComment(field.description!)) lines.push(`    ${c}`);\n  }\n  if (field.default != null) {\n    if (hasDescription) lines.push('    ///');\n    lines.push(`    /// Defaults to \\`${formatDefault(field.default)}\\`.`);\n  }\n\n  const rename = rustField !== field.name ? field.name : null;\n\n  let baseType = mapTypeRef(field.type, {\n    hint: `${typeName(modelName)}${typeName(field.name)}`,\n    registry,\n  });\n  const isOptional = !field.required || field.type.kind === 'nullable';\n  if (isOptional && !baseType.startsWith('Option<')) {\n    baseType = makeOptional(baseType);\n  }\n  // Wrap String / Option<String> in SecretString when the field name implies\n  // the value is a credential or token. Wire format is unchanged.\n  baseType = applySecretRedaction(baseType, field.name);\n\n  if (tagField === field.name) {\n    // This field is the discriminator of an internally-tagged union it belongs\n    // to. serde reads it as the enum tag and strips it from the variant body,\n    // so `default` lets the struct deserialize without it; `skip_serializing`\n    // stops the struct from re-emitting it (serde injects the tag itself,\n    // which would otherwise produce a duplicate key). Standalone uses of the\n    // struct still deserialize the value normally because the key is present.\n    const args = rename ? `rename = \"${rename}\", default, skip_serializing` : 'default, skip_serializing';\n    lines.push(`    #[serde(${args})]`);\n  } else {\n    if (rename) lines.push(`    #[serde(rename = \"${rename}\")]`);\n    if (baseType.startsWith('Option<')) {\n      lines.push('    #[serde(skip_serializing_if = \"Option::is_none\", default)]');\n    }\n  }\n  if (field.deprecated) lines.push('    #[deprecated]');\n  lines.push(`    pub ${rustField}: ${baseType},`);\n  return lines.join('\\n');\n}\n\nfunction renderModelsBarrel(modules: string[]): string {\n  const sorted = [...new Set(modules)].sort();\n  const lines: string[] = [];\n  // Declare the modules privately so `pub use crate::models::*` in lib.rs only\n  // re-exports the struct names, not the module names themselves. Otherwise a\n  // module like `models::organization_membership` collides with the same-named\n  // `resources::organization_membership` when both barrels are glob-re-exported.\n  for (const m of sorted) lines.push(`mod ${m};`);\n  lines.push('');\n  for (const m of sorted) lines.push(`pub use ${m}::*;`);\n  return lines.join('\\n') + '\\n';\n}\n\nfunction docComment(text: string): string[] {\n  return text\n    .split('\\n')\n    .map((l) => l.trim())\n    .filter((l) => l.length > 0)\n    .map((l) => `/// ${l}`);\n}\n\n/**\n * Render a spec-level default value for inclusion in a doc comment. Strings\n * render bare (e.g. `desc`) so they nest naturally inside the surrounding\n * backticks; numbers/booleans use JSON encoding.\n */\nfunction formatDefault(value: unknown): string {\n  if (typeof value === 'string') return value;\n  return JSON.stringify(value);\n}\n","import type { Enum, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport { typeName, moduleName, variantName } from './naming.js';\nimport { isEnumInScope, fileExistsAfterRun, priorManifestBasenames } from '../shared/resolved-ops.js';\n\n/**\n * Generate one Rust source file per enum under `src/enums/`, plus a\n * `src/enums/mod.rs` barrel.\n *\n * Each enum is emitted as a string-backed, forward-compatible Rust enum:\n *   - `#[non_exhaustive]` so callers can't write exhaustive matches that\n *     break when WorkOS adds a new value server-side.\n *   - A fallback variant (`Unknown(String)` by default, or `Unrecognized` /\n *     `Other` / `OagenUnknown` if the spec already defines a variant by that\n *     name) captures any wire value the SDK doesn't yet recognize, preserving\n *     the original string instead of failing deserialization.\n *   - Manual `Serialize`/`Deserialize` map between the canonical wire string\n *     and the Rust variant; alias wire values deserialize into the canonical\n *     variant and re-serialize as the canonical wire string.\n *   - `Display`, `FromStr`, and `AsRef<str>` are implemented for ergonomics.\n */\nexport function generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const seen = new Set<string>();\n  const moduleNames: string[] = [];\n\n  for (const e of enums) {\n    if (!e.values || e.values.length === 0) continue;\n    const mod = moduleName(e.name);\n    if (seen.has(mod)) continue;\n    seen.add(mod);\n\n    // Only the per-enum `.rs` FILE write is scoped (FR-1.4); an out-of-scope\n    // enum's existing `.rs` file stays untouched on disk.\n    const inScope = isEnumInScope(e.name, ctx);\n    const path = `src/enums/${mod}.rs`;\n    if (inScope) {\n      files.push({\n        path,\n        content: renderEnum(e),\n        overwriteExisting: true,\n      });\n    }\n\n    // Declare the module only if its file will exist on disk after this run, so\n    // a scoped run never declares a brand-new out-of-scope enum it doesn't emit.\n    if (fileExistsAfterRun(path, inScope, ctx)) {\n      moduleNames.push(mod);\n    }\n  }\n\n  // Scoped runs: retain barrel entries for enum files still on disk (prior\n  // manifest) that the current spec no longer produces (e.g. renamed for\n  // another service), since out-of-scope code may still reference them.\n  for (const base of priorManifestBasenames(ctx, 'src/enums', '.rs', new Set(['mod']))) {\n    if (!seen.has(base)) {\n      seen.add(base);\n      moduleNames.push(base);\n    }\n  }\n\n  files.push({\n    path: 'src/enums/mod.rs',\n    content: renderEnumsBarrel(moduleNames),\n    overwriteExisting: true,\n  });\n\n  return files;\n}\n\nfunction renderEnum(e: Enum): string {\n  const lines: string[] = [];\n  const tname = typeName(e.name);\n\n  // Collapse wire values that map to the same Rust variant. The first wire\n  // value for a variant is the canonical one (used for serialization); the\n  // remaining ones are aliases (accepted on deserialization).\n  const order: string[] = [];\n  const wireByVariant = new Map<string, string[]>();\n  const descByVariant = new Map<string, string | undefined>();\n  const deprecatedByVariant = new Map<string, boolean>();\n  for (const v of e.values) {\n    const variant = variantName(v.value);\n    if (!wireByVariant.has(variant)) {\n      wireByVariant.set(variant, []);\n      order.push(variant);\n      descByVariant.set(variant, v.description);\n      deprecatedByVariant.set(variant, !!v.deprecated);\n    }\n    wireByVariant.get(variant)!.push(String(v.value));\n  }\n\n  // Pick a fallback-variant name that doesn't collide with an existing one.\n  // Prefer `Unknown` for ergonomics; fall back to less-likely names for the\n  // (rare) enums whose spec already defines `Unknown`/`Unrecognized`/`Other`.\n  const taken = new Set(order);\n  const FB = ['Unknown', 'Unrecognized', 'Other', 'OagenUnknown'].find((c) => !taken.has(c)) ?? 'OagenUnknown';\n\n  lines.push('use serde::{Deserialize, Serialize};');\n  lines.push('use std::fmt;');\n  lines.push('use std::str::FromStr;');\n  lines.push('');\n\n  lines.push('#[derive(Debug, Clone, PartialEq, Eq, Hash)]');\n  lines.push('#[non_exhaustive]');\n  lines.push(`pub enum ${tname} {`);\n  for (const variant of order) {\n    const desc = descByVariant.get(variant);\n    if (desc) {\n      for (const c of docComment(desc)) lines.push(`    ${c}`);\n    }\n    if (deprecatedByVariant.get(variant)) lines.push('    #[allow(deprecated)]');\n    lines.push(`    ${variant},`);\n  }\n  lines.push('    /// Wire value not recognized by this SDK version. The original');\n  lines.push('    /// string is preserved verbatim. WorkOS may add new enum values');\n  lines.push('    /// server-side; matching on this variant lets callers handle');\n  lines.push('    /// forward-compatible values without panicking.');\n  lines.push(`    ${FB}(String),`);\n  lines.push('}');\n  lines.push('');\n\n  // as_str(): canonical wire value for known variants, inner string for fallback.\n  lines.push(`impl ${tname} {`);\n  lines.push(`    /// Canonical wire string for this value. For [\\`Self::${FB}\\`] returns the`);\n  lines.push('    /// original wire value as received from the API.');\n  lines.push('    #[allow(deprecated)]');\n  lines.push('    pub fn as_str(&self) -> &str {');\n  lines.push('        match self {');\n  for (const variant of order) {\n    const canonical = wireByVariant.get(variant)![0]!;\n    lines.push(`            Self::${variant} => ${JSON.stringify(canonical)},`);\n  }\n  lines.push(`            Self::${FB}(s) => s.as_str(),`);\n  lines.push('        }');\n  lines.push('    }');\n  lines.push('}');\n  lines.push('');\n\n  // Display via as_str().\n  lines.push(`impl fmt::Display for ${tname} {`);\n  lines.push(\"    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\");\n  lines.push('        f.write_str(self.as_str())');\n  lines.push('    }');\n  lines.push('}');\n  lines.push('');\n\n  // AsRef<str>.\n  lines.push(`impl AsRef<str> for ${tname} {`);\n  lines.push('    fn as_ref(&self) -> &str {');\n  lines.push('        self.as_str()');\n  lines.push('    }');\n  lines.push('}');\n  lines.push('');\n\n  // FromStr — infallible (fallback variant captures anything else).\n  lines.push(`impl FromStr for ${tname} {`);\n  lines.push('    type Err = std::convert::Infallible;');\n  lines.push('    #[allow(deprecated)]');\n  lines.push('    fn from_str(s: &str) -> Result<Self, Self::Err> {');\n  lines.push('        Ok(match s {');\n  for (const variant of order) {\n    const wires = wireByVariant.get(variant)!;\n    for (const w of wires) {\n      lines.push(`            ${JSON.stringify(w)} => Self::${variant},`);\n    }\n  }\n  lines.push(`            other => Self::${FB}(other.to_string()),`);\n  lines.push('        })');\n  lines.push('    }');\n  lines.push('}');\n  lines.push('');\n\n  // From<String>/From<&str>.\n  lines.push(`impl From<String> for ${tname} {`);\n  lines.push('    fn from(s: String) -> Self {');\n  lines.push('        // Reuse the original `String` allocation in the fallback branch.');\n  lines.push('        match Self::from_str(&s) {');\n  lines.push(`            Ok(Self::${FB}(_)) => Self::${FB}(s),`);\n  lines.push('            Ok(other) => other,');\n  lines.push('        }');\n  lines.push('    }');\n  lines.push('}');\n  lines.push('');\n  lines.push(`impl From<&str> for ${tname} {`);\n  lines.push('    fn from(s: &str) -> Self {');\n  lines.push(`        Self::from_str(s).unwrap_or_else(|_| Self::${FB}(s.to_string()))`);\n  lines.push('    }');\n  lines.push('}');\n  lines.push('');\n\n  // Manual Serialize / Deserialize.\n  lines.push(`impl Serialize for ${tname} {`);\n  lines.push('    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {');\n  lines.push('        serializer.serialize_str(self.as_str())');\n  lines.push('    }');\n  lines.push('}');\n  lines.push('');\n  lines.push(`impl<'de> Deserialize<'de> for ${tname} {`);\n  lines.push(\"    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\");\n  lines.push('        let s = String::deserialize(deserializer)?;');\n  lines.push('        Ok(Self::from(s))');\n  lines.push('    }');\n  lines.push('}');\n\n  return lines.join('\\n') + '\\n';\n}\n\nfunction renderEnumsBarrel(modules: string[]): string {\n  const sorted = [...new Set(modules)].sort();\n  const lines: string[] = [];\n  for (const m of sorted) lines.push(`pub mod ${m};`);\n  lines.push('');\n  for (const m of sorted) lines.push(`pub use ${m}::*;`);\n  return lines.join('\\n') + '\\n';\n}\n\nfunction docComment(text: string): string[] {\n  return text\n    .split('\\n')\n    .map((l) => l.trim())\n    .filter((l) => l.length > 0)\n    .map((l) => `/// ${l}`);\n}\n","import type {\n  Service,\n  Operation,\n  EmitterContext,\n  GeneratedFile,\n  Parameter,\n  ParameterGroup,\n  ResolvedOperation,\n  ResolvedWrapper,\n  TypeRef,\n} from '@workos/oagen';\nimport { planOperation } from '@workos/oagen';\nimport { fieldName, domainFieldName, methodName, typeName, moduleName, variantName } from './naming.js';\nimport { mapTypeRef, makeOptional, UnionRegistry } from './type-map.js';\nimport { applySecretRedaction } from './secret.js';\nimport { parsePathTemplate } from '../shared/path-template.js';\nimport { groupByMount, buildResolvedLookup, isMountInScope, getMountTarget } from '../shared/resolved-ops.js';\nimport { resolveWrapperParams, type ResolvedWrapperParam } from '../shared/wrapper-utils.js';\n\n/**\n * Generate one resource file per mount target under `src/resources/`, plus a\n * `src/resources/mod.rs` barrel. Each file collapses every IR service that\n * mounts on the same target into a single `Api` struct.\n */\nexport function generateResources(services: Service[], ctx: EmitterContext, registry: UnionRegistry): GeneratedFile[] {\n  const groups = groupByMount(ctx);\n  const lookup = buildResolvedLookup(ctx);\n  const files: GeneratedFile[] = [];\n  const exports: { module: string; struct: string }[] = [];\n\n  // The emit surface the core resolved for this run: in a scoped run, the\n  // selected services PLUS every service already on disk — but NOT a service the\n  // spec has that this SDK never generated. The barrel must list exactly these.\n  // Listing every spec mount instead (the old behaviour) emitted `pub mod agents;`\n  // for a service whose `agents.rs` is neither emitted now nor present on disk —\n  // an orphaned module that fails to compile. Full runs pass every service here,\n  // so their barrels are unchanged.\n  const surfaceMounts = new Set(services.map((s) => getMountTarget(s, ctx)));\n\n  for (const [mountName, group] of groups) {\n    if (group.operations.length === 0) continue;\n    // Skip mounts outside the emit surface entirely — no barrel entry (would\n    // dangle) and no file. Present-but-not-selected mounts stay in surfaceMounts,\n    // so their existing `.rs` keeps a barrel entry below.\n    if (!surfaceMounts.has(mountName)) continue;\n    const basename = moduleName(mountName);\n    const struct = mountStructName(mountName);\n    // The barrel (`src/resources/mod.rs`) lists every in-surface mount so Rust\n    // compiles even in a scoped run (on-disk siblings keep their entry).\n    exports.push({ module: basename, struct });\n    // Only the per-service resource `.rs` FILE write is scoped. In a scoped run\n    // we skip emitting files for out-of-scope-but-present mounts; the barrel\n    // above still references their modules (their existing `.rs` stays on disk).\n    if (!isMountInScope(mountName, ctx)) continue;\n    files.push({\n      path: `src/resources/${basename}.rs`,\n      content: renderMountGroup(mountName, group.resolvedOps, ctx, registry, lookup),\n      overwriteExisting: true,\n    });\n  }\n\n  files.push({\n    path: 'src/resources/mod.rs',\n    content: renderResourcesBarrel(exports),\n    overwriteExisting: true,\n  });\n\n  return files;\n}\n\n/** PascalCase struct name for a mount target (e.g., `UserManagementApi`). */\nexport function mountStructName(mountName: string): string {\n  const base = typeName(mountName);\n  return base.endsWith('Api') ? base : `${base}Api`;\n}\n\nfunction renderMountGroup(\n  mountName: string,\n  resolvedOps: ResolvedOperation[],\n  ctx: EmitterContext,\n  registry: UnionRegistry,\n  _lookup: Map<string, ResolvedOperation>,\n): string {\n  const struct = mountStructName(mountName);\n  const lines: string[] = [];\n  lines.push('use crate::client::Client;');\n  lines.push('#[allow(unused_imports)]');\n  lines.push('use crate::enums::*;');\n  lines.push('use crate::error::Error;');\n  lines.push('#[allow(unused_imports)]');\n  lines.push('use crate::models::*;');\n  lines.push('use serde::Serialize;');\n  lines.push('');\n  lines.push(`pub struct ${struct}<'a> {`);\n  lines.push(\"    pub(crate) client: &'a Client,\");\n  lines.push('}');\n  lines.push('');\n\n  // Parameter-group enums and synthetic body types are emitted once per\n  // distinct shape per file (a single mount). Collect them up front so\n  // duplicates collapse and per-method emit can reference stable names.\n  const groupEmitter = new GroupEmitter();\n  const paramsStructs: string[] = [];\n  const methods: string[] = [];\n  const seenMethods = new Set<string>();\n\n  for (const resolved of resolvedOps) {\n    const op = resolved.operation;\n    if ((resolved.wrappers?.length ?? 0) > 0) {\n      for (const wrapper of resolved.wrappers!) {\n        const wrapperMethodName = methodName(wrapper.name);\n        if (seenMethods.has(wrapperMethodName)) continue;\n        seenMethods.add(wrapperMethodName);\n        const paramsType = `${typeName(wrapper.name)}Params`;\n        const params = resolveWrapperParams(wrapper, ctx);\n        paramsStructs.push(renderWrapperParamsStruct(paramsType, op, wrapper, params, registry, ctx));\n        methods.push(renderWrapperMethod(op, wrapper, params, paramsType, wrapperMethodName));\n      }\n      continue;\n    }\n\n    const m = methodName(resolved.methodName);\n    if (seenMethods.has(m)) continue;\n    seenMethods.add(m);\n\n    // URL-builder ops short-circuit: no params struct (just optional one with\n    // the parameters as fields) but no HTTP-issuing methods.\n    if (resolved.urlBuilder) {\n      const paramsType = `${typeName(resolved.methodName)}Params`;\n      const emptyParams = isEmptyParams(op, resolved);\n      if (!emptyParams) {\n        paramsStructs.push(renderParamsStruct(paramsType, op, resolved, registry, ctx, groupEmitter));\n      }\n      methods.push(renderUrlBuilderMethod(op, resolved, paramsType, m, emptyParams));\n      continue;\n    }\n\n    const paramsType = `${typeName(resolved.methodName)}Params`;\n    const emptyParams = isEmptyParams(op, resolved);\n    if (!emptyParams) {\n      paramsStructs.push(renderParamsStruct(paramsType, op, resolved, registry, ctx, groupEmitter));\n    }\n    methods.push(renderMethod(op, resolved, paramsType, m, emptyParams));\n\n    // Auto-paging variant driven by `op.pagination` IR metadata. URL-builder\n    // and HTTP-less ops never qualify.\n    const autoPaging = renderAutoPagingMethod(op, resolved, paramsType, m, ctx);\n    if (autoPaging) methods.push(autoPaging);\n  }\n\n  // Group-related type definitions go between the file header and the params\n  // structs so a single file's params can reference them by short name.\n  const groupBlock = groupEmitter.render();\n  if (groupBlock.length > 0) {\n    lines.push(groupBlock);\n    lines.push('');\n  }\n\n  for (const s of paramsStructs) {\n    lines.push(s);\n    lines.push('');\n  }\n\n  lines.push(`impl<'a> ${struct}<'a> {`);\n  methods.forEach((mm, i) => {\n    lines.push(mm);\n    if (i < methods.length - 1) lines.push('');\n  });\n  lines.push('}');\n\n  return lines.join('\\n').replace(/\\n+$/g, '\\n');\n}\n\n// ─── Parameter-group emitter ────────────────────────────────────────────────\n//\n// A per-file collector that records each unique enum and synthetic body type\n// requested across the file's operations, deduplicates them by structural key,\n// and renders them in dependency order. The emitter is otherwise stateless so\n// individual `renderParamsStruct` calls just stamp their request and reference\n// the resulting Rust names.\n\ninterface GroupEnumSpec {\n  name: string;\n  variants: Array<{\n    name: string;\n    fields: Array<{ rustName: string; wireName: string; rustType: string }>;\n  }>;\n}\n\ninterface SyntheticBodySpec {\n  /** PascalCase type name (e.g. `CheckBody`). */\n  name: string;\n  /** Body model fields that survive after grouped-field removal. */\n  flatFields: Array<{\n    rustName: string;\n    wireName: string;\n    rustType: string;\n    required: boolean;\n    doc?: string;\n  }>;\n  /** `#[serde(flatten)]` fields, one per body parameter group. */\n  flattenEnums: Array<{\n    rustName: string;\n    rustType: string;\n    required: boolean;\n    doc?: string;\n  }>;\n}\n\nclass GroupEmitter {\n  private enums: GroupEnumSpec[] = [];\n  private bodies: SyntheticBodySpec[] = [];\n  private seenEnums = new Set<string>();\n  private seenBodies = new Set<string>();\n\n  /** Register a parameter-group enum, returning the PascalCase Rust name. */\n  registerEnum(group: ParameterGroup): string {\n    const name = typeName(group.name);\n    const variants = group.variants.map((v) => ({\n      name: typeName(v.name),\n      fields: v.parameters.map((p) => ({\n        rustName: fieldName(p.name),\n        wireName: p.name,\n        // Group variant params are always treated as required within their\n        // variant — picking the variant is the caller's commitment to supply\n        // the variant's full payload.\n        rustType: rustTypeForGroupParam(p.type),\n      })),\n    }));\n    if (!this.seenEnums.has(name)) {\n      this.seenEnums.add(name);\n      this.enums.push({ name, variants });\n    }\n    return name;\n  }\n\n  /** Register a synthetic body struct, returning its PascalCase Rust name. */\n  registerBody(spec: SyntheticBodySpec): string {\n    if (!this.seenBodies.has(spec.name)) {\n      this.seenBodies.add(spec.name);\n      this.bodies.push(spec);\n    }\n    return spec.name;\n  }\n\n  render(): string {\n    const blocks: string[] = [];\n    for (const e of this.enums) {\n      const lines: string[] = [];\n      lines.push('#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]');\n      lines.push('#[serde(untagged)]');\n      lines.push(`pub enum ${e.name} {`);\n      for (const v of e.variants) {\n        if (v.fields.length === 0) {\n          lines.push(`    ${v.name},`);\n          continue;\n        }\n        lines.push(`    ${v.name} {`);\n        for (const f of v.fields) {\n          if (f.rustName !== f.wireName) {\n            lines.push(`        #[serde(rename = ${JSON.stringify(f.wireName)})]`);\n          }\n          lines.push(`        ${f.rustName}: ${f.rustType},`);\n        }\n        lines.push('    },');\n      }\n      lines.push('}');\n      blocks.push(lines.join('\\n'));\n    }\n    for (const b of this.bodies) {\n      const lines: string[] = [];\n      // Bodies need `Deserialize` too: the generated test harness builds\n      // request stubs via `serde_json::from_str(\"{}\")` and otherwise can't\n      // refer to the synthetic type without breaking the fixture pipeline.\n      const everythingOptional = b.flatFields.every((f) => !f.required) && b.flattenEnums.every((f) => !f.required);\n      const baseDerives = 'Debug, Clone, serde::Serialize, serde::Deserialize';\n      const derives = everythingOptional ? `${baseDerives}, Default` : baseDerives;\n      lines.push(`#[derive(${derives})]`);\n      lines.push(`pub struct ${b.name} {`);\n      for (const f of b.flatFields) {\n        if (f.doc) {\n          for (const c of paramDocComment(f.doc)) lines.push(`    ${c}`);\n        }\n        if (f.required) {\n          if (f.doc) lines.push('    ///');\n          lines.push('    /// Required.');\n        }\n        if (!f.required) {\n          lines.push('    #[serde(skip_serializing_if = \"Option::is_none\")]');\n        }\n        if (f.rustName !== f.wireName) {\n          lines.push(`    #[serde(rename = ${JSON.stringify(f.wireName)})]`);\n        }\n        lines.push(`    pub ${f.rustName}: ${f.rustType},`);\n      }\n      for (const f of b.flattenEnums) {\n        if (f.doc) {\n          for (const c of paramDocComment(f.doc)) lines.push(`    ${c}`);\n        }\n        lines.push('    #[serde(flatten)]');\n        if (!f.required) {\n          lines.push('    #[serde(skip_serializing_if = \"Option::is_none\")]');\n        }\n        lines.push(`    pub ${f.rustName}: ${f.rustType},`);\n      }\n      lines.push('}');\n\n      // Constructor for the synthetic body type. Mirrors the params struct's\n      // ergonomic: required fields land as positional args, optional ones\n      // default via `Default::default`.\n      const required = [...b.flatFields.filter((f) => f.required), ...b.flattenEnums.filter((f) => f.required)];\n      if (required.length > 0 || b.flatFields.length + b.flattenEnums.length > 0) {\n        const ctorArgs = required.map((f) => `${f.rustName}: ${ctorParamType(f.rustType)}`).join(', ');\n        const init: string[] = [];\n        for (const f of b.flatFields) {\n          if (f.required) {\n            const value = ctorParamConvert(f.rustType, f.rustName);\n            init.push(value === f.rustName ? `            ${f.rustName},` : `            ${f.rustName}: ${value},`);\n          } else {\n            init.push(`            ${f.rustName}: Default::default(),`);\n          }\n        }\n        for (const f of b.flattenEnums) {\n          if (f.required) {\n            const value = ctorParamConvert(f.rustType, f.rustName);\n            init.push(value === f.rustName ? `            ${f.rustName},` : `            ${f.rustName}: ${value},`);\n          } else {\n            init.push(`            ${f.rustName}: Default::default(),`);\n          }\n        }\n        lines.push('');\n        lines.push(`impl ${b.name} {`);\n        lines.push(`    /// Construct a new \\`${b.name}\\` with the required fields set.`);\n        lines.push(`    pub fn new(${ctorArgs}) -> Self {`);\n        lines.push('        Self {');\n        for (const l of init) lines.push(l);\n        lines.push('        }');\n        lines.push('    }');\n        lines.push('}');\n      }\n      blocks.push(lines.join('\\n'));\n    }\n    return blocks.join('\\n\\n');\n  }\n}\n\n/**\n * Render the Rust type for a parameter-group variant field. Variants commit\n * the caller to supplying their full payload, so optional individual params\n * still flow as `String` (not `Option<String>`); the enum-level choice is the\n * one source of truth for \"did the caller pick this variant or not.\"\n */\nfunction rustTypeForGroupParam(type: TypeRef): string {\n  const rust = mapTypeRef(type);\n  // Variant fields are non-optional regardless of the IR's per-param flag.\n  if (rust.startsWith('Option<')) return rust.slice('Option<'.length, -1);\n  return rust;\n}\n\n/** Classify each parameter group on an op as \"query\" or \"body\". */\nfunction classifyGroup(group: ParameterGroup, op: Operation): 'query' | 'body' {\n  const queryNames = new Set(op.queryParams.map((qp) => qp.name));\n  const allInQuery = group.variants.every((v) => v.parameters.every((p) => queryNames.has(p.name)));\n  return allInQuery ? 'query' : 'body';\n}\n\nfunction renderParamsStruct(\n  name: string,\n  op: Operation,\n  resolved: ResolvedOperation,\n  registry: UnionRegistry,\n  ctx: EmitterContext,\n  groupEmitter: GroupEmitter,\n): string {\n  const bodyRequired = isBodyRequired(op);\n  const hidden = new Set<string>([...Object.keys(resolved.defaults ?? {}), ...(resolved.inferFromClient ?? [])]);\n  const materializeSpecDefaults = !resolved.urlBuilder;\n\n  // Names of params that belong to a parameter group; these are folded into\n  // the enum field and must be omitted from the flat params struct.\n  const queryGroupParamNames = new Set<string>();\n  const bodyGroupParamNames = new Set<string>();\n  const queryGroupFields: Array<{\n    name: string;\n    rustType: string;\n    required: boolean;\n    doc?: string;\n  }> = [];\n  const bodyGroupFields: Array<{\n    name: string;\n    rustType: string;\n    required: boolean;\n    doc?: string;\n  }> = [];\n  for (const group of op.parameterGroups ?? []) {\n    const enumName = groupEmitter.registerEnum(group);\n    const rustType = group.optional ? `Option<${enumName}>` : enumName;\n    const groupField = {\n      name: fieldName(group.name),\n      rustType,\n      required: !group.optional,\n      doc: undefined as string | undefined,\n    };\n    if (classifyGroup(group, op) === 'query') {\n      for (const v of group.variants) for (const p of v.parameters) queryGroupParamNames.add(p.name);\n      queryGroupFields.push(groupField);\n    } else {\n      for (const v of group.variants) for (const p of v.parameters) bodyGroupParamNames.add(p.name);\n      bodyGroupFields.push(groupField);\n    }\n  }\n\n  type FieldInfo = {\n    fname: string;\n    rust: string;\n    required: boolean;\n    defaultExpr: string | null;\n    doc?: string;\n  };\n  const fields: FieldInfo[] = [];\n  const fieldLines: string[] = [];\n  const seen = new Set<string>();\n  const emitField = (p: Parameter, opts: { isQuery?: boolean } = {}) => {\n    if (hidden.has(p.name)) return;\n    if (queryGroupParamNames.has(p.name)) return;\n    const fname = fieldName(p.name);\n    if (seen.has(fname)) return;\n    seen.add(fname);\n    let rust = mapTypeRef(p.type, {\n      hint: `${name}${typeName(p.name)}`,\n      registry,\n    });\n    if (!p.required && !rust.startsWith('Option<')) rust = makeOptional(rust);\n    rust = applySecretRedaction(rust, p.name);\n    // Spec-level defaults on HTTP params are materialized so\n    // `Default::default()` and `new(…)` produce the documented value. URL\n    // builders keep optional query params omitted unless the caller supplies\n    // them, because the query string is the public redirect target.\n    const defaultExpr =\n      materializeSpecDefaults && p.default != null\n        ? rustDefaultExpr(p.default, p.type, rust.startsWith('Option<'), ctx)\n        : null;\n    // Field-level documentation derived from the spec.\n    const desc = p.description?.trim();\n    if (desc) {\n      for (const c of paramDocComment(desc)) fieldLines.push(`    ${c}`);\n    }\n    if (p.default != null) {\n      if (desc) fieldLines.push('    ///');\n      fieldLines.push(`    /// Defaults to \\`${formatDefault(p.default)}\\`.`);\n    }\n    if (p.required && !rust.startsWith('Option<')) {\n      if (desc || p.default != null) fieldLines.push('    ///');\n      fieldLines.push('    /// Required.');\n    }\n    if (rust.startsWith('Option<')) {\n      fieldLines.push('    #[serde(skip_serializing_if = \"Option::is_none\")]');\n    }\n    // Vec query params with `style: form, explode: false` (the comma-joined\n    // wire format) need a custom serializer — serde alone serialises Vec as\n    // an array, which our query encoder unrolls into repeated keys.\n    if (opts.isQuery && p.explode === false && isVecType(rust)) {\n      fieldLines.push(\n        rust.startsWith('Option<')\n          ? '    #[serde(serialize_with = \"crate::query::serialize_comma_separated_opt\")]'\n          : '    #[serde(serialize_with = \"crate::query::serialize_comma_separated\")]',\n      );\n    }\n    if (fname !== p.name) {\n      fieldLines.push(`    #[serde(rename = ${JSON.stringify(p.name)})]`);\n    }\n    if (p.deprecated) fieldLines.push('    #[deprecated]');\n    fieldLines.push(`    pub ${fname}: ${rust},`);\n    fields.push({\n      fname,\n      rust,\n      required: !!p.required && !rust.startsWith('Option<'),\n      defaultExpr,\n    });\n  };\n\n  for (const p of op.queryParams) emitField(p, { isQuery: true });\n  for (const p of op.headerParams) emitField(p);\n  for (const p of op.cookieParams ?? []) emitField(p);\n\n  // Query-side parameter group fields. Flattened so the encoder sees the\n  // variant's own fields at the params struct's top level.\n  for (const g of queryGroupFields) {\n    fieldLines.push('    #[serde(flatten)]');\n    if (!g.required) {\n      fieldLines.push('    #[serde(skip_serializing_if = \"Option::is_none\")]');\n    }\n    fieldLines.push(`    pub ${g.name}: ${g.rustType},`);\n    fields.push({\n      fname: g.name,\n      rust: g.rustType,\n      required: g.required,\n      defaultExpr: null,\n    });\n  }\n\n  if (op.requestBody) {\n    let bodyType: string;\n    if (bodyGroupFields.length > 0) {\n      // Synthesise a body struct that replaces the grouped fields with a\n      // flattened enum. The original body model keeps the flat optional\n      // fields (it's shared with other consumers); the synthetic type is\n      // op-local and serialises with the parameter group's variant in\n      // strongly-typed form.\n      bodyType = registerSyntheticBody(op, name, bodyGroupParamNames, bodyGroupFields, ctx, registry, groupEmitter);\n    } else {\n      bodyType = mapTypeRef(op.requestBody, { hint: `${name}Body`, registry });\n    }\n    if (!bodyRequired && !bodyType.startsWith('Option<')) {\n      bodyType = makeOptional(bodyType);\n    }\n    fieldLines.push('    /// Request body sent with this call.');\n    if (bodyRequired) fieldLines.push('    ///');\n    if (bodyRequired) fieldLines.push('    /// Required.');\n    fieldLines.push('    #[serde(skip)]');\n    fieldLines.push(`    pub body: ${bodyType},`);\n    fields.push({\n      fname: 'body',\n      rust: bodyType,\n      required: bodyRequired,\n      defaultExpr: null,\n    });\n  }\n\n  // Default-derive only when every field is optional and no field has a\n  // spec-level default. Spec defaults need a manual `impl Default` since\n  // `Option<T>::default()` is `None`, not `Some(<spec default>)`.\n  const requiredFields = fields.filter((f) => f.required);\n  const allOptional = fields.length === 0 || requiredFields.length === 0;\n  const hasSpecDefault = fields.some((f) => f.defaultExpr !== null);\n  const canDeriveDefault = allOptional && !hasSpecDefault;\n  const derives = canDeriveDefault ? 'Debug, Clone, Default, Serialize' : 'Debug, Clone, Serialize';\n\n  const out: string[] = [];\n  if (fieldLines.length === 0) {\n    out.push(`#[derive(${derives})]`, `pub struct ${name} {}`);\n  } else {\n    out.push(`#[derive(${derives})]`, `pub struct ${name} {`, ...fieldLines, '}');\n  }\n\n  // Manual `Default` impl when every field is optional but some have\n  // spec-level defaults — `Default::default()` now returns those values\n  // instead of `None`.\n  if (allOptional && hasSpecDefault) {\n    const defaultInitLines = fields.map((f) => `            ${f.fname}: ${f.defaultExpr ?? 'Default::default()'},`);\n    out.push('');\n    out.push(`impl Default for ${name} {`);\n    out.push('    #[allow(deprecated)]');\n    out.push('    fn default() -> Self {');\n    out.push('        Self {');\n    out.push(...defaultInitLines);\n    out.push('        }');\n    out.push('    }');\n    out.push('}');\n  }\n\n  // Generate `new(...)` constructor when there is at least one required field\n  // but at least one optional field — gives callers a clear ergonomic entry\n  // point without forcing them to spell out optional fields.\n  if (requiredFields.length > 0) {\n    const ctorArgs = requiredFields.map((f) => `${f.fname}: ${ctorParamType(f.rust)}`).join(', ');\n    const initLines: string[] = [];\n    for (const f of fields) {\n      if (f.required) {\n        const value = ctorParamConvert(f.rust, f.fname);\n        // Use field-init shorthand when the parameter and field names match.\n        initLines.push(value === f.fname ? `            ${f.fname},` : `            ${f.fname}: ${value},`);\n      } else {\n        initLines.push(`            ${f.fname}: ${f.defaultExpr ?? 'Default::default()'},`);\n      }\n    }\n    out.push('');\n    out.push(`impl ${name} {`);\n    out.push(`    /// Construct a new \\`${name}\\` with the required fields set.`);\n    out.push('    #[allow(deprecated)]');\n    out.push(`    pub fn new(${ctorArgs}) -> Self {`);\n    out.push('        Self {');\n    out.push(...initLines);\n    out.push('        }');\n    out.push('    }');\n    out.push('}');\n  }\n\n  return out.join('\\n');\n}\n\n/** True when a Rust type expression is a `Vec<…>` (or `Option<Vec<…>>`). */\nfunction isVecType(rust: string): boolean {\n  const inner = rust.startsWith('Option<') ? rust.slice('Option<'.length, -1) : rust;\n  return inner.startsWith('Vec<');\n}\n\n/**\n * Build a synthetic body struct for an op that has body-side parameter\n * groups. The original body model can't be reused as-is because its grouped\n * fields are still flat optionals; the synthetic type swaps them for a\n * flattened enum so callers commit to one variant at construction time.\n */\nfunction registerSyntheticBody(\n  op: Operation,\n  paramsName: string,\n  bodyGroupParamNames: Set<string>,\n  bodyGroupFields: Array<{\n    name: string;\n    rustType: string;\n    required: boolean;\n    doc?: string;\n  }>,\n  ctx: EmitterContext,\n  registry: UnionRegistry,\n  groupEmitter: GroupEmitter,\n): string {\n  // Resolve the original body model (only model-kind bodies can have body\n  // groups in the spec; other shapes fall back to the model name directly).\n  const bodyRef = op.requestBody;\n  if (!bodyRef || bodyRef.kind !== 'model') {\n    return mapTypeRef(bodyRef!, { hint: `${paramsName}Body`, registry });\n  }\n  const model = ctx.spec.models.find((m) => m.name === bodyRef.name);\n  if (!model) {\n    return typeName(bodyRef.name);\n  }\n  const name = `${paramsName}Body`;\n  const flatFields = model.fields\n    .filter((f) => !bodyGroupParamNames.has(f.name))\n    .map((f) => {\n      let rust = mapTypeRef(f.type, {\n        hint: `${name}${typeName(f.name)}`,\n        registry,\n      });\n      if (!f.required && !rust.startsWith('Option<')) rust = makeOptional(rust);\n      rust = applySecretRedaction(rust, f.name);\n      return {\n        // Domain identifier honors a `fieldHints` override (e.g. wire\n        // `connection_type` → domain `type`); `wireName` keeps `f.name`, and\n        // the `#[serde(rename = wireName)]` emitted in GroupEmitter.render\n        // fires whenever the two differ.\n        rustName: domainFieldName(f),\n        wireName: f.name,\n        rustType: rust,\n        required: !!f.required && !rust.startsWith('Option<'),\n        doc: f.description,\n      };\n    });\n  const flattenEnums = bodyGroupFields.map((g) => ({\n    rustName: g.name,\n    rustType: g.rustType,\n    required: g.required,\n    doc: g.doc,\n  }));\n  return groupEmitter.registerBody({ name, flatFields, flattenEnums });\n}\n\n/** Constructor parameter type — accept `impl Into<String>` for ergonomic strings. */\nfunction ctorParamType(rust: string): string {\n  if (rust === 'String') return 'impl Into<String>';\n  if (rust === 'crate::SecretString') return 'impl Into<crate::SecretString>';\n  return rust;\n}\n\nfunction ctorParamConvert(rust: string, name: string): string {\n  if (rust === 'String') return `${name}.into()`;\n  if (rust === 'crate::SecretString') return `${name}.into()`;\n  return name;\n}\n\n/**\n * Detect a non-default per-operation security requirement (e.g. SSO's\n * `get_profile` requires an OAuth access token rather than the WorkOS API\n * key). Returns the snake_case parameter name to use for the override.\n */\nfunction bearerOverrideToken(op: Operation): string | null {\n  const override = op.security?.find((s) => s.schemeName !== 'bearerAuth');\n  if (!override) return null;\n  return fieldName(override.schemeName);\n}\n\nfunction renderMethod(\n  op: Operation,\n  resolved: ResolvedOperation,\n  paramsType: string,\n  method: string,\n  emptyParams: boolean,\n): string {\n  const plan = planOperation(op);\n  const segments = parsePathTemplate(op.path);\n  const pathArgList = op.pathParams.map((p) => `${methodName(p.name)}: &str`);\n  const pathArgNames = op.pathParams.map((p) => methodName(p.name));\n\n  const returnType = renderResponseType(op);\n  const bodyRequired = isBodyRequired(op);\n  const tokenParam = bearerOverrideToken(op);\n\n  const sig: string[] = [];\n\n  // Convenience method — no per-request options. Delegates to `_with_options`.\n  for (const line of methodDocLines(op)) sig.push(`    ${line}`);\n  if (op.deprecated) sig.push('    #[deprecated]');\n  const argsConvenience = [\n    '&self',\n    ...pathArgList,\n    ...(emptyParams ? [] : [`params: ${paramsType}`]),\n    ...(tokenParam ? [`${tokenParam}: impl Into<String>`] : []),\n  ];\n  const convenienceSig = `    pub async fn ${method}(${argsConvenience.join(', ')}) -> Result<${returnType}, Error> {`;\n  if (convenienceSig.length <= 100) {\n    sig.push(convenienceSig);\n  } else {\n    sig.push(`    pub async fn ${method}(`);\n    for (const arg of argsConvenience) sig.push(`        ${arg},`);\n    sig.push(`    ) -> Result<${returnType}, Error> {`);\n  }\n  const delegateArgs = [\n    ...pathArgNames,\n    ...(emptyParams ? [] : ['params']),\n    ...(tokenParam ? [tokenParam] : []),\n    'None',\n  ].join(', ');\n  sig.push(`        self.${method}_with_options(${delegateArgs}).await`);\n  sig.push('    }');\n  sig.push('');\n\n  // `_with_options` variant — per-request idempotency keys, custom headers, etc.\n  sig.push(`    /// Variant of [\\`Self::${method}\\`] that accepts per-request [\\`crate::RequestOptions\\`].`);\n  if (op.deprecated) sig.push('    #[deprecated]');\n  const argsOpts = [\n    '&self',\n    ...pathArgList,\n    ...(emptyParams ? [] : [`params: ${paramsType}`]),\n    ...(tokenParam ? [`${tokenParam}: impl Into<String>`] : []),\n    'options: Option<&crate::RequestOptions>',\n  ];\n  const optsSig = `    pub async fn ${method}_with_options(${argsOpts.join(', ')}) -> Result<${returnType}, Error> {`;\n  if (optsSig.length <= 100) {\n    sig.push(optsSig);\n  } else {\n    sig.push(`    pub async fn ${method}_with_options(`);\n    for (const arg of argsOpts) sig.push(`        ${arg},`);\n    sig.push(`    ) -> Result<${returnType}, Error> {`);\n  }\n\n  const pathFormat = segments\n    .map((s) => (s.kind === 'literal' ? s.value : `{${methodName(s.name as string)}}`))\n    .join('');\n  const pathHasParams = segments.some((s) => s.kind === 'param');\n\n  if (pathHasParams) {\n    for (const p of op.pathParams) {\n      const n = methodName(p.name);\n      sig.push(`        let ${n} = crate::client::path_segment(${n});`);\n    }\n    sig.push(`        let path = format!(${JSON.stringify(pathFormat)});`);\n  } else {\n    sig.push(`        let path = ${JSON.stringify(pathFormat)}.to_string();`);\n  }\n\n  sig.push(`        let method = http::Method::${op.httpMethod.toUpperCase()};`);\n\n  // Bearer override: build a one-off `RequestOptions` that re-merges any\n  // caller-supplied options with the override Authorization header. Done\n  // inline so the call site can keep using the standard request helpers.\n  if (tokenParam) {\n    sig.push(`        let ${tokenParam}: String = ${tokenParam}.into();`);\n    sig.push(`        let auth = http::HeaderValue::from_str(&format!(\"Bearer {${tokenParam}}\"))`);\n    sig.push(`            .map_err(|e| Error::Builder(format!(\"invalid bearer token: {e}\")))?;`);\n    sig.push('        let mut merged = options.cloned().unwrap_or_default();');\n    sig.push('        merged.extra_headers.push((http::header::AUTHORIZATION, auth));');\n    sig.push('        let options = Some(&merged);');\n  }\n\n  // For empty-params endpoints, pass `&()` as the (empty) query — `()`\n  // serialises to nothing under serde, matching the previous empty-struct\n  // behaviour without surfacing the struct in the public API.\n  const queryRef = emptyParams ? '&()' : '&params';\n  const emptyResp = isEmptyResponse(op);\n  const bodyMethod = emptyResp ? 'request_with_body_opts_empty' : 'request_with_body_opts';\n  const queryMethod = emptyResp ? 'request_with_query_opts_empty' : 'request_with_query_opts';\n\n  if (op.requestBody) {\n    sig.push('        self.client');\n    if (bodyRequired) {\n      sig.push(`            .${bodyMethod}(method, &path, ${queryRef}, Some(&params.body), options)`);\n    } else {\n      sig.push(`            .${bodyMethod}(method, &path, ${queryRef}, params.body.as_ref(), options)`);\n    }\n    sig.push('            .await');\n  } else {\n    sig.push('        self.client');\n    sig.push(`            .${queryMethod}(method, &path, ${queryRef}, options)`);\n    sig.push('            .await');\n  }\n\n  sig.push('    }');\n\n  void plan;\n  void resolved;\n  return sig.join('\\n');\n}\n\n/**\n * Render a URL-builder method. URL-builder ops (e.g. `GET /sso/authorize`,\n * `GET /sso/logout`) issue no HTTP request — they format a redirect URL the\n * application sends the user to. Generated methods return `Result<String,\n * Error>` because percent-encoding the query string can still fail.\n */\nfunction renderUrlBuilderMethod(\n  op: Operation,\n  resolved: ResolvedOperation,\n  paramsType: string,\n  method: string,\n  emptyParams: boolean,\n): string {\n  const segments = parsePathTemplate(op.path);\n  const pathArgList = op.pathParams.map((p) => `${methodName(p.name)}: &str`);\n  const pathArgNames = op.pathParams.map((p) => methodName(p.name));\n\n  const sig: string[] = [];\n  for (const line of methodDocLines(op)) sig.push(`    ${line}`);\n  if (op.deprecated) sig.push('    #[deprecated]');\n  const args = ['&self', ...pathArgList, ...(emptyParams ? [] : [`params: ${paramsType}`])];\n  const headSig = `    pub fn ${method}(${args.join(', ')}) -> Result<String, Error> {`;\n  if (headSig.length <= 100) {\n    sig.push(headSig);\n  } else {\n    sig.push(`    pub fn ${method}(`);\n    for (const arg of args) sig.push(`        ${arg},`);\n    sig.push('    ) -> Result<String, Error> {');\n  }\n\n  const pathFormat = segments\n    .map((s) => (s.kind === 'literal' ? s.value : `{${methodName(s.name as string)}}`))\n    .join('');\n  const pathHasParams = segments.some((s) => s.kind === 'param');\n\n  if (pathHasParams) {\n    for (const p of op.pathParams) {\n      const n = methodName(p.name);\n      sig.push(`        let ${n} = crate::client::path_segment(${n});`);\n    }\n    sig.push(`        let path = format!(${JSON.stringify(pathFormat)});`);\n  } else {\n    sig.push(`        let path = ${JSON.stringify(pathFormat)}.to_string();`);\n  }\n\n  // Bake constant defaults + inferred client fields directly into the query.\n  // The runtime helper handles encoding, including arrays and flatten-enum\n  // groups, so we just hand it whatever serde produces from `params`.\n  const defaults = (resolved.defaults ?? {}) as Record<string, string | number | boolean>;\n  const inferred = resolved.inferFromClient ?? [];\n  const hasDefaults = Object.keys(defaults).length > 0 || inferred.length > 0;\n  if (hasDefaults) {\n    sig.push('        let mut overlay = serde_json::Map::new();');\n    for (const [k, v] of Object.entries(defaults)) {\n      sig.push(`        overlay.insert(${JSON.stringify(k)}.to_string(), serde_json::json!(${JSON.stringify(v)}));`);\n    }\n    for (const k of inferred) {\n      sig.push(\n        `        overlay.insert(${JSON.stringify(k)}.to_string(), serde_json::Value::String(${clientFieldExpression(k)}.to_string()));`,\n      );\n    }\n    if (!emptyParams) {\n      sig.push('        let params_value = serde_json::to_value(&params)');\n      sig.push('            .map_err(|e| Error::Builder(format!(\"query encode failed: {e}\")))?;');\n      sig.push('        if let serde_json::Value::Object(map) = params_value {');\n      sig.push('            for (k, v) in map { overlay.insert(k, v); }');\n      sig.push('        }');\n    }\n    sig.push('        let merged = serde_json::Value::Object(overlay);');\n    sig.push('        let qs = crate::query::encode_query(&merged)?;');\n  } else if (!emptyParams) {\n    sig.push('        let qs = crate::query::encode_query(&params)?;');\n  } else {\n    sig.push('        let qs = String::new();');\n  }\n\n  sig.push('        let url = if qs.is_empty() {');\n  sig.push('            format!(\"{}{}\", self.client.base_url(), path)');\n  sig.push('        } else {');\n  sig.push('            format!(\"{}{}?{}\", self.client.base_url(), path, qs)');\n  sig.push('        };');\n  sig.push('        Ok(url)');\n  sig.push('    }');\n\n  // Unused path params would otherwise warn; keep them in scope.\n  void pathArgNames;\n  return sig.join('\\n');\n}\n\n/**\n * Generate a `<method>_auto_paging` helper from `op.pagination`. Returns null\n * when the operation isn't paginated, when the strategy isn't `cursor`, or\n * when the response model lacks the expected `data` / pagination-cursor\n * fields (defensive — the IR shouldn't produce that combination today).\n */\nfunction renderAutoPagingMethod(\n  op: Operation,\n  resolved: ResolvedOperation,\n  paramsType: string,\n  method: string,\n  ctx: EmitterContext,\n): string | null {\n  if (!op.pagination) return null;\n  // Only cursor pagination is implemented today; offset / link-header would\n  // need a different stream wrapper.\n  if (op.pagination.strategy !== 'cursor') return null;\n  if (resolved.urlBuilder) return null;\n\n  const cursorParam = op.pagination.param;\n  const dataPath = op.pagination.dataPath ?? 'data';\n  let itemType: string;\n\n  if (op.response.kind === 'model') {\n    const responseModel = ctx.spec.models.find((m) => m.name === (op.response as { name: string }).name);\n    if (!responseModel) return null;\n\n    const dataField = responseModel.fields.find((f) => f.name === dataPath);\n    if (!dataField || dataField.type.kind !== 'array') return null;\n    const listMetadataField = responseModel.fields.find((f) => f.name === 'list_metadata');\n    if (!listMetadataField || listMetadataField.type.kind !== 'model') return null;\n\n    // The response cursor lives on the list-metadata model under the same name\n    // as the request param. Bail if it doesn't — that would mean a spec/IR\n    // mismatch and a hand-written wrapper is safer than a broken generated one.\n    const metadataModel = ctx.spec.models.find((m) => m.name === (listMetadataField.type as { name: string }).name);\n    if (!metadataModel) return null;\n    if (!metadataModel.fields.some((f) => f.name === cursorParam)) return null;\n\n    // The IR's `pagination.itemType` is the response wrapper model (e.g.\n    // `OrganizationList`), so reach into the model's `data: Vec<T>` field to\n    // pull out the actual element type.\n    itemType = mapTypeRef(dataField.type.items);\n  } else if (isInlineEnvelopeList(op) && cursorParam === 'after') {\n    // Inline-envelope responses decode into `crate::pagination::Page<T>`,\n    // which declares `data` + `list_metadata.after` by construction — only\n    // the request-side cursor param needs to exist.\n    if (!op.queryParams.some((p) => p.name === cursorParam)) return null;\n    itemType = mapTypeRef((op.response as { items: TypeRef }).items);\n  } else {\n    return null;\n  }\n\n  const cursorField = fieldName(cursorParam);\n  const dataAccessor = fieldName(dataPath);\n\n  // Path args are taken by owned `String` so the returned stream borrows\n  // nothing but `&self`.\n  const pathArgList = op.pathParams.map((p) => `${methodName(p.name)}: impl Into<String>`);\n  const pathArgNames = op.pathParams.map((p) => methodName(p.name));\n\n  const sig: string[] = [];\n  sig.push('');\n  sig.push(`    /// Returns an async [\\`futures_util::Stream\\`] that yields every \\`${itemType}\\``);\n  sig.push(`    /// across all pages, advancing the \\`${cursorParam}\\` cursor under the hood.`);\n  sig.push('    ///');\n  sig.push('    /// ```ignore');\n  sig.push('    /// use futures_util::TryStreamExt;');\n  sig.push(`    /// let all: Vec<${itemType}> = self`);\n  sig.push(`    ///     .${method}_auto_paging(${[...pathArgNames, 'params'].join(', ')})`);\n  sig.push('    ///     .try_collect()');\n  sig.push('    ///     .await?;');\n  sig.push('    /// ```');\n  if (op.deprecated) sig.push('    #[deprecated]');\n\n  const argsAll = ['&self', ...pathArgList, `params: ${paramsType}`];\n  const optsSig = `    pub fn ${method}_auto_paging(${argsAll.join(', ')}) -> impl futures_util::Stream<Item = Result<${itemType}, Error>> + '_ {`;\n  if (optsSig.length <= 110) {\n    sig.push(optsSig);\n  } else {\n    sig.push(`    pub fn ${method}_auto_paging(`);\n    for (const arg of argsAll) sig.push(`        ${arg},`);\n    sig.push(`    ) -> impl futures_util::Stream<Item = Result<${itemType}, Error>> + '_ {`);\n  }\n\n  for (const n of pathArgNames) {\n    sig.push(`        let ${n}: String = ${n}.into();`);\n  }\n  sig.push('        crate::pagination::auto_paginate_pages(move |after| {');\n  for (const n of pathArgNames) sig.push(`            let ${n} = ${n}.clone();`);\n  sig.push('            let mut params = params.clone();');\n  sig.push(`            params.${cursorField} = after;`);\n  sig.push('            async move {');\n  const callArgs = [...pathArgNames.map((n) => `&${n}`), 'params'].join(', ');\n  sig.push(`                let page = self.${method}(${callArgs}).await?;`);\n  sig.push(`                Ok((page.${dataAccessor}, page.list_metadata.${cursorField}))`);\n  sig.push('            }');\n  sig.push('        })');\n  sig.push('    }');\n\n  return sig.join('\\n');\n}\n\nfunction renderWrapperParamsStruct(\n  name: string,\n  _op: Operation,\n  _wrapper: ResolvedWrapper,\n  params: ResolvedWrapperParam[],\n  registry: UnionRegistry,\n  ctx: EmitterContext,\n): string {\n  type FieldInfo = {\n    fname: string;\n    rust: string;\n    required: boolean;\n    defaultExpr: string | null;\n  };\n  const fields: FieldInfo[] = [];\n  const fieldLines: string[] = [];\n  const seen = new Set<string>();\n  for (const rp of params) {\n    const fname = fieldName(rp.paramName);\n    if (seen.has(fname)) continue;\n    seen.add(fname);\n    let rust: string;\n    if (rp.field) {\n      rust = mapTypeRef(rp.field.type, {\n        hint: `${name}${typeName(rp.paramName)}`,\n        registry,\n      });\n    } else {\n      rust = 'String';\n    }\n    if (rp.isOptional && !rust.startsWith('Option<')) rust = makeOptional(rust);\n    rust = applySecretRedaction(rust, rp.paramName);\n    const desc = rp.field?.description?.trim();\n    if (desc) {\n      for (const c of paramDocComment(desc)) fieldLines.push(`    ${c}`);\n    }\n    const fieldDefault = rp.field?.default;\n    if (fieldDefault != null) {\n      if (desc) fieldLines.push('    ///');\n      fieldLines.push(`    /// Defaults to \\`${formatDefault(fieldDefault)}\\`.`);\n    }\n    const required = !rp.isOptional && !rust.startsWith('Option<');\n    if (required) {\n      if (desc || fieldDefault != null) fieldLines.push('    ///');\n      fieldLines.push('    /// Required.');\n    }\n    if (rust.startsWith('Option<')) {\n      fieldLines.push('    #[serde(skip_serializing_if = \"Option::is_none\")]');\n    }\n    if (fname !== rp.paramName) {\n      fieldLines.push(`    #[serde(rename = ${JSON.stringify(rp.paramName)})]`);\n    }\n    fieldLines.push(`    pub ${fname}: ${rust},`);\n    const defaultExpr =\n      fieldDefault != null && rp.field\n        ? rustDefaultExpr(fieldDefault, rp.field.type, rust.startsWith('Option<'), ctx)\n        : null;\n    fields.push({ fname, rust, required, defaultExpr });\n  }\n\n  // Mirror the regular params struct: derive `Default` only when every field\n  // is optional and no field carries a spec-level default; spec defaults need\n  // a manual `impl Default` (Option<T>::default() is None).\n  const requiredFields = fields.filter((f) => f.required);\n  const allOptional = fields.length === 0 || requiredFields.length === 0;\n  const hasSpecDefault = fields.some((f) => f.defaultExpr !== null);\n  const canDeriveDefault = allOptional && !hasSpecDefault;\n  const derives = canDeriveDefault ? 'Debug, Clone, Default, Serialize' : 'Debug, Clone, Serialize';\n\n  const out: string[] = [];\n  if (fieldLines.length === 0) {\n    out.push(`#[derive(${derives})]`, `pub struct ${name} {}`);\n  } else {\n    out.push(`#[derive(${derives})]`, `pub struct ${name} {`, ...fieldLines, '}');\n  }\n\n  if (allOptional && hasSpecDefault) {\n    const defaultInitLines = fields.map((f) => `            ${f.fname}: ${f.defaultExpr ?? 'Default::default()'},`);\n    out.push('');\n    out.push(`impl Default for ${name} {`);\n    out.push('    fn default() -> Self {');\n    out.push('        Self {');\n    out.push(...defaultInitLines);\n    out.push('        }');\n    out.push('    }');\n    out.push('}');\n  }\n\n  if (requiredFields.length > 0) {\n    const ctorArgs = requiredFields.map((f) => `${f.fname}: ${ctorParamType(f.rust)}`).join(', ');\n    const initLines: string[] = [];\n    for (const f of fields) {\n      if (f.required) {\n        const value = ctorParamConvert(f.rust, f.fname);\n        initLines.push(value === f.fname ? `            ${f.fname},` : `            ${f.fname}: ${value},`);\n      } else {\n        initLines.push(`            ${f.fname}: ${f.defaultExpr ?? 'Default::default()'},`);\n      }\n    }\n    out.push('');\n    out.push(`impl ${name} {`);\n    out.push(`    /// Construct a new \\`${name}\\` with the required fields set.`);\n    out.push(`    pub fn new(${ctorArgs}) -> Self {`);\n    out.push('        Self {');\n    out.push(...initLines);\n    out.push('        }');\n    out.push('    }');\n    out.push('}');\n  }\n\n  return out.join('\\n');\n}\n\nfunction renderWrapperMethod(\n  op: Operation,\n  wrapper: ResolvedWrapper,\n  params: ResolvedWrapperParam[],\n  paramsType: string,\n  method: string,\n): string {\n  const segments = parsePathTemplate(op.path);\n  const pathArgList = op.pathParams.map((p) => `${methodName(p.name)}: &str`);\n  const pathArgNames = op.pathParams.map((p) => methodName(p.name));\n  const returnType = wrapper.responseModelName ? typeName(wrapper.responseModelName) : renderResponseType(op);\n\n  const sig: string[] = [];\n  const docLines: string[] = [];\n  const desc = (op.description ?? '').trim();\n  if (desc) {\n    for (const raw of desc.split('\\n')) {\n      const t = raw.trim();\n      docLines.push(t.length === 0 ? '    ///' : `    /// ${t}`);\n    }\n  } else {\n    docLines.push(`    /// ${op.httpMethod.toUpperCase()} ${op.path} (${wrapper.name})`);\n  }\n\n  // Convenience method — delegates to `_with_options`.\n  sig.push(...docLines);\n  if (op.deprecated) sig.push('    #[deprecated]');\n  const argsConvenience = ['&self', ...pathArgList, `params: ${paramsType}`];\n  const convenienceSig = `    pub async fn ${method}(${argsConvenience.join(', ')}) -> Result<${returnType}, Error> {`;\n  if (convenienceSig.length <= 100) {\n    sig.push(convenienceSig);\n  } else {\n    sig.push(`    pub async fn ${method}(`);\n    for (const arg of argsConvenience) sig.push(`        ${arg},`);\n    sig.push(`    ) -> Result<${returnType}, Error> {`);\n  }\n  const delegateArgs = [...pathArgNames, 'params', 'None'].join(', ');\n  sig.push(`        self.${method}_with_options(${delegateArgs}).await`);\n  sig.push('    }');\n  sig.push('');\n\n  // `_with_options` variant.\n  sig.push(`    /// Variant of [\\`Self::${method}\\`] that accepts per-request [\\`crate::RequestOptions\\`].`);\n  if (op.deprecated) sig.push('    #[deprecated]');\n  const argsOpts = ['&self', ...pathArgList, `params: ${paramsType}`, 'options: Option<&crate::RequestOptions>'];\n  const optsSig = `    pub async fn ${method}_with_options(${argsOpts.join(', ')}) -> Result<${returnType}, Error> {`;\n  if (optsSig.length <= 100) {\n    sig.push(optsSig);\n  } else {\n    sig.push(`    pub async fn ${method}_with_options(`);\n    for (const arg of argsOpts) sig.push(`        ${arg},`);\n    sig.push(`    ) -> Result<${returnType}, Error> {`);\n  }\n\n  const pathFormat = segments\n    .map((s) => (s.kind === 'literal' ? s.value : `{${methodName(s.name as string)}}`))\n    .join('');\n  const pathHasParams = segments.some((s) => s.kind === 'param');\n\n  if (pathHasParams) {\n    for (const p of op.pathParams) {\n      const n = methodName(p.name);\n      sig.push(`        let ${n} = crate::client::path_segment(${n});`);\n    }\n    sig.push(`        let path = format!(${JSON.stringify(pathFormat)});`);\n  } else {\n    sig.push(`        let path = ${JSON.stringify(pathFormat)}.to_string();`);\n  }\n\n  sig.push(`        let method = http::Method::${op.httpMethod.toUpperCase()};`);\n\n  // Build the JSON body inline: defaults + each exposed param. inferFromClient\n  // fields (read from the client at request time) are added afterwards, and\n  // only when non-empty — a client configured without an API key (e.g. a\n  // public client running a PKCE flow) must omit `client_secret` entirely\n  // rather than send `\"\"`, which the API rejects. Mirrors the Go emitter's\n  // `omitempty` on inferred fields.\n  const inferredFields = wrapper.inferFromClient ?? [];\n  sig.push(`        let ${inferredFields.length > 0 ? 'mut ' : ''}body = serde_json::json!({`);\n  for (const [k, v] of Object.entries(wrapper.defaults ?? {})) {\n    sig.push(`            ${JSON.stringify(k)}: ${JSON.stringify(v)},`);\n  }\n  for (const rp of params) {\n    sig.push(`            ${JSON.stringify(rp.paramName)}: params.${fieldName(rp.paramName)},`);\n  }\n  sig.push('        });');\n  for (const k of inferredFields) {\n    const expr = clientFieldExpression(k);\n    sig.push(`        if !${expr}.is_empty() {`);\n    sig.push(`            body[${JSON.stringify(k)}] = serde_json::Value::String(${expr}.to_string());`);\n    sig.push('        }');\n  }\n\n  sig.push('        #[derive(Serialize)]');\n  sig.push('        struct EmptyQuery {}');\n  sig.push('        self.client');\n  sig.push('            .request_with_body_opts(method, &path, &EmptyQuery {}, Some(&body), options)');\n  sig.push('            .await');\n  sig.push('    }');\n\n  return sig.join('\\n');\n}\n\n/**\n * Rust expression for reading a client-config field at request time. Mirrors\n * the Go emitter's `clientFieldExpression`. Throws on unknown fields rather\n * than falling back to an empty literal: with the `if !expr.is_empty()` guard\n * in `renderWrapperMethod`, an empty literal would silently drop the field from\n * every request body (and emit dead `if !\"\".is_empty()` Rust). Failing loud at\n * generation time surfaces a missing case instead of shipping a broken SDK.\n */\nfunction clientFieldExpression(field: string): string {\n  switch (field) {\n    case 'client_id':\n      return 'self.client.client_id()';\n    case 'client_secret':\n      return 'self.client.api_key()';\n    default:\n      throw new Error(\n        `Rust emitter: no client-config accessor for inferFromClient field \"${field}\". ` +\n          'Add a case to clientFieldExpression.',\n      );\n  }\n}\n\n/** Multi-line `///` doc comment from a free-form description. */\nfunction paramDocComment(text: string): string[] {\n  return text\n    .split('\\n')\n    .map((l) => l.trim())\n    .filter((l) => l.length > 0)\n    .map((l) => `/// ${l}`);\n}\n\n/**\n * Render a spec-level default value for inclusion in a doc comment. Strings\n * render bare (e.g. `desc`) so they nest naturally inside the surrounding\n * backticks; numbers/booleans use JSON encoding.\n */\nfunction formatDefault(value: unknown): string {\n  if (typeof value === 'string') return value;\n  return JSON.stringify(value);\n}\n\n/**\n * Render a spec-level default value as a Rust expression suitable for an\n * `impl Default` body or a `new(…)` initialiser. When `isOptional` is true the\n * result is wrapped in `Some(…)` so it matches an `Option<T>` field.\n *\n * Returns `null` for types/values the emitter doesn't know how to materialise\n * — caller falls back to `Default::default()`.\n */\nfunction rustDefaultExpr(value: unknown, ref: TypeRef, isOptional: boolean, ctx: EmitterContext): string | null {\n  if (ref.kind === 'nullable') {\n    return rustDefaultExpr(value, ref.inner, isOptional, ctx);\n  }\n\n  let expr: string | null = null;\n  switch (ref.kind) {\n    case 'primitive':\n      if (ref.type === 'integer' && typeof value === 'number' && Number.isFinite(value)) {\n        expr = String(Math.trunc(value));\n      } else if (ref.type === 'number' && typeof value === 'number' && Number.isFinite(value)) {\n        // Floats need a decimal point so the literal parses as `f64`, not `i32`.\n        expr = Number.isInteger(value) ? `${value}.0` : String(value);\n      } else if (ref.type === 'boolean' && typeof value === 'boolean') {\n        expr = String(value);\n      } else if (ref.type === 'string' && typeof value === 'string') {\n        expr = `${JSON.stringify(value)}.to_string()`;\n      }\n      break;\n    case 'enum': {\n      if (typeof value !== 'string' && typeof value !== 'number') break;\n      const enumDef = ctx.spec.enums.find((e) => e.name === ref.name);\n      if (!enumDef) break;\n      const ev = enumDef.values.find((v) => v.value === value);\n      if (!ev) break;\n      expr = `${typeName(ref.name)}::${variantName(ev.value)}`;\n      break;\n    }\n    default:\n      break;\n  }\n\n  if (expr === null) return null;\n  return isOptional ? `Some(${expr})` : expr;\n}\n\nfunction methodDocLines(op: Operation): string[] {\n  const lines: string[] = [];\n  if (op.description && op.description.trim().length > 0) {\n    for (const raw of op.description.split('\\n')) {\n      const trimmed = raw.trim();\n      if (trimmed.length === 0) {\n        lines.push('///');\n      } else {\n        lines.push(`/// ${trimmed}`);\n      }\n    }\n  } else {\n    lines.push(`/// ${op.httpMethod.toUpperCase()} ${op.path}`);\n  }\n  return lines;\n}\n\nfunction renderResponseType(op: Operation): string {\n  if (isEmptyResponse(op)) return '()';\n  if (isInlineEnvelopeList(op)) {\n    return `crate::pagination::Page<${mapTypeRef((op.response as { items: TypeRef }).items)}>`;\n  }\n  return mapTypeRef(op.response!);\n}\n\n/**\n * True when the spec declared this response as an inline pagination envelope\n * (`{ object, data: [...], list_metadata }` without a named component). The IR\n * models these as a bare array plus `pagination.dataPath`, but the wire format\n * is still the envelope — decoding the body straight into `Vec<T>` fails, so\n * these ops decode into the hand-maintained `crate::pagination::Page<T>`\n * instead. Restricted to `data` because that's the field `Page<T>` declares.\n *\n * The `=== 'data'` is a strict equality on purpose — deliberately *not* the\n * `?? 'data'` fallback used elsewhere. `dataPath` is the only signal that\n * separates an inline envelope (decoded as `Page<T>`) from a genuine paginated\n * bare array (decoded as `Vec<T>`, see the `responseKind === 'array'` branch in\n * tests.ts). This therefore relies on the IR setting `dataPath: 'data'`\n * explicitly for envelope responses and leaving it unset for bare arrays. If\n * the IR ever omitted it for an envelope op, this would return `false` and the\n * op would decode into `Vec<T>` and fail — so that invariant must hold upstream.\n */\nexport function isInlineEnvelopeList(op: Operation): boolean {\n  return op.response?.kind === 'array' && op.pagination?.dataPath === 'data';\n}\n\n/**\n * True when the operation has no usable response schema. We treat the IR's\n * `primitive: unknown` and missing-response cases the same way: the spec\n * declared no JSON body, so the SDK promises nothing about the contents.\n * Returning `Result<(), Error>` is more honest than handing back a\n * `serde_json::Value` that's almost always `Object({})` — and it lets the\n * caller `?` the result without an unused-variable warning.\n */\nfunction isEmptyResponse(op: Operation): boolean {\n  if (!op.response) return true;\n  if (op.response.kind === 'primitive' && op.response.type === 'unknown') return true;\n  return false;\n}\n\n/** Treat a body as optional when the IR wraps it in `nullable`. */\nfunction isBodyRequired(op: Operation): boolean {\n  return op.requestBody !== undefined && op.requestBody.kind !== 'nullable';\n}\n\n/**\n * `true` when the resolved operation contributes nothing to a params struct:\n * no request body, and every exposed query/header/cookie parameter is\n * inferred from the client or supplied as a default. Such methods take no\n * `params:` arg in the public API and skip the empty struct entirely.\n */\nfunction isEmptyParams(op: Operation, resolved: ResolvedOperation): boolean {\n  if (op.requestBody) return false;\n  const hidden = new Set<string>([...Object.keys(resolved.defaults ?? {}), ...(resolved.inferFromClient ?? [])]);\n  const grouped = new Set<string>();\n  for (const g of op.parameterGroups ?? []) {\n    for (const v of g.variants) for (const p of v.parameters) grouped.add(p.name);\n  }\n  const visibleQuery = op.queryParams.filter((p) => !hidden.has(p.name) && !grouped.has(p.name));\n  const visibleHeader = op.headerParams.filter((p) => !hidden.has(p.name));\n  const visibleCookie = (op.cookieParams ?? []).filter((p) => !hidden.has(p.name));\n  return (\n    visibleQuery.length === 0 &&\n    visibleHeader.length === 0 &&\n    visibleCookie.length === 0 &&\n    (op.parameterGroups?.length ?? 0) === 0\n  );\n}\n\nfunction renderResourcesBarrel(exports: { module: string; struct: string }[]): string {\n  const seen = new Set<string>();\n  const unique: { module: string; struct: string }[] = [];\n  for (const e of exports) {\n    if (seen.has(e.module)) continue;\n    seen.add(e.module);\n    unique.push(e);\n  }\n  unique.sort((a, b) => a.module.localeCompare(b.module));\n\n  const lines: string[] = [];\n  for (const { module } of unique) lines.push(`pub mod ${module};`);\n  lines.push('');\n  for (const { module, struct } of unique) lines.push(`pub use ${module}::${struct};`);\n  return lines.join('\\n') + '\\n';\n}\n","import type { ApiSpec, EmitterContext, GeneratedFile } from '@workos/oagen';\nimport type { UnionRegistry } from './type-map.js';\nimport { moduleName } from './naming.js';\nimport { groupByMount } from '../shared/resolved-ops.js';\nimport { mountStructName } from './resources.js';\n\n/**\n * The Rust emitter only generates spec-derived endpoint logic. The HTTP\n * client (`src/client.rs`), crate root (`src/lib.rs`), error types\n * (`src/error.rs`), pagination helpers (`src/pagination.rs`), and\n * `Cargo.toml` are hand-maintained in the live SDK — analogous to a\n * `Gemfile` in Ruby.\n *\n * This pass runs last (after `generateModels` and `generateResources`) so\n * the shared {@link UnionRegistry} has collected every synthesised oneOf\n * union before being rendered into `src/models/_unions.rs`.\n *\n * It also emits `src/resources_api.rs`, an auxiliary `impl Client { ... }`\n * block that exposes one accessor method per mount target. Keeping the\n * accessors in a generated file lets `src/client.rs` remain hand-maintained\n * without drifting as services mount/unmount.\n */\nexport function generateClient(_spec: ApiSpec, ctx: EmitterContext, registry: UnionRegistry): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  // _unions.rs — emitted unconditionally so the models barrel reference\n  // keeps the same shape across runs.\n  const unionsContent = registry.size() > 0 ? registry.render() : '// No oneOf-style unions registered.\\n';\n  files.push({ path: 'src/models/_unions.rs', content: unionsContent, overwriteExisting: true });\n\n  // resources_api.rs — `impl Client { fn user_management() -> ... }`.\n  files.push({ path: 'src/resources_api.rs', content: renderResourcesApi(ctx), overwriteExisting: true });\n\n  return files;\n}\n\nfunction renderResourcesApi(ctx: EmitterContext): string {\n  const groups = groupByMount(ctx);\n  const targets: { accessor: string; struct: string }[] = [];\n  for (const [mountName, group] of groups) {\n    if (group.operations.length === 0) continue;\n    targets.push({ accessor: moduleName(mountName), struct: mountStructName(mountName) });\n  }\n  targets.sort((a, b) => a.accessor.localeCompare(b.accessor));\n\n  const lines: string[] = [];\n  lines.push('use crate::client::Client;');\n  for (const { struct } of targets) {\n    lines.push(`use crate::resources::${struct};`);\n  }\n  lines.push('');\n  lines.push('impl Client {');\n  targets.forEach(({ accessor, struct }, i) => {\n    lines.push(`    /// Access the \\`${accessor}\\` resource.`);\n    lines.push(`    pub fn ${accessor}(&self) -> ${struct}<'_> {`);\n    lines.push(`        ${struct} { client: self }`);\n    lines.push('    }');\n    if (i < targets.length - 1) lines.push('');\n  });\n  lines.push('}');\n  return lines.join('\\n') + '\\n';\n}\n","import type { ApiSpec, GeneratedFile, Model, Enum, TypeRef, EmitterContext } from '@workos/oagen';\nimport { walkTypeRef } from '@workos/oagen';\nimport { moduleName } from './naming.js';\nimport { isModelInScope, fileExistsAfterRun } from '../shared/resolved-ops.js';\n\n/**\n * Generate JSON test fixture files under `tests/fixtures/`. The Rust tests\n * pull these in via `include_str!` so no I/O is required at test time.\n *\n * Scoped runs only emit a fixture for a model whose file will exist on disk\n * after the run (in-scope, or already present from a prior run). Emitting a\n * fixture for a brand-new out-of-scope model would add a stray file for a model\n * the SDK can't even reference yet; in-scope tests only `include_str!` fixtures\n * for in-scope models, so gating here is safe.\n */\nexport function generateFixtures(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n  const seen = new Set<string>();\n\n  for (const model of spec.models) {\n    if (seen.has(model.name)) continue;\n    if (model.fields.length === 0) continue;\n    seen.add(model.name);\n\n    const path = `tests/fixtures/${moduleName(model.name)}.json`;\n    if (!fileExistsAfterRun(path, isModelInScope(model.name, ctx), ctx)) continue;\n\n    const fixture = generateModelFixture(model, modelMap, enumMap, new Set());\n    files.push({\n      path,\n      content: JSON.stringify(fixture, null, 2) + '\\n',\n      headerPlacement: 'skip',\n    });\n  }\n\n  return files;\n}\n\nexport function generateModelFixture(\n  model: Model,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n  visiting: Set<string>,\n): Record<string, unknown> {\n  const result: Record<string, unknown> = {};\n  if (visiting.has(model.name)) return result; // Break recursion.\n  visiting.add(model.name);\n\n  for (const field of model.fields) {\n    if (!field.required) continue;\n    // Prefer the spec `example` value when it is shape-compatible with the\n    // declared type. Falls back to the placeholder generator when no example\n    // is provided or when the example would not deserialize cleanly.\n    const fromExample = exampleFromSpec(field.example, field.type, enumMap);\n    result[field.name] =\n      fromExample !== undefined ? fromExample : exampleFor(field.type, modelMap, enumMap, visiting, field.name);\n  }\n\n  if (model.discriminator) {\n    const [firstValue, variantName] = Object.entries(model.discriminator.mapping)[0];\n    result[model.discriminator.property] = firstValue;\n    const variantModel = modelMap.get(variantName);\n    if (variantModel) {\n      for (const field of variantModel.fields) {\n        if (!(field.name in result)) {\n          if (!field.required) continue;\n          const fromExample = exampleFromSpec(field.example, field.type, enumMap);\n          result[field.name] =\n            fromExample !== undefined ? fromExample : exampleFor(field.type, modelMap, enumMap, visiting, field.name);\n        }\n      }\n    }\n  }\n\n  visiting.delete(model.name);\n  return result;\n}\n\nexport function exampleFor(\n  type: TypeRef,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n  visiting: Set<string>,\n  fieldName: string,\n): unknown {\n  switch (type.kind) {\n    case 'primitive':\n      switch (type.type) {\n        case 'string':\n          if (type.format === 'date-time') return '2023-01-01T00:00:00.000Z';\n          if (type.format === 'date') return '2023-01-01';\n          if (type.format === 'uuid') return '00000000-0000-0000-0000-000000000000';\n          if (fieldName === 'id') return 'test_id';\n          if (fieldName === 'email') return 'test@example.com';\n          return `test_${fieldName}`;\n        case 'integer':\n          return 0;\n        case 'number':\n          return 0;\n        case 'boolean':\n          return false;\n        case 'unknown':\n          return {};\n      }\n      return null;\n    case 'array':\n      return [exampleFor(type.items, modelMap, enumMap, visiting, fieldName)];\n    case 'map':\n      return {};\n    case 'nullable':\n      return exampleFor(type.inner, modelMap, enumMap, visiting, fieldName);\n    case 'literal':\n      return type.value;\n    case 'enum': {\n      const e = enumMap.get(type.name);\n      const v = e?.values?.[0]?.value;\n      return v ?? '';\n    }\n    case 'model': {\n      const m = modelMap.get(type.name);\n      if (!m) return {};\n      return generateModelFixture(m, modelMap, enumMap, visiting);\n    }\n    case 'union': {\n      // Find first model variant; fall back to empty object.\n      let result: unknown = null;\n      walkTypeRef(type.variants[0]!, {\n        primitive: () => {\n          result = exampleFor(type.variants[0]!, modelMap, enumMap, visiting, fieldName);\n        },\n      });\n      if (result === null) {\n        result = exampleFor(type.variants[0]!, modelMap, enumMap, visiting, fieldName);\n      }\n      return result;\n    }\n  }\n}\n\n/**\n * Resolve a spec-provided `example` against a TypeRef and return the value to\n * embed in the fixture, or `undefined` when the example cannot be used safely.\n *\n * \"Safely\" means the value would round-trip through serde to the generated\n * Rust type. We deliberately only accept primitives, enum string/number\n * values, and homogenous arrays of those; nested object examples (which the\n * spec sometimes supplies as illustrative metadata blobs) are skipped because\n * they rarely match the strict struct shape Rust expects.\n */\nexport function exampleFromSpec(example: unknown, type: TypeRef, enumMap: Map<string, Enum>): unknown {\n  if (example === undefined) return undefined;\n  // Spec authors sometimes use `null` as a sentinel; let placeholder gen\n  // handle nullable types so we don't emit `null` for required fields.\n  if (example === null) return undefined;\n  return matchExampleToType(example, type, enumMap);\n}\n\nfunction matchExampleToType(value: unknown, type: TypeRef, enumMap: Map<string, Enum>): unknown {\n  switch (type.kind) {\n    case 'primitive':\n      return matchPrimitive(value, type.type);\n    case 'literal':\n      return value === type.value ? value : undefined;\n    case 'enum': {\n      const e = enumMap.get(type.name);\n      if (!e) return undefined;\n      const ok = e.values.some((v) => v.value === value);\n      return ok ? value : undefined;\n    }\n    case 'array': {\n      if (!Array.isArray(value)) return undefined;\n      const out: unknown[] = [];\n      for (const item of value) {\n        const matched = matchExampleToType(item, type.items, enumMap);\n        if (matched === undefined) return undefined;\n        out.push(matched);\n      }\n      // Empty arrays are valid but unhelpful in fixtures — fall back so the\n      // placeholder generator can produce a one-element example.\n      if (out.length === 0) return undefined;\n      return out;\n    }\n    case 'nullable':\n      return matchExampleToType(value, type.inner, enumMap);\n    case 'map':\n      // Map examples are usually free-form metadata blobs that match\n      // `HashMap<String, _>`; only accept plain objects with string-keyed values.\n      if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n      return value;\n    case 'union': {\n      for (const variant of type.variants) {\n        const matched = matchExampleToType(value, variant, enumMap);\n        if (matched !== undefined) return matched;\n      }\n      return undefined;\n    }\n    case 'model':\n      // Model-shaped examples are too risky to copy verbatim: they rarely\n      // supply every required field and may use wire names that don't align\n      // with the generated struct. Let the recursive generator handle them.\n      return undefined;\n  }\n}\n\nfunction matchPrimitive(value: unknown, primitive: 'string' | 'integer' | 'number' | 'boolean' | 'unknown'): unknown {\n  switch (primitive) {\n    case 'string':\n      return typeof value === 'string' ? value : undefined;\n    case 'integer':\n      return typeof value === 'number' && Number.isInteger(value) ? value : undefined;\n    case 'number':\n      return typeof value === 'number' ? value : undefined;\n    case 'boolean':\n      return typeof value === 'boolean' ? value : undefined;\n    case 'unknown':\n      // `unknown` deserialises to `serde_json::Value`, so any JSON value works.\n      return value;\n  }\n}\n","import type {\n  ApiSpec,\n  EmitterContext,\n  Enum,\n  GeneratedFile,\n  Model,\n  Operation,\n  Parameter,\n  ResolvedOperation,\n  ResolvedWrapper,\n  TypeRef,\n} from '@workos/oagen';\nimport { methodName, moduleName, typeName } from './naming.js';\nimport { scopedMountGroups } from '../shared/resolved-ops.js';\nimport { exampleFor, generateFixtures } from './fixtures.js';\nimport { resolveWrapperParams } from '../shared/wrapper-utils.js';\nimport { isInlineEnvelopeList } from './resources.js';\n\n/**\n * Generate integration tests under `tests/`. Each mount group gets one\n * `tests/{mount}_test.rs` file. Per operation the generator emits:\n *\n *   - `_round_trip`: happy-path 200 mock + call.\n *   - `_unauthorized`, `_not_found`, `_rate_limited`, `_server_error`: error\n *     paths for every HTTP-calling op.\n *   - `_bad_request`, `_unprocessable`: additional 4xx error paths for write\n *     ops (POST/PUT/PATCH/DELETE).\n *   - `_empty_page`: empty `data: []` response for paginated ops.\n *   - `_encodes_query_params`: outbound query-string assertion for ops with\n *     array query params (`explode: true` repeated keys, `explode: false`\n *     comma-joined).\n *\n * URL-builder ops (no HTTP call) only get the round-trip test.\n */\nexport function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n  const files: GeneratedFile[] = [];\n\n  files.push(...generateFixtures(spec, ctx));\n\n  files.push({\n    path: 'tests/common/mod.rs',\n    content: renderCommon(ctx),\n    overwriteExisting: true,\n  });\n\n  const groups = scopedMountGroups(ctx);\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n\n  for (const [mountName, group] of groups) {\n    if (group.operations.length === 0) continue;\n    files.push({\n      path: `tests/${moduleName(mountName)}_test.rs`,\n      content: renderMountTest(mountName, group.resolvedOps, ctx, modelMap, enumMap),\n      overwriteExisting: true,\n    });\n  }\n\n  return files;\n}\n\nfunction renderCommon(ctx: EmitterContext): string {\n  const crate = crateName(ctx);\n  const imports = [\n    { path: 'wiremock::MockServer', sort: 'wiremock::MockServer' },\n    { path: `${crate}::Client`, sort: `${crate}::Client` },\n  ].sort((a, b) => a.sort.localeCompare(b.sort));\n\n  const useLines = imports.map((i) => `use ${i.path};`).join('\\n');\n\n  return `#![allow(dead_code)]\n\n${useLines}\n\npub async fn test_client(server: &MockServer) -> Client {\n    Client::builder()\n        .api_key(\"test_api_key\")\n        .base_url(server.uri())\n        .max_retries(0)\n        .build()\n}\n`;\n}\n\nfunction renderMountTest(\n  mountName: string,\n  resolvedOps: ResolvedOperation[],\n  ctx: EmitterContext,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): string {\n  const accessor = moduleName(mountName);\n  const crate = crateName(ctx);\n  const lines: string[] = [];\n  lines.push('mod common;');\n  lines.push('');\n  lines.push('use wiremock::matchers::{method, path as path_matcher};');\n  lines.push('use wiremock::{Mock, MockServer, ResponseTemplate};');\n  lines.push(`use ${crate}::Error;`);\n  lines.push('');\n\n  const seen = new Set<string>();\n\n  for (const r of resolvedOps) {\n    const op = r.operation;\n    if ((r.wrappers?.length ?? 0) > 0) {\n      for (const w of r.wrappers!) {\n        const m = methodName(w.name);\n        if (seen.has(m)) continue;\n        seen.add(m);\n        lines.push(...renderWrapperTest(op, w, ctx, accessor, crate, modelMap, enumMap));\n        lines.push('');\n      }\n      continue;\n    }\n    const m = methodName(r.methodName);\n    if (seen.has(m)) continue;\n    seen.add(m);\n    lines.push(...renderRegularTest(op, r, accessor, crate, modelMap, enumMap));\n    lines.push('');\n  }\n\n  // Trim a trailing blank line.\n  while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();\n\n  return lines.join('\\n') + '\\n';\n}\n\n/**\n * Bundle of inputs computed once per operation and reused across the various\n * test categories (round-trip, error tests, encoding tests). All test\n * categories share the same params construction, path, method, and accessor\n * call shape — the only thing that varies is the response template and the\n * assertion.\n */\ninterface CallShape {\n  /** Operation method name, e.g. `list_events`. */\n  methodIdent: string;\n  /** Literal path with `{id}` placeholders substituted to `test_id`. */\n  literalPath: string;\n  /** Upper-case HTTP verb, e.g. `GET`. */\n  httpMethod: string;\n  /** The args passed to the SDK method call, joined with `, `. */\n  callArgs: string;\n  /** True when the op is a URL-builder (no HTTP call). */\n  isUrlBuilder: boolean;\n  /** True for HTTP methods that mutate state. */\n  isWrite: boolean;\n  /** True when the op declares cursor pagination. */\n  isPaginated: boolean;\n  /** When non-null, the op has a synthetic body group enum. */\n  hasBodyGroup: boolean;\n}\n\n/** Test for a non-wrapper operation. */\nfunction renderRegularTest(\n  op: Operation,\n  resolved: ResolvedOperation,\n  accessor: string,\n  crate: string,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): string[] {\n  const m = methodName(resolved.methodName);\n  const literalPath = op.path.replace(/\\{[^}]+\\}/g, 'test_id');\n  const httpMethod = op.httpMethod.toUpperCase();\n  // Inline-envelope lists decode via crate::pagination::Page<T>, so the mock\n  // must serve the envelope even though the IR types the response as an array.\n  const responseExpr = isInlineEnvelopeList(op)\n    ? JSON.stringify('{\"object\":\"list\",\"data\":[],\"list_metadata\":{\"before\":null,\"after\":null}}')\n    : responseBodyExpr(op.response, modelMap, enumMap);\n  const isUrlBuilder = resolved.urlBuilder === true;\n\n  const callArgs = buildCallArgs(op, resolved, crate, accessor, modelMap, enumMap).join(', ');\n  const shape: CallShape = {\n    methodIdent: m,\n    literalPath,\n    httpMethod,\n    callArgs,\n    isUrlBuilder,\n    isWrite: isWriteMethod(op.httpMethod),\n    isPaginated: !!op.pagination,\n    hasBodyGroup: !!op.requestBody && hasBodyParameterGroup(op),\n  };\n\n  const lines: string[] = [];\n\n  // Round-trip (happy path).\n  lines.push('#[tokio::test]');\n  lines.push(`async fn ${accessor}_${m}_round_trip() {`);\n  if (isUrlBuilder) {\n    // URL-builder ops don't issue HTTP requests; there's nothing to mock.\n    lines.push('    let server = MockServer::start().await;');\n    lines.push('    let client = common::test_client(&server).await;');\n    lines.push(`    let _ = client.${accessor}().${m}(${callArgs});`);\n  } else {\n    lines.push('    let server = MockServer::start().await;');\n    lines.push(`    Mock::given(method(${JSON.stringify(httpMethod)}))`);\n    lines.push(`        .and(path_matcher(${JSON.stringify(literalPath)}))`);\n    lines.push(`        .respond_with(ResponseTemplate::new(200).set_body_string(${responseExpr}))`);\n    lines.push('        .expect(1)');\n    lines.push('        .mount(&server)');\n    lines.push('        .await;');\n    lines.push('    let client = common::test_client(&server).await;');\n    lines.push(`    let _ = client.${accessor}().${m}(${callArgs}).await;`);\n  }\n  // wiremock asserts on drop that the `.expect(1)` mock was matched once;\n  // mismatched method/path produces a panic at end-of-test. We deliberately\n  // ignore the deserialised response: stub fixtures cover the common path\n  // (typed model deserialisation), but discriminated-union responses can't\n  // always be reproduced from a generated fixture without bespoke schema\n  // awareness, so a strict `is_ok()` would over-trigger.\n  lines.push('}');\n\n  if (isUrlBuilder) {\n    // No HTTP call to mock — the round-trip is all we can sensibly emit.\n    return lines;\n  }\n\n  // Error-path tests — same path/method, different response status.\n  for (const errTest of standardErrorTests(shape, accessor)) {\n    lines.push('');\n    lines.push(...errTest);\n  }\n\n  if (shape.isWrite) {\n    for (const errTest of writeErrorTests(shape, accessor)) {\n      lines.push('');\n      lines.push(...errTest);\n    }\n  }\n\n  // Empty-page test for paginated list ops.\n  if (shape.isPaginated) {\n    const emptyTest = emptyPageTest(op, shape, accessor);\n    if (emptyTest) {\n      lines.push('');\n      lines.push(...emptyTest);\n    }\n  }\n\n  // Query-string encoding assertion when an array query param is present.\n  const encodingTest = encodesQueryParamsTest(op, resolved, accessor, crate, modelMap, enumMap);\n  if (encodingTest) {\n    lines.push('');\n    lines.push(...encodingTest);\n  }\n\n  return lines;\n}\n\n/**\n * Build the positional args for the resource method call: path-param literals,\n * then a single params struct (when the op has any), then a token-string for\n * non-bearer security overrides. This factors the constructor logic out of\n * the round-trip renderer so the error/encoding tests can reuse it verbatim\n * — every test category sends the same request, only the mocked response and\n * assertion differ.\n */\nfunction buildCallArgs(\n  op: Operation,\n  resolved: ResolvedOperation,\n  crate: string,\n  accessor: string,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): string[] {\n  const hidden = new Set<string>([...Object.keys(resolved.defaults ?? {}), ...(resolved.inferFromClient ?? [])]);\n  // Names of query/header params that fold into a parameter-group enum and\n  // therefore must not be passed individually to the params constructor.\n  const groupedNames = new Set<string>();\n  for (const g of op.parameterGroups ?? []) {\n    for (const v of g.variants) for (const p of v.parameters) groupedNames.add(p.name);\n  }\n  const visibleQuery = op.queryParams.filter((p) => !hidden.has(p.name) && !groupedNames.has(p.name));\n  const visibleHeader = op.headerParams.filter((p) => !hidden.has(p.name));\n  const visibleParams = [...visibleQuery, ...visibleHeader];\n  const requiredParams = visibleParams.filter((p) => p.required);\n  const hasBody = op.requestBody !== undefined;\n  const bodyRequired = hasBody && op.requestBody!.kind !== 'nullable';\n  const queryNames = new Set(op.queryParams.map((p) => p.name));\n  const requiredGroups = (op.parameterGroups ?? []).filter((g) => !g.optional);\n  const requiredQueryGroups = requiredGroups.filter((g) =>\n    g.variants.every((v) => v.parameters.every((p) => queryNames.has(p.name))),\n  );\n  const emptyParams = !hasBody && visibleParams.length === 0 && (op.parameterGroups?.length ?? 0) === 0;\n\n  const callArgs: string[] = [];\n  for (const _ of op.pathParams) callArgs.push('\"test_id\"');\n\n  if (!emptyParams) {\n    const paramsType = `${crate}::${accessor}::${typeName(resolved.methodName)}Params`;\n    const noCtorRequired = requiredParams.length === 0 && !bodyRequired && requiredQueryGroups.length === 0;\n    if (noCtorRequired) {\n      callArgs.push(`${paramsType}::default()`);\n    } else {\n      const ctorArgs: string[] = [];\n      for (const p of requiredParams) {\n        ctorArgs.push(stubExpr(p.type, p.name, modelMap, enumMap));\n      }\n      for (const g of requiredQueryGroups) {\n        ctorArgs.push(parameterGroupStubExpr(g, crate, accessor));\n      }\n      if (hasBody && bodyRequired) {\n        const hasBodyGroup = hasBodyParameterGroup(op);\n        if (hasBodyGroup) {\n          ctorArgs.push(syntheticBodyStubExpr(op, resolved, crate, accessor, modelMap));\n        } else {\n          ctorArgs.push(stubExpr(op.requestBody!, 'body', modelMap, enumMap));\n        }\n      }\n      callArgs.push(`${paramsType}::new(${ctorArgs.join(', ')})`);\n    }\n  }\n\n  // Per-operation bearer override (e.g. `GET /sso/profile`) — append the\n  // access-token positional arg before the awaiter.\n  const tokenName = bearerOverrideTokenName(op);\n  if (tokenName) {\n    callArgs.push(`\"stub_${tokenName}\".to_string()`);\n  }\n\n  return callArgs;\n}\n\n/**\n * Build the four common-error test bodies (401/404/429/500). Each one mocks a\n * single response with the given status, calls the SDK method (which should\n * fail), and asserts on the unwrapped `Error::Api` payload.\n */\nfunction standardErrorTests(shape: CallShape, accessor: string): string[][] {\n  const tests: string[][] = [];\n  tests.push(errorTestBody(shape, accessor, 'unauthorized', 401, '{\"message\":\"Unauthorized\"}', undefined));\n  tests.push(errorTestBody(shape, accessor, 'not_found', 404, '{\"message\":\"Not found\"}', undefined));\n  tests.push(\n    errorTestBody(shape, accessor, 'rate_limited', 429, '{\"message\":\"Slow down\"}', {\n      retryAfterSeconds: 1,\n      assertRetryAfter: true,\n    }),\n  );\n  tests.push(errorTestBody(shape, accessor, 'server_error', 500, '{\"message\":\"Internal error\"}', undefined));\n  return tests;\n}\n\n/** Build the two write-op-only error tests (400/422). */\nfunction writeErrorTests(shape: CallShape, accessor: string): string[][] {\n  return [\n    errorTestBody(shape, accessor, 'bad_request', 400, '{\"code\":\"validation_error\",\"message\":\"Bad request\"}', {\n      assertCode: 'validation_error',\n    }),\n    errorTestBody(shape, accessor, 'unprocessable', 422, '{\"message\":\"Unprocessable\"}', undefined),\n  ];\n}\n\ninterface ErrorOptions {\n  retryAfterSeconds?: number;\n  assertRetryAfter?: boolean;\n  assertCode?: string;\n}\n\nfunction errorTestBody(\n  shape: CallShape,\n  accessor: string,\n  category: string,\n  status: number,\n  body: string,\n  opts: ErrorOptions | undefined,\n): string[] {\n  const lines: string[] = [];\n  lines.push('#[tokio::test]');\n  lines.push(`async fn ${accessor}_${shape.methodIdent}_${category}() {`);\n  lines.push('    let server = MockServer::start().await;');\n  lines.push(`    let template = ResponseTemplate::new(${status})`);\n  if (opts?.retryAfterSeconds !== undefined) {\n    lines.push(`        .insert_header(\"retry-after\", ${JSON.stringify(String(opts.retryAfterSeconds))})`);\n  }\n  lines.push(`        .set_body_string(${JSON.stringify(body)});`);\n  lines.push(`    Mock::given(method(${JSON.stringify(shape.httpMethod)}))`);\n  lines.push(`        .and(path_matcher(${JSON.stringify(shape.literalPath)}))`);\n  lines.push('        .respond_with(template)');\n  lines.push('        .expect(1)');\n  lines.push('        .mount(&server)');\n  lines.push('        .await;');\n  lines.push('    let client = common::test_client(&server).await;');\n  lines.push(\n    `    let err = client.${accessor}().${shape.methodIdent}(${shape.callArgs}).await.expect_err(\"expected error\");`,\n  );\n  lines.push('    let api = match &err {');\n  lines.push('        Error::Api(api) => api.as_ref(),');\n  lines.push('        other => panic!(\"expected Error::Api, got {other:?}\"),');\n  lines.push('    };');\n  lines.push(`    assert_eq!(api.status, ${status});`);\n  if (opts?.assertRetryAfter) {\n    lines.push(\n      `    assert_eq!(api.retry_after, Some(std::time::Duration::from_secs(${opts.retryAfterSeconds ?? 0})));`,\n    );\n  }\n  if (opts?.assertCode) {\n    lines.push(`    assert_eq!(api.code.as_deref(), Some(${JSON.stringify(opts.assertCode)}));`);\n  }\n  lines.push('}');\n  return lines;\n}\n\n/**\n * Return an `_empty_page` test for a paginated list op. Two shapes are\n * supported:\n *\n *  - Wrapper model: `{\"data\": [], \"list_metadata\": {...}}`, accessed via\n *    `resp.data` on the returned struct.\n *  - Bare array: `[]`, accessed via `resp.is_empty()` directly (the SDK\n *    returns `Vec<T>` for paginated ops without a wrapper model).\n *\n * Returns null when the response shape isn't recognised (e.g. a primitive\n * or unknown shape we can't safely assert against).\n */\nfunction emptyPageTest(op: Operation, shape: CallShape, accessor: string): string[] | null {\n  const responseKind = op.response.kind;\n  let body: string;\n  let dataAccessor: string;\n  if (isInlineEnvelopeList(op)) {\n    // Inline-envelope paginated response: SDK returns crate::pagination::Page<T>,\n    // so the mock must serve the envelope and assertions go through `.data`.\n    body = '{\"object\":\"list\",\"data\":[],\"list_metadata\":{\"before\":null,\"after\":null}}';\n    dataAccessor = 'resp.data';\n  } else if (responseKind === 'array') {\n    // Bare-array paginated response: SDK returns Vec<T>.\n    body = '[]';\n    dataAccessor = 'resp';\n  } else if (responseKind === 'model') {\n    // Wrapper-model paginated response: SDK returns the wrapper struct.\n    // `list_metadata` is always an object — its required field set depends\n    // on the response model, but for the empty case both `before` and `after`\n    // are either present-as-null or absent. We emit both keys as null to\n    // satisfy any shape with optional cursor fields without hard-coding\n    // per-op knowledge.\n    // The wrapper model has a required `object` discriminator field, e.g.\n    // `\"list\"`. Include it so the response deserialises against any\n    // generated wrapper struct.\n    body = '{\"object\":\"list\",\"data\":[],\"list_metadata\":{\"before\":null,\"after\":null}}';\n    dataAccessor = 'resp.data';\n  } else {\n    return null;\n  }\n  const lines: string[] = [];\n  lines.push('#[tokio::test]');\n  lines.push(`async fn ${accessor}_${shape.methodIdent}_empty_page() {`);\n  lines.push('    let server = MockServer::start().await;');\n  lines.push(`    Mock::given(method(${JSON.stringify(shape.httpMethod)}))`);\n  lines.push(`        .and(path_matcher(${JSON.stringify(shape.literalPath)}))`);\n  lines.push(`        .respond_with(ResponseTemplate::new(200).set_body_string(${JSON.stringify(body)}))`);\n  lines.push('        .expect(1)');\n  lines.push('        .mount(&server)');\n  lines.push('        .await;');\n  lines.push('    let client = common::test_client(&server).await;');\n  lines.push(\n    `    let resp = client.${accessor}().${shape.methodIdent}(${shape.callArgs}).await.expect(\"expected success\");`,\n  );\n  lines.push(`    assert!(${dataAccessor}.is_empty(), \"expected empty data array\");`);\n  lines.push('}');\n  return lines;\n}\n\n/**\n * Build an `_encodes_query_params` test when the op declares at least one\n * array query param. Constructs a params struct with a known Vec value on\n * each array field and asserts the actual outbound query string contains\n * either repeated keys (`events=foo&events=bar`, default for `explode: true`)\n * or a comma-joined value (`events=foo%2Cbar`, when `explode: false`).\n *\n * Returns null when no array query params apply — those ops have nothing\n * interesting to encode.\n */\nfunction encodesQueryParamsTest(\n  op: Operation,\n  resolved: ResolvedOperation,\n  accessor: string,\n  crate: string,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): string[] | null {\n  const hidden = new Set<string>([...Object.keys(resolved.defaults ?? {}), ...(resolved.inferFromClient ?? [])]);\n  const groupedNames = new Set<string>();\n  for (const g of op.parameterGroups ?? []) {\n    for (const v of g.variants) for (const p of v.parameters) groupedNames.add(p.name);\n  }\n  // Find at most one Vec<String> query param to drive the assertion. The\n  // order is stable (it follows `op.queryParams`), and one is enough — the\n  // encoder applies the same rule to every array field. We restrict the\n  // assertion to string-element arrays because non-string arrays (e.g.\n  // enums) require per-type constructors we can't reliably synthesise from\n  // the IR alone, and serializing a Vec<EnumX> via vec![\"foo\".into(), ..]\n  // wouldn't type-check.\n  const arrayParams = op.queryParams.filter(\n    (p) => !hidden.has(p.name) && !groupedNames.has(p.name) && isStringArrayParam(p),\n  );\n  if (arrayParams.length === 0) return null;\n  const target = arrayParams[0];\n\n  // The encoded form for both variants. The test inspects the literal query\n  // string returned by wiremock; `assert!(query.contains(...))` matches the\n  // serialized output regardless of where in the string the param sits, so\n  // we don't need to predict the rest of the params' order.\n  const exploded = (target as { explode?: boolean }).explode !== false;\n  const expectedFragment = exploded ? `${target.name}=foo&${target.name}=bar` : `${target.name}=foo%2Cbar`;\n\n  // For the call, we want to set `target` to [\"foo\", \"bar\"] on the params\n  // struct. Build the standard call args, then mutate the params struct to\n  // override the field.\n  const callArgs = buildCallArgs(op, resolved, crate, accessor, modelMap, enumMap);\n  // Locate which entry in callArgs is the params struct so we can mutate it\n  // post-construction. The buildCallArgs result is:\n  //   path_arg_1, path_arg_2, ..., paramsExpr, [token]\n  // Path args are always `\"test_id\"` literals; the params expr is the first\n  // entry past the path arg count.\n  const pathArgCount = op.pathParams.length;\n  const tokenName = bearerOverrideTokenName(op);\n  const expectsParams = callArgs.length > pathArgCount && (tokenName ? callArgs.length > pathArgCount + 1 : true);\n  if (!expectsParams) return null;\n\n  // Build the test body. We materialise the params as a mutable local so we\n  // can set the target array field, then pass it (by value) to the SDK call.\n  const tokenArg = tokenName ? callArgs[callArgs.length - 1] : null;\n  const paramsExpr = callArgs[pathArgCount];\n\n  const lines: string[] = [];\n  const respExpr = encodingResponseExpr(op, modelMap, enumMap);\n  lines.push('#[tokio::test]');\n  lines.push(`async fn ${accessor}_${methodName(resolved.methodName)}_encodes_query_params() {`);\n  lines.push('    let server = MockServer::start().await;');\n  lines.push(`    Mock::given(method(${JSON.stringify('GET'.replace('GET', op.httpMethod.toUpperCase()))}))`);\n  lines.push(`        .and(path_matcher(${JSON.stringify(op.path.replace(/\\{[^}]+\\}/g, 'test_id'))}))`);\n  lines.push(`        .respond_with(ResponseTemplate::new(200).set_body_string(${respExpr}))`);\n  lines.push('        .mount(&server)');\n  lines.push('        .await;');\n  lines.push('    let client = common::test_client(&server).await;');\n  // Clippy's `field_reassign_with_default` fires when fields are mutated on a\n  // value created via `T::default()`. Use struct-update syntax in that case;\n  // otherwise (`Type::new(...)` etc.), fall back to the mutable-binding form\n  // since the lint doesn't apply.\n  if (paramsExpr.endsWith('::default()')) {\n    const ty = paramsExpr.slice(0, -'::default()'.length);\n    lines.push(`    let params = ${ty} {`);\n    lines.push(`        ${fieldIdent(target.name)}: Some(vec![\"foo\".to_string(), \"bar\".to_string()]),`);\n    lines.push('        ..Default::default()');\n    lines.push('    };');\n  } else {\n    lines.push(`    let mut params = ${paramsExpr};`);\n    lines.push(`    params.${fieldIdent(target.name)} = Some(vec![\"foo\".to_string(), \"bar\".to_string()]);`);\n  }\n  // Drop the array param onto the params; ignore any required-cursor fields\n  // — they're already populated by buildCallArgs.\n  const passArgs: string[] = [];\n  for (let i = 0; i < pathArgCount; i++) passArgs.push(callArgs[i]);\n  passArgs.push('params');\n  if (tokenArg) passArgs.push(tokenArg);\n  lines.push(`    let _ = client.${accessor}().${methodName(resolved.methodName)}(${passArgs.join(', ')}).await;`);\n  lines.push('    let received = server.received_requests().await.expect(\"recorded requests\");');\n  lines.push('    let request = received.first().expect(\"at least one request\");');\n  lines.push('    let query = request.url.query().unwrap_or(\"\");');\n  lines.push(\n    `    assert!(query.contains(${JSON.stringify(expectedFragment)}), \"expected query to contain {:?}, got {:?}\", ${JSON.stringify(expectedFragment)}, query);`,\n  );\n  lines.push('}');\n  return lines;\n}\n\n/** Body expression for the encoding-test response (success, ignored). */\nfunction encodingResponseExpr(op: Operation, modelMap: Map<string, Model>, enumMap: Map<string, Enum>): string {\n  // For paginated ops we serve an empty page so the call succeeds. Use the\n  // bare-array shape for `Vec<T>` responses, the wrapper shape for named\n  // wrapper models and inline envelopes (decoded via Page<T>).\n  if (op.pagination) {\n    if (op.response.kind === 'array' && !isInlineEnvelopeList(op)) return JSON.stringify('[]');\n    return JSON.stringify('{\"object\":\"list\",\"data\":[],\"list_metadata\":{\"before\":null,\"after\":null}}');\n  }\n  return responseBodyExpr(op.response, modelMap, enumMap);\n}\n\n/**\n * True if `param.type` is `Vec<String>` (or `Option<Vec<String>>`). Restricts\n * the encoding test to string arrays because non-string arrays would need\n * per-type constructors we can't synthesise reliably.\n */\nfunction isStringArrayParam(p: Parameter): boolean {\n  let t: TypeRef = p.type;\n  while (t.kind === 'nullable') t = t.inner;\n  if (t.kind !== 'array') return false;\n  let inner: TypeRef = t.items;\n  while (inner.kind === 'nullable') inner = inner.inner;\n  return inner.kind === 'primitive' && inner.type === 'string';\n}\n\n/** Snake-case field accessor matching the resources emitter's naming. */\nfunction fieldIdent(name: string): string {\n  // The Rust emitter snake-cases field names via `methodName`. Reuse it so\n  // the generated field name matches the params struct.\n  return methodName(name);\n}\n\n/** True for HTTP methods that mutate state and should retry-defensively. */\nfunction isWriteMethod(method: string): boolean {\n  return method !== 'get' && method !== 'head';\n}\n\n/** True when the op has at least one body-side parameter group. */\nfunction hasBodyParameterGroup(op: Operation): boolean {\n  const queryNames = new Set(op.queryParams.map((p) => p.name));\n  return (op.parameterGroups ?? []).some((g) =>\n    g.variants.every((v) => v.parameters.every((p) => !queryNames.has(p.name))),\n  );\n}\n\n/** Pick the snake_case token-arg name for an op with a non-bearer security override. */\nfunction bearerOverrideTokenName(op: Operation): string | null {\n  const override = op.security?.find((s) => s.schemeName !== 'bearerAuth');\n  if (!override) return null;\n  return override.schemeName.replace(/[A-Z]/g, (m) => `_${m.toLowerCase()}`).replace(/^_/, '');\n}\n\n/**\n * Construct a synthetic body type via its `new(...)` constructor. The\n * resources emitter passes required flat fields and required flatten enums\n * positionally; mirror that ordering here so the stub compiles against the\n * generated `impl <Type> { fn new(...) }`.\n */\nfunction syntheticBodyStubExpr(\n  op: Operation,\n  resolved: ResolvedOperation,\n  crate: string,\n  accessor: string,\n  modelMap: Map<string, Model>,\n): string {\n  const bodyRef = op.requestBody!;\n  const bodyName = `${typeName(resolved.methodName)}ParamsBody`;\n  const fqn = `${crate}::${accessor}::${bodyName}`;\n  const model = bodyRef.kind === 'model' ? (modelMap.get(bodyRef.name) ?? null) : null;\n  const queryNames = new Set(op.queryParams.map((p) => p.name));\n  const bodyGroupNames = new Set<string>();\n  for (const g of op.parameterGroups ?? []) {\n    if (g.variants.every((v) => v.parameters.every((p) => !queryNames.has(p.name)))) {\n      for (const v of g.variants) for (const p of v.parameters) bodyGroupNames.add(p.name);\n    }\n  }\n  // Iteration order must match resources.ts: required flat model fields, then\n  // each parameter-group field (in the order returned by `op.parameterGroups`).\n  const args: string[] = [];\n  if (model) {\n    for (const f of model.fields) {\n      if (bodyGroupNames.has(f.name)) continue;\n      const isRequired = !!f.required && f.type.kind !== 'nullable';\n      if (!isRequired) continue;\n      args.push(`${JSON.stringify(`stub_${f.name}`)}.to_string()`);\n    }\n  }\n  for (const g of op.parameterGroups ?? []) {\n    const isBodyGroup = g.variants.every((v) => v.parameters.every((p) => !queryNames.has(p.name)));\n    if (!isBodyGroup) continue;\n    if (g.optional) continue;\n    args.push(parameterGroupStubExpr(g, crate, accessor));\n  }\n  return `${fqn}::new(${args.join(', ')})`;\n}\n\n/** First-variant stub for a parameter-group enum, fully crate-qualified. */\nfunction parameterGroupStubExpr(\n  group: import('@workos/oagen').ParameterGroup,\n  crate: string,\n  accessor: string,\n): string {\n  const enumName = group.name\n    .split('_')\n    .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n    .join('');\n  const firstVariant = group.variants[0];\n  const variantName = firstVariant.name\n    .split('_')\n    .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n    .join('');\n  const fqn = `${crate}::${accessor}::${enumName}`;\n  if (firstVariant.parameters.length === 0) return `${fqn}::${variantName}`;\n  const fields = firstVariant.parameters\n    .map((p) => `${p.name}: ${JSON.stringify(`stub_${p.name}`)}.to_string()`)\n    .join(', ');\n  return `${fqn}::${variantName} { ${fields} }`;\n}\n\n/** Test for a wrapper-method operation. */\nfunction renderWrapperTest(\n  op: Operation,\n  wrapper: ResolvedWrapper,\n  ctx: EmitterContext,\n  accessor: string,\n  crate: string,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n): string[] {\n  const m = methodName(wrapper.name);\n  const literalPath = op.path.replace(/\\{[^}]+\\}/g, 'test_id');\n  const httpMethod = op.httpMethod.toUpperCase();\n  // Wrapper response is the wrapper's responseModelName (or the operation's\n  // declared response when none is overridden).\n  const responseExpr = wrapper.responseModelName\n    ? responseBodyExpr({ kind: 'model', name: wrapper.responseModelName }, modelMap, enumMap)\n    : responseBodyExpr(op.response, modelMap, enumMap);\n\n  const params = resolveWrapperParams(wrapper, ctx);\n  const callArgs: string[] = [];\n  for (const _ of op.pathParams) callArgs.push('\"test_id\"');\n\n  const paramsType = `${crate}::${accessor}::${typeName(wrapper.name)}Params`;\n  const requiredParams = params.filter((rp) => !rp.isOptional);\n\n  if (requiredParams.length === 0) {\n    callArgs.push(`${paramsType}::default()`);\n  } else {\n    const ctorArgs = requiredParams.map((rp) => {\n      if (!rp.field) return `\"stub_${rp.paramName}\".to_string()`;\n      return stubExpr(rp.field.type, rp.paramName, modelMap, enumMap);\n    });\n    callArgs.push(`${paramsType}::new(${ctorArgs.join(', ')})`);\n  }\n\n  const callArgsStr = callArgs.join(', ');\n\n  const lines: string[] = [];\n  lines.push('#[tokio::test]');\n  lines.push(`async fn ${accessor}_${m}_round_trip() {`);\n  lines.push('    let server = MockServer::start().await;');\n  lines.push(`    Mock::given(method(${JSON.stringify(httpMethod)}))`);\n  lines.push(`        .and(path_matcher(${JSON.stringify(literalPath)}))`);\n  lines.push(`        .respond_with(ResponseTemplate::new(200).set_body_string(${responseExpr}))`);\n  lines.push('        .expect(1)');\n  lines.push('        .mount(&server)');\n  lines.push('        .await;');\n  lines.push('    let client = common::test_client(&server).await;');\n  lines.push(`    let _ = client.${accessor}().${m}(${callArgsStr}).await;`);\n  // Drop assertion on `Mock::expect(1)` validates path/method.\n  lines.push('}');\n\n  // Error tests for wrapper variants — same path/method, different response.\n  const shape: CallShape = {\n    methodIdent: m,\n    literalPath,\n    httpMethod,\n    callArgs: callArgsStr,\n    isUrlBuilder: false,\n    isWrite: isWriteMethod(op.httpMethod),\n    isPaginated: !!op.pagination,\n    hasBodyGroup: false,\n  };\n  for (const errTest of standardErrorTests(shape, accessor)) {\n    lines.push('');\n    lines.push(...errTest);\n  }\n  if (shape.isWrite) {\n    for (const errTest of writeErrorTests(shape, accessor)) {\n      lines.push('');\n      lines.push(...errTest);\n    }\n  }\n\n  return lines;\n}\n\n/** Rust string-expression for the mock response body. */\nfunction responseBodyExpr(ref: TypeRef | undefined, modelMap: Map<string, Model>, enumMap: Map<string, Enum>): string {\n  if (!ref) return JSON.stringify('{}');\n  if (ref.kind === 'primitive' && ref.type === 'unknown') return JSON.stringify('{}');\n  if (ref.kind === 'model') {\n    const m = modelMap.get(ref.name);\n    if (!m || m.fields.length === 0 || m.fields.every((f) => !f.required)) {\n      return JSON.stringify('{}');\n    }\n    return modelFixtureExpr(ref.name);\n  }\n  if (ref.kind === 'nullable') return responseBodyExpr(ref.inner, modelMap, enumMap);\n  // For arrays/primitives/maps/enums/literals/unions, synthesise inline JSON.\n  const example = exampleFor(ref, modelMap, enumMap, new Set(), 'value');\n  return JSON.stringify(JSON.stringify(example));\n}\n\n/** `include_str!(\"fixtures/<snake>.json\")` for a model name. */\nfunction modelFixtureExpr(name: string): string {\n  return `include_str!(${JSON.stringify(`fixtures/${moduleName(name)}.json`)})`;\n}\n\n/**\n * Rust expression for an instance of `type` that satisfies its declared shape.\n * Used to construct required constructor arguments at test-build time.\n *\n * For models we deserialize a JSON fixture; for everything else we synthesise\n * a small example with `serde_json::from_str`. `String` is the one exception:\n * the generator's `new(...)` constructor takes `impl Into<String>`, so we\n * pass a string literal directly to keep type inference happy.\n */\nfunction stubExpr(ref: TypeRef, hint: string, modelMap: Map<string, Model>, enumMap: Map<string, Enum>): string {\n  // Strings: emit `\"stub_x\".to_string()`. Works in struct-literal contexts\n  // (which need `String`) as well as `new(...)` constructors that take\n  // `impl Into<String>`. Avoiding `from_str` keeps type inference simple.\n  if (ref.kind === 'primitive' && ref.type === 'string') {\n    return `${JSON.stringify(`stub_${hint}`)}.to_string()`;\n  }\n  if (ref.kind === 'nullable') return stubExpr(ref.inner, hint, modelMap, enumMap);\n  if (ref.kind === 'model') {\n    // Fixture generator skips models with no required fields; fall back to\n    // an inline `{}` so the test still compiles.\n    const m = modelMap.get(ref.name);\n    if (!m || m.fields.length === 0 || m.fields.every((f) => !f.required)) {\n      return `serde_json::from_str(\"{}\").expect(\"parse stub for ${ref.name}\")`;\n    }\n    return `serde_json::from_str(${modelFixtureExpr(ref.name)}).expect(\"parse fixture for ${ref.name}\")`;\n  }\n  // For other shapes, JSON-serialise an example value and deserialise at\n  // runtime. The generator's constructors fully specify each parameter type,\n  // so type inference flows from the constructor signature back into\n  // `serde_json::from_str`.\n  const example = exampleFor(ref, modelMap, enumMap, new Set(), hint);\n  const json = JSON.stringify(example);\n  return `serde_json::from_str(${JSON.stringify(json)}).expect(\"parse stub\")`;\n}\n\nfunction crateName(ctx: EmitterContext): string {\n  // Cargo crate names are conventionally lowercase with no separators (e.g.\n  // `workos`). The IR's snake-cased namespace (\"work_os\") inserts an\n  // underscore around the \"os\" acronym, so derive from `namespacePascal` —\n  // the verbatim user-supplied namespace — and lowercase it.\n  return ctx.namespacePascal.toLowerCase().replace(/[^a-z0-9]/g, '');\n}\n","import type { ApiSpec, EmitterContext, OperationsMap } from '@workos/oagen';\nimport { methodName, moduleName } from './naming.js';\nimport { groupByMount } from '../shared/resolved-ops.js';\n\n/**\n * Build the operation→SDK-method map written into `.oagen-manifest.json`,\n * which the smoke runner consults to dispatch HTTP operations to SDK calls.\n *\n * Keys are `METHOD /path`; values point at the mount-target accessor on\n * `Client` and the resolved snake_case method name. Split operations register\n * one entry per wrapper (the wrapper name takes precedence over the raw op\n * name since the raw method does not exist in the generated SDK).\n */\nexport function buildOperationsMap(_spec: ApiSpec, ctx: EmitterContext): OperationsMap {\n  const map: OperationsMap = {};\n\n  for (const [mountName, group] of groupByMount(ctx)) {\n    const accessor = moduleName(mountName);\n    for (const r of group.resolvedOps) {\n      const httpKey = `${r.operation.httpMethod.toUpperCase()} ${r.operation.path}`;\n      if ((r.wrappers?.length ?? 0) > 0) {\n        const first = r.wrappers![0]!;\n        map[httpKey] = { sdkMethod: methodName(first.name), service: accessor };\n      } else {\n        map[httpKey] = { sdkMethod: methodName(r.methodName), service: accessor };\n      }\n    }\n  }\n\n  return map;\n}\n","import type {\n  Emitter,\n  EmitterContext,\n  FormatCommand,\n  GeneratedFile,\n  ApiSpec,\n  Model,\n  Enum,\n  Service,\n} from '@workos/oagen';\n\nimport { generateModels } from './models.js';\nimport { generateEnums } from './enums.js';\nimport { generateResources } from './resources.js';\nimport { generateClient } from './client.js';\nimport { generateTests } from './tests.js';\nimport { buildOperationsMap } from './manifest.js';\nimport { UnionRegistry } from './type-map.js';\nimport { enrichModelsFromSpec, getSyntheticEnums } from '../shared/model-utils.js';\nimport { AUTOGEN_NOTICE } from '../shared/file-header.js';\n\n/**\n * Shared per-emit registry that collects synthesised oneOf-style unions\n * encountered in *any* call (model fields, request bodies, etc.). Rendered\n * once into `src/models/_unions.rs` during the final structural pass so\n * downstream files can reference the synthesised type names uniformly.\n */\nconst unionRegistry = new UnionRegistry();\n\nfunction ensureTrailingNewlines(files: GeneratedFile[]): GeneratedFile[] {\n  for (const f of files) {\n    if (f.content && !f.content.endsWith('\\n')) {\n      f.content += '\\n';\n    }\n  }\n  return files;\n}\n\n/**\n * Flatten oneOf / allOf+oneOf variant fields onto each base model and pull\n * in synthetic models / enums for inline variant shapes. Rust emits flat\n * structs (a synthesised enum-union from `UnionRegistry` exists, but the\n * field-on-base pattern is what matches `ConnectApplication` today). A\n * discriminated base whose IR fields the parser stripped gets its original\n * fields restored to avoid losing variant data.\n */\nfunction enrichModelsForRust(models: Model[]): Model[] {\n  const enriched = enrichModelsFromSpec(models);\n  const originalByName = new Map(models.map((m) => [m.name, m]));\n  return enriched.map((m) => {\n    if ((m as { discriminator?: unknown }).discriminator && m.fields.length === 0) {\n      const original = originalByName.get(m.name);\n      if (original && original.fields.length > 0) {\n        return { ...m, fields: original.fields };\n      }\n    }\n    return m;\n  });\n}\n\nexport const rustEmitter: Emitter = {\n  language: 'rust',\n\n  generateModels(models: Model[], ctx: EmitterContext): GeneratedFile[] {\n    unionRegistry.reset();\n    return ensureTrailingNewlines(generateModels(enrichModelsForRust(models), ctx, unionRegistry));\n  },\n\n  generateEnums(enums: Enum[], ctx: EmitterContext): GeneratedFile[] {\n    const syntheticEnums = getSyntheticEnums();\n    return ensureTrailingNewlines(generateEnums([...enums, ...syntheticEnums], ctx));\n  },\n\n  generateResources(services: Service[], ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateResources(services, ctx, unionRegistry));\n  },\n\n  generateClient(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateClient(spec, ctx, unionRegistry));\n  },\n\n  generateErrors(): GeneratedFile[] {\n    // Hand-maintained in the target SDK — `src/error.rs`, `src/client.rs`,\n    // `src/lib.rs`, `src/pagination.rs`, and `Cargo.toml` all carry\n    // `@oagen-ignore-file` and are not regenerated.\n    return [];\n  },\n\n  generateTypeSignatures(): GeneratedFile[] {\n    return [];\n  },\n\n  generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile[] {\n    return ensureTrailingNewlines(generateTests(spec, ctx));\n  },\n\n  buildOperationsMap(spec: ApiSpec, ctx: EmitterContext) {\n    return buildOperationsMap(spec, ctx);\n  },\n\n  fileHeader(): string {\n    return `// ${AUTOGEN_NOTICE}`;\n  },\n\n  formatCommand(_targetDir: string): FormatCommand | null {\n    // oagen appends every generated file path (mixing .rs, Cargo.toml, .json\n    // fixtures) to the format command. `rustfmt` errors on non-`.rs` paths,\n    // so wrap it in a bash filter that only forwards `.rs` files. Same\n    // shape as the Go emitter's gofmt wrapper.\n    return {\n      cmd: 'bash',\n      args: [\n        '-c',\n        'RS_FILES=$(printf \"%s\\\\n\" \"$@\" | grep \"\\\\.rs$\"); [ -n \"$RS_FILES\" ] && echo \"$RS_FILES\" | xargs rustfmt --edition 2024 --quiet',\n        '--',\n      ],\n      batchSize: 999999,\n    };\n  },\n};\n","import { fileURLToPath } from 'node:url';\nimport * as path from 'node:path';\nimport type { OagenConfig } from '@workos/oagen';\nimport { nodeEmitter } from './node/index.js';\nimport { pythonEmitter } from './python/index.js';\nimport { phpEmitter } from './php/index.js';\nimport { goEmitter } from './go/index.js';\nimport { dotnetEmitter } from './dotnet/index.js';\nimport { kotlinEmitter } from './kotlin/index.js';\nimport { rubyEmitter } from './ruby/index.js';\nimport { rustEmitter } from './rust/index.js';\nimport { nodeExtractor } from './compat/extractors/node.js';\nimport { rubyExtractor } from './compat/extractors/ruby.js';\nimport { pythonExtractor } from './compat/extractors/python.js';\nimport { phpExtractor } from './compat/extractors/php.js';\nimport { goExtractor } from './compat/extractors/go.js';\nimport { rustExtractor } from './compat/extractors/rust.js';\nimport { kotlinExtractor } from './compat/extractors/kotlin.js';\nimport { dotnetExtractor } from './compat/extractors/dotnet.js';\nimport { elixirExtractor } from './compat/extractors/elixir.js';\n\n// Resolve smoke runner paths relative to the package root so they work\n// regardless of which project loads the config (CWD-independent).\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst smokeDir = path.resolve(__dirname, '..', 'smoke');\n\nexport const workosEmittersPlugin: Pick<OagenConfig, 'emitters' | 'extractors' | 'smokeRunners'> = {\n  emitters: [nodeEmitter, pythonEmitter, phpEmitter, goEmitter, dotnetEmitter, kotlinEmitter, rubyEmitter, rustEmitter],\n  extractors: [\n    nodeExtractor,\n    rubyExtractor,\n    pythonExtractor,\n    phpExtractor,\n    goExtractor,\n    rustExtractor,\n    kotlinExtractor,\n    dotnetExtractor,\n    elixirExtractor,\n  ],\n  smokeRunners: {\n    node: path.join(smokeDir, 'sdk-node.ts'),\n    ruby: path.join(smokeDir, 'sdk-ruby.ts'),\n    python: path.join(smokeDir, 'sdk-python.ts'),\n    php: path.join(smokeDir, 'sdk-php.ts'),\n    go: path.join(smokeDir, 'sdk-go.ts'),\n    rust: path.join(smokeDir, 'sdk-rust.ts'),\n    elixir: path.join(smokeDir, 'sdk-elixir.ts'),\n    kotlin: path.join(smokeDir, 'sdk-kotlin.ts'),\n    dotnet: path.join(smokeDir, 'sdk-dotnet.ts'),\n  },\n};\n"],"x_google_ignoreList":[2],"mappings":";;;;;;;;;;;;;;AAQA,SAAgB,4BAA4B,KAA2B;CACrE,MAAM,uBAAO,IAAI,IAAkD;CAEnE,KAAK,MAAM,YAAY,IAAI,sBAAsB,CAAC,GAAG;EACnD,MAAM,MAAM,GAAG,SAAS,QAAQ,GAAG,SAAS;EAC5C,MAAM,UAAU;GACd,MAAM,SAAS,UAAU;GACzB,YAAY,SAAS,UAAU,WAAW,YAAY;EACxD;EACA,MAAM,WAAW,KAAK,IAAI,GAAG;EAE7B,IAAI,YAAY,SAAS,SAAS,QAAQ,MACxC,MAAM,IAAI,MACR,yCAAyC,IAAI,IACxC,SAAS,WAAW,GAAG,SAAS,KAAK,kBAAkB,QAAQ,WAAW,GAAG,QAAQ,MAC5F;EAGF,IAAI,CAAC,UACH,KAAK,IAAI,KAAK,OAAO;CAEzB;AACF;;;;;AAMA,SAAgB,oBAAoB,KAAqD;CACvF,4BAA4B,GAAG;CAE/B,MAAM,sBAAM,IAAI,IAA+B;CAC/C,KAAK,MAAM,KAAK,IAAI,sBAAsB,CAAC,GAAG;EAC5C,MAAM,MAAM,GAAG,EAAE,UAAU,WAAW,YAAY,EAAE,GAAG,EAAE,UAAU;EACnE,IAAI,IAAI,KAAK,CAAC;CAChB;CACA,OAAO;AACT;;;;;AAMA,SAAgB,iBAAiB,IAAe,QAA4D;CAC1G,MAAM,MAAM,GAAG,GAAG,WAAW,YAAY,EAAE,GAAG,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