@sdk-it/typescript 0.46.11 → 0.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -12
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1399 -1538
- package/dist/index.js.map +4 -4
- package/dist/lib/agent/ai-sdk.d.ts +2 -1
- package/dist/lib/agent/ai-sdk.d.ts.map +1 -1
- package/dist/lib/agent/openai-agents.d.ts +2 -1
- package/dist/lib/agent/openai-agents.d.ts.map +1 -1
- package/dist/lib/client-name.d.ts +16 -0
- package/dist/lib/client-name.d.ts.map +1 -0
- package/dist/lib/client.d.ts +25 -1
- package/dist/lib/client.d.ts.map +1 -1
- package/dist/lib/emitters/interface.d.ts +4 -2
- package/dist/lib/emitters/interface.d.ts.map +1 -1
- package/dist/lib/emitters/snippet.d.ts.map +1 -1
- package/dist/lib/emitters/zod.d.ts +13 -3
- package/dist/lib/emitters/zod.d.ts.map +1 -1
- package/dist/lib/folder-index.d.ts +7 -0
- package/dist/lib/folder-index.d.ts.map +1 -0
- package/dist/lib/generate.d.ts +28 -3
- package/dist/lib/generate.d.ts.map +1 -1
- package/dist/lib/generator.d.ts +28 -29
- package/dist/lib/generator.d.ts.map +1 -1
- package/dist/lib/group-identifier.d.ts +7 -0
- package/dist/lib/group-identifier.d.ts.map +1 -0
- package/dist/lib/import-utilities.d.ts.map +1 -1
- package/dist/lib/input-schema-name.d.ts +4 -0
- package/dist/lib/input-schema-name.d.ts.map +1 -0
- package/dist/lib/model-name.d.ts +7 -0
- package/dist/lib/model-name.d.ts.map +1 -0
- package/dist/lib/module-file.d.ts +7 -0
- package/dist/lib/module-file.d.ts.map +1 -0
- package/dist/lib/one-module.d.ts +57 -0
- package/dist/lib/one-module.d.ts.map +1 -0
- package/dist/lib/options.d.ts +4 -6
- package/dist/lib/options.d.ts.map +1 -1
- package/dist/lib/readme/prop.emitter.d.ts +4 -4
- package/dist/lib/readme/prop.emitter.d.ts.map +1 -1
- package/dist/lib/readme/readme.d.ts.map +1 -1
- package/dist/lib/references.d.ts +43 -0
- package/dist/lib/references.d.ts.map +1 -0
- package/dist/lib/root-exports.d.ts +6 -0
- package/dist/lib/root-exports.d.ts.map +1 -0
- package/dist/lib/sdk.d.ts +17 -27
- package/dist/lib/sdk.d.ts.map +1 -1
- package/dist/lib/security.d.ts +2 -3
- package/dist/lib/security.d.ts.map +1 -1
- package/dist/lib/server-urls.d.ts.map +1 -1
- package/dist/lib/status-map.d.ts +2 -2
- package/dist/lib/status-map.d.ts.map +1 -1
- package/dist/lib/typescript-snippet.d.ts +4 -8
- package/dist/lib/typescript-snippet.d.ts.map +1 -1
- package/package.json +19 -6
- package/dist/lib/pagination-emit.d.ts +0 -3
- package/dist/lib/pagination-emit.d.ts.map +0 -1
- package/dist/lib/response-shape.d.ts +0 -22
- package/dist/lib/response-shape.d.ts.map +0 -1
- package/dist/lib/style.d.ts +0 -4
- package/dist/lib/style.d.ts.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/
|
|
4
|
-
"sourcesContent": ["import { template } from 'lodash-es';\nimport { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { type OpenAPIDocument, pascalcase, toLitObject } from '@sdk-it/core';\nimport {\n type WriteContent,\n createWriterProxy,\n getFolderExports,\n writeFiles,\n} from '@sdk-it/core/file-system.js';\nimport {\n type IR,\n type ResponseBody,\n cleanFiles,\n forEachOperation,\n readWriteMetadata,\n sanitizeTag,\n toIR,\n} from '@sdk-it/spec';\n\nimport { generateAISDKTools } from './agent/ai-sdk.ts';\nimport { generateOpenAIAgentTools } from './agent/openai-agents.ts';\nimport utilsTxt from './agent/utils.txt';\nimport backend from './client.ts';\nimport { TypeScriptEmitter } from './emitters/interface.ts';\nimport { generateCode } from './generator.ts';\nimport dispatcherTxt from './http/dispatcher.txt';\nimport interceptors from './http/interceptors.txt';\nimport parseResponse from './http/parse-response.txt';\nimport parserTxt from './http/parser.txt';\nimport requestTxt from './http/request.txt';\nimport responseTxt from './http/response.txt';\nimport sseTxt from './http/sse.txt';\nimport { type MakeImportFn } from './import-utilities.ts';\nimport type { TypeScriptGeneratorOptions } from './options.ts';\nimport cursorPaginationTxt from './paginations/cursor-pagination.txt';\nimport offsetPaginationTxt from './paginations/offset-pagination.txt';\nimport paginationTxt from './paginations/page-pagination.txt';\nimport { toReadme } from './readme/readme.ts';\nimport type { Operation } from './sdk.ts';\nimport security from './security.ts';\nimport { expandServerUrls } from './server-urls.ts';\nimport { TypeScriptSnippet } from './typescript-snippet.ts';\n\n// FIXME: there should not be default here\n// instead export this function from the cli package with\n// defaults for programmatic usage\nexport async function generate(\n openapi: OpenAPIDocument,\n settings: TypeScriptGeneratorOptions,\n): Promise<{ packageName: string }> {\n // A requirement with no local scheme leaves the client unable to authenticate,\n // so refuse rather than emit an SDK that always gets a 401.\n const unresolvedSecuritySchemes = new Set<string>();\n const spec = await toIR(\n {\n spec: openapi,\n responses: { flattenErrorResponses: true },\n pagination: settings.pagination,\n onDiagnostic: ({ code, message }) => {\n if (code === 'unresolved-security-scheme') {\n unresolvedSecuritySchemes.add(message);\n }\n },\n },\n false,\n );\n if (unresolvedSecuritySchemes.size) {\n throw new TypeError([...unresolvedSecuritySchemes].join('\\n'));\n }\n\n const style = Object.assign({}, { name: 'github' }, settings.style ?? {});\n const output =\n settings.mode === 'full' ? join(settings.output, 'src') : settings.output;\n\n settings.useTsExtension ??= true;\n settings.readme ??= true;\n const { writer, files: writtenFiles } = createWriterProxy(\n settings.writer ?? writeFiles,\n output,\n );\n settings.writer = writer;\n settings.readFolder ??= async (folder: string) => {\n const files = await readdir(folder, { withFileTypes: true });\n return files.map((file) => ({\n fileName: file.name,\n filePath: join(file.parentPath, file.name),\n isFolder: file.isDirectory(),\n }));\n };\n const makeImport = (moduleSpecifier: string) => {\n return settings.useTsExtension ? `${moduleSpecifier}.ts` : moduleSpecifier;\n };\n const { endpoints, groups, commonZod } = generateCode({\n spec,\n style,\n makeImport,\n });\n\n const clientName = pascalcase((settings.name || 'client').trim());\n\n const packageName =\n settings.packageName ??\n (settings.name\n ? `@${spinalcase(settings.name.trim().toLowerCase())}/sdk`\n : 'sdk');\n\n const inputs = toInputs(groups, commonZod, makeImport);\n const models = serializeModels(spec);\n\n await settings.writer(output, {\n 'outputs/.gitkeep': '',\n 'inputs/.gitkeep': '',\n 'models/.getkeep': '',\n });\n\n await settings.writer(join(output, 'http'), {\n 'parse-response.ts': parseResponse,\n 'response.ts': responseTxt,\n 'parser.ts': parserTxt,\n 'request.ts': requestTxt,\n 'sse.ts': sseTxt,\n 'dispatcher.ts': `import z from 'zod';\nimport { type Interceptor } from '${makeImport('../http/interceptors')}';\nimport { type RequestConfig } from '${makeImport('../http/request')}';\nimport { buffered } from '${makeImport('./parse-response')}';\nimport { type SSEListener } from '${makeImport('./sse')}';\nimport { APIError, APIResponse, type SuccessfulResponse, type RebindSuccessPayload } from '${makeImport('./response')}';\n\n${template(dispatcherTxt, {})()}`,\n\n 'interceptors.ts': `\n import type { RequestConfig, HeadersInit } from './${makeImport('request')}';\n ${interceptors}`,\n 'security.ts': Object.keys(spec.components.securitySchemes).length\n ? security({\n makeImport,\n securitySchemes: spec.components.securitySchemes,\n })\n : null,\n });\n\n await settings.writer(output, {\n 'client.ts': backend({\n name: clientName,\n servers: expandServerUrls(spec.servers ?? []),\n securitySchemes: spec.components.securitySchemes,\n makeImport,\n }),\n ...inputs,\n ...endpoints,\n });\n\n await settings.writer(output, models);\n\n await settings.writer(join(output, 'pagination'), {\n 'cursor-pagination.ts': cursorPaginationTxt,\n 'offset-pagination.ts': offsetPaginationTxt,\n 'page-pagination.ts': paginationTxt,\n });\n\n const metadata = await readWriteMetadata(output, Array.from(writtenFiles));\n if (settings.cleanup !== false && writtenFiles.size > 0) {\n await cleanFiles(metadata.content, output, [\n '/tsconfig*.json',\n '/package.json',\n '/metadata.json',\n '/**/index.ts',\n ]);\n }\n\n const folders = [\n getFolderExports(\n join(output, 'outputs'),\n settings.readFolder,\n settings.useTsExtension,\n ),\n getFolderExports(\n join(output, 'inputs'),\n settings.readFolder,\n settings.useTsExtension,\n ['ts'],\n (dirent) => dirent.isFolder && ['schemas'].includes(dirent.fileName),\n ),\n getFolderExports(\n join(output, 'api'),\n settings.readFolder,\n settings.useTsExtension,\n ),\n getFolderExports(\n join(output, 'http'),\n settings.readFolder,\n settings.useTsExtension,\n ['ts'],\n (dirent) => !['response.ts', 'parser.ts'].includes(dirent.fileName),\n ),\n getFolderExports(\n join(output, 'models'),\n settings.readFolder,\n settings.useTsExtension,\n ),\n ];\n const [outputIndex, inputsIndex, apiIndex, httpIndex, modelsIndex] =\n await Promise.all(folders);\n\n await settings.writer(join(output, 'pagination'), {\n 'index.ts': await getFolderExports(\n join(output, 'pagination'),\n settings.readFolder,\n settings.useTsExtension,\n ['ts'],\n ),\n });\n await settings.writer(output, {\n 'api/index.ts': apiIndex,\n 'outputs/index.ts': outputIndex,\n 'inputs/index.ts': inputsIndex || null,\n 'http/index.ts': httpIndex,\n 'models/index.ts': modelsIndex,\n // ...(modelsImports.length ? { 'models/index.ts': modelsIndex } : {}),\n });\n\n switch (settings.agentTools) {\n case 'openai-agents':\n await settings.writer(output, {\n 'agents.ts': `${generateOpenAIAgentTools(spec)}\\n${utilsTxt}`,\n });\n break;\n case 'ai-sdk':\n await settings.writer(output, {\n 'agents.ts': `${generateAISDKTools(spec)}\\n${utilsTxt}`,\n });\n break;\n }\n await settings.writer(output, {\n 'index.ts': await getFolderExports(\n output,\n settings.readFolder,\n settings.useTsExtension,\n ['ts'],\n (config) =>\n config.fileName.endsWith('pagination') ||\n config.fileName.endsWith('agents'),\n ),\n });\n if (settings.mode === 'full') {\n const configFiles: WriteContent = {\n 'package.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n name: packageName,\n version: '0.0.1',\n type: 'module',\n ...(settings.agentTools === 'ai-sdk'\n ? { engines: { node: '>=22' } }\n : {}),\n main: './src/index.ts',\n module: './src/index.ts',\n types: './src/index.ts',\n publishConfig: {\n access: 'public',\n },\n exports: {\n './package.json': './package.json',\n '.': {\n types: './src/index.ts',\n import: './src/index.ts',\n default: './src/index.ts',\n },\n },\n dependencies: {\n 'fast-content-type-parse': '^3.0.0',\n zod: '^4.3.0',\n ...(settings.agentTools === 'ai-sdk' ? { ai: '^7.0.29' } : {}),\n ...(settings.agentTools === 'openai-agents'\n ? { '@openai/agents': '^0.13.4' }\n : {}),\n },\n },\n null,\n 2,\n ),\n },\n 'tsconfig.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n compilerOptions: {\n skipLibCheck: true,\n skipDefaultLibCheck: true,\n target: 'ESNext',\n noEmit: true,\n allowImportingTsExtensions: true,\n verbatimModuleSyntax: true,\n moduleResolution: 'bundler',\n },\n include: ['**/*.ts'],\n },\n null,\n 2,\n ),\n },\n };\n await settings.writer(settings.output, configFiles);\n }\n\n if (settings.readme) {\n const path =\n typeof settings.readme === 'string' ? settings.readme : 'README.md';\n await settings.writer(settings.output, {\n [path]: toReadme(spec, new TypeScriptSnippet(spec, settings)),\n });\n }\n\n await settings.formatCode?.({\n output: output,\n env: npmRunPathEnv(),\n });\n\n return { packageName };\n}\n\nfunction serializeModels(spec: IR) {\n const filesMap: Record<string, string[]> = {};\n const files: Record<string, string> = {};\n const responseBodies = new Map<string, ResponseBody>();\n forEachOperation(spec, (_, operation) => {\n for (const response of Object.values(operation.responses)) {\n const name = response['x-response-name'];\n if (name) {\n responseBodies.set(name, response['x-body']);\n }\n }\n });\n for (const [name, schema] of Object.entries(spec.components.schemas)) {\n // if (isRef(schema)) {\n // continue;\n // }\n const isResponseBody = (schema as any)['x-responsebody'];\n const isRequestBody = (schema as any)['x-requestbody'];\n const responseGroup = (schema as any)['x-response-group'];\n const body = responseGroup ? responseBodies.get(name) : undefined;\n if (isRequestBody) {\n // we do not generate interfaces for request bodies. we use zod for that.\n // bewary that the sometimes request body content schema is used as model somewhere else.\n // so we need to till the augmenter to create completeley separate model for request body suffixed by `Input`\n continue;\n }\n const folder = isResponseBody ? 'outputs' : 'models';\n let typeContent: string;\n if (body === 'sse') {\n typeContent = 'SSEListener';\n } else if (body === 'stream') {\n typeContent = 'ReadableStream';\n } else {\n typeContent = new TypeScriptEmitter(spec).handle(schema, true);\n }\n\n const imports: string[] = [];\n if (body === 'sse') {\n imports.push(`import type { SSEListener } from '../http/sse.ts';`);\n }\n\n const fileContent = [\n ...imports,\n `\\n${schema.description ? `\\n/** \\n * ${schema.description}\\n */\\n` : ''}`,\n `export type ${pascalcase(sanitizeTag(name))} = ${typeContent};`,\n ];\n const fileName = responseGroup\n ? join(folder, `${spinalcase(responseGroup)}.ts`)\n : join(folder, `${spinalcase(name)}.ts`);\n filesMap[fileName] ??= [];\n filesMap[fileName].push(fileContent.join('\\n'));\n }\n\n for (const [group, contents] of Object.entries(filesMap)) {\n let fileContent = contents.join('\\n');\n if (fileContent.includes('models.')) {\n fileContent = `import type * as models from '../index.ts';\\n${fileContent}`;\n }\n files[group] = fileContent;\n }\n return files;\n}\n\nexport function toInputs(\n operationsSet: Record<string, Operation[]>,\n commonZod: Map<string, string>,\n makeImport: MakeImportFn,\n) {\n const commonImports = commonZod.keys().toArray();\n const inputs: Record<string, string> = {};\n for (const [name, operations] of Object.entries(operationsSet)) {\n const output: string[] = [];\n const imports = new Set(['import { z } from \"zod\";']);\n\n for (const operation of operations) {\n const schemaName = camelcase(`${operation.operationId} schema`);\n\n const schema = `export const ${schemaName} = ${\n Object.keys(operation.schemas).length === 1\n ? Object.values(operation.schemas)[0]\n : toLitObject(operation.schemas)\n };`;\n\n for (const it of commonImports) {\n if (schema.includes(it)) {\n imports.add(\n `import { ${it} } from './schemas/${makeImport(spinalcase(it))}';`,\n );\n }\n }\n output.push(schema);\n }\n inputs[`inputs/${spinalcase(name)}.ts`] =\n [...imports, ...output].join('\\n') + '\\n';\n }\n\n const schemas = commonZod\n .entries()\n .reduce<string[][]>((acc, [name, schema]) => {\n const output = [`import { z } from 'zod';`];\n const content = `export const ${name} = ${schema};`;\n for (const schema of commonImports) {\n const preciseMatch = new RegExp(`\\\\b${schema}\\\\b`);\n if (preciseMatch.test(content) && schema !== name) {\n output.push(\n `import { ${schema} } from './${makeImport(spinalcase(schema))}';`,\n );\n }\n }\n output.push(content);\n return [\n [`inputs/schemas/${spinalcase(name)}.ts`, output.join('\\n')],\n ...acc,\n ];\n }, []);\n\n return {\n ...Object.fromEntries(schemas),\n ...inputs,\n };\n}\n", "import { camelcase } from 'stringcase';\n\nimport {\n type IR,\n type OperationEntry,\n type TunedOperationObject,\n forEachOperation,\n} from '@sdk-it/spec';\n\nexport function generateAISDKTools(ir: IR) {\n const groups: Record<\n string,\n {\n tools: string[];\n instructions: string;\n displayName: string;\n name: string;\n }\n > = {};\n forEachOperation(ir, (entry, operation) => {\n const tagDef = ir.tags.find((tag) => tag.name === entry.tag);\n if (!tagDef) {\n console.warn(`No tag details found for tag: ${entry.tag}`);\n return;\n }\n\n groups[entry.tag] ??= {\n tools: [],\n instructions: '',\n displayName: '',\n name: '',\n };\n groups[entry.tag].tools.push(createTool(entry, operation));\n groups[entry.tag].instructions = tagDef['x-instructions'];\n groups[entry.tag].name = tagDef.name;\n groups[entry.tag].displayName = tagDef['x-name'];\n });\n const imports = [\n `import { z } from 'zod';`,\n `import { tool } from 'ai';`,\n `import * as schemas from './inputs/index.ts';`,\n ];\n const agent = Object.entries(groups).map(\n ([group, { instructions, tools, displayName }]) => {\n return `export const ${camelcase(group)} = {\n name: '${displayName}',\n instructions: \\`${instructions}\\`,\n tools: { ${tools.join(', ')} }\n }`;\n },\n );\n\n return [...imports, ...agent].join('\\n\\n');\n}\n\nfunction createTool(entry: OperationEntry, operation: TunedOperationObject) {\n const schemaName = camelcase(`${operation.operationId} schema`);\n const toolInfo = operation['x-tool'];\n return `'${toolInfo?.name || operation['x-fn-name']}': tool({\n description: \\`${toolInfo?.description || operation.description || operation.summary}\\`,\n inputSchema: schemas.${schemaName},\n\t\t\texecute: async (input, options) => {\n\t\t\t\tconsole.log('Executing ${operation.operationId} tool with input:', input);\n const context = coerceContext(options.context);\n const response = await context.client.request(\n '${entry.method.toUpperCase()} ${entry.path}' ,\n input,\n );\n return JSON.stringify(response);\n },\n })`;\n}\n", "import { camelcase, spinalcase } from 'stringcase';\n\nimport {\n type IR,\n type OperationEntry,\n type TunedOperationObject,\n forEachOperation,\n} from '@sdk-it/spec';\n\nexport function generateOpenAIAgentTools(spec: IR) {\n const groups: Record<string, string[]> = {};\n forEachOperation(spec, (entry, operation) => {\n groups[entry.tag] ??= [];\n groups[entry.tag].push(createTool(entry, operation));\n });\n const imports = [\n `import { z } from 'zod';`,\n `import { tool } from '@openai/agents';`,\n `import * as schemas from './inputs/index.ts';`,\n ];\n const tools = Object.entries(groups).map(([group, tools]) => {\n return `export const ${spinalcase(group)} = [${tools.join(', ')}];`;\n });\n\n return [...imports, ...tools].join('\\n\\n');\n}\n\nfunction createTool(entry: OperationEntry, operation: TunedOperationObject) {\n const schemaName = camelcase(`${operation.operationId} schema`);\n return `tool({\n description: \\`${operation.description || operation.summary}\\`,\n name: '${operation['x-fn-name']}',\n parameters: makeOptionalPropsNullable(schemas.${schemaName}),\n\t\t\texecute: async (input, maybeContext) => {\n\t\t\t\tconsole.log('Executing ${operation.operationId} tool with input:', input);\n const context = coerceContext(maybeContext?.context);\n const client = context.client;\n const response = await client.request(\n '${entry.method.toUpperCase()} ${entry.path}' ,\n input as any,\n );\n return JSON.stringify(response);\n },\n })`;\n}\n", "function coerceContext(context?: any) {\n if (!context) {\n throw new Error('Context is required');\n }\n return context as {\n client: any\n };\n}\n/**\n * Takes a Zod object schema and makes all optional properties nullable as well.\n * This is useful for APIs where optional fields can be explicitly set to null.\n *\n * @param schema - The Zod object schema to transform\n * @returns A new Zod schema with optional properties made nullable\n */\nfunction makeOptionalPropsNullable<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n) {\n const shape = schema.shape;\n const newShape = {} as Record<string, z.ZodType>;\n\n for (const [key, value] of Object.entries(shape) as [string, z.ZodType][]) {\n if (value instanceof z.ZodOptional) {\n // Make optional properties also nullable\n newShape[key] = value.nullable();\n } else {\n // Keep non-optional properties as they are\n newShape[key] = value;\n }\n }\n\n return z.object(newShape);\n}\n", "import { toLitObject } from '@sdk-it/core';\n\nimport type { Spec } from './sdk.ts';\n\nexport default (spec: Omit<Spec, 'operations'>) => {\n const callableString = `z.custom<() => string | Promise<string>>((value) => typeof value === 'function')`;\n const baseUrlSchema = `z.union([z.string(),${callableString},])${spec.servers.length === 1 ? '.default(servers[0])' : ''}`;\n const securitySchemeNames = Object.keys(spec.securitySchemes);\n\n const specOptions: Record<string, { schema: string }> = {\n ...(securitySchemeNames.length\n ? {\n credentials: {\n schema: `credentialsSchema.optional().describe('Credentials keyed by OpenAPI security scheme name.')`,\n },\n }\n : {}),\n fetch: {\n schema: `fetchType.describe('Custom fetch implementation. Defaults to globalThis.fetch.')`,\n },\n baseUrl: {\n schema: `${baseUrlSchema}.transform(async (baseUrl, ctx) => {\n const value = typeof baseUrl === 'function' ? await baseUrl() : baseUrl;\n if (typeof value !== 'string') {\n ctx.addIssue({ code: 'custom', message: 'baseUrl must resolve to a string' });\n return z.NEVER;\n }\n return value;\n }).describe('Base URL of the API server. Can be a string or a function that returns a string.')`,\n },\n headers: {\n schema: `z.record(z.string(), z.string()).optional().describe('Default headers to include in all requests.')`,\n },\n skipValidation: {\n schema: `z.boolean().optional().describe('Skip request input validation. Client options and TypeScript types still enforce correct usage.')`,\n },\n };\n\n return `import z from 'zod';\nimport { APIResponse } from '${spec.makeImport('./http/response')}';\nimport type { HeadersInit, RequestConfig } from './http/${spec.makeImport('request')}';\nimport { fetchType, parse } from './http/${spec.makeImport('dispatcher')}';\nimport schemas from './api/${spec.makeImport('schemas')}';\nimport type { InferData } from '${spec.makeImport('./api/endpoints')}';\nimport {\n createBaseUrlInterceptor,\n createHeadersInterceptor,\n} from './http/${spec.makeImport('interceptors')}';\n\nimport { type ParseError, parseInput } from './http/${spec.makeImport('parser')}';${\n securitySchemeNames.length\n ? `\nimport { credentialsSchema, createSecurityInterceptor } from './http/${spec.makeImport('security')}';\nexport type {\n SecurityContext,\n SecurityCredential,\n SecurityCredentialProvider,\n SecurityCredentialValue,\n} from './http/${spec.makeImport('security')}';`\n : ''\n }\n\n${spec.servers.length ? `export const servers = ${JSON.stringify(spec.servers, null, 2)} as const` : ''}\nconst optionsSchema = z.object(${toLitObject(specOptions, (x) => x.schema)});\n${spec.servers.length ? `export type Servers = typeof servers[number];` : ''}\n\ntype ${spec.name}Options = z.input<typeof optionsSchema>;\n\nexport class ${spec.name} {\n public options: ${spec.name}Options;\n constructor(options: ${spec.name}Options) {\n this.options = options;\n }\n\n /** Sends a request and returns the unwrapped response data. Delegates to the standalone {@link request} function. */\n async request<const E extends keyof typeof schemas>(\n endpoint: E,\n input: z.input<(typeof schemas)[E]['schema']>,\n options?: { signal?: AbortSignal; headers?: HeadersInit },\n ) {\n return request(this, endpoint, input, options).then(function unwrap(\n it: unknown,\n ) {\n if (it instanceof APIResponse) {\n return it.data as InferData<E>;\n }\n return it as InferData<E>;\n });\n }\n\n /** Builds a ready-to-send request without sending it. Delegates to the standalone {@link prepare} function. */\n async prepare<const E extends keyof typeof schemas>(\n endpoint: E,\n input: z.input<(typeof schemas)[E]['schema']>,\n options?: { signal?: AbortSignal; headers?: HeadersInit },\n ) {\n return prepare(this, endpoint, input, options);\n }\n\n async defaultHeaders() {\n const options = await optionsSchema.parseAsync(this.options);\n return { ...options.headers };\n }\n\n setOptions(options: Partial<${spec.name}Options>) {\n this.options = {\n ...this.options,\n ...options,\n };\n }\n\n}\n\n/**\n * Sends a validated request using the client's configuration and returns the parsed response.\n * Applies the client's default headers before sending.\n * Throws \\`APIError\\` on non-ok responses.\n *\n * @example\n * \\`\\`\\`ts\n * const result = await request(client, 'GET /users', { limit: 10 });\n * \\`\\`\\`\n */\nexport async function request<const E extends keyof typeof schemas>(\n client: ${spec.name},\n endpoint: E,\n input: z.input<(typeof schemas)[E]['schema']>,\n requestOptions?: { signal?: AbortSignal; headers?: HeadersInit },\n): Promise<Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>> {\n const route = schemas[endpoint];\n const options = await optionsSchema.parseAsync(client.options);\n const parsedInput = options.skipValidation ? input : parseInput(route.schema, input);\n const result = await route.dispatch(parsedInput as never, {\n fetch: options.fetch,\n interceptors: [\n createHeadersInterceptor(\n { ...options.headers },\n requestOptions?.headers ?? {},\n ),\n${securitySchemeNames.length ? ' createSecurityInterceptor(route.security, options.credentials),\\n' : ''} createBaseUrlInterceptor(options.baseUrl),\n ],\n ...(requestOptions?.signal ? { signal: requestOptions.signal } : {}),\n });\n return result as Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>;\n}\n\n/**\n * Builds a validated \\`RequestConfig\\` (url + init) with a \\`parse\\` function attached, without sending.\n * Use when you need control over the fetch call \u2014 framework integration (Next.js, SvelteKit),\n * custom retry/logging, request batching, or testing.\n *\n * @example\n * \\`\\`\\`ts\n * const { url, init, parse } = await prepare(client, 'GET /users', { limit: 10 });\n * const response = await fetch(new Request(url, init));\n * const result = await parse(response);\n * \\`\\`\\`\n */\nexport async function prepare<const E extends keyof typeof schemas>(\n client: ${spec.name},\n endpoint: E,\n input: z.input<(typeof schemas)[E]['schema']>,\n requestOptions?: { signal?: AbortSignal; headers?: HeadersInit },\n): Promise<RequestConfig & {\n parse: (response: Response) => ReturnType<typeof parse>;\n}> {\n const route = schemas[endpoint];\n const options = await optionsSchema.parseAsync(client.options);\n const parsedInput = options.skipValidation ? input : parseInput(route.schema, input);\n const interceptors = [\n createHeadersInterceptor(\n { ...options.headers },\n requestOptions?.headers ?? {},\n ),\n${securitySchemeNames.length ? ' createSecurityInterceptor(route.security, options.credentials),\\n' : ''} createBaseUrlInterceptor(options.baseUrl),\n ];\n\n let config = route.toRequest(parsedInput as never);\n if (requestOptions?.signal) {\n config = {\n ...config,\n init: {\n ...config.init,\n signal: requestOptions.signal,\n },\n };\n }\n for (const interceptor of interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n return { ...config, parse: (response: Response) => parse(route.output as never, response, (d) => d) as never } as any;\n}\n\n\n`;\n};\n", "import type { ReferenceObject, SchemaObject } from 'openapi3-ts/oas31';\n\nimport {\n followRef,\n isEmpty,\n isRef,\n parseRef,\n pascalcase,\n resolveRef,\n} from '@sdk-it/core';\nimport { type IR, isPrimitiveSchema, sanitizeTag } from '@sdk-it/spec';\n\nexport class TypeScriptEmitter {\n #spec: IR;\n\n constructor(spec: IR) {\n this.#spec = spec;\n }\n #stringifyKey = (value: string): string => {\n return `'${value}'`;\n };\n\n object(schema: SchemaObject, _required = false): string {\n const properties = schema.properties || {};\n\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const tsType = this.handle(propSchema, isRequired);\n return `${this.#stringifyKey(key)}${isRequired ? '' : '?'}: ${tsType}`;\n });\n\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n const indexType = this.handle(schema.additionalProperties, true);\n propEntries.push(`[key: string]: ${indexType}`);\n } else if (schema.additionalProperties === true) {\n propEntries.push('[key: string]: any');\n }\n }\n\n return `${propEntries.length ? `{ ${propEntries.join('; ')} }` : 'unknown'}`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple)\n */\n #array(schema: SchemaObject, _required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => any[]\n return 'any[]';\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n const tupleItems = items.map((sub) => this.handle(sub, true));\n return `[${tupleItems.join(', ')}]`;\n }\n\n // If items is a single schema => standard array\n const itemsType = this.handle(items, true);\n return itemsType.length > 1 ? `(${itemsType})[]` : `${itemsType}[]`;\n }\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to TypeScript\n */\n normal(type: string, schema: SchemaObject, required = false): string {\n switch (type) {\n case 'string':\n return this.string(schema, required);\n case 'number':\n case 'integer':\n return this.number(schema, required);\n case 'boolean':\n return appendOptional('boolean', required);\n case 'object':\n return this.object(schema, required);\n case 'array':\n return this.#array(schema, required);\n case 'null':\n return 'null';\n default:\n console.warn(`Unknown type: ${type}`);\n // Unknown type -> fallback\n return appendOptional('any', required);\n }\n }\n\n #ref($ref: string, required: boolean): string {\n const schemaName = pascalcase(sanitizeTag(parseRef($ref).model));\n const schema = followRef(this.#spec, $ref);\n if (isPrimitiveSchema(schema)) {\n return this.handle(schema, required);\n }\n\n return `models.${appendOptional(schemaName, required)}`;\n }\n\n allOf(schemas: (SchemaObject | ReferenceObject)[]): string {\n // For TypeScript we use intersection types for allOf\n const allOfTypes = schemas.map((sub) => this.handle(sub, true));\n return allOfTypes.length > 1 ? `${allOfTypes.join(' & ')}` : allOfTypes[0];\n }\n\n oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n const isBareString = (s: SchemaObject | ReferenceObject) => {\n const r = resolveRef(this.#spec, s);\n return r.type === 'string' && !r.enum && !r.const && !r.format;\n };\n const isStringLiteral = (s: SchemaObject | ReferenceObject) => {\n const r = resolveRef(this.#spec, s);\n return (\n (Array.isArray(r.enum) &&\n r.enum.every((v: unknown) => typeof v === 'string')) ||\n typeof r.const === 'string'\n );\n };\n const hasStringLiteral = schemas.some(isStringLiteral);\n const seen = new Set<string>();\n const oneOfTypes: string[] = [];\n for (const sub of schemas) {\n const part =\n hasStringLiteral && isBareString(sub)\n ? '(string & {})'\n : this.handle(sub, true);\n if (seen.has(part)) continue;\n seen.add(part);\n oneOfTypes.push(part);\n }\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n return this.oneOf(schemas, required);\n }\n\n enum(values: unknown[], required: boolean): string {\n // For TypeScript enums as union of literals\n const enumValues = values\n .map((val) => (typeof val === 'string' ? `'${val}'` : `${val}`))\n .join(' | ');\n return appendOptional(enumValues, required);\n }\n\n /**\n * Handle string type with formats\n */\n string(schema: SchemaObject, required?: boolean): string {\n let type: string;\n\n if (schema.contentEncoding === 'binary') {\n return appendOptional('Blob', required);\n }\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n case 'date':\n type = 'string';\n break;\n case 'binary':\n case 'byte':\n type = 'Blob';\n break;\n default:\n type = 'string';\n }\n\n return appendOptional(type, required);\n }\n\n /**\n * Handle number/integer types with formats\n */\n number(_schema: SchemaObject, required?: boolean): string {\n return appendOptional('number', required);\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return this.#ref(schema.$ref, required);\n }\n\n if (schema.not && isEmpty(schema.not)) {\n return appendOptional('never', required);\n }\n\n // Handle allOf (intersection in TypeScript)\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf);\n }\n\n // anyOf (union in TypeScript)\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf, required);\n }\n\n // oneOf (union in TypeScript)\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf, required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.enum(schema.enum, required);\n }\n\n if (schema.const) {\n return this.enum([schema.const], true);\n }\n\n // Handle types, in TypeScript we can have union types directly\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to any\n if (!types.length) {\n // unless properties are defined then assume object\n if ('properties' in schema) {\n return this.object(schema, required);\n }\n return appendOptional('any', required);\n }\n\n // Handle union types (multiple types)\n if (types.length > 1) {\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n const tsType = this.normal(realTypes[0], schema, true);\n return appendOptional(`${tsType} | null`, required);\n }\n\n // Multiple different types\n const typeResults = types.map((t) => this.normal(t, schema, true));\n return appendOptional(typeResults.join(' | '), required);\n }\n\n // Single type\n return this.normal(types[0], schema, required);\n }\n}\n\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\n}\n", "import { merge, template } from 'lodash-es';\nimport { join } from 'node:path';\nimport type {\n ParameterObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport {\n type OpenAPIDocument,\n followRef,\n isEmpty,\n isRef,\n resolveRef,\n sortArray,\n} from '@sdk-it/core';\nimport {\n type IR,\n type TunedOperationObject,\n forEachOperation,\n} from '@sdk-it/spec';\n\nimport { ZodEmitter } from './emitters/zod.ts';\nimport { type OperationInput, type Spec, toEndpoint } from './sdk.ts';\nimport type { Style } from './style.ts';\nimport endpointsTxt from './styles/github/endpoints.txt';\n\nfunction coearceRequestInput(\n spec: IR,\n operation: TunedOperationObject,\n type: string,\n) {\n let objectSchema = resolveRef(\n spec,\n operation.requestBody.content[type].schema,\n );\n const xProperties: Record<string, SchemaObject> =\n objectSchema['x-properties'] ?? {};\n const xRequired: string[] = objectSchema['x-required'] ?? [];\n\n if (type === 'application/empty') {\n // if empty body and not params then we need to set it to object with additional properties\n // to avoid unknown input ts errors.\n objectSchema = {\n type: 'object',\n additionalProperties: isEmpty(xProperties),\n };\n } else {\n if (objectSchema.type !== 'object') {\n objectSchema = {\n type: 'object',\n required: [operation.requestBody.required ? '$body' : ''],\n properties: {\n $body: objectSchema,\n },\n };\n }\n }\n return {\n objectSchema,\n xProperties,\n xRequired,\n };\n}\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly: boolean;\n}\nexport interface Import {\n isTypeOnly: boolean;\n moduleSpecifier: string;\n defaultImport: string | undefined;\n namedImports: NamedImport[];\n namespaceImport: string | undefined;\n}\n\nexport function generateCode(config: {\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n spec: IR;\n style: Style;\n makeImport: (module: string) => string;\n}) {\n const commonZod = new Map<string, string>();\n const commonZodImports: Import[] = [];\n const zodDeserialzer = new ZodEmitter(config.spec, (model, schema) => {\n commonZod.set(model, schema);\n commonZodImports.push({\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `./${config.makeImport(model)}`,\n namedImports: [{ isTypeOnly: true, name: model }],\n namespaceImport: undefined,\n });\n });\n\n const groups: Spec['operations'] = {};\n const endpoints: Record<string, ReturnType<typeof toEndpoint>[]> = {};\n\n forEachOperation(config.spec, (entry, operation) => {\n console.log(`Processing ${entry.method} ${entry.path}`);\n groups[entry.tag] ??= [];\n endpoints[entry.tag] ??= [];\n const schemas: Record<string, string> = {};\n const shortContenTypeMap: Record<string, string> = {\n 'application/json': 'json',\n 'application/*+json': 'json', // type specific of json like application/vnd.api+json (from the generation pov it shouldn't matter)\n 'text/json': 'json', // non standard - later standardized to application/json\n 'application/x-www-form-urlencoded': 'urlencoded',\n 'multipart/form-data': 'formdata',\n 'application/xml': 'xml',\n 'text/plain': 'text',\n };\n\n for (const type in operation.requestBody.content) {\n schemas[shortContenTypeMap[type]] = zodDeserialzer.handle(\n operationSchema(config.spec, operation, type),\n true,\n );\n }\n const details = buildInput(config.spec, operation);\n const endpoint = toEndpoint(entry.tag, operation, {\n method: entry.method,\n path: entry.path,\n operationId: operation.operationId,\n schemas,\n outgoingContentType: details.outgoingContentType,\n inputs: details.inputs,\n });\n\n endpoints[entry.tag].push(endpoint);\n\n groups[entry.tag].push({\n method: entry.method,\n path: entry.path,\n operationId: operation.operationId,\n schemas,\n outgoingContentType: details.outgoingContentType,\n inputs: details.inputs,\n });\n });\n const allSchemas = Object.keys(endpoints).map((it) => ({\n import: `import ${camelcase(it)} from './${config.makeImport(spinalcase(it))}';`,\n use: ` ...${camelcase(it)}`,\n }));\n\n return {\n groups,\n commonZod,\n endpoints: {\n [join('api', 'endpoints.ts')]: `\nimport type z from 'zod';\nimport type { ParseError } from '${config.makeImport('../http/parser')}';\nimport type { ProblematicResponse, SuccessfulResponse, APIResponse } from '${config.makeImport(\n '../http/response',\n )}';\n\nimport schemas from '${config.makeImport('./schemas')}';\nimport type { Unionize } from '${config.makeImport('../http/dispatcher')}';\n ${template(endpointsTxt)({})}`,\n [`${join('api', 'schemas.ts')}`]:\n `${allSchemas.map((it) => it.import).join('\\n')}\n\nexport default {\\n${allSchemas.map((it) => it.use).join(',\\n')}\\n};\n\n`.trim(),\n ...Object.fromEntries(\n Object.entries(endpoints)\n .map(([name, endpoint]) => {\n const operations = endpoint.flatMap((it) => it.schemas).join(',\\n');\n return [\n [\n join('api', `${spinalcase(name)}.ts`),\n `${[\n `import z from 'zod';`,\n `import * as http from '${config.makeImport('../http/response')}';`,\n ...(operations.includes('outputs.')\n ? [\n `import * as outputs from '${config.makeImport('../outputs/index')}';`,\n ]\n : []),\n `import { toRequest, json, urlencoded, empty, formdata, type HeadersInit } from '${config.makeImport('../http/request')}';`,\n `import { chunked, buffered, bodyless } from \"${config.makeImport('../http/parse-response')}\";`,\n `import { sse, type SSEListener } from \"${config.makeImport('../http/sse')}\";`,\n `import * as ${camelcase(name)} from '../inputs/${config.makeImport(spinalcase(name))}';`,\n `import { createBaseUrlInterceptor, createHeadersInterceptor, type Interceptor } from '${config.makeImport('../http/interceptors')}';`,\n `import { Dispatcher, fetchType, type InstanceType } from '${config.makeImport('../http/dispatcher')}';`,\n `import { Pagination, OffsetPagination, CursorPagination } from \"${config.makeImport('../pagination/index')}\";`,\n ].join('\\n')}\\nexport default {\\n${operations}\\n}`,\n ],\n ];\n })\n .flat(),\n ),\n },\n };\n}\n\nfunction toProps(\n spec: OpenAPIDocument,\n schemaOrRef: SchemaObject | ReferenceObject,\n aggregator: string[] = [],\n) {\n if (isRef(schemaOrRef)) {\n const schema = followRef(spec, schemaOrRef.$ref);\n return toProps(spec, schema, aggregator);\n } else if (schemaOrRef.type === 'object') {\n for (const [name] of Object.entries(schemaOrRef.properties ?? {})) {\n aggregator.push(name);\n }\n return void 0;\n } else if (\n (schemaOrRef.type === 'array' || schemaOrRef.type?.includes('array')) &&\n schemaOrRef.items\n ) {\n toProps(spec, schemaOrRef.items, aggregator);\n return void 0;\n } else if (schemaOrRef.allOf) {\n for (const it of schemaOrRef.allOf) {\n toProps(spec, it, aggregator);\n }\n return void 0;\n } else if (schemaOrRef.oneOf) {\n for (const it of schemaOrRef.oneOf) {\n toProps(spec, it, aggregator);\n }\n return void 0;\n } else if (schemaOrRef.anyOf) {\n for (const it of schemaOrRef.anyOf) {\n toProps(spec, it, aggregator);\n }\n return void 0;\n }\n console.warn('Unknown schema in body', schemaOrRef);\n return void 0;\n}\n\nfunction bodyInputs(spec: IR, ctSchema: SchemaObject | ReferenceObject) {\n const props: string[] = [];\n toProps(spec, ctSchema, props);\n\n return (\n // TODO: should we preproccess the sort at spec level instead of generator's?\n sortArray(props).reduce<Record<string, OperationInput>>(\n (acc, prop) => ({\n ...acc,\n [prop]: {\n in: 'body',\n schema: '',\n },\n }),\n {},\n )\n );\n}\n\nconst contentTypeSerializerMap = {\n 'application/json': 'json',\n 'application/x-www-form-urlencoded': 'urlencoded',\n 'multipart/form-data': 'formdata',\n 'application/xml': 'xml',\n 'text/plain': 'text',\n 'application/empty': 'empty',\n} as const;\nconst serializerContentTypeMap = Object.fromEntries(\n Object.entries(contentTypeSerializerMap).map(([k, v]) => [v, k]),\n) as Record<\n (typeof contentTypeSerializerMap)[keyof typeof contentTypeSerializerMap],\n string\n>;\n\nexport function buildInput(spec: IR, operation: TunedOperationObject) {\n const inputs: Record<string, OperationInput> = {};\n\n let outgoingContentType: (typeof contentTypeSerializerMap)[keyof typeof contentTypeSerializerMap] =\n 'empty';\n\n for (const [ct, value] of Object.entries(contentTypeSerializerMap)) {\n if (operation.requestBody.content[ct]) {\n outgoingContentType = value;\n const { objectSchema, xProperties } = coearceRequestInput(\n spec,\n operation,\n ct,\n );\n for (const [name, prop] of Object.entries(xProperties)) {\n inputs[name] = {\n in: prop['x-in'],\n schema: '',\n };\n }\n\n Object.assign(inputs, bodyInputs(spec, objectSchema));\n break;\n }\n }\n return {\n inputs,\n outgoingContentType,\n ct: serializerContentTypeMap[outgoingContentType],\n };\n}\n\nexport function operationSchema(\n ir: IR,\n operation: TunedOperationObject,\n type: string,\n) {\n const { objectSchema, xProperties, xRequired } = coearceRequestInput(\n ir,\n operation,\n type,\n );\n const additionalProperties: Record<string, ParameterObject> = {};\n for (const [name, prop] of Object.entries(xProperties)) {\n additionalProperties[name] = {\n name: name,\n required: xRequired?.includes(name),\n schema: prop,\n in: prop['x-in'],\n };\n }\n\n return merge({}, objectSchema, {\n required: Object.values(additionalProperties)\n .filter((p) => p.required)\n .map((p) => p.name),\n properties: Object.entries(additionalProperties).reduce(\n (acc, [, p]) => ({ ...acc, [p.name]: p.schema }),\n {},\n ),\n });\n}\n", "import type { ReferenceObject, SchemaObject } from 'openapi3-ts/oas31';\n\nimport {\n type OpenAPIDocument,\n followRef,\n isEmpty,\n isRef,\n parseRef,\n pascalcase,\n} from '@sdk-it/core';\nimport { isPrimitiveSchema, sanitizeTag } from '@sdk-it/spec';\n\ntype OnRefCallback = (ref: string, content: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into a Zod schema string,\n */\nexport class ZodEmitter {\n #generatedRefs = new Set<string>();\n #spec: OpenAPIDocument;\n #onRef?: OnRefCallback;\n\n constructor(spec: OpenAPIDocument, onRef?: OnRefCallback) {\n this.#spec = spec;\n this.#onRef = onRef;\n }\n\n #object(schema: SchemaObject): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n return `'${key}': ${this.handle(propSchema, isRequired)}`;\n });\n\n let additionalProps = '';\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n // e.g. z.record() if it\u2019s an object schema\n const addPropZod = this.handle(schema.additionalProperties, true);\n additionalProps = `.catchall(${addPropZod})`;\n } else if (schema.additionalProperties === true) {\n // free-form additional props\n additionalProps = `.catchall(z.unknown())`;\n }\n }\n\n return `z.object({${propEntries.join(', ')}})${additionalProps}`;\n }\n\n #array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n return `z.array(z.unknown())${appendOptional(required)}`;\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n // Build a Zod tuple\n const tupleItems = items.map((sub) => this.handle(sub, true));\n const base = `z.tuple([${tupleItems.join(', ')}])`;\n // // If we have additionalItems: false => that\u2019s a fixed length\n // // If additionalItems is a schema => rest(...)\n // if (schema.additionalItems) {\n // if (typeof schema.additionalItems === 'object') {\n // const restSchema = jsonSchemaToZod(spec, schema.additionalItems, true);\n // base += `.rest(${restSchema})`;\n // }\n // // If `additionalItems: false`, no rest is allowed => do nothing\n // }\n return `${base}${appendOptional(required)}`;\n }\n\n // If items is a single schema => standard z.array(...)\n const itemsSchema = this.handle(items, true);\n return `z.array(${itemsSchema})${this.#suffixes(JSON.stringify(schema.default), required, false)}`;\n }\n\n #suffixes = (defaultValue: unknown, required: boolean, nullable: boolean) => {\n return `${nullable ? '.nullable()' : ''}${appendOptional(required)}${appendDefault(defaultValue)}`;\n };\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to Zod.\n * We'll also handle .optional() if needed.\n */\n normal(\n type: string,\n schema: SchemaObject,\n required = false,\n nullable = false,\n ): string {\n switch (type) {\n case 'string': {\n const defaultVal =\n (schema['x-zod-type'] === 'date' ||\n schema['x-zod-type'] === 'coerce-date') &&\n schema.default\n ? `new Date(${JSON.stringify(schema.default)})`\n : JSON.stringify(schema.default);\n return `${this.string(schema)}${this.#suffixes(defaultVal, required, nullable)}`;\n }\n case 'number':\n case 'integer': {\n const { base, defaultValue } = this.#number(schema);\n return `${base}${this.#suffixes(defaultValue, required, nullable)}`;\n }\n case 'boolean':\n return `${schema['x-zod-type'] === 'coerce-boolean' ? 'z.union([z.boolean(), z.stringbool()])' : 'z.boolean()'}${this.#suffixes(schema.default, required, nullable)}`;\n case 'object':\n return `${this.#object(schema)}${this.#suffixes(JSON.stringify(schema.default), required, nullable)}`;\n // required always\n case 'array':\n return this.#array(schema, required);\n case 'null':\n // If \"type\": \"null\" alone, this is basically z.null()\n return `z.null()${appendOptional(required)}`;\n default:\n // Unknown type -> fallback\n return `z.unknown()${appendOptional(required)}`;\n }\n }\n\n #ref($ref: string, required: boolean) {\n const schemaName = pascalcase(sanitizeTag(parseRef($ref).model));\n const schema = followRef(this.#spec, $ref);\n\n if (isPrimitiveSchema(schema)) {\n const result = this.handle(schema, required);\n this.#onRef?.(schemaName, result);\n return result;\n }\n\n if (this.#generatedRefs.has(schemaName)) {\n return schemaName;\n }\n this.#generatedRefs.add(schemaName);\n this.#onRef?.(schemaName, this.handle(schema, required));\n\n return schemaName;\n }\n #toIntersection(schemas: string[]): string {\n const [left, ...right] = schemas;\n if (!right.length) {\n return left;\n }\n return `z.intersection(${left}, ${this.#toIntersection(right)})`;\n }\n\n allOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const allOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (allOfSchemas.length === 0) {\n return `z.unknown()`;\n }\n if (allOfSchemas.length === 1) {\n return `${allOfSchemas[0]}${appendOptional(required)}`;\n }\n return `${this.#toIntersection(allOfSchemas)}${appendOptional(required)}`;\n }\n\n anyOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const anyOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (anyOfSchemas.length === 1) {\n return `${anyOfSchemas[0]}${appendOptional(required)}`;\n }\n return `z.union([${anyOfSchemas.join(', ')}])${appendOptional(required)}`;\n }\n\n oneOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const oneOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (oneOfSchemas.length === 1) {\n return `${oneOfSchemas[0]}${appendOptional(required)}`;\n }\n // oneOf is exclusive-or per JSON Schema; z.xor rejects values matching\n // more than one branch, unlike z.union's anyOf semantics.\n return `z.xor([${oneOfSchemas.join(', ')}])${appendOptional(required)}`;\n }\n\n enum(type: string, values: any[]) {\n if (values.length === 1) {\n return `z.literal(${values.join(', ')})`;\n }\n // Values arrive JSON.stringify'd, so string literals start with a quote.\n // z.enum only takes strings; zod 4 silently filters numeric entries as\n // reverse mappings, so any non-string enum must emit z.literal([...]).\n if (values.every((value) => String(value).startsWith('\"'))) {\n return `z.enum([${values.join(', ')}])`;\n }\n return `z.literal([${values.join(', ')}])`;\n }\n\n /**\n * Handle a `string` schema with possible format keywords (JSON Schema).\n */\n string(schema: SchemaObject): string {\n let base =\n schema['x-zod-type'] === 'coerce-string'\n ? 'z.coerce.string()'\n : 'z.string()';\n\n // 3.1 replaces `example` in the schema with `examples` (array).\n // We do not strictly need them for the Zod type, so they\u2019re optional\n // for validation. However, we could keep them as metadata if you want.\n\n if (schema.contentEncoding === 'binary') {\n // Emitted client code must not reference Blob as a runtime value:\n // it throws ReferenceError where the global is missing and fails\n // instanceof for cross-realm/polyfill Blobs (see e62c4e1 and\n // docs/recipes/file-upload.md).\n base = 'z.custom<Blob>()';\n return base;\n }\n\n const coerced = schema['x-zod-type'] === 'coerce-string';\n const withFormat = (format: string) =>\n coerced ? `${base}.pipe(${format})` : format;\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n if (schema['x-zod-type'] === 'coerce-date') {\n base = 'z.coerce.date()';\n } else if (schema['x-zod-type'] === 'date') {\n base = 'z.date()';\n } else {\n // RFC 3339 date-time allows numeric zone offsets, which\n // z.iso.datetime() rejects by default.\n base = withFormat('z.iso.datetime({ offset: true })');\n }\n break;\n case 'date':\n base = withFormat('z.iso.date()');\n break;\n case 'time':\n // z.iso.time() rejects RFC 3339 zone suffixes, which JSON Schema's\n // format: time allows.\n base = withFormat(\n 'z.string().regex(/^([01]\\\\d|2[0-3]):[0-5]\\\\d(:[0-5]\\\\d(\\\\.\\\\d+)?)?(Z|[+-]([01]\\\\d|2[0-3]):[0-5]\\\\d)?$/)',\n );\n break;\n case 'email':\n base = withFormat('z.email()');\n break;\n case 'uuid':\n // z.guid() preserves zod v3's looser .uuid() semantics; z.uuid()\n // enforces RFC 9562 variant bits and rejects Microsoft-style GUIDs.\n base = withFormat('z.guid()');\n break;\n case 'url':\n case 'uri':\n base = withFormat('z.url()');\n break;\n case 'ipv4':\n base = withFormat('z.ipv4()');\n break;\n case 'ipv6':\n base = withFormat('z.ipv6()');\n break;\n case 'cidrv4':\n base = withFormat('z.cidrv4()');\n break;\n case 'cidrv6':\n base = withFormat('z.cidrv6()');\n break;\n case 'phone':\n base += ' /* or add .regex(...) for phone formats */';\n break;\n case 'byte':\n case 'binary':\n // Bare z.custom on purpose \u2014 see the contentEncoding branch above.\n base = 'z.custom<Blob>()';\n break;\n default:\n // No special format\n break;\n }\n\n return base;\n }\n\n /**\n * Handle number/integer constraints from OpenAPI/JSON Schema.\n * In 3.1, exclusiveMinimum/Maximum hold the actual numeric threshold,\n * rather than a boolean toggling `minimum`/`maximum`.\n */\n #number(schema: SchemaObject) {\n let base =\n schema['x-zod-type'] === 'coerce-number'\n ? 'z.coerce.number()'\n : 'z.number()';\n\n if (schema.type === 'integer') {\n base += '.int()';\n }\n\n // If we see exclusiveMinimum as a number in 3.1:\n if (typeof schema.exclusiveMinimum === 'number') {\n // Zod doesn\u2019t have a direct \"exclusiveMinimum\" method, so we can do .gt()\n // If exclusiveMinimum=7 => .gt(7)\n base += `.gt(${schema.exclusiveMinimum})`;\n }\n // Similarly for exclusiveMaximum\n if (typeof schema.exclusiveMaximum === 'number') {\n // If exclusiveMaximum=10 => .lt(10)\n base += `.lt(${schema.exclusiveMaximum})`;\n }\n\n // If standard minimum/maximum\n if (typeof schema.minimum === 'number') {\n base += `.min(${schema.minimum})`;\n }\n if (typeof schema.maximum === 'number') {\n base += `.max(${schema.maximum})`;\n }\n\n // multipleOf\n if (typeof schema.multipleOf === 'number') {\n // There's no direct multipleOf in Zod. Some folks do a custom refine.\n // For example:\n base += `.refine((val) => Number.isInteger(val / ${schema.multipleOf}), \"Must be a multiple of ${schema.multipleOf}\")`;\n }\n\n return { base, defaultValue: schema.default };\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return `${this.#ref(schema.$ref, true)}${appendOptional(required)}`;\n }\n\n if (schema.not && isEmpty(schema.not)) {\n return `z.never()${appendOptional(required)}`;\n }\n\n // Handle allOf \u2192 intersection\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf ?? [], required);\n }\n\n // anyOf \u2192 union\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf ?? [], required);\n }\n\n // oneOf \u2192 union\n if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length) {\n return this.oneOf(schema.oneOf ?? [], required);\n }\n\n if (schema.const !== undefined) {\n return `z.literal(${JSON.stringify(schema.const)})${this.#suffixes(JSON.stringify(schema.default), required, false)}`;\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n const enumVals = schema.enum.map((val) => JSON.stringify(val));\n const defaultValue = enumVals.includes(JSON.stringify(schema.default))\n ? JSON.stringify(schema.default)\n : undefined;\n return `${this.enum(schema.type as string, enumVals)}${this.#suffixes(defaultValue, required, false)}`;\n }\n\n // 3.1 can have type: string or type: string[] (e.g. [\"string\",\"null\"])\n // Let's parse that carefully.\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to unknown\n if (!types.length) {\n return `z.unknown()${appendOptional(required)}`;\n }\n\n // If it's a union type (like [\"string\", \"null\"]), we'll build a Zod union\n // or apply .nullable() if it's just \"type + null\".\n\n // backward compatibility with openapi 3.0\n if ('nullable' in schema && schema.nullable) {\n types.push('null');\n } else if (schema.default === null) {\n types.push('null');\n }\n\n if (types.length > 1) {\n // If it\u2019s exactly one real type plus \"null\", we can do e.g. `z.string().nullable()`\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n return this.normal(\n realTypes[0],\n { ...schema, type: realTypes[0] },\n required,\n true,\n );\n }\n // If multiple different types, build a union\n const subSchemas = types.map((t) =>\n this.normal(t, { ...schema, type: t }, true),\n );\n return `z.union([${subSchemas.join(', ')}])${appendOptional(required)}`;\n }\n return this.normal(types[0], schema, required, false);\n }\n}\n\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\n\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined || typeof defaultValue !== 'undefined'\n ? `.default(${defaultValue})`\n : '';\n}\n", "import { camelcase } from 'stringcase';\n\nimport { type OpenAPISecuritySchemeObject, pascalcase } from '@sdk-it/core';\nimport {\n type OperationPagination,\n type ResponseBody,\n type TunedOperationObject,\n type TunedResponseObject,\n sanitizeTag,\n} from '@sdk-it/spec';\n\nimport { type MakeImportFn } from './import-utilities.ts';\nimport { paginationOperation } from './pagination-emit.ts';\nimport statusMap from './status-map.ts';\n\nexport type Parser = 'chunked' | 'buffered' | 'sse' | 'bodyless';\n\nexport interface SdkConfig {\n /**\n * The name of the sdk client\n */\n name: string;\n packageName?: string;\n options?: Record<string, unknown>;\n emptyBodyAsNull?: boolean;\n stripBodyFromGetAndHead?: boolean;\n output: string;\n}\n\nexport interface Spec {\n name: string;\n securitySchemes: Record<string, OpenAPISecuritySchemeObject>;\n servers: string[];\n operations: Record<string, Operation[]>;\n makeImport: MakeImportFn;\n}\n\nexport interface OperationInput {\n in: string;\n schema: string;\n}\nexport interface Operation {\n method: string;\n path: string;\n operationId: string;\n schemas: Record<string, string>;\n inputs: Record<string, OperationInput>;\n outgoingContentType?: string;\n}\n\nexport function toEndpoint(\n groupName: string,\n specOperation: TunedOperationObject,\n operation: Operation,\n) {\n const schemaName = camelcase(`${specOperation.operationId} schema`);\n const schemaRef = `${camelcase(groupName)}.${schemaName}`;\n\n const schemas: string[] = [];\n specOperation.responses ??= {};\n const outputs = Object.keys(specOperation.responses).map((status) =>\n toHttpOutput(status, specOperation.responses[status]),\n );\n\n const addTypeParser = Object.keys(operation.schemas).length > 1;\n for (const type in operation.schemas ?? {}) {\n let typePrefix = '';\n if (addTypeParser && type !== 'json') {\n typePrefix = `${type} `;\n }\n const paths = inputToPath(specOperation, operation.inputs);\n const endpoint = `${typePrefix}${operation.method.toUpperCase()} ${operation.path}`;\n schemas.push(\n `\"${endpoint}\": {\n security: ${JSON.stringify(specOperation.security ?? [])} as readonly Record<string, readonly string[]>[],\n schema: ${schemaRef}${addTypeParser ? `.${type}` : ''},\n output:[${outputs.join(',')}],\n toRequest(input: z.input<typeof ${schemaRef}${addTypeParser ? `.${type}` : ''}>) {\n return toRequest('${endpoint}', ${operation.outgoingContentType || 'empty'}(input, {\n inputHeaders: [${paths.inputHeaders}],\n inputQuery: [${paths.inputQuery}],\n inputBody: [${paths.inputBody}],\n inputParams: [${paths.inputParams}],\n }));},\n async dispatch(input: z.input<typeof ${schemaRef}${addTypeParser ? `.${type}` : ''}>,options: {\n signal?: AbortSignal;\n interceptors: Interceptor[];\n fetch: z.infer<typeof fetchType>;\n })${specOperation['x-pagination'] ? paginationOperation(specOperation['x-pagination'] as OperationPagination) : normalOperation()}`,\n );\n }\n return { schemas };\n}\n\nfunction normalOperation() {\n return `{\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n return dispatcher.send(this.toRequest(input), this.output, options?.signal);\n },\n }`;\n}\n\nconst bodyParser: Record<ResponseBody, Parser> = {\n json: 'buffered',\n text: 'buffered',\n binary: 'buffered',\n empty: 'bodyless',\n stream: 'chunked',\n sse: 'sse',\n};\n\nexport function toHttpOutput(status: string, response: TunedResponseObject) {\n const body = response['x-body'];\n const type = status.endsWith('XX')\n ? 'http.APIError'\n : `http.${statusMap[status] || 'APIResponse'}`;\n if (status === '204') {\n return type;\n }\n const data = dataType(status, response);\n const parser = bodyParser[body];\n return parser === 'buffered'\n ? `${type}<${data}>`\n : `{type: ${type}<${data}>, parser: ${parser}}`;\n}\n\nfunction dataType(status: string, response: TunedResponseObject) {\n switch (response['x-body']) {\n case 'empty':\n return 'null';\n case 'stream':\n return 'ReadableStream';\n case 'sse':\n return 'SSEListener';\n default:\n return `outputs.${pascalcase(sanitizeTag(outputName(status, response)))}`;\n }\n}\n\nfunction outputName(status: string, response: TunedResponseObject) {\n const name = response['x-response-name'];\n if (!name) {\n throw new Error(\n `Response ${status} has a ${response['x-body']} body but no output name; generate with responses.flattenErrorResponses so every response is normalized`,\n );\n }\n return name;\n}\n\nexport function inputToPath(\n operation: TunedOperationObject,\n inputs: Record<string, OperationInput>,\n) {\n const inputHeaders: string[] = [];\n const inputQuery: string[] = [];\n const inputBody: string[] = [];\n const inputParams: string[] = [];\n for (const [name, prop] of Object.entries(inputs)) {\n if (prop.in === 'headers' || prop.in === 'header') {\n inputHeaders.push(`\"${name}\"`);\n } else if (prop.in === 'query') {\n inputQuery.push(`\"${name}\"`);\n } else if (prop.in === 'body') {\n inputBody.push(`\"${name}\"`);\n } else if (prop.in === 'path') {\n inputParams.push(`\"${name}\"`);\n } else {\n throw new Error(\n `Unknown source ${prop.in} in ${name} ${JSON.stringify(\n prop,\n )} in ${operation.operationId}`,\n );\n }\n }\n\n return {\n inputHeaders,\n inputQuery,\n inputBody,\n inputParams,\n };\n}\n", "import { removeDuplicates } from '@sdk-it/core';\n\nexport function mergeImports(...imports: Import[]) {\n const merged: Record<string, Import> = {};\n\n for (const it of imports) {\n merged[it.moduleSpecifier] = merged[it.moduleSpecifier] ?? {\n moduleSpecifier: it.moduleSpecifier,\n defaultImport: it.defaultImport,\n namespaceImport: it.namespaceImport,\n namedImports: [],\n };\n for (const named of it.namedImports) {\n if (\n !merged[it.moduleSpecifier].namedImports.some(\n (x) => x.name === named.name,\n )\n ) {\n merged[it.moduleSpecifier].namedImports.push(named);\n }\n }\n }\n\n return Object.values(merged);\n}\n\nexport interface Import {\n isTypeOnly?: boolean;\n moduleSpecifier: string;\n defaultImport?: string | undefined;\n namedImports: NamedImport[];\n namespaceImport?: string | undefined;\n}\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly?: boolean;\n}\n\nexport function importsToString(...imports: Import[]) {\n return imports.map((it) => {\n if (it.defaultImport) {\n return `import ${it.defaultImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namespaceImport) {\n return `import * as ${it.namespaceImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namedImports) {\n return `import {${removeDuplicates(it.namedImports, (it) => it.name)\n .map((n) => `${n.isTypeOnly ? 'type' : ''} ${n.name}`)\n .join(', ')}} from '${it.moduleSpecifier}'`;\n }\n throw new Error(`Invalid import ${JSON.stringify(it)}`);\n });\n}\n\nexport function useImports(content: string, ...imports: Import[]) {\n const output: string[] = [];\n for (const it of mergeImports(...imports)) {\n const singleImport = it.defaultImport ?? it.namespaceImport;\n if (singleImport && content.includes(singleImport)) {\n output.push(importsToString(it).join('\\n'));\n } else if (it.namedImports.length) {\n for (const namedImport of it.namedImports) {\n if (content.includes(namedImport.name)) {\n output.push(importsToString(it).join('\\n'));\n }\n }\n }\n }\n return output;\n}\n\nexport type MakeImportFn = (moduleSpecifier: string) => string;\n", "import type { OperationPagination } from '@sdk-it/spec';\n\ntype PaginationShape = {\n className: string;\n items: string;\n hasMore: string;\n statusCode: number;\n sameInputNames: boolean;\n initialOverride: string;\n nextPageMapping: string;\n};\n\nfunction describe(p: OperationPagination): PaginationShape {\n switch (p.type) {\n case 'offset':\n return {\n className: 'OffsetPagination',\n items: p.items,\n hasMore: p.hasMore,\n statusCode: p.statusCode,\n sameInputNames:\n p.limitParamName === 'limit' && p.offsetParamName === 'offset',\n initialOverride: `limit: input.${p.limitParamName}, offset: input.${p.offsetParamName}`,\n nextPageMapping: `${p.offsetParamName}: nextPageParams.offset, ${p.limitParamName}: nextPageParams.limit`,\n };\n case 'cursor':\n return {\n className: 'CursorPagination',\n items: p.items,\n hasMore: p.hasMore,\n statusCode: p.statusCode,\n sameInputNames: p.cursorParamName === 'cursor',\n initialOverride: `cursor: input[${JSON.stringify(p.cursorParamName)}]`,\n nextPageMapping: `[${JSON.stringify(p.cursorParamName)}]: nextPageParams.cursor ?? input[${JSON.stringify(p.cursorParamName)}]`,\n };\n case 'page':\n return {\n className: 'Pagination',\n items: p.items,\n hasMore: p.hasMore,\n statusCode: p.statusCode,\n sameInputNames:\n p.pageNumberParamName === 'page' &&\n p.pageSizeParamName === 'pageSize',\n initialOverride: `page: input.${p.pageNumberParamName}, pageSize: input.${p.pageSizeParamName}`,\n nextPageMapping: `${p.pageNumberParamName}: nextPageParams.page, ${p.pageSizeParamName}: nextPageParams.pageSize`,\n };\n }\n throw new Error(`Unknown pagination type: ${(p as { type: string }).type}`);\n}\n\nexport function paginationOperation(pagination: OperationPagination): string {\n const shape = describe(pagination);\n const initialParams = shape.sameInputNames\n ? 'input'\n : `{...input, ${shape.initialOverride}}`;\n const nextPageParams =\n shape.sameInputNames && pagination.type !== 'cursor'\n ? '...nextPageParams'\n : shape.nextPageMapping;\n const nextCursor =\n pagination.type === 'cursor' && pagination.nextCursor\n ? `result.data${pagination.nextCursor\n .split('.')\n .map((key) => `?.[${JSON.stringify(key)}]`)\n .join('')}`\n : undefined;\n\n return `{\n const pagination = new ${shape.className}(${initialParams}, async (nextPageParams, requestOptions) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n requestOptions?.signal ?? options.signal,\n );\n if (result.status !== ${shape.statusCode}) { throw result; }\n ${nextCursor ? `const nextCursor = ${nextCursor};` : ''}\n return {\n data: result.data.${shape.items},\n meta: {\n hasMore: Boolean(result.data.${shape.hasMore}),\n ${nextCursor ? '...(typeof nextCursor === \"string\" ? { nextCursor } : {}),' : ''}\n },\n };\n }, options.signal ? { signal: options.signal } : {});\n await pagination.getNextPage();\n return pagination\n }}`;\n}\n", "export default {\n '200': 'Ok',\n '201': 'Created',\n '202': 'Accepted',\n '204': 'NoContent',\n '400': 'BadRequest',\n '401': 'Unauthorized',\n '402': 'PaymentRequired',\n '403': 'Forbidden',\n '404': 'NotFound',\n '405': 'MethodNotAllowed',\n '406': 'NotAcceptable',\n '409': 'Conflict',\n '412': 'PreconditionFailed',\n '413': 'PayloadTooLarge',\n '410': 'Gone',\n '415': 'UnsupportedMediaType',\n '422': 'UnprocessableEntity',\n '429': 'TooManyRequests',\n '500': 'InternalServerError',\n '501': 'NotImplemented',\n '502': 'BadGateway',\n '503': 'ServiceUnavailable',\n '504': 'GatewayTimeout',\n} as Record<string, string>;\n", "type DispatchReturn<E extends keyof typeof schemas> = Awaited<\n ReturnType<(typeof schemas)[E]['dispatch']>\n>;\n\nexport type InferData<E extends keyof typeof schemas> =\n DispatchReturn<E> extends APIResponse<infer D> ? D : DispatchReturn<E>;\n\ntype EndpointOutput<K extends keyof typeof schemas> = Extract<\n Unionize<(typeof schemas)[K]['output']>,\n SuccessfulResponse\n>;\n\ntype EndpointError<K extends keyof typeof schemas> = Extract<\n Unionize<(typeof schemas)[K]['output']>,\n ProblematicResponse\n>;\n\nexport type Endpoints = {\n [E in keyof typeof schemas]: {\n input: z.input<(typeof schemas)[E]['schema']>;\n output: InferData<E>;\n error: EndpointError<E> | ParseError<(typeof schemas)[E]['schema']>;\n };\n};\n", "export type Unionize<T> = T extends [infer Single extends OutputType]\n ? InstanceType<Single>\n : T extends readonly [...infer Tuple extends OutputType[]]\n ? { [I in keyof Tuple]: InstanceType<Tuple[I]> }[number]\n : never;\n\nexport type InstanceType<T> =\n T extends Type<infer U>\n ? U\n : T extends { type: Type<infer U> }\n ? U\n : T extends Array<unknown>\n ? Unionize<T>\n : never;\n\ntype ResponseData<T extends OutputType[]> =\n Extract<InstanceType<T>, SuccessfulResponse> extends SuccessfulResponse<\n infer P\n >\n ? P\n : unknown;\n\ntype ResponseMapper<T extends OutputType[], R> = (data: ResponseData<T>) => R;\n\nexport interface Type<T> {\n new (...args: any[]): T;\n}\nexport type Parser = (\n response: Response,\n) => Promise<unknown> | ReadableStream<any> | SSEListener;\nexport type OutputType =\n | Type<APIResponse>\n | { parser: Parser; type: Type<APIResponse> };\n\n// Bare z.custom (no predicate) on purpose: Request/Response from another\n// realm (undici vs global fetch) fail instanceof checks. The output is\n// typed as a Promise directly \u2014 zod 4 deprecated z.promise.\nexport const fetchType = z\n .function({\n input: [z.custom<Request>()],\n output: z.custom<Promise<Response>>(),\n })\n .optional();\n\nexport async function parse<T extends OutputType[]>(\n outputs: T,\n response: Response,\n): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\nexport async function parse<T extends OutputType[], R>(\n outputs: T,\n response: Response,\n mapper: ResponseMapper<T, R>,\n): Promise<RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>>;\nexport async function parse<T extends OutputType[], R = ResponseData<T>>(\n outputs: T,\n response: Response,\n mapper?: ResponseMapper<T, R>,\n) {\n let output: typeof APIResponse | typeof APIError | null = null;\n let parser: Parser = buffered;\n for (const outputType of outputs) {\n const type = 'parser' in outputType ? outputType.type : outputType;\n if (\n (isTypeOf(type, APIResponse) || isTypeOf(type, APIError)) &&\n response.status === type.status\n ) {\n output = type;\n if ('parser' in outputType) {\n parser = outputType.parser;\n }\n break;\n }\n }\n\n if (response.ok) {\n const data = (await parser(response)) as ResponseData<T>;\n const mapped = mapper ? mapper(data) : data;\n const apiresponse = (output || APIResponse).create(\n response.status,\n response.headers,\n mapped,\n );\n\n return apiresponse as Extract<Unionize<T>, SuccessfulResponse<unknown>>;\n }\n\n const failure = output && isTypeOf(output, APIError) ? output : APIError;\n throw failure.create(\n response.status,\n response.headers,\n await parser(response),\n );\n}\n\nexport function isTypeOf<T extends Type<APIResponse>>(\n instance: any,\n baseType: T,\n): instance is T {\n if (instance === baseType) {\n return true;\n }\n const prototype = Object.getPrototypeOf(instance);\n if (prototype === null) {\n return false;\n }\n return isTypeOf(prototype, baseType);\n}\n\nexport class Dispatcher {\n #interceptors: Interceptor[] = [];\n #fetch: z.infer<typeof fetchType>;\n constructor(interceptors: Interceptor[], fetch?: z.infer<typeof fetchType>) {\n this.#interceptors = interceptors;\n this.#fetch = fetch;\n }\n\n async send<T extends OutputType[]>(\n config: RequestConfig,\n outputs: T,\n signal?: AbortSignal,\n ): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\n async send<T extends OutputType[], R>(\n config: RequestConfig,\n outputs: T,\n signal: AbortSignal | undefined,\n mapper: ResponseMapper<T, R>,\n ): Promise<RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>>;\n async send<T extends OutputType[], R = ResponseData<T>>(\n config: RequestConfig,\n outputs: T,\n signal?: AbortSignal,\n mapper?: ResponseMapper<T, R>,\n ) {\n for (const interceptor of this.#interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n\n const init = signal === undefined ? config.init : { ...config.init, signal };\n\n let response = await (this.#fetch ?? fetch)(new Request(config.url, init));\n\n for (let i = this.#interceptors.length - 1; i >= 0; i--) {\n const interceptor = this.#interceptors[i];\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n\n if (mapper) {\n return await parse(outputs, response, mapper);\n }\n return await parse(outputs, response);\n }\n}\n", "export interface Interceptor {\n before?: (config: RequestConfig) => Promise<RequestConfig> | RequestConfig;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nexport const createHeadersInterceptor = (\n headers: Record<string, string | undefined>,\n requestHeaders: HeadersInit,\n):Interceptor => {\n return {\n before({init, url}) {\n // Priority Levels\n // 1. Headers Input\n // 2. Request Headers\n // 3. Default Headers\n\n for (const [key, value] of new Headers(requestHeaders)) {\n // Only set the header if it doesn't already exist and has a value\n // even though these headers are passed at operation level\n // still they are lower priority compared to the headers input\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n for (const [key, value] of Object.entries(headers)) {\n // Only set the header if it doesn't already exist and has a value\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n return {init, url};\n },\n };\n};\n\nexport const createBaseUrlInterceptor = (baseUrl: string): Interceptor => {\n return {\n before({ init, url }) {\n if (url.protocol === 'local:') {\n return {\n init,\n url: new URL(url.href.replace('local://', baseUrl))\n };\n }\n return { init, url };\n },\n };\n};\n", "import { parse } from \"fast-content-type-parse\";\n\nfunction isBinaryContentType(contentType: string) {\n\tconst type = contentType.toLowerCase();\n\tif (type.startsWith(\"image/\")) {\n\t\treturn true;\n\t}\n\tif (type.startsWith(\"audio/\")) {\n\t\treturn true;\n\t}\n\tif (type.startsWith(\"video/\")) {\n\t\treturn true;\n\t}\n\tswitch (type) {\n\t\tcase \"application/pdf\":\n\t\tcase \"application/zip\":\n\t\tcase \"application/gzip\":\n\t\tcase \"application/x-7z-compressed\":\n\t\tcase \"application/x-tar\":\n\t\tcase \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":\n\t\tcase \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":\n\t\tcase \"application/vnd.openxmlformats-officedocument.presentationml.presentation\":\n\t\tcase \"application/vnd.ms-excel\":\n\t\tcase \"application/vnd.ms-powerpoint\":\n\t\tcase \"application/msword\":\n\t\tcase \"application/octet-stream\":\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nfunction isAttachment(response: Response) {\n\tconst contentDisposition = response.headers.get(\"Content-Disposition\");\n\tconst dispositionType = contentDisposition?.split(\";\", 1)[0];\n\treturn dispositionType?.trim().toLowerCase() === \"attachment\";\n}\n\nexport function chunked(response: Response) {\n\treturn response.body!;\n}\n\n// The operation declares no body; release the unread stream so the\n// connection is not held until garbage collection.\nexport async function bodyless(response: Response) {\n\tawait response.body?.cancel();\n\treturn null;\n}\n\nexport async function buffered(response: Response) {\n\t// Statuses that, per the HTTP spec, carry no message body. These responses\n\t// usually omit Content-Type entirely, so this must run before the guard below.\n\tif (\n\t\tresponse.status === 204 ||\n\t\tresponse.status === 205 ||\n\t\tresponse.status === 304\n\t) {\n\t\treturn null;\n\t}\n\tif (isAttachment(response)) {\n\t\treturn response.blob();\n\t}\n\n\tconst contentType = response.headers.get(\"Content-Type\");\n\tif (!contentType) {\n\t\tthrow new Error(\"Content-Type header is missing\");\n\t}\n\n\tconst { type } = parse(contentType);\n\tif (isBinaryContentType(type)) {\n\t\treturn response.blob();\n\t}\n\tif (type.startsWith(\"text/\")) {\n\t\treturn response.text();\n\t}\n\tswitch (type) {\n\t\tcase \"application/json\":\n\t\t\treturn response.json();\n\t\tcase \"application/xml\":\n\t\t\treturn response.text();\n\t\tcase \"application/x-www-form-urlencoded\": {\n\t\t\tconst text = await response.text();\n\t\t\treturn Object.fromEntries(new URLSearchParams(text));\n\t\t}\n\t\tcase \"multipart/form-data\":\n\t\t\treturn response.formData();\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported content type: ${contentType}`);\n\t}\n}\n", "import { z } from 'zod';\n\nexport class ParseError<T extends z.ZodType> extends Error {\n public data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>;\n constructor(\n data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>,\n ) {\n super('Validation failed');\n this.name = 'ParseError';\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType>(\n schema: T,\n input: unknown,\n): z.infer<T> {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = z.flattenError(result.error, (issue) => issue);\n throw new ParseError<T>(error);\n }\n return result.data as z.infer<T>;\n}\n", "type Init = Omit<RequestInit, 'headers'> & { headers: Headers };\nexport type RequestConfig = { init: Init; url: URL };\nexport type Method =\n | 'GET'\n | 'POST'\n | 'PUT'\n | 'PATCH'\n | 'DELETE'\n | 'HEAD'\n | 'OPTIONS';\nexport type ContentType =\n | 'xml'\n | 'json'\n | 'urlencoded'\n | 'multipart'\n | 'formdata';\nexport type HeadersInit = [string, string][] | Record<string, string>;\nexport type Endpoint =\n | `${ContentType} ${Method} ${string}`\n | `${Method} ${string}`;\n\nexport type BodyInit =\n | ArrayBuffer\n | Blob\n | FormData\n | URLSearchParams\n | null\n | string;\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined\n ? ''\n : encodeURIComponent(String(result));\n });\n}\n\ntype Input = Record<string, any>;\n\n// Validated inputs can carry Date (coerce-date) values; String(new Date())\n// yields a local-time RFC 2822 string, so serialize Dates as ISO 8601.\nfunction toWireValue(value: any): string {\n return value instanceof Date ? value.toISOString() : String(value);\n}\n\ntype Props = {\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n protected input: Input;\n protected props: Props;\n\n constructor(input: Input, props: Props) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(path: string): Serialized {\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n const url = new URL(template(path, params), `local://`);\n\n const headers: Record<string, string> = { ...this.getHeaders() };\n for (const header of this.props.inputHeaders) {\n const value = this.input[header];\n if (value !== undefined) {\n headers[header] = toWireValue(value);\n }\n }\n\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, toWireValue(item));\n }\n } else {\n url.searchParams.set(key, toWireValue(value));\n }\n }\n }\n\n return {\n body: this.getBody(),\n url,\n headers,\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n headers: Record<string, string>;\n url: URL;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n if (\n this.props.inputBody.length === 1 &&\n this.props.inputBody[0] === '$body'\n ) {\n return JSON.stringify(this.input.$body);\n }\n\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n body.set(prop, toWireValue(this.input[prop]));\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n };\n }\n}\n\nclass EmptySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n body.append(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n Accept: 'application/json',\n };\n }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props);\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props);\n}\nexport function empty(input: Input, props: Props) {\n return new EmptySerializer(input, props);\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props);\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n serializer: Serializer,\n): RequestConfig {\n const [method, path] = endpoint.split(' ');\n const input = serializer.serialize(path);\n return {\n url: input.url,\n init: {\n method: method,\n headers: new Headers(input.headers),\n ...(method === 'GET' ? {} : { body: input.body }),\n },\n };\n}\n", "export class APIResponse<Body = unknown, Status extends number = number> {\n static readonly status: number;\n readonly status: Status;\n data: Body;\n readonly headers: Headers;\n\n constructor(status: Status, headers: Headers, data: Body) {\n this.status = status;\n this.headers = headers;\n this.data = data;\n }\n\n static create<Body = unknown>(status: number, headers: Headers, data: Body) {\n return new this(status, headers, data);\n }\n}\n\nexport class APIError<Body, Status extends number = number> extends Error {\n static readonly status: number;\n readonly status: Status;\n data: Body;\n readonly headers: Headers;\n\n constructor(status: Status, headers: Headers, data: Body) {\n super(failureMessage(status, data));\n this.name = 'APIError';\n this.status = status;\n this.headers = headers;\n this.data = data;\n }\n\n static create<T>(status: number, headers: Headers, data: T) {\n return new this(status, headers, data);\n }\n}\n\nfunction failureMessage(status: number, data: unknown) {\n const summary = bodySummary(data);\n return summary\n ? `Request failed with status code ${status}: ${summary}`\n : `Request failed with status code ${status}`;\n}\n\n// Only text and JSON bodies read as a summary; a Blob, stream or FormData body\n// has none. The tag check holds across realms, where prototype checks do not.\nfunction bodySummary(data: unknown) {\n const tag = Object.prototype.toString.call(data);\n let text = '';\n if (typeof data === 'string') {\n text = data;\n } else if (tag === '[object Object]' || tag === '[object Array]') {\n text = JSON.stringify(data);\n }\n const line = text.replace(/\\s+/g, ' ').trim();\n return line.length > 200 ? `${line.slice(0, 200)}\u2026` : line;\n}\n\n// 2xx Success\nexport class Ok<T> extends APIResponse<T, 200> {\n static override readonly status = 200 as const;\n constructor(headers: Headers, data: T) {\n super(Ok.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\nexport class Created<T> extends APIResponse<T, 201> {\n static override status = 201 as const;\n constructor(headers: Headers, data: T) {\n super(Created.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Accepted<T> extends APIResponse<T, 202> {\n static override status = 202 as const;\n constructor(headers: Headers, data: T) {\n super(Accepted.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NoContent extends APIResponse<never, 204> {\n static override status = 204 as const;\n constructor(headers: Headers) {\n super(NoContent.status, headers, null as never);\n }\n static override create(\n status: number,\n headers: Headers,\n data?: unknown,\n ): NoContent {\n return new this(headers);\n }\n}\n\n// 4xx Client Errors\nexport class BadRequest<T> extends APIError<T, 400> {\n static override status = 400 as const;\n constructor(headers: Headers, data: T) {\n super(BadRequest.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Unauthorized<T = { message: string }> extends APIError<T, 401> {\n static override status = 401 as const;\n constructor(headers: Headers, data: T) {\n super(Unauthorized.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class PaymentRequired<T = { message: string }> extends APIError<T, 402> {\n static override status = 402 as const;\n constructor(headers: Headers, data: T) {\n super(PaymentRequired.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Forbidden<T = { message: string }> extends APIError<T, 403> {\n static override status = 403 as const;\n constructor(headers: Headers, data: T) {\n super(Forbidden.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NotFound<T = { message: string }> extends APIError<T, 404> {\n static override status = 404 as const;\n constructor(headers: Headers, data: T) {\n super(NotFound.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class MethodNotAllowed<T = { message: string }> extends APIError<\n T,\n 405\n> {\n static override status = 405 as const;\n constructor(headers: Headers, data: T) {\n super(MethodNotAllowed.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NotAcceptable<T = { message: string }> extends APIError<T, 406> {\n static override status = 406 as const;\n constructor(headers: Headers, data: T) {\n super(NotAcceptable.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Conflict<T = { message: string }> extends APIError<T, 409> {\n static override status = 409 as const;\n constructor(headers: Headers, data: T) {\n super(Conflict.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class Gone<T = { message: string }> extends APIError<T, 410> {\n static override status = 410 as const;\n constructor(headers: Headers, data: T) {\n super(Gone.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class PreconditionFailed<T = { message: string }> extends APIError<\n T,\n 412\n> {\n static override status = 412 as const;\n constructor(headers: Headers, data: T) {\n super(PreconditionFailed.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class UnprocessableEntity<\n T = { message: string; errors?: Record<string, string[]> },\n> extends APIError<T, 422> {\n static override status = 422 as const;\n constructor(headers: Headers, data: T) {\n super(UnprocessableEntity.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class TooManyRequests<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 429> {\n static override status = 429 as const;\n constructor(headers: Headers, data: T) {\n super(TooManyRequests.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {\n static override status = 413 as const;\n constructor(headers: Headers, data: T) {\n super(PayloadTooLarge.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class UnsupportedMediaType<T = { message: string }> extends APIError<\n T,\n 415\n> {\n static override status = 415 as const;\n constructor(headers: Headers, data: T) {\n super(UnsupportedMediaType.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\n// 5xx Server Errors\nexport class InternalServerError<T = { message: string }> extends APIError<\n T,\n 500\n> {\n static override status = 500 as const;\n constructor(headers: Headers, data: T) {\n super(InternalServerError.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class NotImplemented<T = { message: string }> extends APIError<T, 501> {\n static override status = 501 as const;\n constructor(headers: Headers, data: T) {\n super(NotImplemented.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class BadGateway<T = { message: string }> extends APIError<T, 502> {\n static override status = 502 as const;\n constructor(headers: Headers, data: T) {\n super(BadGateway.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class ServiceUnavailable<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 503> {\n static override status = 503 as const;\n constructor(headers: Headers, data: T) {\n super(ServiceUnavailable.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\nexport class GatewayTimeout<T = { message: string }> extends APIError<T, 504> {\n static override status = 504 as const;\n constructor(headers: Headers, data: T) {\n super(GatewayTimeout.status, headers, data);\n }\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(headers, data);\n }\n}\n\nexport type ClientError =\n | BadRequest<unknown>\n | Unauthorized<unknown>\n | PaymentRequired<unknown>\n | Forbidden<unknown>\n | NotFound<unknown>\n | MethodNotAllowed<unknown>\n | NotAcceptable<unknown>\n | Conflict<unknown>\n | Gone<unknown>\n | PreconditionFailed<unknown>\n | PayloadTooLarge<unknown>\n | UnsupportedMediaType<unknown>\n | UnprocessableEntity<unknown>\n | TooManyRequests<unknown>;\n\nexport type ServerError =\n | InternalServerError<unknown>\n | NotImplemented<unknown>\n | BadGateway<unknown>\n | ServiceUnavailable<unknown>\n | GatewayTimeout<unknown>;\n\nexport type ProblematicResponse = ClientError | ServerError;\n\nexport type SuccessfulResponse<T = unknown> =\n | Ok<T>\n | Created<T>\n | Accepted<T>\n | NoContent;\n\nexport type RebindSuccessPayload<Resp, New> =\n Resp extends Ok<infer _>\n ? Ok<New>\n : Resp extends Created<infer _>\n ? Created<New>\n : Resp extends Accepted<infer _>\n ? Accepted<New>\n : Resp extends NoContent\n ? NoContent\n : Resp extends SuccessfulResponse<infer _>\n ? APIResponse<New, Resp['status']>\n : never;\n", "export type SSEListener = (eventType: string) => AsyncIterable<string>;\n\nexport function sse(response: Response): SSEListener {\n\tconst subscribers = new Map<\n\t\tstring,\n\t\t{ queue: string[]; resolve: (() => void) | null }\n\t>();\n\tlet started = false;\n\tlet streamDone = false;\n\tlet streamFailure: { error: unknown } | null = null;\n\n\tfunction dispatch(eventType: string, data: string) {\n\t\tconst sub = subscribers.get(eventType);\n\t\tif (sub) {\n\t\t\tsub.queue.push(data);\n\t\t\tsub.resolve?.();\n\t\t\tsub.resolve = null;\n\t\t}\n\t}\n\n\tfunction endAll() {\n\t\tstreamDone = true;\n\t\tfor (const sub of subscribers.values()) {\n\t\t\tsub.resolve?.();\n\t\t}\n\t}\n\n\tfunction startReading() {\n\t\tif (started) return;\n\t\tstarted = true;\n\t\tconst decoder = new TextDecoder();\n\t\tlet buffer = \"\";\n\n\t\t// The pump never rejects: the catch below hands a stream failure to the\n\t\t// listeners, so nothing awaits it. `void` states that, and keeps generated\n\t\t// output clean under @typescript-eslint/no-floating-promises.\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tfor await (const value of response.body!) {\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tconst parts = buffer.split(\"\\n\\n\");\n\t\t\t\t\tbuffer = parts.pop()!;\n\n\t\t\t\t\tfor (const part of parts) {\n\t\t\t\t\t\tif (!part.trim()) continue;\n\t\t\t\t\t\tlet eventType = \"message\";\n\t\t\t\t\t\tlet data = \"\";\n\t\t\t\t\t\tfor (const line of part.split(\"\\n\")) {\n\t\t\t\t\t\t\tif (line.startsWith(\"event:\")) {\n\t\t\t\t\t\t\t\teventType = line.slice(6).trim();\n\t\t\t\t\t\t\t} else if (line.startsWith(\"data:\")) {\n\t\t\t\t\t\t\t\tdata += (data ? \"\\n\" : \"\") + line.slice(5).trim();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (data) dispatch(eventType, data);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tstreamFailure = { error };\n\t\t\t}\n\t\t\tendAll();\n\t\t})();\n\t}\n\n\treturn function listen(eventType: string): AsyncIterable<string> {\n\t\tif (!subscribers.has(eventType)) {\n\t\t\tsubscribers.set(eventType, { queue: [], resolve: null });\n\t\t}\n\t\tconst sub = subscribers.get(eventType)!;\n\t\tstartReading();\n\n\t\treturn {\n\t\t\t[Symbol.asyncIterator]() {\n\t\t\t\treturn {\n\t\t\t\t\tasync next(): Promise<IteratorResult<string>> {\n\t\t\t\t\t\twhile (sub.queue.length === 0) {\n\t\t\t\t\t\t\tif (streamFailure) throw streamFailure.error;\n\t\t\t\t\t\t\tif (streamDone) return { value: undefined as any, done: true };\n\t\t\t\t\t\t\tconst { promise, resolve } = Promise.withResolvers<void>();\n\t\t\t\t\t\t\tsub.resolve = resolve;\n\t\t\t\t\t\t\tawait promise;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { value: sub.queue.shift()!, done: false };\n\t\t\t\t\t},\n\t\t\t\t\tasync return(): Promise<IteratorResult<string>> {\n\t\t\t\t\t\treturn { value: undefined as any, done: true };\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t},\n\t\t};\n\t};\n}\n", "type CursorPaginationParams = {\n cursor?: string;\n};\n\ninterface CursorMetadata extends Metadata {\n nextCursor?: string;\n}\n\ninterface Metadata {\n hasMore?: boolean;\n}\n\ntype PaginationRequestOptions = {\n signal?: AbortSignal;\n};\n\ntype PaginationResult<T, M extends CursorMetadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<T, M extends CursorMetadata> = (\n input: CursorPaginationParams,\n requestOptions?: PaginationRequestOptions,\n) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class CursorPagination<T, M extends CursorMetadata> {\n #meta: PaginationResult<T, M>['meta'] | null = null;\n #params: CursorPaginationParams;\n #currentPage: Page<T> | null = null;\n readonly #fetchFn: FetchFn<T, M>;\n readonly #requestOptions: PaginationRequestOptions;\n\n constructor(\n initialParams: PartialNullable<CursorPaginationParams>,\n fetchFn: FetchFn<T, M>,\n requestOptions: PaginationRequestOptions = {},\n ) {\n this.#fetchFn = fetchFn;\n this.#requestOptions = requestOptions;\n this.#params = initialParams.cursor == null ? {} : { cursor: initialParams.cursor };\n }\n\n async getNextPage(requestOptions?: PaginationRequestOptions) {\n if (this.#meta?.hasMore && this.#meta.nextCursor == null) {\n throw new Error('Cannot fetch the next page: the response has more items but no next cursor.');\n }\n const result = await this.#fetchFn(this.#params, {\n ...this.#requestOptions,\n ...requestOptions,\n });\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = result.meta.nextCursor === undefined ? {} : { cursor: result.meta.nextCursor };\n return this;\n }\n\n getCurrentPage() {\n if (!this.#currentPage) {\n throw new Error(\n 'No page data available. Please call getNextPage() first.',\n );\n }\n return this.#currentPage;\n }\n\n get hasMore() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta.hasMore;\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iter()) {\n yield page.getCurrentPage();\n }\n }\n\n async *iter(requestOptions?: PaginationRequestOptions) {\n if (!this.#currentPage) {\n yield await this.getNextPage(requestOptions);\n }\n\n while (this.hasMore) {\n yield await this.getNextPage(requestOptions);\n }\n }\n\n get metadata() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta;\n }\n}\n\nclass Page<T> {\n data: T[];\n constructor(data: T[]) {\n this.data = data;\n }\n}\n\ntype PartialNullable<T> = {\n [K in keyof T]?: T[K] | null | undefined;\n};\n", "type OffsetPaginationParams = {\n offset: number;\n limit: number;\n};\n\ninterface Metadata {\n hasMore?: boolean;\n}\n\ntype PaginationRequestOptions = {\n signal?: AbortSignal;\n};\n\ntype PaginationResult<T, M extends Metadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<T, M extends Metadata> = (\n input: OffsetPaginationParams,\n requestOptions?: PaginationRequestOptions,\n) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class OffsetPagination<T, M extends Metadata> {\n #meta: PaginationResult<T, M>['meta'] | null = null;\n #params: OffsetPaginationParams;\n #currentPage: Page<T> | null = null;\n readonly #fetchFn: FetchFn<T, M>;\n readonly #requestOptions: PaginationRequestOptions;\n\n constructor(\n initialParams: { offset?: number | null | undefined; limit?: number | null | undefined },\n fetchFn: FetchFn<T, M>,\n requestOptions: PaginationRequestOptions = {},\n ) {\n this.#fetchFn = fetchFn;\n this.#requestOptions = requestOptions;\n this.#params = {\n limit: initialParams.limit ?? 0,\n offset: initialParams.offset ?? 0,\n };\n }\n\n async getNextPage(requestOptions?: PaginationRequestOptions) {\n const result = await this.#fetchFn(this.#params, {\n ...this.#requestOptions,\n ...requestOptions,\n });\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n offset: this.#params.offset + this.#params.limit,\n };\n return this;\n }\n\n getCurrentPage() {\n if (!this.#currentPage) {\n throw new Error(\n 'No page data available. Please call getNextPage() first.',\n );\n }\n return this.#currentPage;\n }\n\n get hasMore() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta.hasMore;\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iter()) {\n yield page.getCurrentPage();\n }\n }\n\n async *iter(requestOptions?: PaginationRequestOptions) {\n if (!this.#currentPage) {\n yield await this.getNextPage(requestOptions);\n }\n\n while (this.hasMore) {\n yield await this.getNextPage(requestOptions);\n }\n }\n\n get metadata() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta;\n }\n\n reset(params?: Partial<OffsetPaginationParams>) {\n this.#meta = null;\n this.#currentPage = null;\n if (params) {\n this.#params = { ...this.#params, ...params };\n } else {\n this.#params.offset = 0;\n }\n return this;\n }\n}\n\nclass Page<T> {\n data: T[];\n constructor(data: T[]) {\n this.data = data;\n }\n}\n", "type InferPage<T> = T extends Page<infer U> ? U : never;\ntype PaginationParams<P extends number | bigint | null, S extends number | bigint | null> = {\n page?: P;\n pageSize?: S;\n};\n\ninterface Metadata {\n hasMore?: boolean;\n}\n\ntype PaginationRequestOptions = {\n signal?: AbortSignal;\n};\n\ntype PaginationResult<T, M extends Metadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<\n T,\n M extends Metadata,\n P extends number | bigint | null,\n S extends number | bigint | null,\n> = (\n input: Partial<PaginationParams<P, S>>,\n requestOptions?: PaginationRequestOptions,\n) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class Pagination<\n T,\n M extends Metadata,\n P extends number | bigint | null,\n S extends number | bigint | null,\n> {\n #meta: PaginationResult<T, M>['meta'] | null = null;\n #params: PaginationParams<P, S>;\n #currentPage: Page<T> | null = null;\n readonly #fetchFn: FetchFn<T, M, P, S>;\n readonly #requestOptions: PaginationRequestOptions;\n\n constructor(\n initialParams: { page?: P | undefined; pageSize?: S | undefined },\n fetchFn: FetchFn<T, M, P, S>,\n requestOptions: PaginationRequestOptions = {},\n ) {\n this.#fetchFn = fetchFn;\n this.#requestOptions = requestOptions;\n this.#params = {\n ...(initialParams.page === undefined ? {} : { page: initialParams.page }),\n ...(initialParams.pageSize === undefined ? {} : { pageSize: initialParams.pageSize }),\n };\n }\n\n async getNextPage(requestOptions?: PaginationRequestOptions) {\n const result = await this.#fetchFn(this.#params, {\n ...this.#requestOptions,\n ...requestOptions,\n });\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n page: (((this.#params.page as number) || 0) + 1) as never,\n };\n return this;\n }\n\n getCurrentPage() {\n if (!this.#currentPage) {\n throw new Error(\n 'No page data available. Please call getNextPage() first.',\n );\n }\n return this.#currentPage;\n }\n\n get hasMore() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta.hasMore;\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iter()) {\n yield page.getCurrentPage();\n }\n }\n\n async *iter(requestOptions?: PaginationRequestOptions) {\n if (!this.#currentPage) {\n yield await this.getNextPage(requestOptions);\n }\n\n while (this.hasMore) {\n yield await this.getNextPage(requestOptions);\n }\n }\n\n get metadata() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta;\n }\n}\n\nclass Page<T> {\n data: T[];\n constructor(data: T[]) {\n this.data = data;\n }\n}\n", "import { isEmpty } from '@sdk-it/core';\nimport type { Generator } from '@sdk-it/readme';\nimport { type IR, forEachOperation } from '@sdk-it/spec';\n\nimport { PropEmitter } from './prop.emitter.ts';\n\nexport function toReadme(spec: IR, generator: Generator) {\n const propEmitter = new PropEmitter(spec);\n const markdown: string[] = [];\n\n // Add TypeScript SDK heading and description\n markdown.push(`# ${spec.info.title} TypeScript SDK`);\n markdown.push('');\n markdown.push(\n 'A fully-typed TypeScript SDK with comprehensive IntelliSense support, automatic request/response validation, and modern async/await patterns. Built for seamless integration with TypeScript and JavaScript projects. Each endpoint includes a brief description, example usage, and details about request and response formats.',\n );\n\n markdown.push('');\n\n markdown.push(generator.clientSetupDocs());\n markdown.push('');\n\n // Add authentication docs if there are security schemes\n const securitySchemes = spec.components?.securitySchemes || {};\n if (Object.keys(securitySchemes).length > 0) {\n markdown.push(generator.authenticationDocs());\n markdown.push('');\n }\n\n // Add pagination docs if any operations have pagination\n const paginationDocs = generator.paginationDocs();\n if (paginationDocs) {\n markdown.push(paginationDocs);\n markdown.push('');\n }\n\n // Add error handling docs\n markdown.push(generator.errorHandlingDocs());\n markdown.push('');\n\n // Add general usage docs\n markdown.push(generator.generalUsageDocs());\n markdown.push('');\n\n markdown.push('## API Reference');\n markdown.push('');\n\n forEachOperation(spec, (entry, operation) => {\n const { method, path } = entry;\n markdown.push(\n `### ${operation['x-fn-name']} | ${`_${method.toUpperCase()} ${path}_`}`,\n );\n markdown.push(operation.summary || '');\n\n const snippet = generator.snippet(entry, operation);\n markdown.push(`#### Example usage`);\n markdown.push(snippet);\n\n const requestBodyContent = propEmitter.requestBody(operation.requestBody);\n if (requestBodyContent.length > 1) {\n // Check if more than just the header was added\n markdown.push(requestBodyContent.join('\\n\\n'));\n }\n\n markdown.push(`#### Output`);\n for (const status in operation.responses) {\n const response = operation.responses[status];\n\n if (!isEmpty(response.content)) {\n const contentEntries = Object.entries(response.content);\n\n if (contentEntries.length === 1) {\n const [contentType, mediaType] = contentEntries[0];\n markdown.push(`**${status}** - ${response.description}`);\n markdown.push(`\\n**Content Type:** \\`${contentType}\\``);\n\n if (mediaType.schema) {\n const schemaDocs = propEmitter.handle(mediaType.schema);\n markdown.push(...schemaDocs);\n }\n } else {\n // Multiple content types - use collapsible toggle for the entire response\n markdown.push(`<details>`);\n markdown.push(\n `<summary><b>${status}</b> <i>${response.description}</i></summary>`,\n );\n\n for (const [contentType, mediaType] of contentEntries) {\n markdown.push(`\\n**Content Type:** \\`${contentType}\\``);\n if (mediaType.schema) {\n const schemaDocs = propEmitter.handle(mediaType.schema);\n markdown.push(...schemaDocs.map((l) => `\\n${l}`));\n }\n }\n\n markdown.push(`</details>`);\n }\n } else {\n // No content - just show status and description\n markdown.push(`**${status}** - ${response.description}`);\n }\n }\n }); // Add schemas section at the bottom\n if (spec.components?.schemas) {\n markdown.push('## Schemas');\n markdown.push('');\n\n for (const [schemaName, schema] of Object.entries(\n spec.components.schemas,\n )) {\n // Include all schemas except ValidationError which is internal\n if (schemaName === 'ValidationError') {\n continue;\n }\n\n markdown.push(`<details>`);\n markdown.push(\n `<summary><h3 id=\"${schemaName.toLowerCase()}\">${schemaName}</h3></summary>`,\n );\n markdown.push('');\n\n const schemaDocs = propEmitter.handle(schema);\n markdown.push(...schemaDocs.map((line) => line.trim()));\n\n markdown.push('');\n markdown.push(`</details>`);\n markdown.push('');\n }\n }\n\n // Generate Table of Contents\n\n return markdown.join('\\n\\n');\n}\n", "import type {\n ReferenceObject,\n RequestBodyObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { type OpenAPIDocument, followRef, isRef } from '@sdk-it/core';\nimport { coerceTypes } from '@sdk-it/spec';\n\n/**\n * PropEmitter handles converting OpenAPI schemas to Markdown documentation\n */\nexport class PropEmitter {\n #spec: OpenAPIDocument;\n\n constructor(spec: OpenAPIDocument) {\n this.#spec = spec;\n }\n\n /**\n * Handle objects (properties)\n */\n #object(schema: SchemaObject): string[] {\n const lines: string[] = [];\n const properties = schema.properties || {};\n\n if (Object.keys(properties).length > 0) {\n lines.push(`**Properties:**`);\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const isRequired = (schema.required ?? []).includes(propName);\n lines.push(...this.#property(propName, propSchema, isRequired));\n }\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n lines.push(`**Additional Properties:**`);\n if (typeof schema.additionalProperties === 'boolean') {\n lines.push(`- Allowed: ${schema.additionalProperties}`);\n } else {\n // Indent the schema documentation for additional properties\n lines.push(\n ...this.handle(schema.additionalProperties).map((l) => ` ${l}`),\n );\n }\n }\n\n return lines;\n }\n\n /**\n * Format a property with its type and description\n */\n #property(\n name: string,\n schema: SchemaObject | ReferenceObject,\n required: boolean,\n ): string[] {\n // get full docs and extract the type line\n const docs = this.handle(schema);\n const rawType = docs[0]\n .replace('**Type:** ', '')\n .replace(' (nullable)', '|null');\n\n // detect default if present on the schema\n const defaultVal =\n !isRef(schema) && (schema as SchemaObject).default !== undefined\n ? ` default: ${JSON.stringify((schema as SchemaObject).default)}`\n : '';\n\n // build summary line\n const reqMark = required ? ' required' : '';\n const summary = `- \\`${name}\\` ${rawType}${reqMark}${defaultVal}:`;\n\n // assemble final lines (skip the type and any default in details)\n const detailLines = docs\n .slice(1)\n .filter((it) => !it.startsWith('**Default:**'))\n .map((it) => ` ${it}`);\n\n return [summary, ...detailLines];\n }\n\n /**\n * Handle array schemas\n */\n #array(schema: SchemaObject): string[] {\n const lines: string[] = [];\n lines.push(`**Array items:**`);\n\n if (schema.items) {\n // Get documentation for the items schema\n const itemDocs = this.handle(schema.items);\n // Indent item documentation\n lines.push(...itemDocs.map((line) => ` ${line}`));\n } else {\n lines.push(` **Type:** \\`unknown\\``); // Array of unknown items\n }\n // Add array constraints\n if (schema.minItems !== undefined)\n lines.push(`- Minimum items: ${schema.minItems}`);\n if (schema.maxItems !== undefined)\n lines.push(`- Maximum items: ${schema.maxItems}`);\n if (schema.uniqueItems) lines.push(`- Items must be unique.`);\n\n return lines;\n }\n\n #ref($ref: string): string[] {\n const schemaName = $ref.split('/').pop() || 'object';\n const resolved = followRef<SchemaObject>(this.#spec, $ref);\n // Link to the schema definition (assuming heading anchors are generated elsewhere)\n const lines = [\n `**Type:** [\\`${schemaName}\\`](#${schemaName.toLowerCase()})`,\n ];\n if (resolved.description) {\n lines.push(resolved.description);\n }\n // Avoid deep recursion by default, just link and show description.\n // If more detail is needed, the linked definition should provide it.\n return lines;\n }\n\n #allOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**All of (Intersection):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Constraint ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`)); // Indent sub-schema docs\n });\n return lines;\n }\n\n #anyOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**Any of (Union):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Option ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`));\n });\n return lines;\n }\n\n #oneOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**One of (Exclusive Union):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Option ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`));\n });\n return lines;\n }\n\n #enum(schema: SchemaObject): string[] {\n const lines = [`**Type:** \\`${schema.type || 'unknown'}\\` (enum)`];\n if (schema.description) lines.push(schema.description);\n lines.push('**Allowed values:**');\n lines.push(\n ...(schema.enum || []).map((val) => `- \\`${JSON.stringify(val)}\\``),\n );\n if (schema.default !== undefined) {\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n }\n return lines;\n }\n\n #normal(type: string, schema: SchemaObject, nullable: boolean): string[] {\n const lines: string[] = [];\n const nullableSuffix = nullable ? ' (nullable)' : '';\n const description = schema.description ? [schema.description] : [];\n\n switch (type) {\n case 'string':\n lines.push(\n `**Type:** \\`string\\`${schema.format ? ` (format: ${schema.format})` : ''}${nullableSuffix}`,\n );\n lines.push(...description);\n if (schema.minLength !== undefined)\n lines.push(`- Minimum length: ${schema.minLength}`);\n if (schema.maxLength !== undefined)\n lines.push(`- Maximum length: ${schema.maxLength}`);\n if (schema.pattern !== undefined)\n lines.push(`- Pattern: \\`${schema.pattern}\\``);\n break;\n case 'number':\n case 'integer':\n lines.push(\n `**Type:** \\`${type}\\`${schema.format ? ` (format: ${schema.format})` : ''}${nullableSuffix}`,\n );\n lines.push(...description);\n // Add number constraints (OpenAPI 3.1)\n if (schema.minimum !== undefined) {\n // Check if exclusiveMinimum is a number (OAS 3.1)\n const exclusiveMin = typeof schema.exclusiveMinimum === 'number';\n lines.push(\n `- Minimum: ${schema.minimum}${exclusiveMin ? ' (exclusive)' : ''}`,\n );\n if (exclusiveMin) {\n lines.push(\n `- Must be strictly greater than: ${schema.exclusiveMinimum}`,\n );\n }\n } else if (typeof schema.exclusiveMinimum === 'number') {\n lines.push(\n `- Must be strictly greater than: ${schema.exclusiveMinimum}`,\n );\n }\n\n if (schema.maximum !== undefined) {\n // Check if exclusiveMaximum is a number (OAS 3.1)\n const exclusiveMax = typeof schema.exclusiveMaximum === 'number';\n lines.push(\n `- Maximum: ${schema.maximum}${exclusiveMax ? ' (exclusive)' : ''}`,\n );\n if (exclusiveMax) {\n lines.push(\n `- Must be strictly less than: ${schema.exclusiveMaximum}`,\n );\n }\n } else if (typeof schema.exclusiveMaximum === 'number') {\n lines.push(\n `- Must be strictly less than: ${schema.exclusiveMaximum}`,\n );\n }\n if (schema.multipleOf !== undefined)\n lines.push(`- Must be a multiple of: ${schema.multipleOf}`);\n break;\n case 'boolean':\n lines.push(`**Type:** \\`boolean\\`${nullableSuffix}`);\n lines.push(...description);\n break;\n case 'object':\n lines.push(`**Type:** \\`object\\`${nullableSuffix}`);\n lines.push(...description);\n lines.push(...this.#object(schema));\n break;\n case 'array':\n lines.push(`**Type:** \\`array\\`${nullableSuffix}`);\n lines.push(...description);\n lines.push(...this.#array(schema));\n break;\n case 'null':\n lines.push(`**Type:** \\`null\\``);\n lines.push(...description);\n break;\n default:\n lines.push(`**Type:** \\`${type}\\`${nullableSuffix}`);\n lines.push(...description);\n }\n if (schema.default !== undefined) {\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n }\n return lines.filter((l) => l); // Filter out empty description lines\n }\n\n /**\n * Handle schemas by resolving references and delegating to appropriate handler\n */\n public handle(schemaOrRef: SchemaObject | ReferenceObject): string[] {\n if (isRef(schemaOrRef)) {\n return this.#ref(schemaOrRef.$ref);\n }\n\n const schema = schemaOrRef;\n\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.#allOf(schema.allOf);\n }\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.#anyOf(schema.anyOf);\n }\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.#oneOf(schema.oneOf);\n }\n\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.#enum(schema);\n }\n\n let types = coerceTypes(schema);\n let nullable = false; // Default to false\n\n if (types.includes('null')) {\n nullable = true;\n types = types.filter((t) => t !== 'null');\n }\n\n if (types.length === 0) {\n if (schema.properties || schema.additionalProperties) {\n types = ['object'];\n } else if (schema.items) {\n types = ['array'];\n }\n }\n\n if (types.length === 0) {\n const lines = ['**Type:** `unknown`'];\n if (schema.description) lines.push(schema.description);\n if (schema.default !== undefined)\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n return lines;\n }\n\n // Handle single type (potentially nullable)\n if (types.length === 1) {\n return this.#normal(types[0], schema, nullable);\n }\n\n // Handle union of multiple non-null types (potentially nullable overall)\n const typeString = types.join(' | ');\n const nullableSuffix = nullable ? ' (nullable)' : '';\n const lines = [`**Type:** \\`${typeString}\\`${nullableSuffix}`];\n if (schema.description) lines.push(schema.description);\n if (schema.default !== undefined)\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n return lines;\n }\n\n /**\n * Process a request body and return markdown documentation\n */\n requestBody(requestBody: RequestBodyObject): string[] {\n const lines: string[] = [];\n lines.push(`#### Input`);\n lines.push(requestBody.description || '');\n\n const contentEntries = Object.entries(requestBody.content);\n const multipleContentTypes = contentEntries.length > 1;\n if (multipleContentTypes) {\n // Use collapsible toggles\n for (const [contentType, mediaType] of contentEntries) {\n lines.push(`<details>`);\n lines.push(`<summary>Content Type: \\`${contentType}\\`</summary>`);\n lines.push('');\n\n if (mediaType.schema) {\n const schemaDocs = this.handle(mediaType.schema);\n lines.push(...schemaDocs.map((l) => l));\n }\n\n lines.push('');\n lines.push(`</details>`);\n }\n } else {\n // Single content type - show inline\n const [contentType, mediaType] = contentEntries[0];\n lines.push(`Content Type: \\`${contentType}\\``);\n\n if (mediaType.schema) {\n const schemaDocs = this.handle(mediaType.schema);\n lines.push(...schemaDocs);\n }\n }\n\n return lines;\n }\n}\n", "import type { Spec } from './sdk.ts';\n\nexport default (spec: Pick<Spec, 'makeImport' | 'securitySchemes'>) => {\n const securitySchemes = JSON.stringify(spec.securitySchemes, null, 2);\n const credentialProperties = Object.entries(spec.securitySchemes)\n .map(([name, scheme]) => {\n const schema =\n scheme.type === 'mutualTLS'\n ? 'mutualTlsCredentialSchema'\n : scheme.type === 'http' && scheme.scheme?.toLowerCase() === 'basic'\n ? 'basicCredentialSchema'\n : 'stringCredentialSchema';\n return `${JSON.stringify(name)}: ${schema}.optional()`;\n })\n .join(',\\n');\n\n return `import z from 'zod';\nimport type { Interceptor } from './${spec.makeImport('interceptors')}';\nimport type { RequestConfig } from './${spec.makeImport('request')}';\n\nexport type SecurityContext = {\n scheme: string;\n scopes: readonly string[];\n roles: readonly string[];\n};\nexport type SecurityCredentialValue = string | true | {\n username: string;\n password: string;\n};\nexport type SecurityCredentialProvider<T extends SecurityCredentialValue> = (\n context: SecurityContext\n) => T | Promise<T>;\nexport type SecurityCredential<\n T extends SecurityCredentialValue = SecurityCredentialValue,\n> = T | SecurityCredentialProvider<T>;\n\nconst providerSchema = <T extends SecurityCredentialValue>() =>\n z.custom<SecurityCredentialProvider<T>>((value) => typeof value === 'function');\nconst stringCredentialSchema = z.union([\n z.string(),\n z.literal(true),\n providerSchema<string | true>(),\n]);\nconst basicCredentialValueSchema = z.object({\n username: z.string(),\n password: z.string(),\n});\nconst basicCredentialSchema = z.union([\n basicCredentialValueSchema,\n z.literal(true),\n providerSchema<{ username: string; password: string } | true>(),\n]);\nconst mutualTlsCredentialSchema = z.union([\n z.literal(true),\n providerSchema<true>(),\n]);\nexport const credentialsSchema = z.object({${credentialProperties}});\n\ntype RuntimeSecurityScheme =\n | { type: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }\n | { type: 'http'; scheme: string }\n | { type: 'oauth2' }\n | { type: 'openIdConnect' }\n | { type: 'mutualTLS' };\nconst securitySchemes = ${securitySchemes} as const;\n\nexport function createSecurityInterceptor(\n requirements: readonly Record<string, readonly string[]>[],\n credentials: Record<string, SecurityCredential | undefined> | undefined,\n): Interceptor {\n return {\n async before(config) {\n if (requirements.length === 0) return config;\n const secured = requirements.filter(\n (requirement) => Object.keys(requirement).length > 0,\n );\n const selected = secured.find((requirement) =>\n Object.keys(requirement).every(\n (name) => credentials?.[name] !== undefined,\n ),\n );\n if (!selected) {\n if (requirements.some(\n (requirement) => Object.keys(requirement).length === 0,\n )) return config;\n throw new Error(\n \\`Missing credentials for security requirements: \\${secured\n .map((requirement) => Object.keys(requirement).join(' + '))\n .join(' or ')}\\`,\n );\n }\n for (const [name, values] of Object.entries(selected)) {\n const scheme = securitySchemes[\n name as keyof typeof securitySchemes\n ] as RuntimeSecurityScheme | undefined;\n if (!scheme) {\n throw new Error(\\`Unsupported external security scheme: \\${name}\\`);\n }\n const configured = credentials?.[name];\n const isOAuth = scheme.type === 'oauth2' || scheme.type === 'openIdConnect';\n const credential = typeof configured === 'function'\n ? await configured({\n scheme: name,\n scopes: isOAuth ? values : [],\n roles: isOAuth ? [] : values,\n })\n : configured;\n applyCredential(config, scheme, credential);\n }\n return config;\n },\n };\n}\n\nfunction applyCredential(\n config: RequestConfig,\n scheme: RuntimeSecurityScheme,\n credential: SecurityCredentialValue | undefined,\n) {\n if (credential === undefined) {\n throw new Error('Security credential provider returned no credential');\n }\n // true declares a transport-owned credential: the configured fetch, a host\n // proxy, or the browser's cookie jar supplies it, so nothing is set here.\n if (credential === true) return;\n if (scheme.type === 'apiKey') {\n if (typeof credential !== 'string') {\n throw new TypeError('API key credentials must be strings');\n }\n if (scheme.in === 'header') {\n if (!config.init.headers.has(scheme.name)) {\n config.init.headers.set(scheme.name, credential);\n }\n } else if (scheme.in === 'query') {\n if (!config.url.searchParams.has(scheme.name)) {\n config.url.searchParams.set(scheme.name, credential);\n }\n } else if (scheme.in === 'cookie') {\n if ('document' in globalThis) {\n throw new Error(\n \\`Cannot send the \\${scheme.name} cookie credential: browsers forbid setting the Cookie header. Let the browser send the cookie and pass a fetch that sets credentials: 'include'.\\`,\n );\n }\n const cookie = \\`\\${scheme.name}=\\${encodeURIComponent(credential)}\\`;\n const existing = config.init.headers.get('Cookie');\n if (!existing?.split(';').some((part) => part.trim().startsWith(\\`\\${scheme.name}=\\`))) {\n config.init.headers.set('Cookie', existing ? \\`\\${existing}; \\${cookie}\\` : cookie);\n }\n } else {\n throw new TypeError(\\`Unsupported apiKey location: \\${String(scheme.in)}\\`);\n }\n return;\n }\n if (scheme.type === 'mutualTLS') {\n throw new TypeError('mutualTLS credentials must be true when the custom fetch owns the client certificate');\n }\n if (scheme.type === 'http' && scheme.scheme.toLowerCase() === 'basic') {\n if (\n typeof credential !== 'object' ||\n !('username' in credential) ||\n !('password' in credential)\n ) {\n throw new TypeError('Basic credentials require username and password');\n }\n const bytes = new TextEncoder().encode(\n \\`\\${credential.username}:\\${credential.password}\\`,\n );\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n if (!config.init.headers.has('Authorization')) {\n config.init.headers.set('Authorization', \\`Basic \\${btoa(binary)}\\`);\n }\n return;\n }\n if (typeof credential !== 'string') {\n throw new TypeError(\\`\\${scheme.type} credentials must be strings\\`);\n }\n const prefix = scheme.type === 'http' ? authorizationScheme(scheme.scheme) : 'Bearer';\n if (!config.init.headers.has('Authorization')) {\n config.init.headers.set('Authorization', \\`\\${prefix} \\${credential}\\`);\n }\n}\n\n// OpenAPI carries the lowercase registry name, while servers routinely match the\n// Authorization prefix case-sensitively (\\`header.startsWith('Bearer ')\\`).\nconst authorizationSchemes: Record<string, string> = {\n basic: 'Basic',\n bearer: 'Bearer',\n digest: 'Digest',\n hoba: 'HOBA',\n mutual: 'Mutual',\n negotiate: 'Negotiate',\n oauth: 'OAuth',\n 'scram-sha-1': 'SCRAM-SHA-1',\n 'scram-sha-256': 'SCRAM-SHA-256',\n};\n\nfunction authorizationScheme(scheme: string) {\n return authorizationSchemes[scheme.toLowerCase()] ?? scheme;\n}\n`;\n};\n", "import type { ServerObject } from 'openapi3-ts/oas31';\n\nexport function expandServerUrls(servers: ServerObject[]): string[] {\n return servers.flatMap((server) => {\n const variables = server.variables;\n if (!variables || Object.keys(variables).length === 0) {\n return [server.url];\n }\n\n const entries = Object.entries(variables);\n const valueSets = entries.map(([, variable]) => {\n const enumValues = variable.enum?.map(String);\n return enumValues?.length ? enumValues : [String(variable.default)];\n });\n\n const combinations = valueSets.reduce<string[][]>(\n (acc, values) => acc.flatMap((combo) => values.map((v) => [...combo, v])),\n [[]],\n );\n\n return combinations.map((combo) => {\n let url = server.url;\n for (let i = 0; i < entries.length; i++) {\n url = url.replaceAll(`{${entries[i][0]}}`, combo[i]);\n }\n return url;\n });\n });\n}\n", "import type { ResponseObject, SchemaObject } from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport {\n type OpenAPISecuritySchemeObject,\n isEmpty,\n pascalcase,\n resolveRef,\n} from '@sdk-it/core';\nimport { type Generator } from '@sdk-it/readme';\nimport {\n type IR,\n type OperationEntry,\n type OperationPagination,\n type TunedOperationObject,\n forEachOperation,\n patchParameters,\n} from '@sdk-it/spec';\n\nimport { SnippetEmitter } from './emitters/snippet.ts';\nimport type { TypeScriptGeneratorOptions } from './options.ts';\nimport { expandServerUrls } from './server-urls.ts';\n\nexport class TypeScriptSnippet implements Generator {\n #spec: IR;\n #snippetEmitter: SnippetEmitter;\n #clientName: string;\n #packageName: string;\n constructor(spec: IR, settings: TypeScriptGeneratorOptions) {\n this.#spec = spec;\n this.#snippetEmitter = new SnippetEmitter(spec);\n this.#clientName = settings.name?.trim()\n ? pascalcase(settings.name)\n : 'Client';\n\n this.#packageName = settings.name\n ? `@${spinalcase(this.#clientName.toLowerCase())}/sdk`\n : 'sdk';\n }\n succinct(\n entry: OperationEntry,\n operation: TunedOperationObject,\n values: {\n requestBody?: Record<string, unknown>;\n pathParameters?: Record<string, unknown>;\n queryParameters?: Record<string, unknown>;\n headers?: Record<string, unknown>;\n cookies?: Record<string, unknown>;\n },\n ) {\n let payload = '{}';\n if (!isEmpty(operation.requestBody)) {\n const contentTypes = Object.keys(operation.requestBody.content || {});\n const schema = resolveRef(\n this.#spec,\n operation.requestBody.content[contentTypes[0]].schema,\n );\n\n const examplePayload = this.#snippetEmitter.handle({\n ...schema,\n properties: Object.assign({}, schema.properties, schema.properties),\n });\n // merge explicit values into the example payload\n Object.assign(\n examplePayload as Record<string, unknown>,\n values.requestBody ?? {},\n values.pathParameters ?? {},\n values.queryParameters ?? {},\n values.headers ?? {},\n values.cookies ?? {},\n );\n payload = examplePayload as any;\n } else {\n const requestBody: SchemaObject = { type: 'object', properties: {} };\n patchParameters(this.#spec, requestBody, operation.parameters);\n const examplePayload = this.#snippetEmitter.handle(requestBody);\n // merge explicit values into the example payload\n Object.assign(\n examplePayload as Record<string, unknown>,\n values.pathParameters ?? {},\n values.queryParameters ?? {},\n values.headers ?? {},\n values.cookies ?? {},\n );\n payload = examplePayload as any;\n }\n payload = JSON.stringify(\n payload,\n (key, value) => {\n if (value?.startsWith && value.startsWith('new')) {\n return `__REPLACE_${Math.random().toString(36).substring(2, 11)}__${value}__REPLACE_END__`;\n }\n return value;\n },\n 2,\n ).replace(/\"__REPLACE_[^\"]*__([^\"]*?)__REPLACE_END__\"/g, '$1');\n\n let successResponse: ResponseObject | undefined;\n for (const status in operation.responses) {\n if (status.startsWith('2')) {\n successResponse = operation.responses[status] as ResponseObject;\n break;\n }\n }\n\n if (successResponse) {\n if (successResponse.headers?.['Transfer-Encoding']) {\n return this.#httpStreaming(entry, payload);\n }\n if (\n successResponse.content &&\n successResponse.content['application/octet-stream']\n ) {\n return this.#streamDownload(entry, payload);\n }\n }\n\n if (!isEmpty(operation['x-pagination'])) {\n return this.#pagination(operation, entry, payload);\n }\n return this.#normal(entry, payload);\n }\n\n #pagination(\n operation: TunedOperationObject,\n entry: OperationEntry,\n payload: string,\n ) {\n const pagination: OperationPagination = operation['x-pagination'];\n switch (pagination.type) {\n case 'page':\n return {\n content: `const controller = new AbortController();\\nconst result = await ${camelcase(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload}, { signal: controller.signal });`,\n footer: `for await (const page of result.iter({ signal: controller.signal })) {\\n\\t\\tconsole.log(page);\\n}`,\n };\n case 'offset':\n return {\n content: `const controller = new AbortController();\\nconst result = await ${camelcase(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload}, { signal: controller.signal });`,\n footer: `for await (const page of result.iter({ signal: controller.signal })) {\\n\\t\\tconsole.log(page);\\n}`,\n };\n case 'cursor':\n return {\n content: `const controller = new AbortController();\\nconst result = await ${camelcase(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload}, { signal: controller.signal });`,\n footer: `for await (const page of result.iter({ signal: controller.signal })) {\\n\\t\\tconsole.log(page);\\n}`,\n };\n }\n return this.#normal(entry, payload);\n }\n\n #normal(entry: OperationEntry, payload: string) {\n return {\n content: `const result = ${this.#toRequest(entry, payload)};`,\n footer: 'console.log(result.data)',\n };\n }\n\n #streamDownload(entry: OperationEntry, payload: string) {\n return {\n content: `const stream = ${this.#toRequest(entry, payload)}`,\n footer: `await writeFile('./report.pdf', stream);`,\n };\n }\n\n #httpStreaming(entry: OperationEntry, payload: string) {\n return {\n content: `const stream = ${this.#toRequest(entry, payload)}`,\n footer: `for await (const chunk of stream) {\\n\\t\\tconsole.log(chunk);\\n}`,\n };\n }\n\n #toRequest(entry: OperationEntry, payload: string) {\n return `await ${camelcase(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload});`;\n }\n\n snippet(\n entry: OperationEntry,\n operation: TunedOperationObject,\n config: Record<string, unknown> = {},\n ) {\n const payload = this.succinct(entry, operation, config);\n const content: string[] = [\n this.client(),\n '',\n payload.content,\n '',\n payload.footer,\n ];\n if (config.frame !== false) {\n return createCodeBlock('typescript', content);\n }\n return content.join('\\n');\n }\n\n #authentication() {\n const names = new Set<string>();\n for (const requirement of this.#spec.security ?? []) {\n for (const name of Object.keys(requirement)) names.add(name);\n }\n forEachOperation(this.#spec, (_entry, operation) => {\n for (const requirement of operation.security ?? []) {\n for (const name of Object.keys(requirement)) names.add(name);\n }\n });\n return [...names].flatMap((name) => {\n // Requirement names may be external URI references with no local scheme.\n const scheme = this.#spec.components.securitySchemes[name];\n return scheme\n ? [\n {\n name,\n scheme: resolveRef<OpenAPISecuritySchemeObject>(\n this.#spec,\n scheme,\n ),\n },\n ]\n : [];\n });\n }\n\n #credentialExample(\n scheme: OpenAPISecuritySchemeObject,\n ): string | boolean | { username: string; password: string } {\n if (scheme.type === 'mutualTLS') return true;\n if (scheme.type === 'http' && scheme.scheme?.toLowerCase() === 'basic') {\n return { username: 'user', password: 'password' };\n }\n if (scheme.type === 'apiKey') return 'test_api_key_1234567890abcdef';\n return 'test_access_token_1234567890abcdef';\n }\n\n client() {\n const servers = expandServerUrls(this.#spec.servers ?? []);\n const options: Record<string, unknown> = {};\n if (servers.length !== 1) {\n options.baseUrl = servers[0] ?? 'http://localhost:3000';\n }\n\n const authOptions = this.#authentication();\n if (!isEmpty(authOptions)) {\n const [firstAuth] = authOptions;\n options.credentials = {\n [firstAuth.name]: this.#credentialExample(firstAuth.scheme),\n };\n }\n\n const client = this.#constructClient(options);\n return `${client.import}\\n\\n${client.use}`;\n }\n\n #constructClient(options: Record<string, unknown> = {}) {\n return {\n import: `import { ${this.#clientName} } from '${this.#packageName}';`,\n use: `const ${camelcase(this.#clientName)} = new ${this.#clientName}({\\n\\t\\t${Object.entries(\n options,\n )\n .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)\n .join(',\\n\\t\\t')}\\n\\t});`,\n };\n }\n\n clientInstallDocs(): string {\n const sections: string[] = [];\n\n sections.push('## Installation');\n sections.push('');\n sections.push(\n createCodeBlock('bash', [`npm install ${this.#packageName}`]),\n );\n sections.push('');\n\n sections.push('## Basic Usage');\n sections.push('');\n sections.push(createCodeBlock('typescript', [this.client()]));\n\n return sections.join('\\n');\n }\n\n configurationOptions(): {\n sections: string[];\n hasServers: boolean;\n baseUrl: string;\n hasApiKey: boolean;\n } {\n const sections: string[] = [];\n const hasServers = Boolean(\n this.#spec.servers && this.#spec.servers.length > 0,\n );\n const baseUrl =\n expandServerUrls(this.#spec.servers ?? [])[0] ||\n 'https://api.example.com';\n\n const authOptions = this.#authentication();\n const hasApiKey = !isEmpty(authOptions);\n\n sections.push('### Configuration Options');\n sections.push('');\n sections.push('| Option | Type | Required | Description |');\n sections.push('|--------|------|----------|-------------|');\n sections.push(\n '| `fetch` | `fetch compatible` | No | Fetch implementation to use for HTTP requests |',\n );\n\n if (hasServers) {\n sections.push(\n '| `baseUrl` | `string | (() => string | Promise<string>)` | No | API base URL (default: `' +\n baseUrl +\n '`) |',\n );\n }\n\n if (hasApiKey) {\n sections.push(\n '| `credentials` | `Record<string, SecurityCredential>` | No | Credentials keyed by the exact OpenAPI security scheme name |',\n );\n }\n\n return { sections, hasServers, baseUrl, hasApiKey };\n }\n\n clientSetupDocs(): string {\n const sections: string[] = [];\n\n // Use the dedicated install docs method\n sections.push(this.clientInstallDocs());\n sections.push('');\n\n // Use the configuration options method\n const config = this.configurationOptions();\n sections.push(...config.sections);\n sections.push('');\n\n // Add configuration update documentation\n sections.push(this.configurationUpdateDocs());\n\n return sections.join('\\n');\n }\n\n paginationDocs(): string {\n const paginationTypes = availablePaginationTypes(this.#spec);\n\n if (\n !paginationTypes.offset &&\n !paginationTypes.page &&\n !paginationTypes.cursor\n ) {\n return '';\n }\n\n const sections: string[] = [];\n\n sections.push('## Pagination');\n sections.push('');\n sections.push(\n 'This SDK automatically handles pagination for endpoints that return multiple items.',\n );\n sections.push('');\n sections.push('### How it Works');\n sections.push('');\n sections.push(\n 'When you call a paginated endpoint, the SDK returns a pagination object that allows you to iterate through all results:',\n );\n sections.push('');\n\n // Generate examples for each available pagination type\n const availableTypes: Array<'offset' | 'page' | 'cursor'> = [];\n if (paginationTypes.offset) availableTypes.push('offset');\n if (paginationTypes.page) availableTypes.push('page');\n if (paginationTypes.cursor) availableTypes.push('cursor');\n\n // Use the first available type for the main example\n const primaryPaginationType = availableTypes[0];\n const mockPaginatedOperation = {\n 'x-pagination': { type: primaryPaginationType },\n tags: ['Products'],\n operationId: 'listProducts',\n parameters: [],\n 'x-fn-name': 'listProducts',\n responses: {},\n requestBody: {} as TunedOperationObject['requestBody'],\n } as TunedOperationObject;\n const mockOperationEntry = {\n method: 'get' as const,\n path: '/products',\n tag: 'Products',\n } as OperationEntry;\n const initialRequestPayload = createObjectLiteral({ limit: 20 });\n const paginationExample = this.#pagination(\n mockPaginatedOperation,\n mockOperationEntry,\n initialRequestPayload,\n );\n\n sections.push(\n createCodeBlock('typescript', [\n '// The SDK automatically handles pagination',\n paginationExample.content,\n '',\n '// Access the current page data',\n 'const currentPage = result.getCurrentPage();',\n 'console.log(currentPage.data); // Array of product items',\n '',\n '// Check if more pages exist',\n 'if (result.hasMore) {',\n ' await result.getNextPage({ signal: controller.signal });',\n '}',\n '',\n '// Or iterate through all pages with cancellable page fetches',\n paginationExample.footer,\n ]),\n );\n sections.push('');\n\n sections.push('### Iterating Through All Pages');\n sections.push('');\n\n const iterationExample = this.#pagination(\n mockPaginatedOperation,\n mockOperationEntry,\n createObjectLiteral({ limit: 100 }),\n );\n sections.push(\n createCodeBlock('typescript', [\n '// Using async iteration to process all pages',\n iterationExample.content,\n '',\n iterationExample.footer,\n ]),\n );\n sections.push('');\n\n // Show pagination types section with examples for each available type\n if (availableTypes.length > 1) {\n sections.push('### Pagination Types');\n sections.push('');\n sections.push(\n 'Your API uses the following pagination strategies, automatically detected by the SDK:',\n );\n sections.push('');\n } else {\n sections.push('### Pagination Strategy');\n sections.push('');\n sections.push(\n 'Your API uses the following pagination strategy, automatically detected by the SDK:',\n );\n sections.push('');\n }\n\n // Generate specific examples for each available pagination type\n for (const paginationType of availableTypes) {\n const typeSpecificOperation = {\n 'x-pagination': { type: paginationType },\n tags: ['Products'],\n operationId: 'listProducts',\n parameters: [],\n 'x-fn-name': 'listProducts',\n responses: {},\n requestBody: {} as TunedOperationObject['requestBody'],\n } as TunedOperationObject;\n\n const typeSpecificEntry = {\n method: 'get' as const,\n path: '/products',\n tag: 'Products',\n } as OperationEntry;\n\n if (paginationType === 'cursor') {\n sections.push('#### Cursor Pagination');\n sections.push('');\n sections.push('Uses a cursor token to fetch the next page:');\n sections.push('');\n\n const cursorPaginationExample = this.#pagination(\n typeSpecificOperation,\n typeSpecificEntry,\n createObjectLiteral({ limit: 20 }),\n );\n\n sections.push(\n createCodeBlock('typescript', [\n cursorPaginationExample.content,\n '',\n '// Iterate through all pages using cursor',\n cursorPaginationExample.footer,\n ]),\n );\n sections.push('');\n }\n if (paginationType === 'offset') {\n sections.push('#### Offset Pagination');\n sections.push('');\n sections.push('Uses offset and limit parameters:');\n sections.push('');\n\n const offsetPaginationExample = this.#pagination(\n typeSpecificOperation,\n typeSpecificEntry,\n createObjectLiteral({ limit: 20, offset: 0 }),\n );\n\n sections.push(\n createCodeBlock('typescript', [\n offsetPaginationExample.content,\n '',\n '// Iterate through all pages using offset',\n offsetPaginationExample.footer,\n ]),\n );\n sections.push('');\n }\n if (paginationType === 'page') {\n sections.push('#### Page Pagination');\n sections.push('');\n sections.push('Uses page number and page size:');\n sections.push('');\n\n const pagePaginationExample = this.#pagination(\n typeSpecificOperation,\n typeSpecificEntry,\n createObjectLiteral({ page: 1, pageSize: 20 }),\n );\n\n sections.push(\n createCodeBlock('typescript', [\n pagePaginationExample.content,\n '',\n '// Iterate through all pages using page numbers',\n pagePaginationExample.footer,\n ]),\n );\n sections.push('');\n }\n }\n\n if (availableTypes.length > 1) {\n sections.push(\n 'The SDK handles the differences transparently, providing a consistent interface regardless of the underlying pagination type.',\n );\n }\n\n return sections.join('\\n');\n }\n\n errorHandlingDocs(): string {\n const sections: string[] = [];\n\n sections.push('## Error Handling');\n sections.push('');\n sections.push(\n 'The SDK provides structured error handling with typed HTTP error responses.',\n );\n sections.push('');\n\n sections.push('### Error Response Types');\n sections.push('');\n sections.push(\n 'All API errors extend from `APIError` and include the HTTP status code and response data:',\n );\n sections.push('');\n sections.push(\n createCodeBlock('typescript', [\n `import { BadRequest, Unauthorized, NotFound, TooManyRequests, InternalServerError, ParseError } from \"${this.#packageName}\";`,\n 'try {',\n 'const usersList = ',\n this.#toRequest(\n {\n method: 'get',\n path: '/users',\n tag: 'Users',\n },\n createObjectLiteral({}),\n ),\n ' // Handle successful response',\n '} catch (error) {',\n ' // Handle different error types',\n ' if (error instanceof BadRequest) {',\n ' console.error(\"Bad request:\", error.data);',\n ' console.log(\"Status:\", error.status); // 400',\n ' } else if (error instanceof Unauthorized) {',\n ' console.error(\"Authentication failed:\", error.data);',\n ' console.log(\"Status:\", error.status); // 401',\n ' } else if (error instanceof NotFound) {',\n ' console.error(\"Resource not found:\", error.data);',\n ' console.log(\"Status:\", error.status); // 404',\n ' } else if (error instanceof TooManyRequests) {',\n ' console.error(\"Rate limited:\", error.data);',\n ' if (error.data.retryAfter) {',\n ' console.log(\"Retry after:\", error.data.retryAfter);',\n ' }',\n ' } else if (error instanceof InternalServerError) {',\n ' console.error(\"Server error:\", error.data);',\n ' console.log(\"Status:\", error.status); // 500',\n ' } else if (error instanceof ParseError) {',\n ' console.error(\"Input validation failed:\", error.data);',\n ' }',\n '}',\n ]),\n );\n sections.push('');\n\n sections.push('### Available Error Classes');\n sections.push('');\n sections.push('#### Input Validation Errors');\n sections.push(\n '- `ParseError` - Request input validation failed against API schema',\n );\n sections.push('');\n sections.push('#### Client Errors (4xx)');\n sections.push('- `BadRequest` (400) - Invalid request data');\n sections.push('- `Unauthorized` (401) - Authentication required');\n sections.push('- `PaymentRequired` (402) - Payment required');\n sections.push('- `Forbidden` (403) - Access denied');\n sections.push('- `NotFound` (404) - Resource not found');\n sections.push('- `MethodNotAllowed` (405) - HTTP method not allowed');\n sections.push('- `NotAcceptable` (406) - Content type not acceptable');\n sections.push('- `Conflict` (409) - Resource conflict');\n sections.push('- `Gone` (410) - Resource no longer available');\n sections.push('- `PreconditionFailed` (412) - Precondition failed');\n sections.push('- `PayloadTooLarge` (413) - Request payload too large');\n sections.push('- `UnsupportedMediaType` (415) - Unsupported content type');\n sections.push('- `UnprocessableEntity` (422) - Validation errors');\n sections.push('- `TooManyRequests` (429) - Rate limit exceeded');\n sections.push('');\n\n sections.push('#### Server Errors (5xx)');\n sections.push('- `InternalServerError` (500) - Server error');\n sections.push('- `NotImplemented` (501) - Not implemented');\n sections.push('- `BadGateway` (502) - Bad gateway');\n sections.push('- `ServiceUnavailable` (503) - Service unavailable');\n sections.push('- `GatewayTimeout` (504) - Gateway timeout');\n sections.push('');\n\n sections.push('### Validation Errors');\n sections.push('');\n sections.push(\n 'Validation errors (422) include detailed field-level error information:',\n );\n\n sections.push('### Input Validation Errors');\n sections.push('');\n sections.push(\n 'When request input fails validation against the API schema, a `ParseError` is thrown:',\n );\n sections.push('');\n sections.push(\n createCodeBlock('typescript', [\n `import { ParseError } from \"${this.#packageName}\";`,\n '',\n 'try {',\n \" // Invalid input that doesn't match the expected schema\",\n ' const newUser = ',\n this.#toRequest(\n {\n method: 'post',\n path: '/users',\n tag: 'Users',\n },\n createObjectLiteral({\n email: 123, // should be string\n firstName: '', // empty required field\n age: -5, // invalid age value\n }),\n ),\n '} catch (error) {',\n ' if (error instanceof ParseError) {',\n ' console.log(\"Input validation failed:\");',\n ' ',\n ' // Field-level errors',\n ' if (error.data.fieldErrors) {',\n ' Object.entries(error.data.fieldErrors).forEach(([fieldName, validationIssues]) => {',\n ' console.log(` ${fieldName}: ${validationIssues.map(issue => issue.message).join(\", \")}`);',\n ' });',\n ' }',\n ' ',\n ' // Form-level errors',\n ' if (error.data.formErrors.length > 0) {',\n ' console.log(` Form errors: ${error.data.formErrors.map(issue => issue.message).join(\", \")}`);',\n ' }',\n ' }',\n '}',\n ]),\n );\n sections.push('');\n sections.push(\n \"`ParseError` contains detailed validation information using Zod's flattened error format, providing specific field-level and form-level validation messages.\",\n );\n sections.push('');\n\n sections.push('### Rate Limiting');\n sections.push('');\n sections.push(\n 'Rate limit responses may include a `retryAfter` field indicating when to retry:',\n );\n sections.push('');\n sections.push(\n createCodeBlock('typescript', [\n `import { TooManyRequests } from \"${this.#packageName}\";`,\n '',\n 'try {',\n ' const apiResponse = ',\n this.#toRequest(\n {\n method: 'get',\n path: '/api/data',\n tag: 'Data',\n },\n createObjectLiteral({}),\n ),\n '} catch (error) {',\n ' if (error instanceof TooManyRequests) {',\n ' const retryAfterSeconds = error.data.retryAfter;',\n ' if (retryAfterSeconds) {',\n ' console.log(`Rate limited. Retry after: ${retryAfterSeconds} seconds`);',\n ' // Implement your own retry logic',\n ' setTimeout(() => {',\n ' // Retry the request',\n ' }, retryAfterSeconds * 1000);',\n ' }',\n ' }',\n '}',\n ]),\n );\n\n return sections.join('\\n');\n }\n\n authenticationDocs(): string {\n const authOptions = this.#authentication();\n\n if (isEmpty(authOptions)) {\n return '';\n }\n\n const only = authOptions.length === 1;\n const sections: string[] = [\n '## Authentication',\n '',\n only\n ? 'The SDK requires authentication to access the API. Configure your client with the required credentials:'\n : 'The SDK supports the following authentication methods:',\n '',\n ];\n\n for (const { name, scheme } of authOptions) {\n sections.push(`### ${authenticationHeading(name, scheme, only)}`);\n sections.push('');\n if (isBearer(scheme)) {\n sections.push(\n 'Pass your bearer token directly - the \"Bearer\" prefix is automatically added:',\n );\n sections.push('');\n }\n const client = this.#constructClient({\n credentials: { [name]: this.#credentialExample(scheme) },\n });\n sections.push(createCodeBlock('typescript', [client.use]));\n sections.push('');\n }\n\n return sections.join('\\n');\n }\n\n generalUsageDocs(): string {\n const sections: string[] = [];\n\n return sections.join('\\n');\n }\n\n configurationUpdateDocs(): string {\n const sections: string[] = [];\n const authOptions = this.#authentication();\n\n sections.push('### Updating Configuration');\n sections.push('');\n sections.push(\n 'You can update client configuration after initialization using the `setOptions` method:',\n );\n sections.push('');\n\n const initialClientOptions: Record<string, unknown> = {\n baseUrl: 'https://api.production-service.com',\n };\n\n if (!isEmpty(authOptions)) {\n const [primaryAuth] = authOptions;\n initialClientOptions.credentials = {\n [primaryAuth.name]: this.#credentialExample(primaryAuth.scheme),\n };\n }\n\n const initialClientSetup = this.#constructClient(initialClientOptions);\n\n const configurationUpdateCode = [\n '// Initial client setup',\n initialClientSetup.use,\n '',\n '// Later, update specific options',\n 'client.setOptions({',\n \" baseUrl: 'https://api.staging-service.com',\",\n ];\n\n if (!isEmpty(authOptions)) {\n const [primaryAuth] = authOptions;\n configurationUpdateCode.push(\n ` credentials: ${JSON.stringify({\n [primaryAuth.name]: this.#credentialExample(primaryAuth.scheme),\n })}`,\n );\n }\n\n configurationUpdateCode.push('});');\n\n sections.push(createCodeBlock('typescript', configurationUpdateCode));\n sections.push('');\n sections.push(\n 'The `setOptions` method validates the provided options and only updates the specified fields, leaving other configuration unchanged.',\n );\n\n return sections.join('\\n');\n }\n}\n\nfunction isBearer(scheme: OpenAPISecuritySchemeObject) {\n return scheme.type === 'http' && scheme.scheme?.toLowerCase() === 'bearer';\n}\n\nfunction authenticationHeading(\n name: string,\n scheme: OpenAPISecuritySchemeObject,\n only: boolean,\n) {\n if (isBearer(scheme)) {\n return only ? 'Bearer Token' : 'Bearer Token Authentication';\n }\n if (scheme.type === 'apiKey' && scheme.in === 'header') {\n return only ? 'API Key (Header)' : 'API Key Authentication (Header)';\n }\n if (scheme.type === 'apiKey' && scheme.in === 'query') {\n return only\n ? 'API Key (Query Parameter)'\n : 'API Key Authentication (Query Parameter)';\n }\n return only ? name : `${name} Authentication`;\n}\n\nfunction createCodeBlock(language: string, content: string[]) {\n return ['```' + language, ...content, '```'].join('\\n');\n}\n\nfunction createObjectLiteral(\n obj: Record<string, unknown>,\n indent = '\\t',\n): string {\n return (\n '{\\n' +\n Object.entries(obj)\n .map(([key, value]) => `${indent}${key}: ${JSON.stringify(value)}`)\n .join(',\\n') +\n `\\n${indent.slice(0, -1)}}`\n );\n}\n\nfunction availablePaginationTypes(spec: IR) {\n let offset = false;\n let page = false;\n let cursor = false;\n forEachOperation(spec, (entry, operation) => {\n if (operation['x-pagination']) {\n switch (operation['x-pagination'].type) {\n case 'offset':\n offset = true;\n break;\n case 'page':\n page = true;\n break;\n case 'cursor':\n cursor = true;\n break;\n }\n }\n });\n return {\n offset,\n page,\n cursor,\n };\n}\n", "import type { ReferenceObject, SchemaObject } from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, resolveRef } from '@sdk-it/core';\nimport type { IR } from '@sdk-it/spec';\n\n/**\n * Generate example values for OpenAPI schemas\n * This emitter creates sample input payloads for API documentation and code snippets\n */\nexport class SnippetEmitter {\n private spec: IR;\n public generatedRefs = new Set<string>();\n private cache = new Map<string, unknown>();\n\n constructor(spec: IR) {\n this.spec = spec;\n }\n\n public object(\n schema: SchemaObject | ReferenceObject,\n ): Record<string, unknown> {\n const schemaObj = resolveRef(this.spec, schema) as SchemaObject;\n const result: Record<string, unknown> = {};\n const properties = schemaObj.properties || {};\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const isRequired = (schemaObj.required ?? []).includes(propName);\n const resolvedProp = resolveRef(this.spec, propSchema);\n\n if (\n isRequired ||\n resolvedProp.example !== undefined ||\n resolvedProp.default !== undefined\n ) {\n result[propName] = this.handle(propSchema);\n }\n }\n\n if (\n schemaObj.additionalProperties &&\n typeof schemaObj.additionalProperties === 'object'\n ) {\n result['additionalPropExample'] = this.handle(\n schemaObj.additionalProperties,\n );\n }\n\n return result;\n }\n\n public array(schema: SchemaObject | ReferenceObject): unknown[] {\n const schemaObj = resolveRef(this.spec, schema);\n const itemsSchema = schemaObj.items;\n if (!itemsSchema) {\n return [];\n }\n\n const count = Math.min(schemaObj.minItems ?? 1, 2);\n const result: unknown[] = [];\n\n for (let i = 0; i < count; i++) {\n result.push(this.handle(itemsSchema));\n }\n\n return result;\n }\n\n public string(schema: SchemaObject): string {\n if (schema.example !== undefined) return String(schema.example);\n if (schema.default !== undefined) return String(schema.default);\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n return `2025-07-17T09:08:00.097Z`;\n case 'date':\n return `2025-07-17`;\n case 'time':\n return `09:08:00.097Z`;\n case 'email':\n return 'user@example.com';\n case 'uuid':\n return '123e4567-e89b-12d3-a456-426614174000';\n case 'uri':\n case 'url':\n return 'https://example.com';\n case 'ipv4':\n return '192.168.1.1';\n case 'ipv6':\n return '2001:0db8:85a3:0000:0000:8a2e:0370:7334';\n case 'hostname':\n return 'example.com';\n case 'binary':\n case 'byte':\n return `new Blob(['example'], { type: 'text/plain' })`;\n default:\n if (schema.enum && schema.enum.length > 0) {\n return String(schema.enum[0]);\n }\n return schema.pattern ? `string matching ${schema.pattern}` : 'example';\n }\n }\n\n public number(schema: SchemaObject): number {\n if (schema.example !== undefined) return Number(schema.example);\n if (schema.default !== undefined) return Number(schema.default);\n\n let value: number;\n if (typeof schema.exclusiveMinimum === 'number') {\n value = schema.exclusiveMinimum + 1;\n } else if (typeof schema.minimum === 'number') {\n value = schema.minimum;\n } else {\n value = schema.type === 'integer' ? 42 : 42.42;\n }\n\n if (\n typeof schema.exclusiveMaximum === 'number' &&\n value >= schema.exclusiveMaximum\n ) {\n value = schema.exclusiveMaximum - 1;\n } else if (typeof schema.maximum === 'number' && value > schema.maximum) {\n value = schema.maximum;\n }\n\n if (\n typeof schema.multipleOf === 'number' &&\n value % schema.multipleOf !== 0\n ) {\n value = Math.floor(value / schema.multipleOf) * schema.multipleOf;\n }\n\n return schema.type === 'integer' ? Math.floor(value) : value;\n }\n\n public boolean(schema: SchemaObject): boolean {\n if (schema.example !== undefined) return Boolean(schema.example);\n if (schema.default !== undefined) return Boolean(schema.default);\n return true;\n }\n\n public null(): null {\n return null;\n }\n\n public ref($ref: string): unknown {\n const parts = $ref.split('/');\n const refKey = parts[parts.length - 1] || '';\n\n if (this.cache.has($ref)) {\n return this.cache.get($ref) as unknown;\n }\n\n this.cache.set($ref, { _ref: refKey });\n\n const resolved = followRef<SchemaObject>(this.spec, $ref);\n const result = this.handle(resolved);\n\n this.cache.set($ref, result);\n return result;\n }\n\n public allOf(schemas: (SchemaObject | ReferenceObject)[]): unknown {\n const initial: Record<string, unknown> = {};\n return schemas.reduce<Record<string, unknown>>((result, schema) => {\n const example = this.handle(schema);\n if (typeof example === 'object' && example !== null) {\n return { ...result, ...example };\n }\n return result;\n }, initial);\n }\n\n public anyOf(schemas: (SchemaObject | ReferenceObject)[]): unknown {\n if (schemas.length === 0) return {};\n return this.handle(schemas[0]);\n }\n\n public oneOf(schemas: (SchemaObject | ReferenceObject)[]): unknown {\n if (schemas.length === 0) return {};\n return this.handle(schemas[0]);\n }\n\n public enum(schema: SchemaObject): unknown {\n return Array.isArray(schema.enum) && schema.enum.length > 0\n ? schema.enum[0]\n : undefined;\n }\n\n public handle(schemaOrRef: SchemaObject | ReferenceObject): unknown {\n if (isRef(schemaOrRef)) {\n return this.ref(schemaOrRef.$ref);\n }\n\n const schema = resolveRef(this.spec, schemaOrRef);\n\n if (schema.example !== undefined) {\n return schema.example;\n }\n\n if (schema.default !== undefined) {\n return schema.default;\n }\n\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf);\n }\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf);\n }\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf);\n }\n\n if (schema.enum && Array.isArray(schema.enum) && schema.enum.length > 0) {\n return this.enum(schema);\n }\n\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n if (types.length === 0) {\n if (schema.properties || schema.additionalProperties) {\n return this.object(schema);\n } else if (schema.items) {\n return this.array(schema);\n }\n return 'example';\n }\n\n const primaryType = types.find((t) => t !== 'null') || types[0];\n\n switch (primaryType) {\n case 'string':\n return this.string(schema);\n case 'number':\n case 'integer':\n return this.number(schema);\n case 'boolean':\n return this.boolean(schema);\n case 'object':\n return this.object(schema);\n case 'array':\n return this.array(schema);\n case 'null':\n return this.null();\n default:\n return 'unknown';\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,QAAAC,aAAY;AACrB,SAAS,qBAAqB;AAC9B,SAAS,aAAAC,YAAW,cAAAC,mBAAkB;AAEtC,SAA+B,cAAAC,aAAY,eAAAC,oBAAmB;AAC9D;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EAGE;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA,eAAAC;AA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AA,MACL,CAAC,kBAAkBN,YAAW,IAAI,CAAC,OAAO,OAAO,KAAK,IAAI,CAAC;AAAA,MAC3D,GAAG;AAAA,IACL;AAAA,EACF,GAAG,CAAC,CAAC;AAEP,SAAO;AAAA,IACL,GAAG,OAAO,YAAY,OAAO;AAAA,IAC7B,GAAG;AAAA,EACL;AACF;",
|
|
6
|
-
"names": ["
|
|
3
|
+
"sources": ["../src/lib/client-name.ts", "../src/lib/client.ts", "../src/lib/group-identifier.ts", "../src/lib/references.ts", "../src/lib/security.ts", "runtime-module:runtime-module", "../src/lib/root-exports.ts", "../src/lib/generate.ts", "runtime-sources:runtime-sources", "../src/lib/agent/ai-sdk.ts", "../src/lib/import-utilities.ts", "../src/lib/input-schema-name.ts", "../src/lib/agent/openai-agents.ts", "../src/lib/agent/utils.txt", "../src/lib/emitters/interface.ts", "../src/lib/folder-index.ts", "../src/lib/generator.ts", "../src/lib/emitters/zod.ts", "../src/lib/module-file.ts", "../src/lib/sdk.ts", "../src/lib/status-map.ts", "../src/lib/model-name.ts", "../src/lib/one-module.ts", "../src/lib/readme/readme.ts", "../src/lib/readme/prop.emitter.ts", "../src/lib/server-urls.ts", "../src/lib/typescript-snippet.ts", "../src/lib/emitters/snippet.ts"],
|
|
4
|
+
"sourcesContent": ["import { camelcase } from 'stringcase';\n\nimport { pascalcase } from '@sdk-it/core';\n\nimport {\n clientDeclarationBindings,\n clientFileBindings,\n clientNamedExports,\n} from './client.ts';\nimport { runtimeRootExports } from './root-exports.ts';\nimport { securityTypeExports } from './security.ts';\n\n/** ECMAScript reserved words, and the names strict-mode code cannot bind. */\nconst reservedWords = new Set([\n 'arguments',\n 'await',\n 'break',\n 'case',\n 'catch',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'finally',\n 'for',\n 'function',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'interface',\n 'let',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'static',\n 'super',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'while',\n 'with',\n 'yield',\n]);\n\n/** The names an SDK declares or exports beside the ones it builds from the client name. */\nconst sdkNames = new Set<string>([\n ...runtimeRootExports.map((binding) => binding.name),\n ...securityTypeExports,\n ...clientFileBindings,\n ...clientDeclarationBindings,\n]);\n\n/**\n * The name a generated SDK builds its exports from (`create<Name>`,\n * `<Name>Client`, the default instance `<name>`): `name` in PascalCase.\n * Throws a TypeError, naming `name`, when that is not a TypeScript identifier,\n * the default instance would be a reserved word, or a name built from it is\n * one the SDK already declares or exports (`Request` makes the default\n * instance `request`, which the SDK root exports).\n */\nexport function clientName(name: string): string {\n const pascal = pascalcase(name.trim());\n if (!/^[\\p{ID_Start}_$][\\p{ID_Continue}$\u200C\u200D]*$/u.test(pascal)) {\n throw new TypeError(\n `The client name \"${name}\" becomes ${pascal ? `\"${pascal}\"` : 'an empty name'}, which is not a TypeScript identifier. A client name starts with a letter, _ or $, and has only letters, digits, _ and $.`,\n );\n }\n const instance = camelcase(pascal);\n if (reservedWords.has(instance)) {\n throw new TypeError(\n `The client name \"${name}\" makes the default instance ${instance}, which is a reserved word. Rename the client.`,\n );\n }\n refuseTakenNames(name, pascal, sdkNames);\n return pascal;\n}\n\n/**\n * Throws the TypeError of `clientName` when a name built from `pascal`, the\n * client name `name` gives, is one of `taken`: names that come from the spec,\n * such as the input schemas the SDK root exports (`listItemsSchema`).\n */\nexport function refuseTakenNames(\n name: string,\n pascal: string,\n taken: ReadonlySet<string>,\n) {\n const clash = clientNamedExports(pascal).find((built) => taken.has(built));\n if (clash !== undefined) {\n throw new TypeError(\n `The client name \"${name}\" makes ${clash}, a name the SDK already declares or exports. Rename the client.`,\n );\n }\n}\n", "import { camelcase } from 'stringcase';\n\nimport {\n type References,\n type RuntimeName,\n fileReferences,\n} from './references.ts';\nimport type { Spec } from './sdk.ts';\nimport { securityTypeExports } from './security.ts';\n\ntype SecurityScheme = Spec['securitySchemes'][string];\ntype ClientSpec = Omit<Spec, 'operations' | 'makeImport'>;\n\n/** The runtime schemas a client file imports to validate credentials. */\nconst credentialSchemaNames = [\n 'stringCredentialSchema',\n 'basicCredentialSchema',\n 'mutualTlsCredentialSchema',\n] as const satisfies RuntimeName[];\n\nfunction credentialSchemaName(\n scheme: SecurityScheme,\n): (typeof credentialSchemaNames)[number] {\n if (scheme.type === 'mutualTLS') {\n return 'mutualTlsCredentialSchema';\n }\n if (scheme.type === 'http' && scheme.scheme?.toLowerCase() === 'basic') {\n return 'basicCredentialSchema';\n }\n return 'stringCredentialSchema';\n}\n\nfunction credentialSchemas(spec: ClientSpec) {\n return Object.entries(spec.securitySchemes).map(\n ([scheme, definition]) =>\n [scheme, credentialSchemaName(definition)] as const,\n );\n}\n\n/** Names the generated client module exports at the SDK root besides its models. */\nexport function clientExports(name: string) {\n return [\n `${name}Client`,\n `${name}Credentials`,\n `${name}Endpoints`,\n `${name}Servers`,\n `${name}Settings`,\n ];\n}\n\n/** The names a client named `name` declares and exports from the SDK root. */\nexport function clientNamedExports(name: string) {\n return [...clientExports(name), `create${name}`, camelcase(name)];\n}\n\n/** The module bindings `clientDeclarations` declares besides `clientNamedExports`. */\nexport const clientDeclarationBindings = [\n 'servers',\n '__securitySchemes',\n '__credentialsSchema',\n '__api',\n];\n\n/** Every name `clientDeclarations` can declare for a client named `name`. */\nexport function clientDeclaredNames(name: string) {\n return [...clientNamedExports(name), ...clientDeclarationBindings];\n}\n\n/** The runtime functions the SDK root exports from the client module. */\nexport const clientRuntimeExports = ['prepare', 'request'];\n\n/** The runtime types the SDK root exports when the spec names security schemes. */\nexport function clientRuntimeTypeExports(spec: ClientSpec) {\n return credentialSchemas(spec).length > 0 ? securityTypeExports : [];\n}\n\n/**\n * The spec-specific part of a generated SDK's client: its servers and security\n * as an `api` over the endpoint table `routes`, a `create<Name>(settings)`\n * factory over @sdk-it/runtime's Client, and a default instance when the spec\n * names at most one server.\n */\nexport function clientDeclarations(\n spec: ClientSpec,\n refs: References,\n routes: string,\n) {\n const { name } = spec;\n const credentials = credentialSchemas(spec);\n return `${spec.servers.length ? 'export ' : ''}const servers = ${JSON.stringify(spec.servers, null, 2)} as const;\n${spec.servers.length ? `export type ${name}Servers = (typeof servers)[number];` : ''}\nconst __securitySchemes = ${JSON.stringify(spec.securitySchemes, null, 2)} as const;\nconst __credentialsSchema = z.object({\n${credentials.map(([scheme, schema]) => ` ${JSON.stringify(scheme)}: ${refs.runtime(schema)}.optional(),`).join('\\n')}\n});\nconst __api = { routes: ${routes}, servers, securitySchemes: __securitySchemes, credentials: __credentialsSchema };\n\nexport interface ${name}Client extends ${refs.runtime('Client')}<typeof __api> {}\nexport type ${name}Settings = ${refs.runtime('ClientSettings')}<typeof __api>;\nexport type ${name}Endpoints = ${refs.runtime('EndpointsOf')}<typeof __api>;\n${credentials.length ? `export type ${name}Credentials = z.input<typeof __credentialsSchema>;` : ''}\n\nexport function ${refs.located(`create${name}`, title)}(settings: ${name}Settings): ${name}Client {\n return ${refs.runtime('createClient')}(__api, settings);\n}\n${spec.servers.length <= 1 ? `\\nexport const ${refs.located(camelcase(name), title)} = create${name}({});\\n` : ''}`;\n}\n\n/** The provider exports name the API the document describes. */\nconst title = ['info', 'title'];\n\n/** client.ts imports the client types and factory under `__` aliases. */\nconst aliased = new Set<RuntimeName>([\n 'Client',\n 'ClientSettings',\n 'EndpointsOf',\n 'createClient',\n]);\n/** The module bindings client.ts makes besides `clientDeclarations`: zod, its imports and re-exports. */\nexport const clientFileBindings = [\n 'z',\n '__schemas',\n ...[...aliased].map((name) => `__${name}`),\n ...credentialSchemaNames,\n ...clientRuntimeExports,\n];\nconst clientFileReferences: References = {\n ...fileReferences('outputs'),\n runtime: (name) => (aliased.has(name) ? `__${name}` : name),\n};\n\n/** The client.ts file of a multi-file SDK. */\nexport default (spec: Omit<Spec, 'operations'>) => {\n const { makeImport } = spec;\n const typeExports = clientRuntimeTypeExports(spec);\n const credentialImports = [\n ...new Set(credentialSchemas(spec).map(([, schema]) => schema)),\n ].sort();\n\n return `import { z } from 'zod';\nimport __schemas from './api/${makeImport('schemas')}';\nimport { type Client as __Client, type ClientSettings as __ClientSettings, type EndpointsOf as __EndpointsOf, createClient as __createClient } from './http/${makeImport('client')}';${\n typeExports.length\n ? `\nimport { ${credentialImports.join(', ')} } from './http/${makeImport('security')}';\nexport type {\n${typeExports.map((type) => ` ${type},`).join('\\n')}\n} from './http/${makeImport('security')}';`\n : ''\n }\nexport { ${clientRuntimeExports.join(', ')} } from './http/${makeImport('client')}';\n\n${clientDeclarations(spec, clientFileReferences, '__schemas')}`;\n};\n", "import { camelcase } from 'stringcase';\n\nimport { sanitizeTag } from '@sdk-it/spec';\n\n/**\n * The identifier a group (operation tag) gets in generated code. camelcase\n * drops the leading `_` that keeps a digit-leading tag like `_2fa` a valid\n * identifier, so the tag is sanitized again afterwards.\n */\nexport function groupIdentifier(group: string) {\n return sanitizeTag(camelcase(group));\n}\n", "import type { RequestEncoding } from '@sdk-it/spec';\n\nimport { groupIdentifier } from './group-identifier.ts';\n\n/** The runtime declarations that emitted code refers to, besides the response classes. */\nexport type RuntimeName =\n | RequestEncoding\n | 'toRequest'\n | 'Dispatcher'\n | 'fetchType'\n | 'Interceptor'\n | 'chunked'\n | 'buffered'\n | 'sse'\n | 'bodyless'\n | 'SSEListener'\n | 'Client'\n | 'ClientSettings'\n | 'EndpointsOf'\n | 'createClient'\n | 'stringCredentialSchema'\n | 'basicCredentialSchema'\n | 'mutualTlsCredentialSchema';\n\n/** The globals that emitted code refers to. */\nexport type EmittedGlobal =\n 'Blob' | 'Date' | 'Record' | 'AbortSignal' | 'ReadableStream';\n\n/**\n * How emitted code names a declaration that another part of the SDK makes.\n * A multi-file SDK reaches other files through the namespace imports each file\n * makes (`models.Pet`, `pets.listPetsSchema`, `http.Ok`); a one-module SDK\n * declares everything in one scope.\n */\nexport interface References {\n /** A model type, by its TypeScript name. */\n model(typeName: string): string;\n /** The schema const of an operation input in `group`. */\n input(group: string, schemaName: string): string;\n /** A declaration of the runtime's response module: a class (`Ok`, `NotFound`, `APIError`, \u2026) or `RangeStatus`. */\n status(className: string): string;\n runtime(name: RuntimeName): string;\n global(name: EmittedGlobal): string;\n /**\n * `text`, which names what the OpenAPI document declares at `location`\n * (RFC 6901 reference tokens, unescaped).\n */\n located(text: string, location: readonly string[]): string;\n}\n\n/**\n * The names a file of the multi-file SDK uses. Each file imports models as\n * `modelNamespace` (`models` from a model file, `outputs` from an endpoint\n * file), the response classes as `http` and other runtime declarations by name.\n */\nexport function fileReferences(\n modelNamespace: 'models' | 'outputs',\n): References {\n return {\n model: (typeName) => `${modelNamespace}.${typeName}`,\n input: (group, schemaName) => `${groupIdentifier(group)}.${schemaName}`,\n status: (className) => `http.${className}`,\n runtime: (name) => name,\n global: (name) => name,\n located: (text) => text,\n };\n}\n\n/**\n * The names an inputs file of the multi-file SDK uses. It imports the shared\n * schemas it uses by name, and a shared schema may take a global's name\n * (`Date`), so a global is a mark that `inputGlobals` resolves once the shared\n * schemas are known. Generated code never contains a NUL character\n * (JSON.stringify escapes it), so a mark cannot collide.\n */\nexport const inputFileReferences: References = {\n ...fileReferences('models'),\n global: (name) => `\\0${name}\\0`,\n};\n\n/** `text` with each global mark of `inputFileReferences` read as `globalThis.<name>` when a shared schema takes the name. */\nexport function inputGlobals(text: string, schemaNames: ReadonlySet<string>) {\n return text.replaceAll(/\\0(\\w+)\\0/g, (_, name: string) =>\n schemaNames.has(name) ? `globalThis.${name}` : name,\n );\n}\n", "/** Security types the generated client re-exports from the SDK root. */\nexport const securityTypeExports = [\n 'SecurityContext',\n 'SecurityCredential',\n 'SecurityCredentialProvider',\n 'SecurityCredentialValue',\n] as const;\n", "export default {\"text\":\"type Init = Omit<RequestInit, 'headers'> & { headers: Headers };\\ntype RequestConfig = { init: Init; url: URL };\\n/** The methods an OpenAPI operation uses, as an HTTP request line writes them. */\\ntype Method =\\n 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'TRACE' | 'HEAD';\\ntype HeadersInit = [string, string][] | Record<string, string>;\\n\\ntype BodyInit =\\n ArrayBuffer | Blob | FormData | URLSearchParams | null | string;\\n\\nfunction template(\\n templateString: string,\\n templateVariables: Record<string, any>,\\n): string {\\n const nargs = /{([0-9a-zA-Z_]+)}/g;\\n return templateString.replace(nargs, (match, key: string, index: number) => {\\n // Handle escaped double braces\\n if (\\n templateString[index - 1] === '{' &&\\n templateString[index + match.length] === '}'\\n ) {\\n return key;\\n }\\n\\n const result = key in templateVariables ? templateVariables[key] : null;\\n return result === null || result === undefined\\n ? ''\\n : encodeURIComponent(String(result));\\n });\\n}\\n\\ntype Input = Record<string, any>;\\n\\n// Validated inputs can carry Date (coerce-date) values; String(new Date())\\n// yields a local-time RFC 2822 string, so serialize Dates as ISO 8601.\\nfunction toWireValue(value: any): string {\\n return value instanceof Date ? value.toISOString() : String(value);\\n}\\n\\n/** The values a field sends: none when the caller left it out, one per item of an array. */\\nfunction wireItems(value: any): any[] {\\n if (value === undefined) {\\n return [];\\n }\\n return Array.isArray(value) ? value : [value];\\n}\\n\\ntype Props = {\\n /** The media type the body is sent as. */\\n contentType: string;\\n inputHeaders: string[];\\n inputQuery: string[];\\n inputBody: string[];\\n inputParams: string[];\\n};\\n\\nabstract class Serializer {\\n protected input: Input;\\n protected props: Props;\\n\\n constructor(input: Input, props: Props) {\\n this.input = input;\\n this.props = props;\\n }\\n\\n abstract getBody(): BodyInit | null;\\n abstract getHeaders(): Record<string, string>;\\n serialize(path: string, baseUrl: string): Serialized {\\n const params = this.props.inputParams.reduce<Record<string, any>>(\\n (acc, key) => {\\n acc[key] = this.input[key];\\n return acc;\\n },\\n {},\\n );\\n const url = new URL(`${baseUrl}${template(path, params)}`);\\n\\n const headers: Record<string, string> = { ...this.getHeaders() };\\n for (const header of this.props.inputHeaders) {\\n const value = this.input[header];\\n if (value !== undefined) {\\n headers[header] = toWireValue(value);\\n }\\n }\\n\\n for (const key of this.props.inputQuery) {\\n for (const item of wireItems(this.input[key])) {\\n url.searchParams.append(key, toWireValue(item));\\n }\\n }\\n\\n return {\\n body: this.getBody(),\\n url,\\n headers,\\n };\\n }\\n}\\n\\ninterface Serialized {\\n body: BodyInit | null;\\n headers: Record<string, string>;\\n url: URL;\\n}\\n\\nclass JsonSerializer extends Serializer {\\n getBody(): BodyInit | null {\\n const body: Record<string, any> = {};\\n if (\\n this.props.inputBody.length === 1 &&\\n this.props.inputBody[0] === '$body'\\n ) {\\n return JSON.stringify(this.input.$body);\\n }\\n\\n for (const prop of this.props.inputBody) {\\n body[prop] = this.input[prop];\\n }\\n return JSON.stringify(body);\\n }\\n getHeaders(): Record<string, string> {\\n return {\\n 'Content-Type': this.props.contentType,\\n Accept: 'application/json',\\n };\\n }\\n}\\n\\nclass UrlencodedSerializer extends Serializer {\\n getBody(): BodyInit | null {\\n const body = new URLSearchParams();\\n for (const prop of this.props.inputBody) {\\n for (const item of wireItems(this.input[prop])) {\\n body.append(prop, toWireValue(item));\\n }\\n }\\n return body;\\n }\\n getHeaders(): Record<string, string> {\\n return {\\n 'Content-Type': this.props.contentType,\\n Accept: 'application/json',\\n };\\n }\\n}\\n\\nclass EmptySerializer extends Serializer {\\n getBody(): BodyInit | null {\\n return null;\\n }\\n getHeaders(): Record<string, string> {\\n return {};\\n }\\n}\\n\\nclass FormDataSerializer extends Serializer {\\n getBody(): BodyInit | null {\\n const body = new FormData();\\n for (const prop of this.props.inputBody) {\\n for (const item of wireItems(this.input[prop])) {\\n body.append(prop, item);\\n }\\n }\\n return body;\\n }\\n getHeaders(): Record<string, string> {\\n return {\\n Accept: 'application/json',\\n };\\n }\\n}\\n\\n// A text or binary body is the caller's own string or Blob, sent as is.\\nclass RawSerializer extends Serializer {\\n getBody(): BodyInit | null {\\n return this.input.$body;\\n }\\n getHeaders(): Record<string, string> {\\n return {\\n 'Content-Type': this.props.contentType,\\n };\\n }\\n}\\n\\nfunction json(input: Input, props: Props) {\\n return new JsonSerializer(input, props);\\n}\\nfunction urlencoded(input: Input, props: Props) {\\n return new UrlencodedSerializer(input, props);\\n}\\nfunction empty(input: Input, props: Props) {\\n return new EmptySerializer(input, props);\\n}\\nfunction formdata(input: Input, props: Props) {\\n return new FormDataSerializer(input, props);\\n}\\nfunction text(input: Input, props: Props) {\\n return new RawSerializer(input, props);\\n}\\nfunction binary(input: Input, props: Props) {\\n return new RawSerializer(input, props);\\n}\\n\\nfunction toRequest(\\n method: Method,\\n path: string,\\n serializer: Serializer,\\n baseUrl: string,\\n): RequestConfig {\\n const input = serializer.serialize(path, baseUrl);\\n return {\\n url: input.url,\\n init: {\\n method: method,\\n headers: new Headers(input.headers),\\n ...(method === 'GET' ? {} : { body: input.body }),\\n },\\n };\\n}\\n\\n\\n\\ninterface Interceptor {\\n before?: (config: RequestConfig) => Promise<RequestConfig> | RequestConfig;\\n after?: (response: Response) => Promise<Response> | Response;\\n}\\n\\nconst createHeadersInterceptor = (\\n headers: Record<string, string | undefined>,\\n requestHeaders: HeadersInit,\\n): Interceptor => {\\n return {\\n before({ init, url }) {\\n // Priority Levels\\n // 1. Headers Input\\n // 2. Request Headers\\n // 3. Default Headers\\n\\n for (const [key, value] of new Headers(requestHeaders)) {\\n // Only set the header if it doesn't already exist and has a value\\n // even though these headers are passed at operation level\\n // still they are lower priority compared to the headers input\\n if (value !== undefined && !init.headers.has(key)) {\\n init.headers.set(key, value);\\n }\\n }\\n\\n for (const [key, value] of Object.entries(headers)) {\\n // Only set the header if it doesn't already exist and has a value\\n if (value !== undefined && !init.headers.has(key)) {\\n init.headers.set(key, value);\\n }\\n }\\n\\n return { init, url };\\n },\\n };\\n};\\n\\n\\n\\nfunction isBinaryContentType(contentType: string) {\\n const type = contentType.toLowerCase();\\n if (type.startsWith('image/')) {\\n return true;\\n }\\n if (type.startsWith('audio/')) {\\n return true;\\n }\\n if (type.startsWith('video/')) {\\n return true;\\n }\\n switch (type) {\\n case 'application/pdf':\\n case 'application/zip':\\n case 'application/gzip':\\n case 'application/x-7z-compressed':\\n case 'application/x-tar':\\n case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':\\n case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':\\n case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':\\n case 'application/vnd.ms-excel':\\n case 'application/vnd.ms-powerpoint':\\n case 'application/msword':\\n case 'application/octet-stream':\\n return true;\\n default:\\n return false;\\n }\\n}\\n\\nfunction chunked(response: Response) {\\n return response.body!;\\n}\\n\\n// The operation declares no body; release the unread stream so the\\n// connection is not held until garbage collection.\\nasync function bodyless(response: Response) {\\n await response.body?.cancel();\\n return null;\\n}\\n\\n/** The body kinds the buffered parser reads: what the spec declares for a status. */\\ntype BufferedBody = 'json' | 'text' | 'binary';\\n\\n/**\\n * Reads a body by its Content-Type. A response without one reads as the body\\n * the spec declares for its status, or, with none declared, as the\\n * application/octet-stream that RFC 9110 \u00A78.3 lets a recipient assume.\\n */\\nfunction buffered(declared?: BufferedBody) {\\n return async (response: Response): Promise<unknown> => {\\n // Statuses that, per the HTTP spec, carry no message body. These\\n // responses usually omit Content-Type entirely.\\n if (\\n response.status === 204 ||\\n response.status === 205 ||\\n response.status === 304\\n ) {\\n return null;\\n }\\n const contentType = response.headers.get('Content-Type');\\n if (contentType) {\\n return byContentType(response, contentType);\\n }\\n const bytes = await response.bytes();\\n if (bytes.byteLength === 0) {\\n return null;\\n }\\n switch (declared) {\\n case 'json':\\n return JSON.parse(new TextDecoder().decode(bytes));\\n case 'text':\\n return new TextDecoder().decode(bytes);\\n default:\\n return new Blob([bytes], { type: 'application/octet-stream' });\\n }\\n };\\n}\\n\\nasync function byContentType(response: Response, contentType: string) {\\n const { type } = parse(contentType);\\n if (isBinaryContentType(type)) {\\n return response.blob();\\n }\\n if (type.startsWith('text/')) {\\n return response.text();\\n }\\n if (type === 'application/json' || type.endsWith('+json')) {\\n return response.json();\\n }\\n switch (type) {\\n case 'application/xml':\\n return response.text();\\n case 'application/x-www-form-urlencoded': {\\n const text = await response.text();\\n return Object.fromEntries(new URLSearchParams(text));\\n }\\n case 'multipart/form-data':\\n return response.formData();\\n default:\\n throw new Error(`Unsupported content type: ${contentType}`);\\n }\\n}\\n\\n/** The status ranges an OpenAPI 3.2 Responses Object may declare. */\\ntype StatusRange = '1XX' | '2XX' | '3XX' | '4XX' | '5XX';\\ntype Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';\\ntype ToNumber<S> = S extends `${infer N extends number}` ? N : never;\\n/** Every status code a range covers: `RangeStatus<'4XX'>` is 400 | 401 | \u2026 | 499. */\\ntype RangeStatus<R extends StatusRange> = R extends `${infer C}XX`\\n ? ToNumber<`${C}${Digit}${Digit}`>\\n : never;\\nclass APIResponse<Body = unknown, Status extends number = number> {\\n static readonly status: number;\\n readonly status: Status;\\n data: Body;\\n readonly headers: Headers;\\n\\n constructor(status: Status, headers: Headers, data: Body) {\\n this.status = status;\\n this.headers = headers;\\n this.data = data;\\n }\\n\\n static create(status: number, headers: Headers, data: unknown) {\\n return new this(status, headers, data);\\n }\\n}\\n\\nclass APIError<Body, Status extends number = number> extends Error {\\n static readonly status: number;\\n readonly status: Status;\\n data: Body;\\n readonly headers: Headers;\\n\\n constructor(status: Status, headers: Headers, data: Body) {\\n super(failureMessage(status, data));\\n this.name = 'APIError';\\n this.status = status;\\n this.headers = headers;\\n this.data = data;\\n }\\n\\n static create<T>(status: number, headers: Headers, data: T) {\\n return new this(status, headers, data);\\n }\\n}\\n\\nfunction failureMessage(status: number, data: unknown) {\\n const summary = bodySummary(data);\\n return summary\\n ? `Request failed with status code ${status}: ${summary}`\\n : `Request failed with status code ${status}`;\\n}\\n\\n// Only text and JSON bodies read as a summary; a Blob, stream or FormData body\\n// has none. The tag check holds across realms, where prototype checks do not.\\nfunction bodySummary(data: unknown) {\\n const tag = Object.prototype.toString.call(data);\\n let text = '';\\n if (typeof data === 'string') {\\n text = data;\\n } else if (tag === '[object Object]' || tag === '[object Array]') {\\n text = JSON.stringify(data);\\n }\\n const line = text.replace(/\\\\s+/g, ' ').trim();\\n return line.length > 200 ? `${line.slice(0, 200)}\u2026` : line;\\n}\\n\\n// 2xx Success\\nclass Ok<T> extends APIResponse<T, 200> {\\n static override readonly status = 200 as const;\\n constructor(headers: Headers, data: T) {\\n super(Ok.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\n\\nclass Created<T> extends APIResponse<T, 201> {\\n static override status = 201 as const;\\n constructor(headers: Headers, data: T) {\\n super(Created.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass Accepted<T> extends APIResponse<T, 202> {\\n static override status = 202 as const;\\n constructor(headers: Headers, data: T) {\\n super(Accepted.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass NoContent extends APIResponse<null, 204> {\\n static override status = 204 as const;\\n constructor(headers: Headers) {\\n super(NoContent.status, headers, null);\\n }\\n static override create(status: number, headers: Headers): NoContent {\\n return new this(headers);\\n }\\n}\\n\\n// 4xx Client Errors\\nclass BadRequest<T> extends APIError<T, 400> {\\n static override status = 400 as const;\\n constructor(headers: Headers, data: T) {\\n super(BadRequest.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass Unauthorized<T = { message: string }> extends APIError<T, 401> {\\n static override status = 401 as const;\\n constructor(headers: Headers, data: T) {\\n super(Unauthorized.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass PaymentRequired<T = { message: string }> extends APIError<T, 402> {\\n static override status = 402 as const;\\n constructor(headers: Headers, data: T) {\\n super(PaymentRequired.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass Forbidden<T = { message: string }> extends APIError<T, 403> {\\n static override status = 403 as const;\\n constructor(headers: Headers, data: T) {\\n super(Forbidden.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass NotFound<T = { message: string }> extends APIError<T, 404> {\\n static override status = 404 as const;\\n constructor(headers: Headers, data: T) {\\n super(NotFound.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass MethodNotAllowed<T = { message: string }> extends APIError<\\n T,\\n 405\\n> {\\n static override status = 405 as const;\\n constructor(headers: Headers, data: T) {\\n super(MethodNotAllowed.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass NotAcceptable<T = { message: string }> extends APIError<T, 406> {\\n static override status = 406 as const;\\n constructor(headers: Headers, data: T) {\\n super(NotAcceptable.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass Conflict<T = { message: string }> extends APIError<T, 409> {\\n static override status = 409 as const;\\n constructor(headers: Headers, data: T) {\\n super(Conflict.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass Gone<T = { message: string }> extends APIError<T, 410> {\\n static override status = 410 as const;\\n constructor(headers: Headers, data: T) {\\n super(Gone.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass PreconditionFailed<T = { message: string }> extends APIError<\\n T,\\n 412\\n> {\\n static override status = 412 as const;\\n constructor(headers: Headers, data: T) {\\n super(PreconditionFailed.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass UnprocessableEntity<\\n T = { message: string; errors?: Record<string, string[]> },\\n> extends APIError<T, 422> {\\n static override status = 422 as const;\\n constructor(headers: Headers, data: T) {\\n super(UnprocessableEntity.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass TooManyRequests<\\n T = { message: string; retryAfter?: string },\\n> extends APIError<T, 429> {\\n static override status = 429 as const;\\n constructor(headers: Headers, data: T) {\\n super(TooManyRequests.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {\\n static override status = 413 as const;\\n constructor(headers: Headers, data: T) {\\n super(PayloadTooLarge.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass UnsupportedMediaType<T = { message: string }> extends APIError<\\n T,\\n 415\\n> {\\n static override status = 415 as const;\\n constructor(headers: Headers, data: T) {\\n super(UnsupportedMediaType.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\n\\n// 5xx Server Errors\\nclass InternalServerError<T = { message: string }> extends APIError<\\n T,\\n 500\\n> {\\n static override status = 500 as const;\\n constructor(headers: Headers, data: T) {\\n super(InternalServerError.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass NotImplemented<T = { message: string }> extends APIError<T, 501> {\\n static override status = 501 as const;\\n constructor(headers: Headers, data: T) {\\n super(NotImplemented.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass BadGateway<T = { message: string }> extends APIError<T, 502> {\\n static override status = 502 as const;\\n constructor(headers: Headers, data: T) {\\n super(BadGateway.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass ServiceUnavailable<\\n T = { message: string; retryAfter?: string },\\n> extends APIError<T, 503> {\\n static override status = 503 as const;\\n constructor(headers: Headers, data: T) {\\n super(ServiceUnavailable.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nclass GatewayTimeout<T = { message: string }> extends APIError<T, 504> {\\n static override status = 504 as const;\\n constructor(headers: Headers, data: T) {\\n super(GatewayTimeout.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\n\\ntype ClientError =\\n | BadRequest<unknown>\\n | Unauthorized<unknown>\\n | PaymentRequired<unknown>\\n | Forbidden<unknown>\\n | NotFound<unknown>\\n | MethodNotAllowed<unknown>\\n | NotAcceptable<unknown>\\n | Conflict<unknown>\\n | Gone<unknown>\\n | PreconditionFailed<unknown>\\n | PayloadTooLarge<unknown>\\n | UnsupportedMediaType<unknown>\\n | UnprocessableEntity<unknown>\\n | TooManyRequests<unknown>\\n | APIError<unknown, RangeStatus<'4XX'>>;\\n\\ntype ServerError =\\n | InternalServerError<unknown>\\n | NotImplemented<unknown>\\n | BadGateway<unknown>\\n | ServiceUnavailable<unknown>\\n | GatewayTimeout<unknown>\\n | APIError<unknown, RangeStatus<'5XX'>>;\\n\\ntype ProblematicResponse = ClientError | ServerError;\\n\\ntype SuccessfulResponse<T = unknown> =\\n | Ok<T>\\n | Created<T>\\n | Accepted<T>\\n | NoContent\\n | APIResponse<T, RangeStatus<'2XX'>>;\\n\\ntype RebindSuccessPayload<Resp, New> =\\n Resp extends Ok<infer _>\\n ? Ok<New>\\n : Resp extends Created<infer _>\\n ? Created<New>\\n : Resp extends Accepted<infer _>\\n ? Accepted<New>\\n : Resp extends NoContent\\n ? NoContent\\n : Resp extends SuccessfulResponse<infer _>\\n ? APIResponse<New, Resp['status']>\\n : never;\\n\\ntype SSEListener = (eventType: string) => AsyncIterable<string>;\\n\\nfunction sse(response: Response): SSEListener {\\n // Every iterator of an event type reads one queue. Each waiting next() keeps\\n // its own wake-up in `waiters`, and a push or the end of the stream wakes all\\n // of them: a woken next() that finds the queue empty waits again. One shared\\n // wake-up slot would let a second iterator overwrite the first one's, which\\n // then never wakes.\\n const subscribers = new Map<\\n string,\\n { queue: string[]; waiters: Set<() => void> }\\n >();\\n let started = false;\\n let streamDone = false;\\n let streamFailure: { error: unknown } | null = null;\\n\\n function wake(waiters: Set<() => void>) {\\n for (const resolve of waiters) resolve();\\n waiters.clear();\\n }\\n\\n function dispatch(eventType: string, data: string) {\\n const sub = subscribers.get(eventType);\\n if (sub) {\\n sub.queue.push(data);\\n wake(sub.waiters);\\n }\\n }\\n\\n function endAll() {\\n streamDone = true;\\n for (const sub of subscribers.values()) {\\n wake(sub.waiters);\\n }\\n }\\n\\n function startReading() {\\n if (started) return;\\n started = true;\\n const decoder = new TextDecoder();\\n let buffer = '';\\n\\n // The pump never rejects: the catch below hands a stream failure to the\\n // listeners, so nothing awaits it. `void` states that, and keeps generated\\n // output clean under @typescript-eslint/no-floating-promises.\\n void (async () => {\\n try {\\n for await (const value of response.body!) {\\n buffer += decoder.decode(value, { stream: true });\\n const parts = buffer.split('\\\\n\\\\n');\\n buffer = parts.pop()!;\\n\\n for (const part of parts) {\\n if (!part.trim()) continue;\\n let eventType = 'message';\\n let data = '';\\n for (const line of part.split('\\\\n')) {\\n if (line.startsWith('event:')) {\\n eventType = line.slice(6).trim();\\n } else if (line.startsWith('data:')) {\\n data += (data ? '\\\\n' : '') + line.slice(5).trim();\\n }\\n }\\n if (data) dispatch(eventType, data);\\n }\\n }\\n } catch (error) {\\n streamFailure = { error };\\n }\\n endAll();\\n })();\\n }\\n\\n return function listen(eventType: string): AsyncIterable<string> {\\n if (!subscribers.has(eventType)) {\\n subscribers.set(eventType, { queue: [], waiters: new Set() });\\n }\\n const sub = subscribers.get(eventType)!;\\n startReading();\\n\\n return {\\n [Symbol.asyncIterator]() {\\n return {\\n async next(): Promise<IteratorResult<string>> {\\n while (sub.queue.length === 0) {\\n if (streamFailure) throw streamFailure.error;\\n if (streamDone) return { value: undefined, done: true };\\n const { promise, resolve } = Promise.withResolvers<void>();\\n sub.waiters.add(resolve);\\n await promise;\\n }\\n return { value: sub.queue.shift()!, done: false };\\n },\\n async return(): Promise<IteratorResult<string>> {\\n return { value: undefined, done: true };\\n },\\n };\\n },\\n };\\n };\\n}\\n\\n\\n\\ntype Unionize<T> = T extends [infer Single extends OutputType]\\n ? InstanceType<Single>\\n : T extends readonly [...infer Tuple extends OutputType[]]\\n ? { [I in keyof Tuple]: InstanceType<Tuple[I]> }[number]\\n : never;\\n\\ntype InstanceType<T> =\\n T extends Type<infer U>\\n ? U\\n : T extends { type: Type<infer U> }\\n ? U\\n : T extends Array<unknown>\\n ? Unionize<T>\\n : never;\\n\\ntype ResponseData<T extends OutputType[]> =\\n Extract<InstanceType<T>, SuccessfulResponse> extends SuccessfulResponse<\\n infer P\\n >\\n ? P\\n : unknown;\\n\\ntype ResponseMapper<T extends OutputType[], R> = (data: ResponseData<T>) => R;\\n\\ninterface Type<T> {\\n new (...args: any[]): T;\\n}\\ntype Parser = (\\n response: Response,\\n) => Promise<unknown> | ReadableStream<any> | SSEListener;\\n/** An output that `range` declares reads every status of the range that no exact output declares. */\\ntype OutputType =\\n | Type<APIResponse>\\n | { parser: Parser; type: Type<APIResponse>; range?: StatusRange };\\n\\n// Bare z.custom (no predicate) on purpose: Request/Response from another\\n// realm (undici vs global fetch) fail instanceof checks. The output is\\n// typed as a Promise directly \u2014 zod 4 deprecated z.promise.\\nconst fetchType = z\\n .function({\\n input: [z.custom<Request>()],\\n output: z.custom<Promise<Response>>(),\\n })\\n .optional();\\n\\n/** Reads the body of a status the operation declares no output for. */\\nconst undeclared: Parser = buffered();\\n\\nasync function parse<T extends OutputType[]>(\\n outputs: T,\\n response: Response,\\n): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\\nasync function parse<T extends OutputType[], R>(\\n outputs: T,\\n response: Response,\\n mapper: ResponseMapper<T, R>,\\n): Promise<\\n RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>\\n>;\\nasync function parse(\\n outputs: OutputType[],\\n response: Response,\\n mapper?: (data: unknown) => unknown,\\n): Promise<APIResponse> {\\n const declared = match(outputs, response.status);\\n const output = declared ? typeOf(declared) : null;\\n const parser =\\n declared && 'parser' in declared ? declared.parser : undeclared;\\n\\n if (response.ok) {\\n const data = await parser(response);\\n const mapped = mapper ? mapper(data) : data;\\n const success =\\n output && isTypeOf(output, APIResponse) ? output : APIResponse;\\n return success.create(response.status, response.headers, mapped);\\n }\\n\\n const failure = output && isTypeOf(output, APIError) ? output : APIError;\\n throw failure.create(\\n response.status,\\n response.headers,\\n await parser(response),\\n );\\n}\\n\\n// OpenAPI 3.2 Responses Object: an explicit code takes precedence over the\\n// range that covers it.\\nfunction match(outputs: OutputType[], status: number) {\\n const range = `${Math.trunc(status / 100)}XX`;\\n return (\\n outputs.find(\\n (output) => !('range' in output) && statusOf(output) === status,\\n ) ?? outputs.find((output) => 'range' in output && output.range === range)\\n );\\n}\\n\\nfunction typeOf(output: OutputType) {\\n return 'parser' in output ? output.type : output;\\n}\\n\\nfunction statusOf(output: OutputType) {\\n const type = typeOf(output);\\n return isTypeOf(type, APIResponse) || isTypeOf(type, APIError)\\n ? type.status\\n : undefined;\\n}\\n\\nfunction isTypeOf<T extends Type<APIResponse>>(\\n instance: any,\\n baseType: T,\\n): instance is T {\\n return (\\n instance === baseType ||\\n Object.prototype.isPrototypeOf.call(baseType, instance)\\n );\\n}\\n\\nclass Dispatcher {\\n #interceptors: Interceptor[] = [];\\n #fetch: z.infer<typeof fetchType>;\\n constructor(interceptors: Interceptor[], fetch?: z.infer<typeof fetchType>) {\\n this.#interceptors = interceptors;\\n this.#fetch = fetch;\\n }\\n\\n async send<T extends OutputType[]>(\\n config: RequestConfig,\\n outputs: T,\\n signal?: AbortSignal,\\n ): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\\n async send<T extends OutputType[], R>(\\n config: RequestConfig,\\n outputs: T,\\n signal: AbortSignal | undefined,\\n mapper: ResponseMapper<T, R>,\\n ): Promise<\\n RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>\\n >;\\n async send<T extends OutputType[], R = ResponseData<T>>(\\n config: RequestConfig,\\n outputs: T,\\n signal?: AbortSignal,\\n mapper?: ResponseMapper<T, R>,\\n ) {\\n for (const interceptor of this.#interceptors) {\\n if (interceptor.before) {\\n config = await interceptor.before(config);\\n }\\n }\\n\\n const init =\\n signal === undefined ? config.init : { ...config.init, signal };\\n\\n let response = await (this.#fetch ?? fetch)(new Request(config.url, init));\\n\\n for (const interceptor of this.#interceptors.toReversed()) {\\n if (interceptor.after) {\\n response = await interceptor.after(response.clone());\\n }\\n }\\n\\n if (mapper) {\\n return await parse(outputs, response, mapper);\\n }\\n return await parse(outputs, response);\\n }\\n}\\n\\n/** How an operation pages, as the spec IR records it. Paths are dot-separated paths into the response body. */\\ntype Pagination =\\n | {\\n type: 'offset';\\n offsetParamName: string;\\n limitParamName: string;\\n items: string;\\n hasMore: string;\\n statusCode: number;\\n /** The offset parameter's default in the spec. */\\n start?: number;\\n }\\n | {\\n type: 'page';\\n pageNumberParamName: string;\\n pageSizeParamName: string;\\n items: string;\\n hasMore: string;\\n statusCode: number;\\n /** The page parameter's default in the spec. */\\n start?: number;\\n }\\n | {\\n type: 'cursor';\\n cursorParamName: string;\\n items: string;\\n hasMore: string;\\n statusCode: number;\\n /** Path of the cursor that requests the next page. */\\n nextCursor?: string;\\n };\\n\\ntype PathValue<T, P extends string> = P extends `${infer K}.${infer Rest}`\\n ? K extends keyof NonNullable<T>\\n ? PathValue<NonNullable<T>[K], Rest>\\n : never\\n : P extends keyof NonNullable<T>\\n ? NonNullable<T>[P]\\n : never;\\n\\n/** The item type of the array at `P` in `Data`. */\\ntype ItemOf<Data, P extends string> =\\n NonNullable<PathValue<Data, P>> extends readonly (infer I)[] ? I : never;\\n\\n/** Options for the request a page fetch sends; they override the first request's. */\\ninterface PageRequestOptions {\\n signal?: AbortSignal;\\n}\\n\\n/**\\n * The way from a page to the next. A next page has the type of the page it\\n * comes from, so generic code over one endpoint keeps that endpoint's type.\\n */\\ninterface PageControls<Item> extends AsyncIterable<Item> {\\n hasNextPage(): boolean;\\n getNextPage<P extends PageControls<unknown>>(\\n this: P,\\n options?: PageRequestOptions,\\n ): Promise<P>;\\n /** This page, then each following page. */\\n iterPages<P extends PageControls<unknown>>(\\n this: P,\\n options?: PageRequestOptions,\\n ): AsyncGenerator<P>;\\n}\\n\\n/** A page: the response body's fields, and the way to the next page. */\\ntype Page<Data, Item> = Data & PageControls<Item>;\\n\\ntype FetchPage = (\\n input: Record<string, unknown>,\\n options: PageRequestOptions | undefined,\\n) => Promise<ResponsePage>;\\n\\nfunction at(data: unknown, path: string): unknown {\\n let value = data;\\n for (const key of path.split('.')) {\\n if (typeof value !== 'object' || value === null) return undefined;\\n value = Reflect.get(value, key);\\n }\\n return value;\\n}\\n\\n/**\\n * The position an omitted offset or page parameter stands for: the spec's\\n * default, else the first offset (0) or the first page (1).\\n */\\nfunction position(sent: unknown, start: number | undefined, first: number) {\\n if (typeof sent === 'number') return sent;\\n return start ?? first;\\n}\\n\\nclass ResponsePage {\\n readonly #input: Record<string, unknown>;\\n readonly #pagination: Pagination;\\n readonly #fetchPage: FetchPage;\\n readonly #items: unknown[];\\n\\n constructor(\\n data: object,\\n input: Record<string, unknown>,\\n pagination: Pagination,\\n fetchPage: FetchPage,\\n ) {\\n Object.assign(this, data);\\n this.#input = input;\\n this.#pagination = pagination;\\n this.#fetchPage = fetchPage;\\n const items = at(data, pagination.items);\\n // A spec may declare the items array nullable; a page without one is empty.\\n this.#items = Array.isArray(items) ? items : [];\\n }\\n\\n hasNextPage() {\\n return Boolean(at(this, this.#pagination.hasMore));\\n }\\n\\n async getNextPage(options?: PageRequestOptions) {\\n return this.#fetchPage(this.#nextInput(), options);\\n }\\n\\n async *iterPages(options?: PageRequestOptions) {\\n yield this;\\n let page = this.hasNextPage() ? await this.getNextPage(options) : undefined;\\n while (page) {\\n yield page;\\n page = page.hasNextPage() ? await page.getNextPage(options) : undefined;\\n }\\n }\\n\\n async *[Symbol.asyncIterator]() {\\n for await (const page of this.iterPages()) {\\n yield* page.#items;\\n }\\n }\\n\\n #nextInput(): Record<string, unknown> {\\n const pagination = this.#pagination;\\n switch (pagination.type) {\\n case 'offset': {\\n const offset = position(\\n this.#input[pagination.offsetParamName],\\n pagination.start,\\n 0,\\n );\\n return {\\n ...this.#input,\\n [pagination.offsetParamName]: offset + this.#items.length,\\n };\\n }\\n case 'page': {\\n const page = position(\\n this.#input[pagination.pageNumberParamName],\\n pagination.start,\\n 1,\\n );\\n return { ...this.#input, [pagination.pageNumberParamName]: page + 1 };\\n }\\n case 'cursor': {\\n const cursor = pagination.nextCursor\\n ? at(this, pagination.nextCursor)\\n : undefined;\\n if (typeof cursor !== 'string') {\\n throw new Error(\\n 'The response says more pages exist but names no next cursor',\\n );\\n }\\n return { ...this.#input, [pagination.cursorParamName]: cursor };\\n }\\n }\\n }\\n}\\n\\n/** Builds the Page for `data`, the body of a response to `input`. */\\nfunction createPage(\\n data: object,\\n input: Record<string, unknown>,\\n pagination: Pagination,\\n fetchPage: FetchPage,\\n): ResponsePage {\\n return new ResponsePage(data, input, pagination, fetchPage);\\n}\\n\\n/**\\n * The promise of a page that is also an async iterable of every item across\\n * pages, so `for await (const item of client.request(\u2026))` needs no `await`.\\n */\\nclass PagePromise<P extends AsyncIterable<Item>, Item>\\n extends Promise<P>\\n implements AsyncIterable<Item>\\n{\\n static override get [Symbol.species]() {\\n return Promise;\\n }\\n\\n constructor(page: Promise<P>) {\\n super((resolve, reject) => {\\n page.then(resolve, reject);\\n });\\n }\\n\\n async *[Symbol.asyncIterator]() {\\n yield* await this;\\n }\\n}\\n\\n\\n\\nclass ParseError<T extends z.ZodType> extends Error {\\n public data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>;\\n constructor(data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>) {\\n super('Validation failed');\\n this.name = 'ParseError';\\n this.data = data;\\n }\\n}\\n\\nfunction parseInput<T extends z.ZodType>(\\n schema: T,\\n input: unknown,\\n): z.infer<T> {\\n const result = schema.safeParse(input);\\n if (!result.success) {\\n const error = z.flattenError(result.error, (issue) => issue);\\n throw new ParseError<T>(error);\\n }\\n return result.data;\\n}\\n\\n\\n\\ntype SecurityContext = {\\n scheme: string;\\n scopes: readonly string[];\\n roles: readonly string[];\\n};\\ntype SecurityCredentialValue =\\n | string\\n | true\\n | {\\n username: string;\\n password: string;\\n };\\ntype SecurityCredentialProvider<T extends SecurityCredentialValue> = (\\n context: SecurityContext,\\n) => T | Promise<T>;\\ntype SecurityCredential<\\n T extends SecurityCredentialValue = SecurityCredentialValue,\\n> = T | SecurityCredentialProvider<T>;\\n\\nconst providerSchema = <T extends SecurityCredentialValue>() =>\\n z.custom<SecurityCredentialProvider<T>>(\\n (value) => typeof value === 'function',\\n );\\nconst stringCredentialSchema = z.union([\\n z.string(),\\n z.literal(true),\\n providerSchema<string | true>(),\\n]);\\nconst basicCredentialValueSchema = z.object({\\n username: z.string(),\\n password: z.string(),\\n});\\nconst basicCredentialSchema = z.union([\\n basicCredentialValueSchema,\\n z.literal(true),\\n providerSchema<{ username: string; password: string } | true>(),\\n]);\\nconst mutualTlsCredentialSchema = z.union([\\n z.literal(true),\\n providerSchema<true>(),\\n]);\\n\\ntype RuntimeSecurityScheme =\\n | { type: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }\\n | { type: 'http'; scheme: string }\\n | { type: 'oauth2' }\\n | { type: 'openIdConnect' }\\n | { type: 'mutualTLS' };\\n\\n/** The spec's components.securitySchemes; a requirement can name a scheme it lacks (an unresolved external one). */\\ntype RuntimeSecuritySchemes = {\\n readonly [name: string]: RuntimeSecurityScheme | undefined;\\n};\\n\\nfunction createSecurityInterceptor(\\n requirements: readonly Record<string, readonly string[]>[],\\n credentials: Record<string, SecurityCredential | undefined> | undefined,\\n schemes: RuntimeSecuritySchemes,\\n): Interceptor {\\n return {\\n async before(config) {\\n if (requirements.length === 0) return config;\\n const secured = requirements.filter(\\n (requirement) => Object.keys(requirement).length > 0,\\n );\\n const selected = secured.find((requirement) =>\\n Object.keys(requirement).every(\\n (name) => credentials?.[name] !== undefined,\\n ),\\n );\\n if (!selected) {\\n if (\\n requirements.some(\\n (requirement) => Object.keys(requirement).length === 0,\\n )\\n )\\n return config;\\n throw new Error(\\n `Missing credentials for security requirements: ${secured\\n .map((requirement) => Object.keys(requirement).join(' + '))\\n .join(' or ')}`,\\n );\\n }\\n for (const [name, values] of Object.entries(selected)) {\\n const scheme = schemes[name];\\n if (!scheme) {\\n throw new Error(`Unsupported external security scheme: ${name}`);\\n }\\n const configured = credentials?.[name];\\n const isOAuth =\\n scheme.type === 'oauth2' || scheme.type === 'openIdConnect';\\n const credential =\\n typeof configured === 'function'\\n ? await configured({\\n scheme: name,\\n scopes: isOAuth ? values : [],\\n roles: isOAuth ? [] : values,\\n })\\n : configured;\\n applyCredential(config, scheme, credential);\\n }\\n return config;\\n },\\n };\\n}\\n\\nfunction applyCredential(\\n config: RequestConfig,\\n scheme: RuntimeSecurityScheme,\\n credential: SecurityCredentialValue | undefined,\\n) {\\n if (credential === undefined) {\\n throw new Error('Security credential provider returned no credential');\\n }\\n // true declares a transport-owned credential: the configured fetch, a host\\n // proxy, or the browser's cookie jar supplies it, so nothing is set here.\\n if (credential === true) return;\\n if (scheme.type === 'apiKey') {\\n if (typeof credential !== 'string') {\\n throw new TypeError('API key credentials must be strings');\\n }\\n if (scheme.in === 'header') {\\n if (!config.init.headers.has(scheme.name)) {\\n config.init.headers.set(scheme.name, credential);\\n }\\n } else if (scheme.in === 'query') {\\n if (!config.url.searchParams.has(scheme.name)) {\\n config.url.searchParams.set(scheme.name, credential);\\n }\\n } else if (scheme.in === 'cookie') {\\n if ('document' in globalThis) {\\n throw new Error(\\n `Cannot send the ${scheme.name} cookie credential: browsers forbid setting the Cookie header. Let the browser send the cookie and pass a fetch that sets credentials: 'include'.`,\\n );\\n }\\n const cookie = `${scheme.name}=${encodeURIComponent(credential)}`;\\n const existing = config.init.headers.get('Cookie');\\n if (\\n !existing\\n ?.split(';')\\n .some((part) => part.trim().startsWith(`${scheme.name}=`))\\n ) {\\n config.init.headers.set(\\n 'Cookie',\\n existing ? `${existing}; ${cookie}` : cookie,\\n );\\n }\\n } else {\\n throw new TypeError(`Unsupported apiKey location: ${String(scheme.in)}`);\\n }\\n return;\\n }\\n if (scheme.type === 'mutualTLS') {\\n throw new TypeError(\\n 'mutualTLS credentials must be true when the custom fetch owns the client certificate',\\n );\\n }\\n if (scheme.type === 'http' && scheme.scheme.toLowerCase() === 'basic') {\\n if (\\n typeof credential !== 'object' ||\\n !('username' in credential) ||\\n !('password' in credential)\\n ) {\\n throw new TypeError('Basic credentials require username and password');\\n }\\n const bytes = new TextEncoder().encode(\\n `${credential.username}:${credential.password}`,\\n );\\n let binary = '';\\n for (const byte of bytes) binary += String.fromCharCode(byte);\\n if (!config.init.headers.has('Authorization')) {\\n config.init.headers.set('Authorization', `Basic ${btoa(binary)}`);\\n }\\n return;\\n }\\n if (typeof credential !== 'string') {\\n throw new TypeError(`${scheme.type} credentials must be strings`);\\n }\\n const prefix =\\n scheme.type === 'http' ? authorizationScheme(scheme.scheme) : 'Bearer';\\n if (!config.init.headers.has('Authorization')) {\\n config.init.headers.set('Authorization', `${prefix} ${credential}`);\\n }\\n}\\n\\n// OpenAPI carries the lowercase registry name, while servers routinely match the\\n// Authorization prefix case-sensitively (`header.startsWith('Bearer ')`).\\nconst authorizationSchemes: Record<string, string> = {\\n basic: 'Basic',\\n bearer: 'Bearer',\\n digest: 'Digest',\\n hoba: 'HOBA',\\n mutual: 'Mutual',\\n negotiate: 'Negotiate',\\n oauth: 'OAuth',\\n 'scram-sha-1': 'SCRAM-SHA-1',\\n 'scram-sha-256': 'SCRAM-SHA-256',\\n};\\n\\nfunction authorizationScheme(scheme: string) {\\n return authorizationSchemes[scheme.toLowerCase()] ?? scheme;\\n}\\n\\n\\n\\ninterface DispatchOptions {\\n interceptors: Interceptor[];\\n fetch: z.infer<typeof fetchType>;\\n baseUrl: string;\\n signal?: AbortSignal;\\n}\\n\\n/** One operation of a generated SDK's endpoint table. */\\ninterface Route {\\n schema: z.ZodType;\\n output: OutputType[];\\n security: readonly Record<string, readonly string[]>[];\\n toRequest(input: unknown, baseUrl: string): RequestConfig;\\n dispatch(input: unknown, options: DispatchOptions): Promise<unknown>;\\n /** Present when the operation pages; `request()` then resolves to a Page. */\\n pagination?: Pagination;\\n}\\n\\n/** What a generated SDK knows about its API: its endpoint table, servers and security. */\\ninterface Api {\\n routes: Record<string, Route>;\\n /** The spec's server URLs with their variables' defaults. */\\n servers: readonly string[];\\n securitySchemes: RuntimeSecuritySchemes;\\n /** Validates `credentials`: one optional entry per security scheme. */\\n credentials: z.ZodType<Record<string, SecurityCredential | undefined>>;\\n}\\n\\ntype BaseUrl = string | (() => string | Promise<string>);\\n\\n/** A spec with two or more servers has no single default, so the caller picks one. */\\ntype BaseUrlSetting<A extends Api> = A['servers'] extends readonly [\\n unknown,\\n unknown,\\n ...unknown[],\\n]\\n ? { baseUrl: BaseUrl }\\n : { baseUrl?: BaseUrl };\\n\\ntype CredentialsSetting<A extends Api> =\\n keyof A['securitySchemes'] extends never\\n ? unknown\\n : { credentials?: z.input<A['credentials']> };\\n\\ntype ClientSettings<A extends Api> = BaseUrlSetting<A> &\\n CredentialsSetting<A> & {\\n headers?: Record<string, string>;\\n fetch?: (request: Request) => Promise<Response>;\\n /** Skip request input validation. Settings and TypeScript types still enforce correct usage. */\\n skipValidation?: boolean;\\n };\\n\\ninterface RequestOptions {\\n signal?: AbortSignal;\\n headers?: HeadersInit;\\n}\\n\\ntype DispatchReturn<A extends Api, E extends keyof A['routes']> = Awaited<\\n ReturnType<A['routes'][E]['dispatch']>\\n>;\\n\\ntype InferData<A extends Api, E extends keyof A['routes']> =\\n DispatchReturn<A, E> extends APIResponse<infer D> ? D : DispatchReturn<A, E>;\\n\\n/**\\n * What `request()` resolves to: the first Page for an operation that pages,\\n * its output otherwise. Distributive over `E`, so for a generic `E` TypeScript\\n * reads it through `E`'s constraint.\\n */\\ntype RouteResult<A extends Api, E extends keyof A['routes']> = E extends unknown\\n ? A['routes'][E] extends { pagination: { items: infer P extends string } }\\n ? Page<InferData<A, E>, ItemOf<InferData<A, E>, P>>\\n : InferData<A, E>\\n : never;\\n\\n/**\\n * What `client.request(endpoint)` returns: a promise of the result that, for\\n * an operation that pages, is also an async iterable of every item. An\\n * interface, not an intersection, so TypeScript awaits it for a generic\\n * endpoint too.\\n */\\ninterface RequestPromise<Result> extends Promise<Result> {\\n [Symbol.asyncIterator]: Result extends AsyncIterable<infer Item>\\n ? () => AsyncIterator<Item>\\n : undefined;\\n}\\n\\ntype EndpointsOf<A extends Api> = {\\n [E in keyof A['routes']]: {\\n input: z.input<A['routes'][E]['schema']>;\\n output: InferData<A, E>;\\n /** What `request()` resolves to: the first Page for an operation that pages, its output otherwise. */\\n result: RouteResult<A, E>;\\n error:\\n | Extract<Unionize<A['routes'][E]['output']>, ProblematicResponse>\\n | ParseError<A['routes'][E]['schema']>;\\n };\\n};\\n\\nconst baseUrlSchema = z\\n .union([\\n z.string(),\\n z.custom<() => string | Promise<string>>(\\n (value) => typeof value === 'function',\\n ),\\n ])\\n .transform(async (baseUrl, ctx) => {\\n const value = typeof baseUrl === 'function' ? await baseUrl() : baseUrl;\\n if (typeof value !== 'string') {\\n ctx.addIssue({\\n code: 'custom',\\n message: 'baseUrl must resolve to a string',\\n });\\n return z.NEVER;\\n }\\n if (/^[a-z][a-z\\\\d+.-]*:/i.test(value)) {\\n return value;\\n }\\n const page: { href: string } | undefined = Reflect.get(\\n globalThis,\\n 'location',\\n );\\n if (page === undefined) {\\n throw new TypeError(\\n `baseUrl \\\"${value}\\\" is relative, and there is no page location to resolve it against.`,\\n );\\n }\\n return new URL(value, page.href).href;\\n });\\n\\nfunction settingsSchema(api: Api) {\\n const [server, ...others] = api.servers;\\n return z.object({\\n // OpenAPI 3.2: a spec without servers is served from \\\"/\\\".\\n baseUrl:\\n others.length > 0 ? baseUrlSchema : baseUrlSchema.prefault(server ?? '/'),\\n headers: z.record(z.string(), z.string()).optional(),\\n fetch: fetchType,\\n skipValidation: z.boolean().optional(),\\n credentials: api.credentials.optional(),\\n });\\n}\\n\\nclass Client<A extends Api> {\\n readonly api: A;\\n options: ClientSettings<A>;\\n readonly #settings: ReturnType<typeof settingsSchema>;\\n\\n constructor(api: A, options: ClientSettings<A>) {\\n this.api = api;\\n this.options = options;\\n this.#settings = settingsSchema(api);\\n }\\n\\n /** The settings, validated, with baseUrl resolved. */\\n async settings() {\\n return this.#settings.parseAsync(this.options);\\n }\\n\\n /**\\n * Sends a request and returns the unwrapped response data, or, for an\\n * operation that pages, its first Page.\\n */\\n request<const E extends keyof A['routes'] & string>(\\n endpoint: E,\\n input: z.input<A['routes'][E]['schema']>,\\n options?: RequestOptions,\\n ): RequestPromise<EndpointsOf<A>[E]['result']>;\\n request(\\n endpoint: string,\\n input: unknown,\\n options?: RequestOptions,\\n ): Promise<unknown> {\\n const pagination = this.api.routes[endpoint]?.pagination;\\n if (pagination) {\\n return new PagePromise(\\n firstPage(this, endpoint, input, pagination, options),\\n );\\n }\\n return send(this, endpoint, input, options).then((result) =>\\n result instanceof APIResponse ? result.data : result,\\n );\\n }\\n\\n /** Builds a ready-to-send request without sending it. */\\n async prepare<const E extends keyof A['routes'] & string>(\\n endpoint: E,\\n input: z.input<A['routes'][E]['schema']>,\\n options?: RequestOptions,\\n ) {\\n return prepare(this, endpoint, input, options);\\n }\\n\\n async defaultHeaders() {\\n const settings = await this.settings();\\n return { ...settings.headers };\\n }\\n\\n setOptions(options: Partial<ClientSettings<A>>) {\\n this.options = { ...this.options, ...options };\\n }\\n}\\n\\nfunction createClient<A extends Api>(\\n api: A,\\n settings: ClientSettings<A>,\\n): Client<A> {\\n return new Client(api, settings);\\n}\\n\\nasync function firstPage(\\n client: Client<Api>,\\n endpoint: string,\\n input: unknown,\\n pagination: Pagination,\\n options: RequestOptions | undefined,\\n) {\\n if (typeof input !== 'object' || input === null) {\\n throw new TypeError(\\n `${endpoint} pages through its input, so the input must be an object`,\\n );\\n }\\n const fetchPage = async (\\n pageInput: Record<string, unknown>,\\n pageOptions: PageRequestOptions | undefined,\\n ) => {\\n const result = await send(client, endpoint, pageInput, {\\n ...options,\\n ...pageOptions,\\n });\\n if (\\n !(result instanceof APIResponse) ||\\n result.status !== pagination.statusCode\\n ) {\\n throw result;\\n }\\n const data: unknown = result.data;\\n if (typeof data !== 'object' || data === null) {\\n throw new TypeError(`${endpoint} answered a page that is not an object`);\\n }\\n return createPage(data, pageInput, pagination, fetchPage);\\n };\\n return fetchPage(Object.fromEntries(Object.entries(input)), undefined);\\n}\\n\\nfunction interceptorsFor(\\n route: Route,\\n settings: Awaited<ReturnType<Client<Api>['settings']>>,\\n api: Api,\\n options: RequestOptions | undefined,\\n) {\\n return [\\n createHeadersInterceptor({ ...settings.headers }, options?.headers ?? {}),\\n createSecurityInterceptor(\\n route.security,\\n settings.credentials,\\n api.securitySchemes,\\n ),\\n ];\\n}\\n\\n/**\\n * Sends a validated request with the client's settings and returns the\\n * response status class (status, headers, data). Throws `APIError` on\\n * non-ok responses.\\n */\\nasync function request<\\n A extends Api,\\n const E extends keyof A['routes'] & string,\\n>(\\n client: Client<A>,\\n endpoint: E,\\n input: z.input<A['routes'][E]['schema']>,\\n options?: RequestOptions,\\n): Promise<DispatchReturn<A, E>>;\\nasync function request(\\n client: Client<Api>,\\n endpoint: string,\\n input: unknown,\\n options?: RequestOptions,\\n): Promise<unknown> {\\n return send(client, endpoint, input, options);\\n}\\n\\nfunction routeOf(api: Api, endpoint: string) {\\n const route = api.routes[endpoint];\\n if (route === undefined) {\\n throw new Error(`The api has no endpoint '${endpoint}'`);\\n }\\n return route;\\n}\\n\\nasync function send(\\n client: Client<Api>,\\n endpoint: string,\\n input: unknown,\\n options: RequestOptions | undefined,\\n) {\\n const route = routeOf(client.api, endpoint);\\n const settings = await client.settings();\\n const parsedInput = settings.skipValidation\\n ? input\\n : parseInput(route.schema, input);\\n return route.dispatch(parsedInput, {\\n fetch: settings.fetch,\\n baseUrl: settings.baseUrl,\\n interceptors: interceptorsFor(route, settings, client.api, options),\\n ...(options?.signal ? { signal: options.signal } : {}),\\n });\\n}\\n\\n/**\\n * Builds a validated `RequestConfig` (url + init) with a `parse` function\\n * attached, without sending it.\\n */\\nasync function prepare<\\n A extends Api,\\n const E extends keyof A['routes'] & string,\\n>(\\n client: Client<A>,\\n endpoint: E,\\n input: z.input<A['routes'][E]['schema']>,\\n options?: RequestOptions,\\n): Promise<\\n RequestConfig & {\\n parse: (response: Response) => Promise<DispatchReturn<A, E>>;\\n }\\n>;\\nasync function prepare(\\n client: Client<Api>,\\n endpoint: string,\\n input: unknown,\\n options?: RequestOptions,\\n): Promise<\\n RequestConfig & { parse: (response: Response) => Promise<unknown> }\\n> {\\n const route = routeOf(client.api, endpoint);\\n const settings = await client.settings();\\n const parsedInput = settings.skipValidation\\n ? input\\n : parseInput(route.schema, input);\\n let config = route.toRequest(parsedInput, settings.baseUrl);\\n if (options?.signal) {\\n config = { ...config, init: { ...config.init, signal: options.signal } };\\n }\\n for (const interceptor of interceptorsFor(\\n route,\\n settings,\\n client.api,\\n options,\\n )) {\\n if (interceptor.before) {\\n config = await interceptor.before(config);\\n }\\n }\\n return {\\n ...config,\\n parse: (response: Response) => parse(route.output, response),\\n };\\n}\\n\",\"bindings\":[{\"kind\":\"declared\",\"name\":\"Init\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":true,\"occurrences\":[5,94],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"RequestConfig\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":true,\"occurrences\":[70,5383,5678,5704,5721,27744,27919,28190,38498,42224,51389,51607],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Method\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":true,\"occurrences\":[200,5311],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"HeadersInit\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":true,\"occurrences\":[280,5903,43683],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"BodyInit\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":true,\"occurrences\":[345,1922,2827,2949,3501,3947,4108,4559],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"template\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":false,\"occurrences\":[433,2257],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Input\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":true,\"occurrences\":[1010,1769,1824,4745,4840,4936,5030,5123,5213],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"toWireValue\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":false,\"occurrences\":[1197,2506,2680,3688],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"wireItems\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":false,\"occurrences\":[1406,2613,3631,4231],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Props\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":true,\"occurrences\":[1542,1795,1838,4759,4854,4950,5044,5137,5227],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Serializer\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":false,\"occurrences\":[1737,2923,3475,3921,4082,4533,5349],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Serialized\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":true,\"occurrences\":[2032,2806],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"JsonSerializer\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":false,\"occurrences\":[2900,4781],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"UrlencodedSerializer\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":false,\"occurrences\":[3446,4876],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"EmptySerializer\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":false,\"occurrences\":[3897,4972],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"FormDataSerializer\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":false,\"occurrences\":[4055,5066],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"RawSerializer\",\"file\":\"http/request.ts\",\"exported\":false,\"type\":false,\"occurrences\":[4511,5159,5249],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"json\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":false,\"occurrences\":[4733],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"urlencoded\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":false,\"occurrences\":[4822],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"empty\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":false,\"occurrences\":[4923],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"formdata\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":false,\"occurrences\":[5014],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"text\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":false,\"occurrences\":[5111],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"binary\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":false,\"occurrences\":[5199],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"toRequest\",\"file\":\"http/request.ts\",\"exported\":true,\"type\":false,\"occurrences\":[5290],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Interceptor\",\"file\":\"http/interceptors.ts\",\"exported\":true,\"type\":true,\"occurrences\":[5644,5919,27488,27573,36964,41902],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"createHeadersInterceptor\",\"file\":\"http/interceptors.ts\",\"exported\":true,\"type\":false,\"occurrences\":[5809,49521],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"isBinaryContentType\",\"file\":\"http/parse-response.ts\",\"exported\":false,\"type\":false,\"occurrences\":[6790,9311],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"chunked\",\"file\":\"http/parse-response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[7679],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"bodyless\",\"file\":\"http/parse-response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[7872],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"BufferedBody\",\"file\":\"http/parse-response.ts\",\"exported\":true,\"type\":true,\"occurrences\":[8045,8344],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"buffered\",\"file\":\"http/parse-response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[8324,25437],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"byContentType\",\"file\":\"http/parse-response.ts\",\"exported\":false,\"type\":false,\"occurrences\":[8778,9209],\"shorthands\":[]},{\"kind\":\"external\",\"name\":\"parse\",\"module\":\"fast-content-type-parse\",\"occurrences\":[9285],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"StatusRange\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":true,\"occurrences\":[9993,10301,24983],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Digit\",\"file\":\"http/response.ts\",\"exported\":false,\"type\":true,\"occurrences\":[10051,10361,10369],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ToNumber\",\"file\":\"http/response.ts\",\"exported\":false,\"type\":true,\"occurrences\":[10123,10345],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"RangeStatus\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":true,\"occurrences\":[10279,19977,20185,20375],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"APIResponse\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[10395,12124,12421,12714,13006,20360,20719,24915,24961,25923,26294,26318,27166,27278,43911,47659,48932],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"APIError\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[10829,13312,13631,13955,14276,14590,14911,15243,15561,15870,16189,16569,16926,17253,17585,17949,18285,18606,18957,19286,19959,20167,26451,26472,27197],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"failureMessage\",\"file\":\"http/response.ts\",\"exported\":false,\"type\":false,\"occurrences\":[11069,11333],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"bodySummary\",\"file\":\"http/response.ts\",\"exported\":false,\"type\":false,\"occurrences\":[11399,11719],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Ok\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[12110,12249,20305,20451,20469],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Created\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[12402,12537,20315,20496,20521],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Accepted\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[12694,12830,20330,20555,20583],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"NoContent\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[12988,13116,13214,20346,20620,20642],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"BadRequest\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[13290,13425,19581],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Unauthorized\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[13585,13744,19605],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"PaymentRequired\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[13906,14068,19631],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Forbidden\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[14233,14389,19660],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"NotFound\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[14548,14703,19683],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"MethodNotAllowed\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[14861,15030,19705],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"NotAcceptable\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[15196,15356,19735],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Conflict\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[15519,15674,19762],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Gone\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[15832,15983,19784],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"PreconditionFailed\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[16137,16308,19802],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"UnprocessableEntity\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[16476,16682,19897],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"TooManyRequests\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[16851,17039,19930],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"PayloadTooLarge\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[17204,17366,19834],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"UnsupportedMediaType\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[17531,17704,19863],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"InternalServerError\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[17896,18068,20022],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"NotImplemented\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[18237,18398,20055],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"BadGateway\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[18562,18719,20083],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ServiceUnavailable\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[18879,19070,20107],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"GatewayTimeout\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":false,\"occurrences\":[19238,19399,20139],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ClientError\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":true,\"occurrences\":[19563,20234],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ServerError\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":true,\"occurrences\":[20004,20248],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ProblematicResponse\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":true,\"occurrences\":[20212,45180],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"SuccessfulResponse\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":true,\"occurrences\":[20267,20677,24472,24500,25564,25768,27835,28081],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"RebindSuccessPayload\",\"file\":\"http/response.ts\",\"exported\":true,\"type\":true,\"occurrences\":[20402,25726,28039],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"SSEListener\",\"file\":\"http/sse.ts\",\"exported\":true,\"type\":true,\"occurrences\":[20779,20874,24773],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"sse\",\"file\":\"http/sse.ts\",\"exported\":true,\"type\":false,\"occurrences\":[20849],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Unionize\",\"file\":\"http/dispatcher.ts\",\"exported\":true,\"type\":true,\"occurrences\":[24002,24371,25551,25755,27822,28068,45144],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"InstanceType\",\"file\":\"http/dispatcher.ts\",\"exported\":true,\"type\":true,\"occurrences\":[24064,24174,24226,24455],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ResponseData\",\"file\":\"http/dispatcher.ts\",\"exported\":false,\"type\":true,\"occurrences\":[24406,24616,28160],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ResponseMapper\",\"file\":\"http/dispatcher.ts\",\"exported\":false,\"type\":true,\"occurrences\":[24565,25690,27999,28260],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Type\",\"file\":\"http/dispatcher.ts\",\"exported\":true,\"type\":true,\"occurrences\":[24256,24302,24650,24910,24956,27273],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Parser\",\"file\":\"http/dispatcher.ts\",\"exported\":true,\"type\":true,\"occurrences\":[24694,24942,25428],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"OutputType\",\"file\":\"http/dispatcher.ts\",\"exported\":true,\"type\":true,\"occurrences\":[24048,24132,24429,24590,24893,25481,25626,25837,26710,27002,27097,27717,27889,28142,42106],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"fetchType\",\"file\":\"http/dispatcher.ts\",\"exported\":true,\"type\":false,\"occurrences\":[25212,27533,27611,41941,46417],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"undeclared\",\"file\":\"http/dispatcher.ts\",\"exported\":false,\"type\":false,\"occurrences\":[25416,26117],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"parse\",\"file\":\"http/dispatcher.ts\",\"exported\":true,\"type\":false,\"occurrences\":[25465,25610,25819,28818,28875,52293],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"match\",\"file\":\"http/dispatcher.ts\",\"exported\":false,\"type\":false,\"occurrences\":[25957,26695],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"typeOf\",\"file\":\"http/dispatcher.ts\",\"exported\":false,\"type\":false,\"occurrences\":[26018,26987,27126],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"statusOf\",\"file\":\"http/dispatcher.ts\",\"exported\":false,\"type\":false,\"occurrences\":[26862,27080],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"isTypeOf\",\"file\":\"http/dispatcher.ts\",\"exported\":true,\"type\":false,\"occurrences\":[26277,26434,27151,27182,27254],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Dispatcher\",\"file\":\"http/dispatcher.ts\",\"exported\":true,\"type\":false,\"occurrences\":[27458],\"shorthands\":[]},{\"kind\":\"external\",\"name\":\"z\",\"module\":\"zod\",\"occurrences\":[25224,25252,25286,27518,27596,34675,34717,34743,34756,34795,34821,34834,34976,35022,35120,35764,35885,35897,35911,36002,36025,36049,36095,36137,36259,36271,41926,42085,42787,43277,44915,45278,45295,45311,45685,46180,46361,46370,46382,46448,47156,47856,50026,51312],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Pagination\",\"file\":\"http/page.ts\",\"exported\":true,\"type\":true,\"occurrences\":[29025,31700,31862,34005,42406,48441],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"PathValue\",\"file\":\"http/page.ts\",\"exported\":false,\"type\":true,\"occurrences\":[29759,29870,30094],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ItemOf\",\"file\":\"http/page.ts\",\"exported\":true,\"type\":true,\"occurrences\":[30047,44350],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"PageRequestOptions\",\"file\":\"http/page.ts\",\"exported\":true,\"type\":true,\"occurrences\":[30253,30622,30778,31014,32324,32436,48747],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"PageControls\",\"file\":\"http/page.ts\",\"exported\":true,\"type\":true,\"occurrences\":[30472,30571,30727,30929],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Page\",\"file\":\"http/page.ts\",\"exported\":true,\"type\":true,\"occurrences\":[30903,44328],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"FetchPage\",\"file\":\"http/page.ts\",\"exported\":false,\"type\":true,\"occurrences\":[30955,31735,31889,34030],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"at\",\"file\":\"http/page.ts\",\"exported\":false,\"type\":false,\"occurrences\":[31084,32048,32252,33534],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"position\",\"file\":\"http/page.ts\",\"exported\":false,\"type\":false,\"occurrences\":[31470,32964,33250],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ResponsePage\",\"file\":\"http/page.ts\",\"exported\":false,\"type\":false,\"occurrences\":[31059,31617,34044,34072],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"createPage\",\"file\":\"http/page.ts\",\"exported\":true,\"type\":false,\"occurrences\":[33929,49217],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"PagePromise\",\"file\":\"http/page.ts\",\"exported\":true,\"type\":false,\"occurrences\":[34293,47479],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ParseError\",\"file\":\"http/parser.ts\",\"exported\":true,\"type\":false,\"occurrences\":[34654,35182,45209],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"parseInput\",\"file\":\"http/parser.ts\",\"exported\":true,\"type\":false,\"occurrences\":[34955,50789,51834],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"SecurityContext\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":true,\"occurrences\":[35240,35532],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"SecurityCredentialValue\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":true,\"occurrences\":[35343,35492,35607,35633,35732,38560],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"SecurityCredentialProvider\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":true,\"occurrences\":[35455,35666,35773],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"SecurityCredential\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":true,\"occurrences\":[35575,36881,42812],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"providerSchema\",\"file\":\"http/security.ts\",\"exported\":false,\"type\":false,\"occurrences\":[35704,35930,36156,36290],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"stringCredentialSchema\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":false,\"occurrences\":[35860],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"basicCredentialValueSchema\",\"file\":\"http/security.ts\",\"exported\":false,\"type\":false,\"occurrences\":[35973,36107],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"basicCredentialSchema\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":false,\"occurrences\":[36071],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"mutualTlsCredentialSchema\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":false,\"occurrences\":[36231],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"RuntimeSecurityScheme\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":true,\"occurrences\":[36324,36714,38523],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"RuntimeSecuritySchemes\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":true,\"occurrences\":[36660,36937,42674],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"createSecurityInterceptor\",\"file\":\"http/security.ts\",\"exported\":true,\"type\":false,\"occurrences\":[36762,49600],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"applyCredential\",\"file\":\"http/security.ts\",\"exported\":false,\"type\":false,\"occurrences\":[38373,38471],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"authorizationSchemes\",\"file\":\"http/security.ts\",\"exported\":false,\"type\":false,\"occurrences\":[41484,41799],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"authorizationScheme\",\"file\":\"http/security.ts\",\"exported\":false,\"type\":false,\"occurrences\":[41143,41752],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"DispatchOptions\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":true,\"occurrences\":[41868,42275],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Route\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":true,\"occurrences\":[42067,42553,49386],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Api\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":true,\"occurrences\":[42522,43025,43191,43337,43729,43844,44191,44865,46121,46549,48239,48383,49431,49458,49927,50164,50332,50547,51213,51521],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"BaseUrl\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":true,\"occurrences\":[42854,43119,43145],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"BaseUrlSetting\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":true,\"occurrences\":[43000,43344],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"CredentialsSetting\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":true,\"occurrences\":[43162,43366],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"ClientSettings\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":true,\"occurrences\":[43312,46586,46694,48126,48267],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"RequestOptions\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":true,\"occurrences\":[43630,47205,47338,47905,48464,49474,50073,50220,50602,51359,51577],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"DispatchReturn\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":true,\"occurrences\":[43704,43882,43938,50100,51450],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"InferData\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":true,\"occurrences\":[43824,44333,44357,44384,44962],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"RouteResult\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":true,\"occurrences\":[44169,45098],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"RequestPromise\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":true,\"occurrences\":[44670,47226],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"EndpointsOf\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":true,\"occurrences\":[44843,47241],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"baseUrlSchema\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":false,\"occurrences\":[45262,46293,46309],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"settingsSchema\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":false,\"occurrences\":[46101,46645,46784],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"Client\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":false,\"occurrences\":[46532,48289,48314,48376,49424,49991,50157,50540,51277,51514],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"createClient\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":false,\"occurrences\":[48216],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"firstPage\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":false,\"occurrences\":[47500,48355],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"interceptorsFor\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":false,\"occurrences\":[49360,50937,52065],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"request\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":false,\"occurrences\":[49906,50138],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"routeOf\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":false,\"occurrences\":[50319,50650,51695],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"send\",\"file\":\"http/client.ts\",\"exported\":false,\"type\":false,\"occurrences\":[47581,48813,50267,50524],\"shorthands\":[]},{\"kind\":\"declared\",\"name\":\"prepare\",\"file\":\"http/client.ts\",\"exported\":true,\"type\":false,\"occurrences\":[47938,51192,51495],\"shorthands\":[]}],\"globals\":[{\"name\":\"Omit\",\"occurrences\":[12]},{\"name\":\"RequestInit\",\"occurrences\":[17]},{\"name\":\"Headers\",\"occurrences\":[54,5536,6120,10552,10601,10746,10987,11036,11253,12219,12333,12507,12626,12800,12920,13095,13204,13395,13517,13714,13838,14038,14165,14359,14480,14673,14793,15000,15128,15326,15451,15644,15764,15953,16069,16278,16408,16652,16783,17009,17136,17336,17463,17674,17806,18038,18169,18368,18494,18689,18811,19040,19170,19369,19495]},{\"name\":\"URL\",\"occurrences\":[105,2240,2886,46057]},{\"name\":\"Record\",\"occurrences\":[315,490,1018,1964,2094,2304,2855,2983,3308,3759,4002,4346,4626,5849,16531,30978,31651,31821,32820,33966,36814,36866,41506,42141,42538,42797,43406,48705]},{\"name\":\"ArrayBuffer\",\"occurrences\":[358]},{\"name\":\"Blob\",\"occurrences\":[372,9127]},{\"name\":\"FormData\",\"occurrences\":[379,4147]},{\"name\":\"URLSearchParams\",\"occurrences\":[390,3540,9735]},{\"name\":\"encodeURIComponent\",\"occurrences\":[960,39720]},{\"name\":\"String\",\"occurrences\":[979,1286,40142,40807]},{\"name\":\"Date\",\"occurrences\":[1257]},{\"name\":\"Array\",\"occurrences\":[1494,24346,32175]},{\"name\":\"JSON\",\"occurrences\":[3124,3266,8981,11949]},{\"name\":\"Promise\",\"occurrences\":[5696,5770,8397,23391,23644,23860,24732,25295,25535,25715,25915,27806,28026,30647,31051,34352,34452,34486,35558,42293,42889,43464,44701,45335,47359,50092,50239,51378,51442,51596,51656]},{\"name\":\"Response\",\"occurrences\":[5757,5778,5790,7697,7891,8386,9233,20863,24717,25303,25522,25670,25863,43472,51429,51643,52280]},{\"name\":\"Object\",\"occurrences\":[6513,9712,11762,27388,31910,37136,37243,37444,37657,37778,49293,49312]},{\"name\":\"TextDecoder\",\"occurrences\":[8996,9064,21954]},{\"name\":\"Error\",\"occurrences\":[9860,10884,33651,34694,37548,37887,38649,39466,50438]},{\"name\":\"AsyncIterable\",\"occurrences\":[20816,23100,30499,34315,34376,44760]},{\"name\":\"Map\",\"occurrences\":[21257]},{\"name\":\"Set\",\"occurrences\":[21306,21461,23222]},{\"name\":\"Symbol\",\"occurrences\":[23324,32692,34421,34590,44722]},{\"name\":\"IteratorResult\",\"occurrences\":[23399,23868]},{\"name\":\"Extract\",\"occurrences\":[24447,25543,25747,27814,28060,45136]},{\"name\":\"ReadableStream\",\"occurrences\":[24751]},{\"name\":\"Request\",\"occurrences\":[25261,28579,43452]},{\"name\":\"Math\",\"occurrences\":[26761]},{\"name\":\"AbortSignal\",\"occurrences\":[27788,27962,28234,30285,41983,43658]},{\"name\":\"fetch\",\"occurrences\":[28568]},{\"name\":\"NonNullable\",\"occurrences\":[29849,29880,29937,29958,30082]},{\"name\":\"AsyncGenerator\",\"occurrences\":[30803]},{\"name\":\"Reflect\",\"occurrences\":[31269,45818]},{\"name\":\"Boolean\",\"occurrences\":[32244]},{\"name\":\"TypeError\",\"occurrences\":[38997,40100,40237,40572,41036,45920,48563,49136]},{\"name\":\"TextEncoder\",\"occurrences\":[40662]},{\"name\":\"btoa\",\"occurrences\":[40943]},{\"name\":\"Awaited\",\"occurrences\":[43765,49405]},{\"name\":\"ReturnType\",\"occurrences\":[43776,46627,49413]},{\"name\":\"AsyncIterator\",\"occurrences\":[44798]},{\"name\":\"Partial\",\"occurrences\":[48118]}]};", "import runtime, { type DeclaredBinding } from 'runtime-module';\n\n/** The runtime files whose exports the SDK root re-exports: the response classes, ParseError and parseInput. */\nexport const rootRuntimeFiles = ['http/response.ts', 'http/parser.ts'];\n\n/** The runtime declarations the SDK root re-exports. */\nexport const runtimeRootExports = runtime.bindings.filter(\n (binding): binding is DeclaredBinding =>\n binding.kind === 'declared' &&\n binding.exported &&\n rootRuntimeFiles.includes(binding.file),\n);\n", "import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport runtimeSources from 'runtime-sources';\n\nimport {\n type OpenAPIDocument,\n isRef,\n parseRef,\n pointerTokens,\n valueAtPointer,\n} from '@sdk-it/core';\nimport {\n type WriteContent,\n addLeadingSlash,\n readFolder,\n writeFiles,\n} from '@sdk-it/core/file-system.js';\nimport {\n type IR,\n type PaginationConfig,\n type ResponseBody,\n cleanFiles,\n forEachOperation,\n readWriteMetadata,\n toIR,\n} from '@sdk-it/spec';\n\nimport { generateAISDKTools } from './agent/ai-sdk.ts';\nimport { generateOpenAIAgentTools } from './agent/openai-agents.ts';\nimport utilsTxt from './agent/utils.txt';\nimport { clientName, refuseTakenNames } from './client-name.ts';\nimport backend, {\n clientDeclarations,\n clientDeclaredNames,\n clientRuntimeExports,\n clientRuntimeTypeExports,\n} from './client.ts';\nimport { TypeScriptEmitter } from './emitters/interface.ts';\nimport type { EmittedZod } from './emitters/zod.ts';\nimport { indexFiles } from './folder-index.ts';\nimport { generateCode, operationFragments } from './generator.ts';\nimport { type MakeImportFn } from './import-utilities.ts';\nimport { type ModelNamer, createModelNamer } from './model-name.ts';\nimport { moduleFileName } from './module-file.ts';\nimport {\n type ModuleSpan,\n assembleModule,\n moduleReferences,\n} from './one-module.ts';\nimport type { TypeScriptGeneratorOptions } from './options.ts';\nimport { toReadme } from './readme/readme.ts';\nimport { type References, fileReferences, inputGlobals } from './references.ts';\nimport type { Operation } from './sdk.ts';\nimport { expandServerUrls } from './server-urls.ts';\nimport { TypeScriptSnippet } from './typescript-snippet.ts';\n\nexport type { ModuleSpan } from './one-module.ts';\n\nexport interface RenderOptions {\n name: string;\n useTsExtension: boolean;\n pagination?: PaginationConfig | false;\n agentTools?: 'ai-sdk' | 'openai-agents';\n}\n\n/**\n * The SDK's source files, keyed by path relative to the SDK source root,\n * index files included. Reads and writes nothing on disk.\n */\nexport async function render(\n openapi: OpenAPIDocument,\n options: RenderOptions,\n): Promise<Record<string, string>> {\n return renderFiles(await toSdkIR(openapi, options), options);\n}\n\nexport interface ModuleOptions {\n name: string;\n}\n\n/**\n * The SDK as one TypeScript module that carries the runtime source, for hosts\n * that load a spec as a module (a content mapper, a bundler plugin, a loader).\n * It exports what the SDK root of `render()` exports. `spans` maps the names\n * the module declares to where the document declares them. Reads and writes\n * nothing on disk.\n */\nexport async function renderModule(\n openapi: OpenAPIDocument,\n options: ModuleOptions,\n): Promise<{ text: string; spans: ModuleSpan[] }> {\n const spec = await toSdkIR(openapi, {});\n const name = clientName(options.name);\n const modelName = createModelNamer(name);\n const { groups, commonZod, endpoints } = operationFragments({\n spec,\n modelName,\n zodRefs: moduleReferences,\n endpointRefs: moduleReferences,\n });\n refuseTakenNames(options.name, name, inputSchemaNames(groups));\n const client = {\n name,\n servers: expandServerUrls(spec.servers),\n securitySchemes: spec.components.securitySchemes,\n };\n const bodies = inlineBodyLocations(spec);\n const { text, spans } = assembleModule({\n commonZod,\n inputs: Object.values(groups)\n .flat()\n .flatMap((operation) =>\n operation.inputs.map(({ schemaName, zod }) => ({\n name: schemaName,\n zod,\n })),\n ),\n models: modelDeclarations(spec, modelName, moduleReferences).map(\n ({ schemaName, inline, typeName, doc, type }) => ({\n typeName,\n doc,\n type,\n location: inline\n ? bodies.get(schemaName)\n : ['components', 'schemas', schemaName],\n }),\n ),\n endpoints: Object.values(endpoints).flat(),\n client: clientDeclarations(client, moduleReferences, '__routes'),\n clientNames: clientDeclaredNames(name),\n runtimeExports: clientRuntimeExports,\n runtimeTypeExports: clientRuntimeTypeExports(client),\n });\n return {\n text,\n spans: spans.flatMap((span) => {\n const location = documentLocation(openapi, span.location);\n return location ? [{ ...span, location }] : [];\n }),\n };\n}\n\n/**\n * Where the document the caller passed holds what `location` names in the IR.\n * The walk follows each `$ref` it meets as a pointer into this document, so\n * the body of a referenced response is where the reference points. Undefined\n * where the document has nothing there: spec made it up (a success response\n * for an operation without one), rewrote its key (a `:id` path), or a\n * reference leads to another document.\n */\nfunction documentLocation(document: unknown, location: readonly string[]) {\n let current = document;\n let path: readonly string[] = [];\n for (const token of location) {\n while (isRef(current)) {\n path = pointerTokens(current.$ref.slice(1));\n current = valueAtPointer(document, path);\n }\n if (!hasMember(current, token)) {\n return undefined;\n }\n current = Reflect.get(current, token);\n path = [...path, token];\n }\n return path;\n}\n\nfunction hasMember(value: unknown, token: string): value is object {\n return typeof value === 'object' && value !== null && token in value;\n}\n\n/**\n * The response body that references each schema. Spec replaces an inline body\n * with a reference to the schema it makes from it, so for such a schema this is\n * where its body sat in the document.\n */\nfunction inlineBodyLocations(spec: IR) {\n const locations = new Map<string, readonly string[]>();\n forEachOperation(spec, (entry, operation) => {\n for (const [status, response] of Object.entries(operation.responses)) {\n for (const [type, media] of Object.entries(response.content)) {\n if (isRef(media.schema)) {\n locations.set(parseRef(media.schema.$ref).model, [\n 'paths',\n entry.path,\n entry.method,\n 'responses',\n status,\n 'content',\n type,\n 'schema',\n ]);\n }\n }\n }\n });\n return locations;\n}\n\nexport async function generate(\n openapi: OpenAPIDocument,\n settings: TypeScriptGeneratorOptions,\n): Promise<{ packageName: string }> {\n const { packageName } = settings;\n if (!packageName.trim()) {\n throw new TypeError(\n `packageName must name the generated npm package (packageName: '@acme/pets'); got ${JSON.stringify(packageName)}.`,\n );\n }\n const options: RenderOptions = {\n name: settings.name,\n useTsExtension: settings.useTsExtension ?? true,\n pagination: settings.pagination,\n agentTools: settings.agentTools,\n };\n const spec = await toSdkIR(openapi, options);\n const files = renderFiles(spec, options);\n const output =\n settings.mode === 'full' ? join(settings.output, 'src') : settings.output;\n const writer = settings.writer ?? writeFiles;\n await writer(output, files);\n\n const metadata = await readWriteMetadata(\n output,\n Object.keys(files).map(addLeadingSlash),\n writer,\n );\n if (settings.cleanup !== false) {\n await cleanFiles(metadata, output, [\n '/tsconfig*.json',\n '/package.json',\n '/metadata.json',\n '/**/index.ts',\n ]);\n }\n\n // Index files also export what the output folder holds beyond this run's\n // files: files a user added, and stale files when cleanup is off.\n const listed = await readFolder(output, true);\n const userIndexes = new Map(\n await Promise.all(\n listed\n .filter((path) => path.endsWith('/index.ts') && !(path in files))\n .map(\n async (path) =>\n [path, await readFile(join(output, path), 'utf-8')] as const,\n ),\n ),\n );\n const indexes = indexFiles(\n new Set([...Object.keys(files), ...listed]),\n (path) => files[path] ?? userIndexes.get(path),\n options.useTsExtension,\n );\n const changedIndexes = Object.fromEntries(\n Object.entries(indexes).filter(\n ([path, content]) => files[path] !== content,\n ),\n );\n if (Object.keys(changedIndexes).length) {\n await writer(output, changedIndexes);\n }\n\n if (settings.mode === 'full') {\n const configFiles: WriteContent = {\n 'package.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n name: packageName,\n version: '0.0.1',\n type: 'module',\n main: './src/index.ts',\n module: './src/index.ts',\n types: './src/index.ts',\n publishConfig: {\n access: 'public',\n },\n exports: {\n './package.json': './package.json',\n '.': {\n types: './src/index.ts',\n import: './src/index.ts',\n default: './src/index.ts',\n },\n },\n dependencies: {\n 'fast-content-type-parse': '^3.0.0',\n zod: '^4.6.7',\n ...(settings.agentTools === 'ai-sdk' ? { ai: '^7.0.29' } : {}),\n ...(settings.agentTools === 'openai-agents'\n ? { '@openai/agents': '^0.21.0' }\n : {}),\n },\n },\n null,\n 2,\n ),\n },\n 'tsconfig.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n compilerOptions: {\n skipLibCheck: true,\n skipDefaultLibCheck: true,\n target: 'ESNext',\n noEmit: true,\n allowImportingTsExtensions: true,\n verbatimModuleSyntax: true,\n moduleResolution: 'bundler',\n },\n include: ['**/*.ts'],\n },\n null,\n 2,\n ),\n },\n };\n await writer(settings.output, configFiles);\n }\n\n const readme = settings.readme ?? true;\n if (readme) {\n const path = typeof readme === 'string' ? readme : 'README.md';\n await writer(settings.output, {\n [path]: toReadme(spec, new TypeScriptSnippet(spec, settings)),\n });\n }\n\n await settings.formatCode?.({\n output: output,\n env: npmRunPathEnv(),\n });\n\n return { packageName };\n}\n\nasync function toSdkIR(\n openapi: OpenAPIDocument,\n options: Pick<RenderOptions, 'pagination'>,\n) {\n // A requirement with no local scheme leaves the client unable to authenticate,\n // so refuse rather than emit an SDK that always gets a 401.\n const unresolvedSecuritySchemes = new Set<string>();\n const spec = await toIR(\n {\n spec: openapi,\n responses: { flattenErrorResponses: true },\n pagination: options.pagination,\n onDiagnostic: ({ code, message }) => {\n if (code === 'unresolved-security-scheme') {\n unresolvedSecuritySchemes.add(message);\n }\n },\n },\n false,\n );\n if (unresolvedSecuritySchemes.size) {\n throw new TypeError([...unresolvedSecuritySchemes].join('\\n'));\n }\n return spec;\n}\n\nconst agentTools = {\n 'ai-sdk': generateAISDKTools,\n 'openai-agents': generateOpenAIAgentTools,\n};\n\n/** Runtime files import their siblings as './x.ts'; the SDK's import style decides the extension. */\nfunction withSdkImports(source: string, makeImport: MakeImportFn) {\n return source.replaceAll(\n /(from ')(\\.\\.?\\/[^']+)\\.ts(')/g,\n (_, from: string, path: string, quote: string) =>\n `${from}${makeImport(path)}${quote}`,\n );\n}\n\nfunction renderFiles(spec: IR, options: RenderOptions) {\n const { useTsExtension } = options;\n const makeImport = (moduleSpecifier: string) => {\n return useTsExtension ? `${moduleSpecifier}.ts` : moduleSpecifier;\n };\n const name = clientName(options.name);\n const modelName = createModelNamer(name);\n const { endpoints, groups, commonZod } = generateCode({\n spec,\n makeImport,\n modelName,\n });\n refuseTakenNames(options.name, name, inputSchemaNames(groups));\n\n const files: Record<string, string> = {\n ...Object.fromEntries(\n Object.entries(runtimeSources).map(([path, source]) => [\n path,\n withSdkImports(source, makeImport),\n ]),\n ),\n 'client.ts': backend({\n name,\n servers: expandServerUrls(spec.servers ?? []),\n securitySchemes: spec.components.securitySchemes,\n makeImport,\n }),\n ...toInputs(groups, commonZod, makeImport),\n ...endpoints,\n ...serializeModels(spec, modelName),\n ...(options.agentTools\n ? {\n 'agents.ts': `${agentTools[options.agentTools](spec, makeImport)}\\n${utilsTxt}`,\n }\n : {}),\n };\n return {\n ...files,\n ...indexFiles(Object.keys(files), (path) => files[path], useTsExtension),\n };\n}\n\n/** The names the SDK root exports the operations' input schemas under. */\nfunction inputSchemaNames(groups: Record<string, Operation[]>) {\n return new Set(\n Object.values(groups)\n .flat()\n .flatMap((operation) =>\n operation.inputs.map(({ schemaName }) => schemaName),\n ),\n );\n}\n\n/** A model type an SDK declares. */\ninterface ModelDeclaration {\n /** The key of its schema in the IR's `components.schemas`. */\n schemaName: string;\n /** Whether spec made the schema from an inline response body. */\n inline: boolean;\n typeName: string;\n /** The JSDoc that goes before the declaration, or ''. */\n doc: string;\n type: string;\n /** The file a multi-file SDK declares it in. */\n file: string;\n /** Whether `type` is the runtime's SSEListener. */\n sse: boolean;\n}\n\nfunction serializeModels(spec: IR, modelName: ModelNamer) {\n const filesMap: Record<string, string[]> = {};\n const files: Record<string, string> = {};\n for (const model of modelDeclarations(\n spec,\n modelName,\n fileReferences('models'),\n )) {\n const fileContent = [\n ...(model.sse\n ? [`import type { SSEListener } from '../http/sse.ts';`]\n : []),\n `\\n${model.doc}`,\n `export type ${model.typeName} = ${model.type};`,\n ];\n filesMap[model.file] ??= [];\n filesMap[model.file].push(fileContent.join('\\n'));\n }\n\n for (const [group, contents] of Object.entries(filesMap)) {\n let fileContent = contents.join('\\n');\n if (fileContent.includes('models.')) {\n fileContent = `import type * as models from '../index.ts';\\n${fileContent}`;\n }\n files[group] = fileContent;\n }\n return files;\n}\n\nfunction modelDeclarations(\n spec: IR,\n modelName: ModelNamer,\n refs: References,\n): ModelDeclaration[] {\n const models: ModelDeclaration[] = [];\n const responseBodies = new Map<string, ResponseBody>();\n forEachOperation(spec, (_, operation) => {\n for (const response of Object.values(operation.responses)) {\n const name = response['x-response-name'];\n if (name) {\n responseBodies.set(name, response['x-body']);\n }\n }\n });\n for (const [name, schema] of Object.entries(spec.components.schemas)) {\n const isResponseBody =\n 'x-responsebody' in schema && schema['x-responsebody'];\n const isRequestBody = 'x-requestbody' in schema && schema['x-requestbody'];\n const responseGroup =\n 'x-response-group' in schema &&\n typeof schema['x-response-group'] === 'string'\n ? schema['x-response-group']\n : undefined;\n const body = responseGroup ? responseBodies.get(name) : undefined;\n if (isRequestBody) {\n // we do not generate interfaces for request bodies. we use zod for that.\n // bewary that the sometimes request body content schema is used as model somewhere else.\n // so we need to till the augmenter to create completeley separate model for request body suffixed by `Input`\n continue;\n }\n const folder = isResponseBody ? 'outputs' : 'models';\n let typeContent: string;\n if (body === 'sse') {\n typeContent = refs.runtime('SSEListener');\n } else if (body === 'stream') {\n typeContent = refs.global('ReadableStream');\n } else {\n typeContent = new TypeScriptEmitter(spec, modelName, refs).handle(\n schema,\n true,\n );\n }\n\n models.push({\n schemaName: name,\n inline: responseGroup !== undefined,\n typeName: modelName(name),\n doc: schema.description ? `\\n/** \\n * ${schema.description}\\n */\\n` : '',\n type: typeContent,\n file: responseGroup\n ? join(folder, `${moduleFileName(responseGroup)}.ts`)\n : join(folder, `${moduleFileName(name)}.ts`),\n sse: body === 'sse',\n });\n }\n return models;\n}\n\nfunction toInputs(\n operationsSet: Record<string, Operation[]>,\n commonZod: Map<string, EmittedZod>,\n makeImport: MakeImportFn,\n) {\n const schemaNames = new Set(commonZod.keys());\n const inputs: Record<string, string> = {};\n for (const [name, operations] of Object.entries(operationsSet)) {\n const output: string[] = [];\n const imports = new Set(['import { z } from \"zod\";']);\n\n for (const route of operations.flatMap((operation) => operation.inputs)) {\n for (const reference of route.references) {\n imports.add(\n `import { ${reference} } from './schemas/${makeImport(moduleFileName(reference))}';`,\n );\n }\n output.push(\n inputGlobals(\n `export const ${route.schemaName} = ${route.zod};`,\n schemaNames,\n ),\n );\n }\n inputs[`inputs/${moduleFileName(name)}.ts`] =\n [...imports, ...output].join('\\n') + '\\n';\n }\n\n const schemas = commonZod\n .entries()\n .reduce<string[][]>((acc, [name, { zod, references }]) => {\n const output = [`import { z } from 'zod';`];\n const content = inputGlobals(\n `export const ${name} = ${zod};`,\n schemaNames,\n );\n if (content.includes('z.ZodType<models.')) {\n output.push(\n `import type * as models from '${makeImport('../../models/index')}';`,\n );\n }\n for (const reference of references) {\n if (reference !== name) {\n output.push(\n `import { ${reference} } from './${makeImport(moduleFileName(reference))}';`,\n );\n }\n }\n output.push(content);\n return [\n [`inputs/schemas/${moduleFileName(name)}.ts`, output.join('\\n')],\n ...acc,\n ];\n }, []);\n\n return {\n ...Object.fromEntries(schemas),\n ...inputs,\n };\n}\n", "export default {\"http/client.ts\":\"import { z } from 'zod';\\n\\nimport {\\n type OutputType,\\n type Unionize,\\n fetchType,\\n parse,\\n} from './dispatcher.ts';\\nimport { type Interceptor, createHeadersInterceptor } from './interceptors.ts';\\nimport {\\n type ItemOf,\\n type Page,\\n PagePromise,\\n type PageRequestOptions,\\n type Pagination,\\n createPage,\\n} from './page.ts';\\nimport { type ParseError, parseInput } from './parser.ts';\\nimport type { HeadersInit, RequestConfig } from './request.ts';\\nimport {\\n APIResponse,\\n type ProblematicResponse,\\n type SuccessfulResponse,\\n} from './response.ts';\\nimport {\\n type RuntimeSecuritySchemes,\\n type SecurityCredential,\\n createSecurityInterceptor,\\n} from './security.ts';\\n\\nexport interface DispatchOptions {\\n interceptors: Interceptor[];\\n fetch: z.infer<typeof fetchType>;\\n baseUrl: string;\\n signal?: AbortSignal;\\n}\\n\\n/** One operation of a generated SDK's endpoint table. */\\nexport interface Route {\\n schema: z.ZodType;\\n output: OutputType[];\\n security: readonly Record<string, readonly string[]>[];\\n toRequest(input: unknown, baseUrl: string): RequestConfig;\\n dispatch(input: unknown, options: DispatchOptions): Promise<unknown>;\\n /** Present when the operation pages; `request()` then resolves to a Page. */\\n pagination?: Pagination;\\n}\\n\\n/** What a generated SDK knows about its API: its endpoint table, servers and security. */\\nexport interface Api {\\n routes: Record<string, Route>;\\n /** The spec's server URLs with their variables' defaults. */\\n servers: readonly string[];\\n securitySchemes: RuntimeSecuritySchemes;\\n /** Validates `credentials`: one optional entry per security scheme. */\\n credentials: z.ZodType<Record<string, SecurityCredential | undefined>>;\\n}\\n\\ntype BaseUrl = string | (() => string | Promise<string>);\\n\\n/** A spec with two or more servers has no single default, so the caller picks one. */\\ntype BaseUrlSetting<A extends Api> = A['servers'] extends readonly [\\n unknown,\\n unknown,\\n ...unknown[],\\n]\\n ? { baseUrl: BaseUrl }\\n : { baseUrl?: BaseUrl };\\n\\ntype CredentialsSetting<A extends Api> =\\n keyof A['securitySchemes'] extends never\\n ? unknown\\n : { credentials?: z.input<A['credentials']> };\\n\\nexport type ClientSettings<A extends Api> = BaseUrlSetting<A> &\\n CredentialsSetting<A> & {\\n headers?: Record<string, string>;\\n fetch?: (request: Request) => Promise<Response>;\\n /** Skip request input validation. Settings and TypeScript types still enforce correct usage. */\\n skipValidation?: boolean;\\n };\\n\\nexport interface RequestOptions {\\n signal?: AbortSignal;\\n headers?: HeadersInit;\\n}\\n\\ntype DispatchReturn<A extends Api, E extends keyof A['routes']> = Awaited<\\n ReturnType<A['routes'][E]['dispatch']>\\n>;\\n\\nexport type InferData<A extends Api, E extends keyof A['routes']> =\\n DispatchReturn<A, E> extends APIResponse<infer D> ? D : DispatchReturn<A, E>;\\n\\n/**\\n * What `request()` resolves to: the first Page for an operation that pages,\\n * its output otherwise. Distributive over `E`, so for a generic `E` TypeScript\\n * reads it through `E`'s constraint.\\n */\\ntype RouteResult<A extends Api, E extends keyof A['routes']> = E extends unknown\\n ? A['routes'][E] extends { pagination: { items: infer P extends string } }\\n ? Page<InferData<A, E>, ItemOf<InferData<A, E>, P>>\\n : InferData<A, E>\\n : never;\\n\\n/**\\n * What `client.request(endpoint)` returns: a promise of the result that, for\\n * an operation that pages, is also an async iterable of every item. An\\n * interface, not an intersection, so TypeScript awaits it for a generic\\n * endpoint too.\\n */\\nexport interface RequestPromise<Result> extends Promise<Result> {\\n [Symbol.asyncIterator]: Result extends AsyncIterable<infer Item>\\n ? () => AsyncIterator<Item>\\n : undefined;\\n}\\n\\nexport type EndpointsOf<A extends Api> = {\\n [E in keyof A['routes']]: {\\n input: z.input<A['routes'][E]['schema']>;\\n output: InferData<A, E>;\\n /** What `request()` resolves to: the first Page for an operation that pages, its output otherwise. */\\n result: RouteResult<A, E>;\\n error:\\n | Extract<Unionize<A['routes'][E]['output']>, ProblematicResponse>\\n | ParseError<A['routes'][E]['schema']>;\\n };\\n};\\n\\nconst baseUrlSchema = z\\n .union([\\n z.string(),\\n z.custom<() => string | Promise<string>>(\\n (value) => typeof value === 'function',\\n ),\\n ])\\n .transform(async (baseUrl, ctx) => {\\n const value = typeof baseUrl === 'function' ? await baseUrl() : baseUrl;\\n if (typeof value !== 'string') {\\n ctx.addIssue({\\n code: 'custom',\\n message: 'baseUrl must resolve to a string',\\n });\\n return z.NEVER;\\n }\\n if (/^[a-z][a-z\\\\d+.-]*:/i.test(value)) {\\n return value;\\n }\\n const page: { href: string } | undefined = Reflect.get(\\n globalThis,\\n 'location',\\n );\\n if (page === undefined) {\\n throw new TypeError(\\n `baseUrl \\\"${value}\\\" is relative, and there is no page location to resolve it against.`,\\n );\\n }\\n return new URL(value, page.href).href;\\n });\\n\\nfunction settingsSchema(api: Api) {\\n const [server, ...others] = api.servers;\\n return z.object({\\n // OpenAPI 3.2: a spec without servers is served from \\\"/\\\".\\n baseUrl:\\n others.length > 0 ? baseUrlSchema : baseUrlSchema.prefault(server ?? '/'),\\n headers: z.record(z.string(), z.string()).optional(),\\n fetch: fetchType,\\n skipValidation: z.boolean().optional(),\\n credentials: api.credentials.optional(),\\n });\\n}\\n\\nexport class Client<A extends Api> {\\n readonly api: A;\\n options: ClientSettings<A>;\\n readonly #settings: ReturnType<typeof settingsSchema>;\\n\\n constructor(api: A, options: ClientSettings<A>) {\\n this.api = api;\\n this.options = options;\\n this.#settings = settingsSchema(api);\\n }\\n\\n /** The settings, validated, with baseUrl resolved. */\\n async settings() {\\n return this.#settings.parseAsync(this.options);\\n }\\n\\n /**\\n * Sends a request and returns the unwrapped response data, or, for an\\n * operation that pages, its first Page.\\n */\\n request<const E extends keyof A['routes'] & string>(\\n endpoint: E,\\n input: z.input<A['routes'][E]['schema']>,\\n options?: RequestOptions,\\n ): RequestPromise<EndpointsOf<A>[E]['result']>;\\n request(\\n endpoint: string,\\n input: unknown,\\n options?: RequestOptions,\\n ): Promise<unknown> {\\n const pagination = this.api.routes[endpoint]?.pagination;\\n if (pagination) {\\n return new PagePromise(\\n firstPage(this, endpoint, input, pagination, options),\\n );\\n }\\n return send(this, endpoint, input, options).then((result) =>\\n result instanceof APIResponse ? result.data : result,\\n );\\n }\\n\\n /** Builds a ready-to-send request without sending it. */\\n async prepare<const E extends keyof A['routes'] & string>(\\n endpoint: E,\\n input: z.input<A['routes'][E]['schema']>,\\n options?: RequestOptions,\\n ) {\\n return prepare(this, endpoint, input, options);\\n }\\n\\n async defaultHeaders() {\\n const settings = await this.settings();\\n return { ...settings.headers };\\n }\\n\\n setOptions(options: Partial<ClientSettings<A>>) {\\n this.options = { ...this.options, ...options };\\n }\\n}\\n\\nexport function createClient<A extends Api>(\\n api: A,\\n settings: ClientSettings<A>,\\n): Client<A> {\\n return new Client(api, settings);\\n}\\n\\nasync function firstPage(\\n client: Client<Api>,\\n endpoint: string,\\n input: unknown,\\n pagination: Pagination,\\n options: RequestOptions | undefined,\\n) {\\n if (typeof input !== 'object' || input === null) {\\n throw new TypeError(\\n `${endpoint} pages through its input, so the input must be an object`,\\n );\\n }\\n const fetchPage = async (\\n pageInput: Record<string, unknown>,\\n pageOptions: PageRequestOptions | undefined,\\n ) => {\\n const result = await send(client, endpoint, pageInput, {\\n ...options,\\n ...pageOptions,\\n });\\n if (\\n !(result instanceof APIResponse) ||\\n result.status !== pagination.statusCode\\n ) {\\n throw result;\\n }\\n const data: unknown = result.data;\\n if (typeof data !== 'object' || data === null) {\\n throw new TypeError(`${endpoint} answered a page that is not an object`);\\n }\\n return createPage(data, pageInput, pagination, fetchPage);\\n };\\n return fetchPage(Object.fromEntries(Object.entries(input)), undefined);\\n}\\n\\nfunction interceptorsFor(\\n route: Route,\\n settings: Awaited<ReturnType<Client<Api>['settings']>>,\\n api: Api,\\n options: RequestOptions | undefined,\\n) {\\n return [\\n createHeadersInterceptor({ ...settings.headers }, options?.headers ?? {}),\\n createSecurityInterceptor(\\n route.security,\\n settings.credentials,\\n api.securitySchemes,\\n ),\\n ];\\n}\\n\\n/**\\n * Sends a validated request with the client's settings and returns the\\n * response status class (status, headers, data). Throws `APIError` on\\n * non-ok responses.\\n */\\nexport async function request<\\n A extends Api,\\n const E extends keyof A['routes'] & string,\\n>(\\n client: Client<A>,\\n endpoint: E,\\n input: z.input<A['routes'][E]['schema']>,\\n options?: RequestOptions,\\n): Promise<DispatchReturn<A, E>>;\\nexport async function request(\\n client: Client<Api>,\\n endpoint: string,\\n input: unknown,\\n options?: RequestOptions,\\n): Promise<unknown> {\\n return send(client, endpoint, input, options);\\n}\\n\\nfunction routeOf(api: Api, endpoint: string) {\\n const route = api.routes[endpoint];\\n if (route === undefined) {\\n throw new Error(`The api has no endpoint '${endpoint}'`);\\n }\\n return route;\\n}\\n\\nasync function send(\\n client: Client<Api>,\\n endpoint: string,\\n input: unknown,\\n options: RequestOptions | undefined,\\n) {\\n const route = routeOf(client.api, endpoint);\\n const settings = await client.settings();\\n const parsedInput = settings.skipValidation\\n ? input\\n : parseInput(route.schema, input);\\n return route.dispatch(parsedInput, {\\n fetch: settings.fetch,\\n baseUrl: settings.baseUrl,\\n interceptors: interceptorsFor(route, settings, client.api, options),\\n ...(options?.signal ? { signal: options.signal } : {}),\\n });\\n}\\n\\n/**\\n * Builds a validated `RequestConfig` (url + init) with a `parse` function\\n * attached, without sending it.\\n */\\nexport async function prepare<\\n A extends Api,\\n const E extends keyof A['routes'] & string,\\n>(\\n client: Client<A>,\\n endpoint: E,\\n input: z.input<A['routes'][E]['schema']>,\\n options?: RequestOptions,\\n): Promise<\\n RequestConfig & {\\n parse: (response: Response) => Promise<DispatchReturn<A, E>>;\\n }\\n>;\\nexport async function prepare(\\n client: Client<Api>,\\n endpoint: string,\\n input: unknown,\\n options?: RequestOptions,\\n): Promise<\\n RequestConfig & { parse: (response: Response) => Promise<unknown> }\\n> {\\n const route = routeOf(client.api, endpoint);\\n const settings = await client.settings();\\n const parsedInput = settings.skipValidation\\n ? input\\n : parseInput(route.schema, input);\\n let config = route.toRequest(parsedInput, settings.baseUrl);\\n if (options?.signal) {\\n config = { ...config, init: { ...config.init, signal: options.signal } };\\n }\\n for (const interceptor of interceptorsFor(\\n route,\\n settings,\\n client.api,\\n options,\\n )) {\\n if (interceptor.before) {\\n config = await interceptor.before(config);\\n }\\n }\\n return {\\n ...config,\\n parse: (response: Response) => parse(route.output, response),\\n };\\n}\\n\",\"http/dispatcher.ts\":\"import { z } from 'zod';\\n\\nimport { type Interceptor } from './interceptors.ts';\\nimport { buffered } from './parse-response.ts';\\nimport { type RequestConfig } from './request.ts';\\nimport {\\n APIError,\\n APIResponse,\\n type RebindSuccessPayload,\\n type StatusRange,\\n type SuccessfulResponse,\\n} from './response.ts';\\nimport { type SSEListener } from './sse.ts';\\n\\nexport type Unionize<T> = T extends [infer Single extends OutputType]\\n ? InstanceType<Single>\\n : T extends readonly [...infer Tuple extends OutputType[]]\\n ? { [I in keyof Tuple]: InstanceType<Tuple[I]> }[number]\\n : never;\\n\\nexport type InstanceType<T> =\\n T extends Type<infer U>\\n ? U\\n : T extends { type: Type<infer U> }\\n ? U\\n : T extends Array<unknown>\\n ? Unionize<T>\\n : never;\\n\\ntype ResponseData<T extends OutputType[]> =\\n Extract<InstanceType<T>, SuccessfulResponse> extends SuccessfulResponse<\\n infer P\\n >\\n ? P\\n : unknown;\\n\\ntype ResponseMapper<T extends OutputType[], R> = (data: ResponseData<T>) => R;\\n\\nexport interface Type<T> {\\n new (...args: any[]): T;\\n}\\nexport type Parser = (\\n response: Response,\\n) => Promise<unknown> | ReadableStream<any> | SSEListener;\\n/** An output that `range` declares reads every status of the range that no exact output declares. */\\nexport type OutputType =\\n | Type<APIResponse>\\n | { parser: Parser; type: Type<APIResponse>; range?: StatusRange };\\n\\n// Bare z.custom (no predicate) on purpose: Request/Response from another\\n// realm (undici vs global fetch) fail instanceof checks. The output is\\n// typed as a Promise directly \u2014 zod 4 deprecated z.promise.\\nexport const fetchType = z\\n .function({\\n input: [z.custom<Request>()],\\n output: z.custom<Promise<Response>>(),\\n })\\n .optional();\\n\\n/** Reads the body of a status the operation declares no output for. */\\nconst undeclared: Parser = buffered();\\n\\nexport async function parse<T extends OutputType[]>(\\n outputs: T,\\n response: Response,\\n): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\\nexport async function parse<T extends OutputType[], R>(\\n outputs: T,\\n response: Response,\\n mapper: ResponseMapper<T, R>,\\n): Promise<\\n RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>\\n>;\\nexport async function parse(\\n outputs: OutputType[],\\n response: Response,\\n mapper?: (data: unknown) => unknown,\\n): Promise<APIResponse> {\\n const declared = match(outputs, response.status);\\n const output = declared ? typeOf(declared) : null;\\n const parser =\\n declared && 'parser' in declared ? declared.parser : undeclared;\\n\\n if (response.ok) {\\n const data = await parser(response);\\n const mapped = mapper ? mapper(data) : data;\\n const success =\\n output && isTypeOf(output, APIResponse) ? output : APIResponse;\\n return success.create(response.status, response.headers, mapped);\\n }\\n\\n const failure = output && isTypeOf(output, APIError) ? output : APIError;\\n throw failure.create(\\n response.status,\\n response.headers,\\n await parser(response),\\n );\\n}\\n\\n// OpenAPI 3.2 Responses Object: an explicit code takes precedence over the\\n// range that covers it.\\nfunction match(outputs: OutputType[], status: number) {\\n const range = `${Math.trunc(status / 100)}XX`;\\n return (\\n outputs.find(\\n (output) => !('range' in output) && statusOf(output) === status,\\n ) ?? outputs.find((output) => 'range' in output && output.range === range)\\n );\\n}\\n\\nfunction typeOf(output: OutputType) {\\n return 'parser' in output ? output.type : output;\\n}\\n\\nfunction statusOf(output: OutputType) {\\n const type = typeOf(output);\\n return isTypeOf(type, APIResponse) || isTypeOf(type, APIError)\\n ? type.status\\n : undefined;\\n}\\n\\nexport function isTypeOf<T extends Type<APIResponse>>(\\n instance: any,\\n baseType: T,\\n): instance is T {\\n return (\\n instance === baseType ||\\n Object.prototype.isPrototypeOf.call(baseType, instance)\\n );\\n}\\n\\nexport class Dispatcher {\\n #interceptors: Interceptor[] = [];\\n #fetch: z.infer<typeof fetchType>;\\n constructor(interceptors: Interceptor[], fetch?: z.infer<typeof fetchType>) {\\n this.#interceptors = interceptors;\\n this.#fetch = fetch;\\n }\\n\\n async send<T extends OutputType[]>(\\n config: RequestConfig,\\n outputs: T,\\n signal?: AbortSignal,\\n ): Promise<Extract<Unionize<T>, SuccessfulResponse<unknown>>>;\\n async send<T extends OutputType[], R>(\\n config: RequestConfig,\\n outputs: T,\\n signal: AbortSignal | undefined,\\n mapper: ResponseMapper<T, R>,\\n ): Promise<\\n RebindSuccessPayload<Extract<Unionize<T>, SuccessfulResponse<unknown>>, R>\\n >;\\n async send<T extends OutputType[], R = ResponseData<T>>(\\n config: RequestConfig,\\n outputs: T,\\n signal?: AbortSignal,\\n mapper?: ResponseMapper<T, R>,\\n ) {\\n for (const interceptor of this.#interceptors) {\\n if (interceptor.before) {\\n config = await interceptor.before(config);\\n }\\n }\\n\\n const init =\\n signal === undefined ? config.init : { ...config.init, signal };\\n\\n let response = await (this.#fetch ?? fetch)(new Request(config.url, init));\\n\\n for (const interceptor of this.#interceptors.toReversed()) {\\n if (interceptor.after) {\\n response = await interceptor.after(response.clone());\\n }\\n }\\n\\n if (mapper) {\\n return await parse(outputs, response, mapper);\\n }\\n return await parse(outputs, response);\\n }\\n}\\n\",\"http/interceptors.ts\":\"import type { HeadersInit, RequestConfig } from './request.ts';\\n\\nexport interface Interceptor {\\n before?: (config: RequestConfig) => Promise<RequestConfig> | RequestConfig;\\n after?: (response: Response) => Promise<Response> | Response;\\n}\\n\\nexport const createHeadersInterceptor = (\\n headers: Record<string, string | undefined>,\\n requestHeaders: HeadersInit,\\n): Interceptor => {\\n return {\\n before({ init, url }) {\\n // Priority Levels\\n // 1. Headers Input\\n // 2. Request Headers\\n // 3. Default Headers\\n\\n for (const [key, value] of new Headers(requestHeaders)) {\\n // Only set the header if it doesn't already exist and has a value\\n // even though these headers are passed at operation level\\n // still they are lower priority compared to the headers input\\n if (value !== undefined && !init.headers.has(key)) {\\n init.headers.set(key, value);\\n }\\n }\\n\\n for (const [key, value] of Object.entries(headers)) {\\n // Only set the header if it doesn't already exist and has a value\\n if (value !== undefined && !init.headers.has(key)) {\\n init.headers.set(key, value);\\n }\\n }\\n\\n return { init, url };\\n },\\n };\\n};\\n\",\"http/page.ts\":\"/** How an operation pages, as the spec IR records it. Paths are dot-separated paths into the response body. */\\nexport type Pagination =\\n | {\\n type: 'offset';\\n offsetParamName: string;\\n limitParamName: string;\\n items: string;\\n hasMore: string;\\n statusCode: number;\\n /** The offset parameter's default in the spec. */\\n start?: number;\\n }\\n | {\\n type: 'page';\\n pageNumberParamName: string;\\n pageSizeParamName: string;\\n items: string;\\n hasMore: string;\\n statusCode: number;\\n /** The page parameter's default in the spec. */\\n start?: number;\\n }\\n | {\\n type: 'cursor';\\n cursorParamName: string;\\n items: string;\\n hasMore: string;\\n statusCode: number;\\n /** Path of the cursor that requests the next page. */\\n nextCursor?: string;\\n };\\n\\ntype PathValue<T, P extends string> = P extends `${infer K}.${infer Rest}`\\n ? K extends keyof NonNullable<T>\\n ? PathValue<NonNullable<T>[K], Rest>\\n : never\\n : P extends keyof NonNullable<T>\\n ? NonNullable<T>[P]\\n : never;\\n\\n/** The item type of the array at `P` in `Data`. */\\nexport type ItemOf<Data, P extends string> =\\n NonNullable<PathValue<Data, P>> extends readonly (infer I)[] ? I : never;\\n\\n/** Options for the request a page fetch sends; they override the first request's. */\\nexport interface PageRequestOptions {\\n signal?: AbortSignal;\\n}\\n\\n/**\\n * The way from a page to the next. A next page has the type of the page it\\n * comes from, so generic code over one endpoint keeps that endpoint's type.\\n */\\nexport interface PageControls<Item> extends AsyncIterable<Item> {\\n hasNextPage(): boolean;\\n getNextPage<P extends PageControls<unknown>>(\\n this: P,\\n options?: PageRequestOptions,\\n ): Promise<P>;\\n /** This page, then each following page. */\\n iterPages<P extends PageControls<unknown>>(\\n this: P,\\n options?: PageRequestOptions,\\n ): AsyncGenerator<P>;\\n}\\n\\n/** A page: the response body's fields, and the way to the next page. */\\nexport type Page<Data, Item> = Data & PageControls<Item>;\\n\\ntype FetchPage = (\\n input: Record<string, unknown>,\\n options: PageRequestOptions | undefined,\\n) => Promise<ResponsePage>;\\n\\nfunction at(data: unknown, path: string): unknown {\\n let value = data;\\n for (const key of path.split('.')) {\\n if (typeof value !== 'object' || value === null) return undefined;\\n value = Reflect.get(value, key);\\n }\\n return value;\\n}\\n\\n/**\\n * The position an omitted offset or page parameter stands for: the spec's\\n * default, else the first offset (0) or the first page (1).\\n */\\nfunction position(sent: unknown, start: number | undefined, first: number) {\\n if (typeof sent === 'number') return sent;\\n return start ?? first;\\n}\\n\\nclass ResponsePage {\\n readonly #input: Record<string, unknown>;\\n readonly #pagination: Pagination;\\n readonly #fetchPage: FetchPage;\\n readonly #items: unknown[];\\n\\n constructor(\\n data: object,\\n input: Record<string, unknown>,\\n pagination: Pagination,\\n fetchPage: FetchPage,\\n ) {\\n Object.assign(this, data);\\n this.#input = input;\\n this.#pagination = pagination;\\n this.#fetchPage = fetchPage;\\n const items = at(data, pagination.items);\\n // A spec may declare the items array nullable; a page without one is empty.\\n this.#items = Array.isArray(items) ? items : [];\\n }\\n\\n hasNextPage() {\\n return Boolean(at(this, this.#pagination.hasMore));\\n }\\n\\n async getNextPage(options?: PageRequestOptions) {\\n return this.#fetchPage(this.#nextInput(), options);\\n }\\n\\n async *iterPages(options?: PageRequestOptions) {\\n yield this;\\n let page = this.hasNextPage() ? await this.getNextPage(options) : undefined;\\n while (page) {\\n yield page;\\n page = page.hasNextPage() ? await page.getNextPage(options) : undefined;\\n }\\n }\\n\\n async *[Symbol.asyncIterator]() {\\n for await (const page of this.iterPages()) {\\n yield* page.#items;\\n }\\n }\\n\\n #nextInput(): Record<string, unknown> {\\n const pagination = this.#pagination;\\n switch (pagination.type) {\\n case 'offset': {\\n const offset = position(\\n this.#input[pagination.offsetParamName],\\n pagination.start,\\n 0,\\n );\\n return {\\n ...this.#input,\\n [pagination.offsetParamName]: offset + this.#items.length,\\n };\\n }\\n case 'page': {\\n const page = position(\\n this.#input[pagination.pageNumberParamName],\\n pagination.start,\\n 1,\\n );\\n return { ...this.#input, [pagination.pageNumberParamName]: page + 1 };\\n }\\n case 'cursor': {\\n const cursor = pagination.nextCursor\\n ? at(this, pagination.nextCursor)\\n : undefined;\\n if (typeof cursor !== 'string') {\\n throw new Error(\\n 'The response says more pages exist but names no next cursor',\\n );\\n }\\n return { ...this.#input, [pagination.cursorParamName]: cursor };\\n }\\n }\\n }\\n}\\n\\n/** Builds the Page for `data`, the body of a response to `input`. */\\nexport function createPage(\\n data: object,\\n input: Record<string, unknown>,\\n pagination: Pagination,\\n fetchPage: FetchPage,\\n): ResponsePage {\\n return new ResponsePage(data, input, pagination, fetchPage);\\n}\\n\\n/**\\n * The promise of a page that is also an async iterable of every item across\\n * pages, so `for await (const item of client.request(\u2026))` needs no `await`.\\n */\\nexport class PagePromise<P extends AsyncIterable<Item>, Item>\\n extends Promise<P>\\n implements AsyncIterable<Item>\\n{\\n static override get [Symbol.species]() {\\n return Promise;\\n }\\n\\n constructor(page: Promise<P>) {\\n super((resolve, reject) => {\\n page.then(resolve, reject);\\n });\\n }\\n\\n async *[Symbol.asyncIterator]() {\\n yield* await this;\\n }\\n}\\n\",\"http/parse-response.ts\":\"import { parse } from 'fast-content-type-parse';\\n\\nfunction isBinaryContentType(contentType: string) {\\n const type = contentType.toLowerCase();\\n if (type.startsWith('image/')) {\\n return true;\\n }\\n if (type.startsWith('audio/')) {\\n return true;\\n }\\n if (type.startsWith('video/')) {\\n return true;\\n }\\n switch (type) {\\n case 'application/pdf':\\n case 'application/zip':\\n case 'application/gzip':\\n case 'application/x-7z-compressed':\\n case 'application/x-tar':\\n case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':\\n case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':\\n case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':\\n case 'application/vnd.ms-excel':\\n case 'application/vnd.ms-powerpoint':\\n case 'application/msword':\\n case 'application/octet-stream':\\n return true;\\n default:\\n return false;\\n }\\n}\\n\\nexport function chunked(response: Response) {\\n return response.body!;\\n}\\n\\n// The operation declares no body; release the unread stream so the\\n// connection is not held until garbage collection.\\nexport async function bodyless(response: Response) {\\n await response.body?.cancel();\\n return null;\\n}\\n\\n/** The body kinds the buffered parser reads: what the spec declares for a status. */\\nexport type BufferedBody = 'json' | 'text' | 'binary';\\n\\n/**\\n * Reads a body by its Content-Type. A response without one reads as the body\\n * the spec declares for its status, or, with none declared, as the\\n * application/octet-stream that RFC 9110 \u00A78.3 lets a recipient assume.\\n */\\nexport function buffered(declared?: BufferedBody) {\\n return async (response: Response): Promise<unknown> => {\\n // Statuses that, per the HTTP spec, carry no message body. These\\n // responses usually omit Content-Type entirely.\\n if (\\n response.status === 204 ||\\n response.status === 205 ||\\n response.status === 304\\n ) {\\n return null;\\n }\\n const contentType = response.headers.get('Content-Type');\\n if (contentType) {\\n return byContentType(response, contentType);\\n }\\n const bytes = await response.bytes();\\n if (bytes.byteLength === 0) {\\n return null;\\n }\\n switch (declared) {\\n case 'json':\\n return JSON.parse(new TextDecoder().decode(bytes));\\n case 'text':\\n return new TextDecoder().decode(bytes);\\n default:\\n return new Blob([bytes], { type: 'application/octet-stream' });\\n }\\n };\\n}\\n\\nasync function byContentType(response: Response, contentType: string) {\\n const { type } = parse(contentType);\\n if (isBinaryContentType(type)) {\\n return response.blob();\\n }\\n if (type.startsWith('text/')) {\\n return response.text();\\n }\\n if (type === 'application/json' || type.endsWith('+json')) {\\n return response.json();\\n }\\n switch (type) {\\n case 'application/xml':\\n return response.text();\\n case 'application/x-www-form-urlencoded': {\\n const text = await response.text();\\n return Object.fromEntries(new URLSearchParams(text));\\n }\\n case 'multipart/form-data':\\n return response.formData();\\n default:\\n throw new Error(`Unsupported content type: ${contentType}`);\\n }\\n}\\n\",\"http/parser.ts\":\"import { z } from 'zod';\\n\\nexport class ParseError<T extends z.ZodType> extends Error {\\n public data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>;\\n constructor(data: z.core.$ZodFlattenedError<z.output<T>, z.core.$ZodIssue>) {\\n super('Validation failed');\\n this.name = 'ParseError';\\n this.data = data;\\n }\\n}\\n\\nexport function parseInput<T extends z.ZodType>(\\n schema: T,\\n input: unknown,\\n): z.infer<T> {\\n const result = schema.safeParse(input);\\n if (!result.success) {\\n const error = z.flattenError(result.error, (issue) => issue);\\n throw new ParseError<T>(error);\\n }\\n return result.data;\\n}\\n\",\"http/request.ts\":\"type Init = Omit<RequestInit, 'headers'> & { headers: Headers };\\nexport type RequestConfig = { init: Init; url: URL };\\n/** The methods an OpenAPI operation uses, as an HTTP request line writes them. */\\nexport type Method =\\n 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'TRACE' | 'HEAD';\\nexport type HeadersInit = [string, string][] | Record<string, string>;\\n\\nexport type BodyInit =\\n ArrayBuffer | Blob | FormData | URLSearchParams | null | string;\\n\\nfunction template(\\n templateString: string,\\n templateVariables: Record<string, any>,\\n): string {\\n const nargs = /{([0-9a-zA-Z_]+)}/g;\\n return templateString.replace(nargs, (match, key: string, index: number) => {\\n // Handle escaped double braces\\n if (\\n templateString[index - 1] === '{' &&\\n templateString[index + match.length] === '}'\\n ) {\\n return key;\\n }\\n\\n const result = key in templateVariables ? templateVariables[key] : null;\\n return result === null || result === undefined\\n ? ''\\n : encodeURIComponent(String(result));\\n });\\n}\\n\\ntype Input = Record<string, any>;\\n\\n// Validated inputs can carry Date (coerce-date) values; String(new Date())\\n// yields a local-time RFC 2822 string, so serialize Dates as ISO 8601.\\nfunction toWireValue(value: any): string {\\n return value instanceof Date ? value.toISOString() : String(value);\\n}\\n\\n/** The values a field sends: none when the caller left it out, one per item of an array. */\\nfunction wireItems(value: any): any[] {\\n if (value === undefined) {\\n return [];\\n }\\n return Array.isArray(value) ? value : [value];\\n}\\n\\ntype Props = {\\n /** The media type the body is sent as. */\\n contentType: string;\\n inputHeaders: string[];\\n inputQuery: string[];\\n inputBody: string[];\\n inputParams: string[];\\n};\\n\\nabstract class Serializer {\\n protected input: Input;\\n protected props: Props;\\n\\n constructor(input: Input, props: Props) {\\n this.input = input;\\n this.props = props;\\n }\\n\\n abstract getBody(): BodyInit | null;\\n abstract getHeaders(): Record<string, string>;\\n serialize(path: string, baseUrl: string): Serialized {\\n const params = this.props.inputParams.reduce<Record<string, any>>(\\n (acc, key) => {\\n acc[key] = this.input[key];\\n return acc;\\n },\\n {},\\n );\\n const url = new URL(`${baseUrl}${template(path, params)}`);\\n\\n const headers: Record<string, string> = { ...this.getHeaders() };\\n for (const header of this.props.inputHeaders) {\\n const value = this.input[header];\\n if (value !== undefined) {\\n headers[header] = toWireValue(value);\\n }\\n }\\n\\n for (const key of this.props.inputQuery) {\\n for (const item of wireItems(this.input[key])) {\\n url.searchParams.append(key, toWireValue(item));\\n }\\n }\\n\\n return {\\n body: this.getBody(),\\n url,\\n headers,\\n };\\n }\\n}\\n\\ninterface Serialized {\\n body: BodyInit | null;\\n headers: Record<string, string>;\\n url: URL;\\n}\\n\\nclass JsonSerializer extends Serializer {\\n getBody(): BodyInit | null {\\n const body: Record<string, any> = {};\\n if (\\n this.props.inputBody.length === 1 &&\\n this.props.inputBody[0] === '$body'\\n ) {\\n return JSON.stringify(this.input.$body);\\n }\\n\\n for (const prop of this.props.inputBody) {\\n body[prop] = this.input[prop];\\n }\\n return JSON.stringify(body);\\n }\\n getHeaders(): Record<string, string> {\\n return {\\n 'Content-Type': this.props.contentType,\\n Accept: 'application/json',\\n };\\n }\\n}\\n\\nclass UrlencodedSerializer extends Serializer {\\n getBody(): BodyInit | null {\\n const body = new URLSearchParams();\\n for (const prop of this.props.inputBody) {\\n for (const item of wireItems(this.input[prop])) {\\n body.append(prop, toWireValue(item));\\n }\\n }\\n return body;\\n }\\n getHeaders(): Record<string, string> {\\n return {\\n 'Content-Type': this.props.contentType,\\n Accept: 'application/json',\\n };\\n }\\n}\\n\\nclass EmptySerializer extends Serializer {\\n getBody(): BodyInit | null {\\n return null;\\n }\\n getHeaders(): Record<string, string> {\\n return {};\\n }\\n}\\n\\nclass FormDataSerializer extends Serializer {\\n getBody(): BodyInit | null {\\n const body = new FormData();\\n for (const prop of this.props.inputBody) {\\n for (const item of wireItems(this.input[prop])) {\\n body.append(prop, item);\\n }\\n }\\n return body;\\n }\\n getHeaders(): Record<string, string> {\\n return {\\n Accept: 'application/json',\\n };\\n }\\n}\\n\\n// A text or binary body is the caller's own string or Blob, sent as is.\\nclass RawSerializer extends Serializer {\\n getBody(): BodyInit | null {\\n return this.input.$body;\\n }\\n getHeaders(): Record<string, string> {\\n return {\\n 'Content-Type': this.props.contentType,\\n };\\n }\\n}\\n\\nexport function json(input: Input, props: Props) {\\n return new JsonSerializer(input, props);\\n}\\nexport function urlencoded(input: Input, props: Props) {\\n return new UrlencodedSerializer(input, props);\\n}\\nexport function empty(input: Input, props: Props) {\\n return new EmptySerializer(input, props);\\n}\\nexport function formdata(input: Input, props: Props) {\\n return new FormDataSerializer(input, props);\\n}\\nexport function text(input: Input, props: Props) {\\n return new RawSerializer(input, props);\\n}\\nexport function binary(input: Input, props: Props) {\\n return new RawSerializer(input, props);\\n}\\n\\nexport function toRequest(\\n method: Method,\\n path: string,\\n serializer: Serializer,\\n baseUrl: string,\\n): RequestConfig {\\n const input = serializer.serialize(path, baseUrl);\\n return {\\n url: input.url,\\n init: {\\n method: method,\\n headers: new Headers(input.headers),\\n ...(method === 'GET' ? {} : { body: input.body }),\\n },\\n };\\n}\\n\",\"http/response.ts\":\"/** The status ranges an OpenAPI 3.2 Responses Object may declare. */\\nexport type StatusRange = '1XX' | '2XX' | '3XX' | '4XX' | '5XX';\\ntype Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';\\ntype ToNumber<S> = S extends `${infer N extends number}` ? N : never;\\n/** Every status code a range covers: `RangeStatus<'4XX'>` is 400 | 401 | \u2026 | 499. */\\nexport type RangeStatus<R extends StatusRange> = R extends `${infer C}XX`\\n ? ToNumber<`${C}${Digit}${Digit}`>\\n : never;\\nexport class APIResponse<Body = unknown, Status extends number = number> {\\n static readonly status: number;\\n readonly status: Status;\\n data: Body;\\n readonly headers: Headers;\\n\\n constructor(status: Status, headers: Headers, data: Body) {\\n this.status = status;\\n this.headers = headers;\\n this.data = data;\\n }\\n\\n static create(status: number, headers: Headers, data: unknown) {\\n return new this(status, headers, data);\\n }\\n}\\n\\nexport class APIError<Body, Status extends number = number> extends Error {\\n static readonly status: number;\\n readonly status: Status;\\n data: Body;\\n readonly headers: Headers;\\n\\n constructor(status: Status, headers: Headers, data: Body) {\\n super(failureMessage(status, data));\\n this.name = 'APIError';\\n this.status = status;\\n this.headers = headers;\\n this.data = data;\\n }\\n\\n static create<T>(status: number, headers: Headers, data: T) {\\n return new this(status, headers, data);\\n }\\n}\\n\\nfunction failureMessage(status: number, data: unknown) {\\n const summary = bodySummary(data);\\n return summary\\n ? `Request failed with status code ${status}: ${summary}`\\n : `Request failed with status code ${status}`;\\n}\\n\\n// Only text and JSON bodies read as a summary; a Blob, stream or FormData body\\n// has none. The tag check holds across realms, where prototype checks do not.\\nfunction bodySummary(data: unknown) {\\n const tag = Object.prototype.toString.call(data);\\n let text = '';\\n if (typeof data === 'string') {\\n text = data;\\n } else if (tag === '[object Object]' || tag === '[object Array]') {\\n text = JSON.stringify(data);\\n }\\n const line = text.replace(/\\\\s+/g, ' ').trim();\\n return line.length > 200 ? `${line.slice(0, 200)}\u2026` : line;\\n}\\n\\n// 2xx Success\\nexport class Ok<T> extends APIResponse<T, 200> {\\n static override readonly status = 200 as const;\\n constructor(headers: Headers, data: T) {\\n super(Ok.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\n\\nexport class Created<T> extends APIResponse<T, 201> {\\n static override status = 201 as const;\\n constructor(headers: Headers, data: T) {\\n super(Created.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class Accepted<T> extends APIResponse<T, 202> {\\n static override status = 202 as const;\\n constructor(headers: Headers, data: T) {\\n super(Accepted.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class NoContent extends APIResponse<null, 204> {\\n static override status = 204 as const;\\n constructor(headers: Headers) {\\n super(NoContent.status, headers, null);\\n }\\n static override create(status: number, headers: Headers): NoContent {\\n return new this(headers);\\n }\\n}\\n\\n// 4xx Client Errors\\nexport class BadRequest<T> extends APIError<T, 400> {\\n static override status = 400 as const;\\n constructor(headers: Headers, data: T) {\\n super(BadRequest.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class Unauthorized<T = { message: string }> extends APIError<T, 401> {\\n static override status = 401 as const;\\n constructor(headers: Headers, data: T) {\\n super(Unauthorized.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class PaymentRequired<T = { message: string }> extends APIError<T, 402> {\\n static override status = 402 as const;\\n constructor(headers: Headers, data: T) {\\n super(PaymentRequired.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class Forbidden<T = { message: string }> extends APIError<T, 403> {\\n static override status = 403 as const;\\n constructor(headers: Headers, data: T) {\\n super(Forbidden.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class NotFound<T = { message: string }> extends APIError<T, 404> {\\n static override status = 404 as const;\\n constructor(headers: Headers, data: T) {\\n super(NotFound.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class MethodNotAllowed<T = { message: string }> extends APIError<\\n T,\\n 405\\n> {\\n static override status = 405 as const;\\n constructor(headers: Headers, data: T) {\\n super(MethodNotAllowed.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class NotAcceptable<T = { message: string }> extends APIError<T, 406> {\\n static override status = 406 as const;\\n constructor(headers: Headers, data: T) {\\n super(NotAcceptable.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class Conflict<T = { message: string }> extends APIError<T, 409> {\\n static override status = 409 as const;\\n constructor(headers: Headers, data: T) {\\n super(Conflict.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class Gone<T = { message: string }> extends APIError<T, 410> {\\n static override status = 410 as const;\\n constructor(headers: Headers, data: T) {\\n super(Gone.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class PreconditionFailed<T = { message: string }> extends APIError<\\n T,\\n 412\\n> {\\n static override status = 412 as const;\\n constructor(headers: Headers, data: T) {\\n super(PreconditionFailed.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class UnprocessableEntity<\\n T = { message: string; errors?: Record<string, string[]> },\\n> extends APIError<T, 422> {\\n static override status = 422 as const;\\n constructor(headers: Headers, data: T) {\\n super(UnprocessableEntity.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class TooManyRequests<\\n T = { message: string; retryAfter?: string },\\n> extends APIError<T, 429> {\\n static override status = 429 as const;\\n constructor(headers: Headers, data: T) {\\n super(TooManyRequests.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {\\n static override status = 413 as const;\\n constructor(headers: Headers, data: T) {\\n super(PayloadTooLarge.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class UnsupportedMediaType<T = { message: string }> extends APIError<\\n T,\\n 415\\n> {\\n static override status = 415 as const;\\n constructor(headers: Headers, data: T) {\\n super(UnsupportedMediaType.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\n\\n// 5xx Server Errors\\nexport class InternalServerError<T = { message: string }> extends APIError<\\n T,\\n 500\\n> {\\n static override status = 500 as const;\\n constructor(headers: Headers, data: T) {\\n super(InternalServerError.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class NotImplemented<T = { message: string }> extends APIError<T, 501> {\\n static override status = 501 as const;\\n constructor(headers: Headers, data: T) {\\n super(NotImplemented.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class BadGateway<T = { message: string }> extends APIError<T, 502> {\\n static override status = 502 as const;\\n constructor(headers: Headers, data: T) {\\n super(BadGateway.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class ServiceUnavailable<\\n T = { message: string; retryAfter?: string },\\n> extends APIError<T, 503> {\\n static override status = 503 as const;\\n constructor(headers: Headers, data: T) {\\n super(ServiceUnavailable.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\nexport class GatewayTimeout<T = { message: string }> extends APIError<T, 504> {\\n static override status = 504 as const;\\n constructor(headers: Headers, data: T) {\\n super(GatewayTimeout.status, headers, data);\\n }\\n static override create<T>(status: number, headers: Headers, data: T) {\\n return new this(headers, data);\\n }\\n}\\n\\nexport type ClientError =\\n | BadRequest<unknown>\\n | Unauthorized<unknown>\\n | PaymentRequired<unknown>\\n | Forbidden<unknown>\\n | NotFound<unknown>\\n | MethodNotAllowed<unknown>\\n | NotAcceptable<unknown>\\n | Conflict<unknown>\\n | Gone<unknown>\\n | PreconditionFailed<unknown>\\n | PayloadTooLarge<unknown>\\n | UnsupportedMediaType<unknown>\\n | UnprocessableEntity<unknown>\\n | TooManyRequests<unknown>\\n | APIError<unknown, RangeStatus<'4XX'>>;\\n\\nexport type ServerError =\\n | InternalServerError<unknown>\\n | NotImplemented<unknown>\\n | BadGateway<unknown>\\n | ServiceUnavailable<unknown>\\n | GatewayTimeout<unknown>\\n | APIError<unknown, RangeStatus<'5XX'>>;\\n\\nexport type ProblematicResponse = ClientError | ServerError;\\n\\nexport type SuccessfulResponse<T = unknown> =\\n | Ok<T>\\n | Created<T>\\n | Accepted<T>\\n | NoContent\\n | APIResponse<T, RangeStatus<'2XX'>>;\\n\\nexport type RebindSuccessPayload<Resp, New> =\\n Resp extends Ok<infer _>\\n ? Ok<New>\\n : Resp extends Created<infer _>\\n ? Created<New>\\n : Resp extends Accepted<infer _>\\n ? Accepted<New>\\n : Resp extends NoContent\\n ? NoContent\\n : Resp extends SuccessfulResponse<infer _>\\n ? APIResponse<New, Resp['status']>\\n : never;\\n\",\"http/security.ts\":\"import { z } from 'zod';\\n\\nimport type { Interceptor } from './interceptors.ts';\\nimport type { RequestConfig } from './request.ts';\\n\\nexport type SecurityContext = {\\n scheme: string;\\n scopes: readonly string[];\\n roles: readonly string[];\\n};\\nexport type SecurityCredentialValue =\\n | string\\n | true\\n | {\\n username: string;\\n password: string;\\n };\\nexport type SecurityCredentialProvider<T extends SecurityCredentialValue> = (\\n context: SecurityContext,\\n) => T | Promise<T>;\\nexport type SecurityCredential<\\n T extends SecurityCredentialValue = SecurityCredentialValue,\\n> = T | SecurityCredentialProvider<T>;\\n\\nconst providerSchema = <T extends SecurityCredentialValue>() =>\\n z.custom<SecurityCredentialProvider<T>>(\\n (value) => typeof value === 'function',\\n );\\nexport const stringCredentialSchema = z.union([\\n z.string(),\\n z.literal(true),\\n providerSchema<string | true>(),\\n]);\\nconst basicCredentialValueSchema = z.object({\\n username: z.string(),\\n password: z.string(),\\n});\\nexport const basicCredentialSchema = z.union([\\n basicCredentialValueSchema,\\n z.literal(true),\\n providerSchema<{ username: string; password: string } | true>(),\\n]);\\nexport const mutualTlsCredentialSchema = z.union([\\n z.literal(true),\\n providerSchema<true>(),\\n]);\\n\\nexport type RuntimeSecurityScheme =\\n | { type: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }\\n | { type: 'http'; scheme: string }\\n | { type: 'oauth2' }\\n | { type: 'openIdConnect' }\\n | { type: 'mutualTLS' };\\n\\n/** The spec's components.securitySchemes; a requirement can name a scheme it lacks (an unresolved external one). */\\nexport type RuntimeSecuritySchemes = {\\n readonly [name: string]: RuntimeSecurityScheme | undefined;\\n};\\n\\nexport function createSecurityInterceptor(\\n requirements: readonly Record<string, readonly string[]>[],\\n credentials: Record<string, SecurityCredential | undefined> | undefined,\\n schemes: RuntimeSecuritySchemes,\\n): Interceptor {\\n return {\\n async before(config) {\\n if (requirements.length === 0) return config;\\n const secured = requirements.filter(\\n (requirement) => Object.keys(requirement).length > 0,\\n );\\n const selected = secured.find((requirement) =>\\n Object.keys(requirement).every(\\n (name) => credentials?.[name] !== undefined,\\n ),\\n );\\n if (!selected) {\\n if (\\n requirements.some(\\n (requirement) => Object.keys(requirement).length === 0,\\n )\\n )\\n return config;\\n throw new Error(\\n `Missing credentials for security requirements: ${secured\\n .map((requirement) => Object.keys(requirement).join(' + '))\\n .join(' or ')}`,\\n );\\n }\\n for (const [name, values] of Object.entries(selected)) {\\n const scheme = schemes[name];\\n if (!scheme) {\\n throw new Error(`Unsupported external security scheme: ${name}`);\\n }\\n const configured = credentials?.[name];\\n const isOAuth =\\n scheme.type === 'oauth2' || scheme.type === 'openIdConnect';\\n const credential =\\n typeof configured === 'function'\\n ? await configured({\\n scheme: name,\\n scopes: isOAuth ? values : [],\\n roles: isOAuth ? [] : values,\\n })\\n : configured;\\n applyCredential(config, scheme, credential);\\n }\\n return config;\\n },\\n };\\n}\\n\\nfunction applyCredential(\\n config: RequestConfig,\\n scheme: RuntimeSecurityScheme,\\n credential: SecurityCredentialValue | undefined,\\n) {\\n if (credential === undefined) {\\n throw new Error('Security credential provider returned no credential');\\n }\\n // true declares a transport-owned credential: the configured fetch, a host\\n // proxy, or the browser's cookie jar supplies it, so nothing is set here.\\n if (credential === true) return;\\n if (scheme.type === 'apiKey') {\\n if (typeof credential !== 'string') {\\n throw new TypeError('API key credentials must be strings');\\n }\\n if (scheme.in === 'header') {\\n if (!config.init.headers.has(scheme.name)) {\\n config.init.headers.set(scheme.name, credential);\\n }\\n } else if (scheme.in === 'query') {\\n if (!config.url.searchParams.has(scheme.name)) {\\n config.url.searchParams.set(scheme.name, credential);\\n }\\n } else if (scheme.in === 'cookie') {\\n if ('document' in globalThis) {\\n throw new Error(\\n `Cannot send the ${scheme.name} cookie credential: browsers forbid setting the Cookie header. Let the browser send the cookie and pass a fetch that sets credentials: 'include'.`,\\n );\\n }\\n const cookie = `${scheme.name}=${encodeURIComponent(credential)}`;\\n const existing = config.init.headers.get('Cookie');\\n if (\\n !existing\\n ?.split(';')\\n .some((part) => part.trim().startsWith(`${scheme.name}=`))\\n ) {\\n config.init.headers.set(\\n 'Cookie',\\n existing ? `${existing}; ${cookie}` : cookie,\\n );\\n }\\n } else {\\n throw new TypeError(`Unsupported apiKey location: ${String(scheme.in)}`);\\n }\\n return;\\n }\\n if (scheme.type === 'mutualTLS') {\\n throw new TypeError(\\n 'mutualTLS credentials must be true when the custom fetch owns the client certificate',\\n );\\n }\\n if (scheme.type === 'http' && scheme.scheme.toLowerCase() === 'basic') {\\n if (\\n typeof credential !== 'object' ||\\n !('username' in credential) ||\\n !('password' in credential)\\n ) {\\n throw new TypeError('Basic credentials require username and password');\\n }\\n const bytes = new TextEncoder().encode(\\n `${credential.username}:${credential.password}`,\\n );\\n let binary = '';\\n for (const byte of bytes) binary += String.fromCharCode(byte);\\n if (!config.init.headers.has('Authorization')) {\\n config.init.headers.set('Authorization', `Basic ${btoa(binary)}`);\\n }\\n return;\\n }\\n if (typeof credential !== 'string') {\\n throw new TypeError(`${scheme.type} credentials must be strings`);\\n }\\n const prefix =\\n scheme.type === 'http' ? authorizationScheme(scheme.scheme) : 'Bearer';\\n if (!config.init.headers.has('Authorization')) {\\n config.init.headers.set('Authorization', `${prefix} ${credential}`);\\n }\\n}\\n\\n// OpenAPI carries the lowercase registry name, while servers routinely match the\\n// Authorization prefix case-sensitively (`header.startsWith('Bearer ')`).\\nconst authorizationSchemes: Record<string, string> = {\\n basic: 'Basic',\\n bearer: 'Bearer',\\n digest: 'Digest',\\n hoba: 'HOBA',\\n mutual: 'Mutual',\\n negotiate: 'Negotiate',\\n oauth: 'OAuth',\\n 'scram-sha-1': 'SCRAM-SHA-1',\\n 'scram-sha-256': 'SCRAM-SHA-256',\\n};\\n\\nfunction authorizationScheme(scheme: string) {\\n return authorizationSchemes[scheme.toLowerCase()] ?? scheme;\\n}\\n\",\"http/sse.ts\":\"export type SSEListener = (eventType: string) => AsyncIterable<string>;\\n\\nexport function sse(response: Response): SSEListener {\\n // Every iterator of an event type reads one queue. Each waiting next() keeps\\n // its own wake-up in `waiters`, and a push or the end of the stream wakes all\\n // of them: a woken next() that finds the queue empty waits again. One shared\\n // wake-up slot would let a second iterator overwrite the first one's, which\\n // then never wakes.\\n const subscribers = new Map<\\n string,\\n { queue: string[]; waiters: Set<() => void> }\\n >();\\n let started = false;\\n let streamDone = false;\\n let streamFailure: { error: unknown } | null = null;\\n\\n function wake(waiters: Set<() => void>) {\\n for (const resolve of waiters) resolve();\\n waiters.clear();\\n }\\n\\n function dispatch(eventType: string, data: string) {\\n const sub = subscribers.get(eventType);\\n if (sub) {\\n sub.queue.push(data);\\n wake(sub.waiters);\\n }\\n }\\n\\n function endAll() {\\n streamDone = true;\\n for (const sub of subscribers.values()) {\\n wake(sub.waiters);\\n }\\n }\\n\\n function startReading() {\\n if (started) return;\\n started = true;\\n const decoder = new TextDecoder();\\n let buffer = '';\\n\\n // The pump never rejects: the catch below hands a stream failure to the\\n // listeners, so nothing awaits it. `void` states that, and keeps generated\\n // output clean under @typescript-eslint/no-floating-promises.\\n void (async () => {\\n try {\\n for await (const value of response.body!) {\\n buffer += decoder.decode(value, { stream: true });\\n const parts = buffer.split('\\\\n\\\\n');\\n buffer = parts.pop()!;\\n\\n for (const part of parts) {\\n if (!part.trim()) continue;\\n let eventType = 'message';\\n let data = '';\\n for (const line of part.split('\\\\n')) {\\n if (line.startsWith('event:')) {\\n eventType = line.slice(6).trim();\\n } else if (line.startsWith('data:')) {\\n data += (data ? '\\\\n' : '') + line.slice(5).trim();\\n }\\n }\\n if (data) dispatch(eventType, data);\\n }\\n }\\n } catch (error) {\\n streamFailure = { error };\\n }\\n endAll();\\n })();\\n }\\n\\n return function listen(eventType: string): AsyncIterable<string> {\\n if (!subscribers.has(eventType)) {\\n subscribers.set(eventType, { queue: [], waiters: new Set() });\\n }\\n const sub = subscribers.get(eventType)!;\\n startReading();\\n\\n return {\\n [Symbol.asyncIterator]() {\\n return {\\n async next(): Promise<IteratorResult<string>> {\\n while (sub.queue.length === 0) {\\n if (streamFailure) throw streamFailure.error;\\n if (streamDone) return { value: undefined, done: true };\\n const { promise, resolve } = Promise.withResolvers<void>();\\n sub.waiters.add(resolve);\\n await promise;\\n }\\n return { value: sub.queue.shift()!, done: false };\\n },\\n async return(): Promise<IteratorResult<string>> {\\n return { value: undefined, done: true };\\n },\\n };\\n },\\n };\\n };\\n}\\n\"};", "import type { TagObject } from 'openapi3-ts/oas32';\n\nimport {\n type IR,\n type OperationEntry,\n type TunedOperationObject,\n carriesBinary,\n forEachOperation,\n inputEndpoint,\n inputName,\n operationInputs,\n} from '@sdk-it/spec';\n\nimport { groupIdentifier } from '../group-identifier.ts';\nimport { type MakeImportFn } from '../import-utilities.ts';\nimport { inputSchemaName } from '../input-schema-name.ts';\n\nexport function generateAISDKTools(ir: IR, makeImport: MakeImportFn) {\n const groups: Record<\n string,\n {\n tools: string[];\n definition: TagObject;\n }\n > = {};\n forEachOperation(ir, (entry, operation) => {\n const tagDef = ir.tags.find((tag) => tag.name === entry.tag);\n if (!tagDef) {\n // normalize-tags gives every operation's tag a definition.\n throw new Error(`The IR defines no tag ${entry.tag}`);\n }\n\n groups[entry.tag] ??= { tools: [], definition: tagDef };\n groups[entry.tag].tools.push(...createTools(ir, entry, operation));\n });\n const imports = [\n `import { z } from 'zod';`,\n `import { tool } from 'ai';`,\n `import * as schemas from '${makeImport('./inputs/index')}';`,\n ];\n // Each group is ToolLoopAgent settings: new ToolLoopAgent({ model, ...group }).\n const agent = Object.entries(groups).map(([group, { tools, definition }]) => {\n const { id, instructions } = agentSettings(definition);\n const instructionsLine =\n instructions === undefined\n ? ''\n : `\\n instructions: ${JSON.stringify(instructions)},`;\n return `export const ${groupIdentifier(group)} = {\n id: ${JSON.stringify(id)},${instructionsLine}\n tools: { ${tools.join(', ')} },\n };`;\n });\n\n return [...imports, ...agent].join('\\n\\n');\n}\n\n/** A group's agent id and instructions: the tag's x-name, else its display name, and its x-instructions, else its description. rpc's toAgents repeats this rule. */\nfunction agentSettings(definition: TagObject) {\n const id: string =\n definition['x-name'] ?? definition.summary ?? definition.name;\n const instructions: string | undefined =\n definition['x-instructions'] ?? definition.description;\n return { id, instructions };\n}\n\n/**\n * One tool per input of `operation` that a JSON tool call can send: the\n * preferred input under the tool's own name, each variant under its encoding.\n */\nfunction createTools(\n ir: IR,\n entry: OperationEntry,\n operation: TunedOperationObject,\n) {\n const toolInfo = operation['x-tool'];\n const name = toolInfo?.name || operation['x-fn-name'];\n const endpoint = `${entry.method.toUpperCase()} ${entry.path}`;\n return operationInputs(ir, operation)\n .filter((input) => !carriesBinary(ir, input))\n .map(\n (input) => `'${inputName(name, input)}': tool({\n description: \\`${toolInfo?.description || operation.description || operation.summary}\\`,\n inputSchema: schemas.${inputSchemaName(operation.operationId, input)},\n\t\t\texecute: async (input, options) => {\n const context = coerceContext(options.context);\n const response = await context.client.request(\n '${inputEndpoint(endpoint, input)}' ,\n input,\n );\n return JSON.stringify(response);\n },\n })`,\n );\n}\n", "import { removeDuplicates } from '@sdk-it/core';\n\nexport function mergeImports(...imports: Import[]) {\n const merged: Record<string, Import> = {};\n\n for (const it of imports) {\n merged[it.moduleSpecifier] = merged[it.moduleSpecifier] ?? {\n moduleSpecifier: it.moduleSpecifier,\n defaultImport: it.defaultImport,\n namespaceImport: it.namespaceImport,\n namedImports: [],\n };\n for (const named of it.namedImports) {\n if (\n !merged[it.moduleSpecifier].namedImports.some(\n (x) => x.name === named.name,\n )\n ) {\n merged[it.moduleSpecifier].namedImports.push(named);\n }\n }\n }\n\n return Object.values(merged);\n}\n\nexport interface Import {\n isTypeOnly?: boolean;\n moduleSpecifier: string;\n defaultImport?: string | undefined;\n namedImports: NamedImport[];\n namespaceImport?: string | undefined;\n}\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly?: boolean;\n}\n\nexport function importsToString(...imports: Import[]) {\n return imports.map((it) => {\n if (it.defaultImport) {\n return `import ${it.defaultImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namespaceImport) {\n return `import * as ${it.namespaceImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namedImports) {\n return `import {${removeDuplicates(it.namedImports, (it) => it.name)\n .map((n) => `${n.isTypeOnly ? 'type' : ''} ${n.name}`)\n .join(', ')}} from '${it.moduleSpecifier}'`;\n }\n throw new Error(`Invalid import ${JSON.stringify(it)}`);\n });\n}\n\nexport function useImports(content: string, ...imports: Import[]) {\n const output: string[] = [];\n for (const it of mergeImports(...imports)) {\n const singleImport = it.defaultImport ?? it.namespaceImport;\n if (singleImport && content.includes(singleImport)) {\n output.push(importsToString(it).join('\\n'));\n } else if (it.namedImports.length) {\n for (const namedImport of it.namedImports) {\n if (content.includes(namedImport.name)) {\n output.push(importsToString(it).join('\\n'));\n }\n }\n }\n }\n return output;\n}\n\nexport type MakeImportFn = (moduleSpecifier: string) => string;\n", "import { camelcase } from 'stringcase';\n\nimport { type OperationInput, inputName } from '@sdk-it/spec';\n\n/** The name the generated `inputs` module exports `input`'s schema under: `uploadFileSchema`, or `uploadFileFormdataSchema` for a variant. */\nexport function inputSchemaName(operationId: string, input: OperationInput) {\n return camelcase(`${inputName(operationId, input)} schema`);\n}\n", "import {\n type IR,\n type OperationEntry,\n type TunedOperationObject,\n carriesBinary,\n forEachOperation,\n inputEndpoint,\n inputName,\n operationInputs,\n} from '@sdk-it/spec';\n\nimport { groupIdentifier } from '../group-identifier.ts';\nimport { type MakeImportFn } from '../import-utilities.ts';\nimport { inputSchemaName } from '../input-schema-name.ts';\n\nexport function generateOpenAIAgentTools(spec: IR, makeImport: MakeImportFn) {\n const groups: Record<string, string[]> = {};\n forEachOperation(spec, (entry, operation) => {\n groups[entry.tag] ??= [];\n groups[entry.tag].push(...createTools(spec, entry, operation));\n });\n const imports = [\n `import { z } from 'zod';`,\n `import { tool } from '@openai/agents';`,\n `import * as schemas from '${makeImport('./inputs/index')}';`,\n ];\n const tools = Object.entries(groups).map(([group, tools]) => {\n return `export const ${groupIdentifier(group)} = [${tools.join(', ')}];`;\n });\n\n return [...imports, ...tools].join('\\n\\n');\n}\n\n/**\n * One tool per input of `operation` that a JSON tool call can send: the\n * preferred input under the tool's own name, each variant under its encoding.\n */\nfunction createTools(\n spec: IR,\n entry: OperationEntry,\n operation: TunedOperationObject,\n) {\n const endpoint = `${entry.method.toUpperCase()} ${entry.path}`;\n return operationInputs(spec, operation)\n .filter((input) => !carriesBinary(spec, input))\n .map(\n (input) => `tool({\n description: \\`${operation.description || operation.summary}\\`,\n name: '${inputName(operation['x-fn-name'], input)}',\n parameters: schemas.${inputSchemaName(operation.operationId, input)},\n\t\t\texecute: async (input, maybeContext) => {\n const context = coerceContext(maybeContext?.context);\n const client = context.client;\n const response = await client.request(\n '${inputEndpoint(endpoint, input)}' ,\n input as any,\n );\n return JSON.stringify(response);\n },\n })`,\n );\n}\n", "function coerceContext(context?: any) {\n if (!context) {\n throw new Error('Context is required');\n }\n return context as {\n client: any\n };\n}\n", "import type { ReferenceObject, SchemaObject } from 'openapi3-ts/oas31';\n\nimport {\n type OpenAPIDocument,\n followRef,\n isEmpty,\n isRef,\n parseRef,\n resolveRef,\n} from '@sdk-it/core';\nimport { isInlinable } from '@sdk-it/spec';\n\nimport type { ModelNamer } from '../model-name.ts';\nimport type { References } from '../references.ts';\n\nexport class TypeScriptEmitter {\n #spec: OpenAPIDocument;\n #modelName: ModelNamer;\n #refs: References;\n\n constructor(spec: OpenAPIDocument, modelName: ModelNamer, refs: References) {\n this.#spec = spec;\n this.#modelName = modelName;\n this.#refs = refs;\n }\n #stringifyKey = (value: string): string => {\n return `'${value}'`;\n };\n\n object(schema: SchemaObject, _required = false): string {\n const properties = schema.properties || {};\n\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const tsType = this.handle(propSchema, isRequired);\n return `${this.#stringifyKey(key)}${isRequired ? '' : '?'}: ${tsType}`;\n });\n\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n const indexType = this.handle(schema.additionalProperties, true);\n propEntries.push(`[key: string]: ${indexType}`);\n } else if (schema.additionalProperties === true) {\n propEntries.push('[key: string]: any');\n }\n }\n\n return `${propEntries.length ? `{ ${propEntries.join('; ')} }` : 'unknown'}`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple)\n */\n #array(schema: SchemaObject, _required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => any[]\n return 'any[]';\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n const tupleItems = items.map((sub) => this.handle(sub, true));\n return `[${tupleItems.join(', ')}]`;\n }\n\n // If items is a single schema => standard array\n const itemsType = this.handle(items, true);\n return itemsType.length > 1 ? `(${itemsType})[]` : `${itemsType}[]`;\n }\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to TypeScript\n */\n normal(type: string, schema: SchemaObject, required = false): string {\n switch (type) {\n case 'string':\n return this.string(schema, required);\n case 'number':\n case 'integer':\n return this.number(schema, required);\n case 'boolean':\n return appendOptional('boolean', required);\n case 'object':\n return this.object(schema, required);\n case 'array':\n return this.#array(schema, required);\n case 'null':\n return 'null';\n default:\n console.warn(`Unknown type: ${type}`);\n // Unknown type -> fallback\n return appendOptional('any', required);\n }\n }\n\n #ref($ref: string, required: boolean): string {\n const schemaName = this.#modelName(parseRef($ref).model);\n if (isInlinable(this.#spec, $ref)) {\n return this.handle(followRef(this.#spec, $ref), required);\n }\n\n return appendOptional(this.#refs.model(schemaName), required);\n }\n\n allOf(schemas: (SchemaObject | ReferenceObject)[]): string {\n // For TypeScript we use intersection types for allOf\n const allOfTypes = schemas.map((sub) => this.handle(sub, true));\n return allOfTypes.length > 1 ? `${allOfTypes.join(' & ')}` : allOfTypes[0];\n }\n\n oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n const isBareString = (s: SchemaObject | ReferenceObject) => {\n const r = resolveRef(this.#spec, s);\n return r.type === 'string' && !r.enum && !r.const && !r.format;\n };\n const isStringLiteral = (s: SchemaObject | ReferenceObject) => {\n const r = resolveRef(this.#spec, s);\n return (\n (Array.isArray(r.enum) &&\n r.enum.every((v: unknown) => typeof v === 'string')) ||\n typeof r.const === 'string'\n );\n };\n const hasStringLiteral = schemas.some(isStringLiteral);\n const seen = new Set<string>();\n const oneOfTypes: string[] = [];\n for (const sub of schemas) {\n const part =\n hasStringLiteral && isBareString(sub)\n ? '(string & {})'\n : this.handle(sub, true);\n if (seen.has(part)) continue;\n seen.add(part);\n oneOfTypes.push(part);\n }\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n return this.oneOf(schemas, required);\n }\n\n enum(values: unknown[], required: boolean): string {\n // For TypeScript enums as union of literals\n const enumValues = values\n .map((val) => (typeof val === 'string' ? `'${val}'` : `${val}`))\n .join(' | ');\n return appendOptional(enumValues, required);\n }\n\n /**\n * Handle string type with formats\n */\n string(schema: SchemaObject, required?: boolean): string {\n let type: string;\n\n if (schema.contentEncoding === 'binary') {\n return appendOptional(this.#refs.global('Blob'), required);\n }\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n case 'date':\n type = 'string';\n break;\n case 'binary':\n case 'byte':\n type = this.#refs.global('Blob');\n break;\n default:\n type = 'string';\n }\n\n return appendOptional(type, required);\n }\n\n /**\n * Handle number/integer types with formats\n */\n number(_schema: SchemaObject, required?: boolean): string {\n return appendOptional('number', required);\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return this.#ref(schema.$ref, required);\n }\n\n if (schema.not && isEmpty(schema.not)) {\n return appendOptional('never', required);\n }\n\n // Handle allOf (intersection in TypeScript)\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf);\n }\n\n // anyOf (union in TypeScript)\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf, required);\n }\n\n // oneOf (union in TypeScript)\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf, required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.enum(schema.enum, required);\n }\n\n if (schema.const) {\n return this.enum([schema.const], true);\n }\n\n // Handle types, in TypeScript we can have union types directly\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to any\n if (!types.length) {\n // unless properties are defined then assume object\n if ('properties' in schema) {\n return this.object(schema, required);\n }\n return appendOptional('any', required);\n }\n\n // Handle union types (multiple types)\n if (types.length > 1) {\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n const tsType = this.normal(realTypes[0], schema, true);\n return appendOptional(`${tsType} | null`, required);\n }\n\n // Multiple different types\n const typeResults = types.map((t) => this.normal(t, schema, true));\n return appendOptional(typeResults.join(' | '), required);\n }\n\n // Single type\n return this.normal(types[0], schema, required);\n }\n}\n\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\n}\n", "import { extname } from 'node:path';\n\nimport { rootRuntimeFiles } from './root-exports.ts';\n\ninterface Entry {\n name: string;\n isFolder: boolean;\n}\n\ninterface IndexedFolder {\n folder: string;\n ignore?: (entry: Entry) => boolean;\n}\n\nconst folders: IndexedFolder[] = [\n { folder: 'outputs' },\n {\n folder: 'inputs',\n ignore: (entry) => entry.isFolder && entry.name === 'schemas',\n },\n { folder: 'api' },\n {\n folder: 'http',\n ignore: (entry) => !rootRuntimeFiles.includes(`http/${entry.name}`),\n },\n { folder: 'models' },\n];\n\n// Agent tool groups are named after tags, so they stay out of the root, where\n// a group could share a name with the client's default instance.\nconst root: IndexedFolder = {\n folder: '',\n ignore: (entry) => entry.name === 'agents.ts',\n};\n\n/**\n * The index.ts files of an SDK whose source files are `paths` (relative to the\n * SDK source root). `contentOf` gives the content of an index.ts the SDK does\n * not generate, such as one a user added to a subfolder.\n */\nexport function indexFiles(\n paths: Iterable<string>,\n contentOf: (path: string) => string | undefined,\n useTsExtension: boolean,\n): Record<string, string> {\n const listed = [...paths];\n const indexes: Record<string, string> = {};\n const content = (path: string) =>\n path in indexes ? indexes[path] : contentOf(path);\n for (const folder of folders) {\n indexes[`${folder.folder}/index.ts`] = folderExports(\n listed,\n folder,\n content,\n useTsExtension,\n );\n }\n if (indexes['inputs/index.ts'] === '') delete indexes['inputs/index.ts'];\n indexes['index.ts'] = folderExports(listed, root, content, useTsExtension);\n return indexes;\n}\n\nfunction folderExports(\n paths: string[],\n { folder, ignore }: IndexedFolder,\n contentOf: (path: string) => string | undefined,\n useTsExtension: boolean,\n) {\n const prefix = folder ? `${folder}/` : '';\n const entries = new Map<string, Entry>();\n for (const path of paths) {\n if (!path.startsWith(prefix)) continue;\n const [name, ...rest] = path.slice(prefix.length).split('/');\n entries.set(name, { name, isFolder: rest.length > 0 });\n }\n const exports: string[] = [];\n for (const entry of [...entries.values()].sort((a, b) =>\n a.name < b.name ? -1 : 1,\n )) {\n if (ignore?.(entry)) continue;\n if (entry.isFolder) {\n if (contentOf(`${prefix}${entry.name}/index.ts`)) {\n exports.push(\n `export * from './${entry.name}/index${useTsExtension ? '.ts' : ''}';`,\n );\n }\n } else if (entry.name !== 'index.ts' && extname(entry.name) === '.ts') {\n exports.push(\n `export * from './${useTsExtension ? entry.name : entry.name.slice(0, -'.ts'.length)}';`,\n );\n }\n }\n return exports.join('\\n');\n}\n", "import { join } from 'node:path';\n\nimport {\n type IR,\n forEachOperation,\n inputEndpoint,\n operationInputs,\n} from '@sdk-it/spec';\n\nimport { type EmittedZod, ZodEmitter } from './emitters/zod.ts';\nimport { groupIdentifier } from './group-identifier.ts';\nimport { inputSchemaName } from './input-schema-name.ts';\nimport type { ModelNamer } from './model-name.ts';\nimport { moduleFileName } from './module-file.ts';\nimport {\n type References,\n fileReferences,\n inputFileReferences,\n} from './references.ts';\nimport { type Operation, type Spec, toEndpoint } from './sdk.ts';\n\n/**\n * A spec's operations as code: per group, its routes (with their input\n * schemas) and endpoint entries, and the shared zod schemas the inputs\n * reference, each after the ones it uses.\n */\nexport function operationFragments(config: {\n spec: IR;\n modelName: ModelNamer;\n /** How shared zod schemas name model types. */\n zodRefs: References;\n /** How endpoint entries name what they use. */\n endpointRefs: References;\n}) {\n const commonZod = new Map<string, EmittedZod>();\n const zodDeserialzer = new ZodEmitter(\n config.spec,\n config.modelName,\n config.zodRefs,\n (model, schema) => {\n commonZod.set(model, schema);\n },\n );\n\n const groups: Spec['operations'] = {};\n const endpoints: Record<string, string[]> = {};\n\n forEachOperation(config.spec, (entry, operation) => {\n groups[entry.tag] ??= [];\n endpoints[entry.tag] ??= [];\n const endpoint = `${entry.method.toUpperCase()} ${entry.path}`;\n const route: Operation = {\n method: entry.method,\n path: entry.path,\n operationId: operation.operationId,\n inputs: operationInputs(config.spec, operation).map((input) => ({\n endpoint: inputEndpoint(endpoint, input),\n schemaName: inputSchemaName(operation.operationId, input),\n ...zodDeserialzer.emit(input.schema, true),\n input,\n })),\n };\n endpoints[entry.tag].push(\n ...toEndpoint(\n entry.tag,\n operation,\n route,\n config.modelName,\n config.endpointRefs,\n ).schemas,\n );\n groups[entry.tag].push(route);\n });\n return { groups, commonZod, endpoints };\n}\n\nexport function generateCode(config: {\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n spec: IR;\n makeImport: (module: string) => string;\n modelName: ModelNamer;\n}) {\n const { groups, commonZod, endpoints } = operationFragments({\n spec: config.spec,\n modelName: config.modelName,\n zodRefs: inputFileReferences,\n endpointRefs: fileReferences('outputs'),\n });\n const allSchemas = Object.keys(endpoints).map((it) => ({\n import: `import ${groupIdentifier(it)} from './${config.makeImport(moduleFileName(it))}';`,\n use: ` ...${groupIdentifier(it)}`,\n }));\n\n return {\n groups,\n commonZod,\n endpoints: {\n [`${join('api', 'schemas.ts')}`]:\n `${allSchemas.map((it) => it.import).join('\\n')}\n\nexport default {\\n${allSchemas.map((it) => it.use).join(',\\n')}\\n};\n\n`.trim(),\n ...Object.fromEntries(\n Object.entries(endpoints).flatMap(([name, entries]) => {\n const operations = entries.join(',\\n');\n return [\n [\n join('api', `${moduleFileName(name)}.ts`),\n `${[\n `import { z } from 'zod';`,\n `import * as http from '${config.makeImport('../http/response')}';`,\n ...(operations.includes('outputs.')\n ? [\n `import * as outputs from '${config.makeImport('../outputs/index')}';`,\n ]\n : []),\n `import { toRequest, json, urlencoded, formdata, text, binary, empty, type HeadersInit } from '${config.makeImport('../http/request')}';`,\n `import { chunked, buffered, bodyless } from \"${config.makeImport('../http/parse-response')}\";`,\n `import { sse, type SSEListener } from \"${config.makeImport('../http/sse')}\";`,\n `import * as ${groupIdentifier(name)} from '../inputs/${config.makeImport(moduleFileName(name))}';`,\n `import { createHeadersInterceptor, type Interceptor } from '${config.makeImport('../http/interceptors')}';`,\n `import { Dispatcher, fetchType, type InstanceType } from '${config.makeImport('../http/dispatcher')}';`,\n ].join('\\n')}\\nexport default {\\n${operations}\\n}`,\n ],\n ];\n }),\n ),\n },\n };\n}\n", "import type { ReferenceObject, SchemaObject } from 'openapi3-ts/oas31';\n\nimport {\n type OpenAPIDocument,\n followRef,\n isEmpty,\n isRef,\n parseRef,\n} from '@sdk-it/core';\nimport { isInlinable, isRecursiveRef } from '@sdk-it/spec';\n\nimport type { ModelNamer } from '../model-name.ts';\nimport type { References } from '../references.ts';\n\n/** Zod source and the shared schemas it names. */\nexport interface EmittedZod {\n zod: string;\n /** The names of the shared schemas `zod` references. */\n references: ReadonlySet<string>;\n}\n\ntype OnRefCallback = (ref: string, schema: EmittedZod) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into a Zod schema string,\n */\nexport class ZodEmitter {\n #generatedRefs = new Set<string>();\n #spec: OpenAPIDocument;\n #modelName: ModelNamer;\n #refs: References;\n #onRef?: OnRefCallback;\n /** The shared schemas each schema being emitted references, innermost last. */\n #references: Set<string>[] = [];\n\n constructor(\n spec: OpenAPIDocument,\n modelName: ModelNamer,\n refs: References,\n onRef?: OnRefCallback,\n ) {\n this.#spec = spec;\n this.#modelName = modelName;\n this.#refs = refs;\n this.#onRef = onRef;\n }\n\n #object(schema: SchemaObject): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n return `'${key}': ${this.handle(propSchema, isRequired)}`;\n });\n\n let additionalProps = '';\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n // e.g. z.record() if it\u2019s an object schema\n const addPropZod = this.handle(schema.additionalProperties, true);\n additionalProps = `.catchall(${addPropZod})`;\n } else if (schema.additionalProperties === true) {\n // free-form additional props\n additionalProps = `.catchall(z.unknown())`;\n }\n }\n\n return `z.object({${propEntries.join(', ')}})${additionalProps}`;\n }\n\n #array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n return `z.array(z.unknown())${appendOptional(required)}`;\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n // Build a Zod tuple\n const tupleItems = items.map((sub) => this.handle(sub, true));\n const base = `z.tuple([${tupleItems.join(', ')}])`;\n // // If we have additionalItems: false => that\u2019s a fixed length\n // // If additionalItems is a schema => rest(...)\n // if (schema.additionalItems) {\n // if (typeof schema.additionalItems === 'object') {\n // const restSchema = jsonSchemaToZod(spec, schema.additionalItems, true);\n // base += `.rest(${restSchema})`;\n // }\n // // If `additionalItems: false`, no rest is allowed => do nothing\n // }\n return `${base}${appendOptional(required)}`;\n }\n\n // If items is a single schema => standard z.array(...)\n const itemsSchema = this.handle(items, true);\n return `z.array(${itemsSchema})${this.#suffixes(JSON.stringify(schema.default), required, false)}`;\n }\n\n #suffixes = (defaultValue: unknown, required: boolean, nullable: boolean) => {\n return `${nullable ? '.nullable()' : ''}${appendOptional(required)}${appendDefault(defaultValue)}`;\n };\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to Zod.\n * We'll also handle .optional() if needed.\n */\n normal(\n type: string,\n schema: SchemaObject,\n required = false,\n nullable = false,\n ): string {\n switch (type) {\n case 'string': {\n const defaultVal =\n (schema['x-zod-type'] === 'date' ||\n schema['x-zod-type'] === 'coerce-date') &&\n schema.default\n ? `new ${this.#refs.global('Date')}(${JSON.stringify(schema.default)})`\n : JSON.stringify(schema.default);\n return `${this.string(schema)}${this.#suffixes(defaultVal, required, nullable)}`;\n }\n case 'number':\n case 'integer': {\n const { base, defaultValue } = this.#number(schema);\n return `${base}${this.#suffixes(defaultValue, required, nullable)}`;\n }\n case 'boolean':\n return `${schema['x-zod-type'] === 'coerce-boolean' ? 'z.union([z.boolean(), z.stringbool()])' : 'z.boolean()'}${this.#suffixes(schema.default, required, nullable)}`;\n case 'object':\n return `${this.#object(schema)}${this.#suffixes(JSON.stringify(schema.default), required, nullable)}`;\n // required always\n case 'array':\n return this.#array(schema, required);\n case 'null':\n // If \"type\": \"null\" alone, this is basically z.null()\n return `z.null()${appendOptional(required)}`;\n default:\n // Unknown type -> fallback\n return `z.unknown()${appendOptional(required)}`;\n }\n }\n\n #ref($ref: string, required: boolean) {\n const schemaName = this.#modelName(parseRef($ref).model);\n const schema = followRef(this.#spec, $ref);\n\n if (isInlinable(this.#spec, $ref)) {\n const inlined = this.emit(schema, required);\n for (const name of inlined.references) {\n this.#references.at(-1)?.add(name);\n }\n this.#onRef?.(schemaName, inlined);\n return inlined.zod;\n }\n\n this.#references.at(-1)?.add(schemaName);\n if (this.#generatedRefs.has(schemaName)) {\n return schemaName;\n }\n this.#generatedRefs.add(schemaName);\n const body = this.emit(schema, required);\n const modelType = this.#refs.model(schemaName);\n // A schema that reaches itself is read only when it validates, and its\n // model type names what TypeScript cannot infer from its own initializer.\n this.#onRef?.(schemaName, {\n zod: isRecursiveRef(this.#spec, $ref)\n ? `z.lazy((): z.ZodType<${modelType}, ${modelType}> => ${body.zod})`\n : body.zod,\n references: body.references,\n });\n\n return schemaName;\n }\n\n /** `schema` as zod source, with the shared schemas that source references. */\n emit(schema: SchemaObject | ReferenceObject, required: boolean): EmittedZod {\n const references = new Set<string>();\n this.#references.push(references);\n try {\n return { zod: this.handle(schema, required), references };\n } finally {\n this.#references.pop();\n }\n }\n #toIntersection(schemas: string[]): string {\n const [left, ...right] = schemas;\n if (!right.length) {\n return left;\n }\n return `z.intersection(${left}, ${this.#toIntersection(right)})`;\n }\n\n allOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const allOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (allOfSchemas.length === 0) {\n return `z.unknown()`;\n }\n if (allOfSchemas.length === 1) {\n return `${allOfSchemas[0]}${appendOptional(required)}`;\n }\n return `${this.#toIntersection(allOfSchemas)}${appendOptional(required)}`;\n }\n\n anyOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const anyOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (anyOfSchemas.length === 1) {\n return `${anyOfSchemas[0]}${appendOptional(required)}`;\n }\n return `z.union([${anyOfSchemas.join(', ')}])${appendOptional(required)}`;\n }\n\n oneOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const oneOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (oneOfSchemas.length === 1) {\n return `${oneOfSchemas[0]}${appendOptional(required)}`;\n }\n // oneOf is exclusive-or per JSON Schema; z.xor rejects values matching\n // more than one branch, unlike z.union's anyOf semantics.\n return `z.xor([${oneOfSchemas.join(', ')}])${appendOptional(required)}`;\n }\n\n enum(values: any[]) {\n if (values.length === 1) {\n return `z.literal(${values.join(', ')})`;\n }\n // Values arrive JSON.stringify'd, so string literals start with a quote.\n // z.enum only takes strings; zod 4 silently filters numeric entries as\n // reverse mappings, so any non-string enum must emit z.literal([...]).\n if (values.every((value) => String(value).startsWith('\"'))) {\n return `z.enum([${values.join(', ')}])`;\n }\n return `z.literal([${values.join(', ')}])`;\n }\n\n /**\n * Handle a `string` schema with possible format keywords (JSON Schema).\n */\n string(schema: SchemaObject): string {\n let base =\n schema['x-zod-type'] === 'coerce-string'\n ? 'z.coerce.string()'\n : 'z.string()';\n\n // 3.1 replaces `example` in the schema with `examples` (array).\n // We do not strictly need them for the Zod type, so they\u2019re optional\n // for validation. However, we could keep them as metadata if you want.\n\n if (schema.contentEncoding === 'binary') {\n // Emitted client code must not reference Blob as a runtime value:\n // it throws ReferenceError where the global is missing and fails\n // instanceof for cross-realm/polyfill Blobs (see e62c4e1 and\n // docs/recipes/file-upload.md).\n base = `z.custom<${this.#refs.global('Blob')}>()`;\n return base;\n }\n\n const coerced = schema['x-zod-type'] === 'coerce-string';\n const limits = stringLimits(schema);\n const withFormat = (format: string) =>\n coerced ? `${base}.pipe(${format}${limits})` : `${format}${limits}`;\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n if (schema['x-zod-type'] === 'coerce-date') {\n base = 'z.coerce.date()';\n } else if (schema['x-zod-type'] === 'date') {\n base = 'z.date()';\n } else {\n // RFC 3339 date-time allows numeric zone offsets, which\n // z.iso.datetime() rejects by default.\n base = withFormat('z.iso.datetime({ offset: true })');\n }\n break;\n case 'date':\n base = withFormat('z.iso.date()');\n break;\n case 'time':\n // z.iso.time() rejects RFC 3339 zone suffixes, which JSON Schema's\n // format: time allows.\n base = withFormat(\n 'z.string().regex(/^([01]\\\\d|2[0-3]):[0-5]\\\\d(:[0-5]\\\\d(\\\\.\\\\d+)?)?(Z|[+-]([01]\\\\d|2[0-3]):[0-5]\\\\d)?$/)',\n );\n break;\n case 'email':\n base = withFormat('z.email()');\n break;\n case 'uuid':\n // z.guid() preserves zod v3's looser .uuid() semantics; z.uuid()\n // enforces RFC 9562 variant bits and rejects Microsoft-style GUIDs.\n base = withFormat('z.guid()');\n break;\n case 'url':\n case 'uri':\n base = withFormat('z.url()');\n break;\n case 'ipv4':\n base = withFormat('z.ipv4()');\n break;\n case 'ipv6':\n base = withFormat('z.ipv6()');\n break;\n case 'cidrv4':\n base = withFormat('z.cidrv4()');\n break;\n case 'cidrv6':\n base = withFormat('z.cidrv6()');\n break;\n case 'phone':\n base += `${limits} /* or add .regex(...) for phone formats */`;\n break;\n case 'byte':\n case 'binary':\n // Bare z.custom on purpose \u2014 see the contentEncoding branch above.\n base = `z.custom<${this.#refs.global('Blob')}>()`;\n break;\n default:\n base += limits;\n break;\n }\n\n return base;\n }\n\n /**\n * Handle number/integer constraints from OpenAPI/JSON Schema.\n * In 3.1, exclusiveMinimum/Maximum hold the actual numeric threshold,\n * rather than a boolean toggling `minimum`/`maximum`.\n */\n #number(schema: SchemaObject) {\n let base =\n schema['x-zod-type'] === 'coerce-number'\n ? 'z.coerce.number()'\n : 'z.number()';\n\n if (schema.type === 'integer') {\n base += '.int()';\n }\n\n // If we see exclusiveMinimum as a number in 3.1:\n if (typeof schema.exclusiveMinimum === 'number') {\n // Zod doesn\u2019t have a direct \"exclusiveMinimum\" method, so we can do .gt()\n // If exclusiveMinimum=7 => .gt(7)\n base += `.gt(${schema.exclusiveMinimum})`;\n }\n // Similarly for exclusiveMaximum\n if (typeof schema.exclusiveMaximum === 'number') {\n // If exclusiveMaximum=10 => .lt(10)\n base += `.lt(${schema.exclusiveMaximum})`;\n }\n\n // If standard minimum/maximum\n if (typeof schema.minimum === 'number') {\n base += `.min(${schema.minimum})`;\n }\n if (typeof schema.maximum === 'number') {\n base += `.max(${schema.maximum})`;\n }\n\n // multipleOf\n if (typeof schema.multipleOf === 'number') {\n // There's no direct multipleOf in Zod. Some folks do a custom refine.\n // For example:\n base += `.refine((val) => Number.isInteger(val / ${schema.multipleOf}), \"Must be a multiple of ${schema.multipleOf}\")`;\n }\n\n return { base, defaultValue: schema.default };\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return `${this.#ref(schema.$ref, true)}${appendOptional(required)}`;\n }\n\n if (schema.not && isEmpty(schema.not)) {\n return `z.never()${appendOptional(required)}`;\n }\n\n // Handle allOf \u2192 intersection\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf ?? [], required);\n }\n\n // anyOf \u2192 union\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf ?? [], required);\n }\n\n // oneOf \u2192 union\n if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length) {\n return this.oneOf(schema.oneOf ?? [], required);\n }\n\n if (schema.const !== undefined) {\n return `z.literal(${JSON.stringify(schema.const)})${this.#suffixes(JSON.stringify(schema.default), required, false)}`;\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n const enumVals = schema.enum.map((val) => JSON.stringify(val));\n const defaultValue = enumVals.includes(JSON.stringify(schema.default))\n ? JSON.stringify(schema.default)\n : undefined;\n return `${this.enum(enumVals)}${this.#suffixes(defaultValue, required, false)}`;\n }\n\n // 3.1 can have type: string or type: string[] (e.g. [\"string\",\"null\"])\n // Let's parse that carefully.\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to unknown\n if (!types.length) {\n return `z.unknown()${appendOptional(required)}`;\n }\n\n // If it's a union type (like [\"string\", \"null\"]), we'll build a Zod union\n // or apply .nullable() if it's just \"type + null\".\n\n // backward compatibility with openapi 3.0\n if ('nullable' in schema && schema.nullable) {\n types.push('null');\n } else if (schema.default === null) {\n types.push('null');\n }\n\n if (types.length > 1) {\n // If it\u2019s exactly one real type plus \"null\", we can do e.g. `z.string().nullable()`\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n return this.normal(\n realTypes[0],\n { ...schema, type: realTypes[0] },\n required,\n true,\n );\n }\n // If multiple different types, build a union\n const subSchemas = types.map((t) =>\n this.normal(t, { ...schema, type: t }, true),\n );\n return `z.union([${subSchemas.join(', ')}])${appendOptional(required)}`;\n }\n return this.normal(types[0], schema, required, false);\n }\n}\n\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\n\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined || typeof defaultValue !== 'undefined'\n ? `.default(${defaultValue})`\n : '';\n}\n\n/** JSON Schema's string length and pattern keywords, mapped as zod's own `z.fromJSONSchema` maps them. */\nfunction stringLimits(schema: SchemaObject) {\n let limits = '';\n if (typeof schema.minLength === 'number') {\n limits += `.min(${schema.minLength})`;\n }\n if (typeof schema.maxLength === 'number') {\n limits += `.max(${schema.maxLength})`;\n }\n if (typeof schema.pattern === 'string') {\n limits += `.regex(${regexLiteral(schema.pattern)})`;\n }\n return limits;\n}\n\n/**\n * A regular expression literal for a JSON Schema `pattern`, which is an\n * ECMA-262 regular expression that is not anchored. Compiling it here fails\n * generation on a pattern that JavaScript rejects, instead of the SDK failing\n * when it is imported. The literal names no global that a spec name can hide.\n */\nfunction regexLiteral(pattern: string) {\n try {\n return `/${new RegExp(pattern).source}/`;\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new SyntaxError(\n `The pattern ${JSON.stringify(pattern)} is not an ECMA-262 regular expression: ${error.message}`,\n { cause: error },\n );\n }\n throw error;\n }\n}\n", "import { spinalcase } from 'stringcase';\n\n/**\n * The file name (without extension) of a generated module. A module named\n * `index` would collide with its folder's barrel, so it gets a trailing `-`,\n * the way spinalcase renders the namer's trailing `_`.\n */\nexport function moduleFileName(name: string) {\n const file = spinalcase(name);\n return file === 'index' ? 'index-' : file;\n}\n", "import { type OpenAPISecuritySchemeObject } from '@sdk-it/core';\nimport {\n type OperationInput,\n type OperationPagination,\n type ResponseBody,\n type TunedOperationObject,\n type TunedResponseObject,\n statusRange,\n} from '@sdk-it/spec';\n\nimport { type MakeImportFn } from './import-utilities.ts';\nimport type { ModelNamer } from './model-name.ts';\nimport type { References } from './references.ts';\nimport statusMap from './status-map.ts';\n\nexport interface Spec {\n name: string;\n securitySchemes: Record<string, OpenAPISecuritySchemeObject>;\n servers: string[];\n operations: Record<string, Operation[]>;\n makeImport: MakeImportFn;\n}\n\n/** One way a client sends an operation: the key it is exposed under and the input it takes. */\nexport interface OperationRoute {\n endpoint: string;\n /** The name the `inputs` module exports the input schema under. */\n schemaName: string;\n /** The input schema as zod source. */\n zod: string;\n /** The names of the shared schemas `zod` references. */\n references: ReadonlySet<string>;\n input: OperationInput;\n}\n\nexport interface Operation {\n method: string;\n path: string;\n operationId: string;\n /** The preferred input first, then its variants. */\n inputs: OperationRoute[];\n}\n\nexport function toEndpoint(\n groupName: string,\n specOperation: TunedOperationObject,\n operation: Operation,\n modelName: ModelNamer,\n refs: References,\n) {\n const schemas: string[] = [];\n specOperation.responses ??= {};\n const outputs = Object.keys(specOperation.responses).map((status) =>\n toHttpOutput(status, specOperation.responses[status], modelName, refs),\n );\n\n for (const route of operation.inputs) {\n const schemaRef = refs.input(groupName, route.schemaName);\n const key = refs.located(`\"${route.endpoint}\"`, [\n 'paths',\n operation.path,\n operation.method,\n ]);\n schemas.push(\n `${key}: {\n security: ${JSON.stringify(specOperation.security)} as readonly ${refs.global('Record')}<string, readonly string[]>[],\n schema: ${schemaRef},\n output:[${outputs.join(',')}],\n toRequest(input: z.input<typeof ${schemaRef}>, baseUrl: string) {\n return ${refs.runtime('toRequest')}('${operation.method.toUpperCase()}', '${operation.path}', ${refs.runtime(route.input.encoding)}(input, {\n contentType: ${JSON.stringify(route.input.contentType)},\n inputHeaders: [${quoted(route.input.header)}],\n inputQuery: [${quoted(route.input.query)}],\n inputBody: [${quoted(route.input.body)}],\n inputParams: [${quoted(route.input.path)}],\n }), baseUrl);},\n async dispatch(input: z.output<typeof ${schemaRef}>,options: {\n signal?: ${refs.global('AbortSignal')};\n interceptors: ${refs.runtime('Interceptor')}[];\n fetch: z.infer<typeof ${refs.runtime('fetchType')}>;\n baseUrl: string;\n })${normalOperation(specOperation['x-pagination'], refs)}`,\n );\n }\n return { schemas };\n}\n\nfunction normalOperation(\n pagination: OperationPagination | undefined,\n refs: References,\n) {\n return `{\n const dispatcher = new ${refs.runtime('Dispatcher')}(options.interceptors, options.fetch);\n return dispatcher.send(this.toRequest(input, options.baseUrl), this.output, options?.signal);\n },${pagination ? `\\n pagination: ${JSON.stringify(runtimePagination(pagination))} as const,` : ''}\n }`;\n}\n\n/**\n * The fields of an operation's pagination that @sdk-it/runtime's Page reads.\n * `JSON.stringify` omits the optional ones that are undefined.\n */\nfunction runtimePagination(pagination: OperationPagination) {\n const { items, hasMore, statusCode } = pagination;\n switch (pagination.type) {\n case 'offset':\n return {\n type: pagination.type,\n offsetParamName: pagination.offsetParamName,\n limitParamName: pagination.limitParamName,\n items,\n hasMore,\n statusCode,\n start: pagination.start,\n };\n case 'page':\n return {\n type: pagination.type,\n pageNumberParamName: pagination.pageNumberParamName,\n pageSizeParamName: pagination.pageSizeParamName,\n items,\n hasMore,\n statusCode,\n start: pagination.start,\n };\n case 'cursor':\n return {\n type: pagination.type,\n cursorParamName: pagination.cursorParamName,\n items,\n hasMore,\n statusCode,\n nextCursor: pagination.nextCursor,\n };\n }\n}\n\n/** The runtime parser call that reads each body kind. */\nfunction bodyParser(body: ResponseBody, refs: References) {\n switch (body) {\n case 'json':\n case 'text':\n case 'binary':\n return `${refs.runtime('buffered')}(${JSON.stringify(body)})`;\n case 'empty':\n return refs.runtime('bodyless');\n case 'stream':\n return refs.runtime('chunked');\n case 'sse':\n return refs.runtime('sse');\n }\n}\n\nexport function toHttpOutput(\n status: string,\n response: TunedResponseObject,\n modelName: ModelNamer,\n refs: References,\n) {\n if (status === '204') {\n return refs.status('NoContent');\n }\n const data = dataType(status, response, modelName, refs);\n const parser = bodyParser(response['x-body'], refs);\n const range = statusRange(status);\n if (range) {\n const type = refs.status(range === '2XX' ? 'APIResponse' : 'APIError');\n return `{type: ${type}<${data}, ${refs.status('RangeStatus')}<'${range}'>>, parser: ${parser}, range: '${range}' as const}`;\n }\n const type = refs.status(statusMap[status] || 'APIResponse');\n return `{type: ${type}<${data}>, parser: ${parser}}`;\n}\n\nfunction dataType(\n status: string,\n response: TunedResponseObject,\n modelName: ModelNamer,\n refs: References,\n) {\n switch (response['x-body']) {\n case 'empty':\n return 'null';\n case 'stream':\n return refs.global('ReadableStream');\n case 'sse':\n return refs.runtime('SSEListener');\n default:\n return refs.model(modelName(outputName(status, response)));\n }\n}\n\nfunction outputName(status: string, response: TunedResponseObject) {\n const name = response['x-response-name'];\n if (!name) {\n throw new Error(\n `Response ${status} has a ${response['x-body']} body but no output name; generate with responses.flattenErrorResponses so every response is normalized`,\n );\n }\n return name;\n}\n\nfunction quoted(names: readonly string[]) {\n return names.map((name) => `\"${name}\"`);\n}\n", "const statusMap: Record<string, string> = {\n '200': 'Ok',\n '201': 'Created',\n '202': 'Accepted',\n '204': 'NoContent',\n '400': 'BadRequest',\n '401': 'Unauthorized',\n '402': 'PaymentRequired',\n '403': 'Forbidden',\n '404': 'NotFound',\n '405': 'MethodNotAllowed',\n '406': 'NotAcceptable',\n '409': 'Conflict',\n '412': 'PreconditionFailed',\n '413': 'PayloadTooLarge',\n '410': 'Gone',\n '415': 'UnsupportedMediaType',\n '422': 'UnprocessableEntity',\n '429': 'TooManyRequests',\n '500': 'InternalServerError',\n '501': 'NotImplemented',\n '502': 'BadGateway',\n '503': 'ServiceUnavailable',\n '504': 'GatewayTimeout',\n};\n\nexport default statusMap;\n", "import { pascalcase } from '@sdk-it/core';\nimport { sanitizeTag } from '@sdk-it/spec';\n\nimport { clientExports } from './client.ts';\nimport { runtimeRootExports } from './root-exports.ts';\nimport { securityTypeExports } from './security.ts';\n\nexport type ModelNamer = (schemaName: string) => string;\n\n/**\n * Names model types so that none shadows a runtime or client export of the SDK\n * root (a trailing `_` is appended), and no two schemas share one.\n */\nexport function createModelNamer(clientName: string): ModelNamer {\n const reserved = new Set([\n ...runtimeRootExports.map(({ name }) => name),\n ...securityTypeExports,\n ...clientExports(clientName),\n ]);\n const owners = new Map<string, string>();\n return (schemaName) => {\n const base = pascalcase(sanitizeTag(schemaName));\n const name = reserved.has(base) ? `${base}_` : base;\n const owner = owners.getOrInsert(name, schemaName);\n if (owner !== schemaName) {\n throw new TypeError(\n `Schemas \"${owner}\" and \"${schemaName}\" both become the TypeScript type ${name}; rename one of them in the spec`,\n );\n }\n return name;\n };\n}\n", "import runtime, { type RuntimeBinding } from 'runtime-module';\n\nimport type { EmittedZod } from './emitters/zod.ts';\nimport type { References } from './references.ts';\nimport { runtimeRootExports } from './root-exports.ts';\n\n/**\n * The names a one-module SDK uses: spec names as declared, and runtime names\n * and globals as marks that `assembleModule` resolves once it knows which spec\n * names take a runtime name or shadow a global; a located name is marked with\n * its location (`@` and the location JSON, then the name). Generated code never\n * contains a NUL character (JSON.stringify escapes it), so a mark cannot collide.\n */\nexport const moduleReferences: References = {\n model: (typeName) => typeName,\n input: (_group, schemaName) => schemaName,\n status: (className) => `\\0${className}\\0`,\n runtime: (name) => `\\0${name}\\0`,\n global: (name) => `\\0globalThis.${name}\\0`,\n located: (text, location) => `\\0@${JSON.stringify(location)}\\0${text}\\0`,\n};\n\n/**\n * A range of a one-module SDK's text (UTF-16 offsets, `end` exclusive) that\n * names what the OpenAPI document declares at `location` (RFC 6901 reference\n * tokens, unescaped): an endpoint key, a model, create<Name>, the default\n * instance.\n */\nexport interface ModuleSpan {\n start: number;\n end: number;\n location: readonly string[];\n}\n\nexport interface ModuleParts {\n /** Shared zod schemas by name, each after the ones it uses. */\n commonZod: Map<string, EmittedZod>;\n inputs: { name: string; zod: string }[];\n /** `location` is where the document declares the model, when it does. */\n models: {\n typeName: string;\n doc: string;\n type: string;\n location: readonly string[] | undefined;\n }[];\n /** Endpoint entries (`\"GET /pets\": {\u2026}`) of the table the client reads as `__routes`. */\n endpoints: string[];\n /** The client declarations over `__routes`. */\n client: string;\n /** The names `client` declares. */\n clientNames: readonly string[];\n /** Runtime functions and types the SDK root exports besides the response and parser ones. */\n runtimeExports: readonly string[];\n runtimeTypeExports: readonly string[];\n}\n\n/**\n * The SDK as one module text: the runtime, then the spec's shared schemas,\n * inputs, models, endpoint table and client, each after what it uses.\n * Runtime and spec share one scope, and spec names win: a runtime binding a\n * spec name takes is renamed `__<name>`, and a global a spec name shadows is\n * read as `globalThis.<name>`.\n */\nexport function assembleModule(parts: ModuleParts): {\n text: string;\n spans: ModuleSpan[];\n} {\n const specNames = new Set([\n ...parts.commonZod.keys(),\n ...parts.inputs.map(({ name }) => name),\n ...parts.models.map(({ typeName }) => typeName),\n ...parts.clientNames,\n '__routes',\n ]);\n const names = runtimeNames(specNames);\n const declaredName = new Map(\n runtime.bindings.flatMap((binding, index) =>\n binding.kind === 'declared'\n ? [[binding.name, names[index]] as const]\n : [],\n ),\n );\n const nameOf = (name: string, global: boolean) => {\n if (global) {\n return specNames.has(name) ? `globalThis.${name}` : name;\n }\n const finalName = declaredName.get(name);\n if (finalName === undefined) {\n throw new TypeError(`The runtime declares no ${name}`);\n }\n return finalName;\n };\n\n const values = runtimeRootExports\n .filter(({ type }) => !type)\n .map(({ name }) => name);\n const types = runtimeRootExports\n .filter(({ type }) => type)\n .map(({ name }) => name);\n const pieces = [\n externalImports(names),\n runtimeText(names, specNames),\n ...[...parts.commonZod].map(([name, { zod }]) => `const ${name} = ${zod};`),\n ...parts.inputs.map(({ name, zod }) => `export const ${name} = ${zod};`),\n ...parts.models.map(\n ({ typeName, doc, type, location }) =>\n `${doc}export type ${location ? moduleReferences.located(typeName, location) : typeName} = ${type};`,\n ),\n `const __routes = {\\n${parts.endpoints.join(',\\n')}\\n};`,\n parts.client,\n `export { ${[...values, ...parts.runtimeExports].join(', ')} };`,\n `export type { ${[...types, ...parts.runtimeTypeExports].join(', ')} };`,\n ];\n\n let text = '';\n const spans: ModuleSpan[] = [];\n for (const [index, piece] of pieces.entries()) {\n if (index > 0) text += '\\n';\n let cursor = 0;\n for (const mark of piece.matchAll(marks)) {\n text += piece.slice(cursor, mark.index);\n const [, location, located, global, name] = mark;\n if (location !== undefined) {\n const start = text.length;\n text += located;\n spans.push({ start, end: text.length, location: JSON.parse(location) });\n } else {\n text += nameOf(name, global !== undefined);\n }\n cursor = mark.index + mark[0].length;\n }\n text += piece.slice(cursor);\n }\n return { text, spans };\n}\n\n/** A located name (location JSON, then text) or a runtime name or global mark of `moduleReferences`. */\nconst marks = /\\0@([^\\0]*)\\0([^\\0]*)\\0|\\0(globalThis\\.)?([A-Za-z_$][\\w$]*)\\0/g;\n\n/**\n * Each runtime binding's name in the module, by its index in\n * `runtime.bindings`: its own, unless a spec name or a binding placed before it\n * takes that name. Declarations are placed before the names the runtime\n * imports from packages.\n */\nfunction runtimeNames(specNames: ReadonlySet<string>) {\n const ownNames = new Set(runtime.bindings.map(({ name }) => name));\n const taken = new Set(specNames);\n const names = runtime.bindings.map(({ name }) => name);\n const order = [...runtime.bindings.keys()].sort(\n (a, b) => rank(runtime.bindings[a]) - rank(runtime.bindings[b]),\n );\n for (const index of order) {\n const own = runtime.bindings[index].name;\n let name = own;\n while (taken.has(name) || (name !== own && ownNames.has(name))) {\n name = `__${name}`;\n }\n taken.add(name);\n names[index] = name;\n }\n return names;\n}\n\nfunction rank(binding: RuntimeBinding) {\n return binding.kind === 'declared' ? 0 : 1;\n}\n\nfunction externalImports(names: readonly string[]) {\n return runtime.bindings\n .flatMap((binding, index) => {\n if (binding.kind !== 'external') return [];\n const local = names[index];\n const name =\n local === binding.name ? local : `${binding.name} as ${local}`;\n return [`import { ${name} } from '${binding.module}';`];\n })\n .join('\\n');\n}\n\n/** The runtime source with the renamed bindings and the shadowed globals applied. */\nfunction runtimeText(names: readonly string[], specNames: ReadonlySet<string>) {\n const edits: { at: number; length: number; text: string }[] = [];\n for (const [index, binding] of runtime.bindings.entries()) {\n const name = names[index];\n if (name === binding.name) continue;\n const length = binding.name.length;\n for (const at of binding.occurrences)\n edits.push({ at, length, text: name });\n for (const at of binding.shorthands) {\n edits.push({ at, length, text: `${binding.name}: ${name}` });\n }\n }\n for (const global of runtime.globals) {\n if (!specNames.has(global.name)) continue;\n for (const at of global.occurrences) {\n edits.push({ at, length: 0, text: 'globalThis.' });\n }\n }\n edits.sort((a, b) => a.at - b.at);\n let text = '';\n let cursor = 0;\n for (const { at, length, text: replacement } of edits) {\n text += runtime.text.slice(cursor, at) + replacement;\n cursor = at + length;\n }\n return text + runtime.text.slice(cursor);\n}\n", "import { isEmpty } from '@sdk-it/core';\nimport type { Generator } from '@sdk-it/readme';\nimport { type IR, forEachOperation, operationInputs } from '@sdk-it/spec';\n\nimport { PropEmitter } from './prop.emitter.ts';\n\nexport function toReadme(spec: IR, generator: Generator) {\n const propEmitter = new PropEmitter(spec);\n const bodylessInputs = new Set<string>();\n const markdown: string[] = [];\n\n // Add TypeScript SDK heading and description\n markdown.push(`# ${spec.info.title} TypeScript SDK`);\n markdown.push('');\n markdown.push(\n 'A fully-typed TypeScript SDK with comprehensive IntelliSense support, automatic request/response validation, and modern async/await patterns. Built for seamless integration with TypeScript and JavaScript projects. Each endpoint includes a brief description, example usage, and details about request and response formats.',\n );\n\n markdown.push('');\n\n markdown.push(generator.clientSetupDocs());\n markdown.push('');\n\n // Add authentication docs if there are security schemes\n const securitySchemes = spec.components?.securitySchemes || {};\n if (Object.keys(securitySchemes).length > 0) {\n markdown.push(generator.authenticationDocs());\n markdown.push('');\n }\n\n // Add pagination docs if any operations have pagination\n const paginationDocs = generator.paginationDocs();\n if (paginationDocs) {\n markdown.push(paginationDocs);\n markdown.push('');\n }\n\n // Add error handling docs\n markdown.push(generator.errorHandlingDocs());\n markdown.push('');\n\n // Add general usage docs\n markdown.push(generator.generalUsageDocs());\n markdown.push('');\n\n markdown.push('## API Reference');\n markdown.push('');\n\n forEachOperation(spec, (entry, operation) => {\n const { method, path } = entry;\n markdown.push(\n `### ${operation['x-fn-name']} | ${`_${method.toUpperCase()} ${path}_`}`,\n );\n markdown.push(operation.summary || '');\n\n const snippet = generator.snippet(entry, operation);\n markdown.push(`#### Example usage`);\n markdown.push(snippet);\n\n const [preferred] = operationInputs(spec, operation);\n const input = propEmitter.parameters(operation.parameters);\n if (preferred.encoding === 'empty') {\n bodylessInputs.add(\n operation.requestBody.content[preferred.contentType].schema.$ref,\n );\n } else {\n input.push(...propEmitter.requestBody(operation.requestBody));\n }\n if (input.length > 0) {\n markdown.push(['#### Input', ...input].join('\\n\\n'));\n }\n\n markdown.push(`#### Output`);\n for (const status in operation.responses) {\n const response = operation.responses[status];\n\n if (!isEmpty(response.content)) {\n const contentEntries = Object.entries(response.content);\n\n if (contentEntries.length === 1) {\n const [contentType, mediaType] = contentEntries[0];\n markdown.push(`**${status}** - ${response.description}`);\n markdown.push(`\\n**Content Type:** \\`${contentType}\\``);\n\n if (mediaType.schema) {\n const schemaDocs = propEmitter.handle(mediaType.schema);\n markdown.push(...schemaDocs);\n }\n } else {\n // Multiple content types - use collapsible toggle for the entire response\n markdown.push(`<details>`);\n markdown.push(\n `<summary><b>${status}</b> <i>${response.description}</i></summary>`,\n );\n\n for (const [contentType, mediaType] of contentEntries) {\n markdown.push(`\\n**Content Type:** \\`${contentType}\\``);\n if (mediaType.schema) {\n const schemaDocs = propEmitter.handle(mediaType.schema);\n markdown.push(...schemaDocs.map((l) => `\\n${l}`));\n }\n }\n\n markdown.push(`</details>`);\n }\n } else {\n // No content - just show status and description\n markdown.push(`**${status}** - ${response.description}`);\n }\n }\n }); // Add schemas section at the bottom\n if (spec.components?.schemas) {\n markdown.push('## Schemas');\n markdown.push('');\n\n for (const [schemaName, schema] of Object.entries(\n spec.components.schemas,\n )) {\n // ValidationError is internal, and a bodyless input's schema only\n // holds the parameters its operation documents.\n if (\n schemaName === 'ValidationError' ||\n bodylessInputs.has(\n `#/components/schemas/${schemaName.replaceAll('~', '~0').replaceAll('/', '~1')}`,\n )\n ) {\n continue;\n }\n\n markdown.push(`<details>`);\n markdown.push(\n `<summary><h3 id=\"${schemaName.toLowerCase()}\">${schemaName}</h3></summary>`,\n );\n markdown.push('');\n\n const schemaDocs = propEmitter.handle(schema);\n markdown.push(...schemaDocs.map((line) => line.trim()));\n\n markdown.push('');\n markdown.push(`</details>`);\n markdown.push('');\n }\n }\n\n // Generate Table of Contents\n\n return markdown.join('\\n\\n');\n}\n", "import type {\n ParameterObject,\n ReferenceObject,\n RequestBodyObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { type OpenAPIDocument, followRef, isRef } from '@sdk-it/core';\nimport { coerceTypes } from '@sdk-it/spec';\n\n/**\n * PropEmitter handles converting OpenAPI schemas to Markdown documentation\n */\nexport class PropEmitter {\n #spec: OpenAPIDocument;\n\n constructor(spec: OpenAPIDocument) {\n this.#spec = spec;\n }\n\n /**\n * Handle objects (properties)\n */\n #object(schema: SchemaObject): string[] {\n const lines: string[] = [];\n const properties = schema.properties || {};\n\n if (Object.keys(properties).length > 0) {\n lines.push(`**Properties:**`);\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const isRequired = (schema.required ?? []).includes(propName);\n lines.push(...this.#property(propName, propSchema, isRequired));\n }\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n lines.push(`**Additional Properties:**`);\n if (typeof schema.additionalProperties === 'boolean') {\n lines.push(`- Allowed: ${schema.additionalProperties}`);\n } else {\n // Indent the schema documentation for additional properties\n lines.push(\n ...this.handle(schema.additionalProperties).map((l) => ` ${l}`),\n );\n }\n }\n\n return lines;\n }\n\n /**\n * Format a property with its type and description\n */\n #property(\n name: string,\n schema: SchemaObject | ReferenceObject,\n required: boolean,\n ): string[] {\n // get full docs and extract the type line\n const docs = this.handle(schema);\n const rawType = docs[0]\n .replace('**Type:** ', '')\n .replace(' (nullable)', '|null');\n\n // detect default if present on the schema\n const defaultVal =\n !isRef(schema) && schema.default !== undefined\n ? ` default: ${JSON.stringify(schema.default)}`\n : '';\n\n // build summary line\n const reqMark = required ? ' required' : '';\n const summary = `- \\`${name}\\` ${rawType}${reqMark}${defaultVal}:`;\n\n // assemble final lines (skip the type and any default in details)\n const detailLines = docs\n .slice(1)\n .filter((it) => !it.startsWith('**Default:**'))\n .map((it) => ` ${it}`);\n\n return [summary, ...detailLines];\n }\n\n /**\n * Handle array schemas\n */\n #array(schema: SchemaObject): string[] {\n const lines: string[] = [];\n lines.push(`**Array items:**`);\n\n if (schema.items) {\n // Get documentation for the items schema\n const itemDocs = this.handle(schema.items);\n // Indent item documentation\n lines.push(...itemDocs.map((line) => ` ${line}`));\n } else {\n lines.push(` **Type:** \\`unknown\\``); // Array of unknown items\n }\n // Add array constraints\n if (schema.minItems !== undefined)\n lines.push(`- Minimum items: ${schema.minItems}`);\n if (schema.maxItems !== undefined)\n lines.push(`- Maximum items: ${schema.maxItems}`);\n if (schema.uniqueItems) lines.push(`- Items must be unique.`);\n\n return lines;\n }\n\n #ref($ref: string): string[] {\n const schemaName = $ref.split('/').pop() || 'object';\n const resolved = followRef<SchemaObject>(this.#spec, $ref);\n // Link to the schema definition (assuming heading anchors are generated elsewhere)\n const lines = [\n `**Type:** [\\`${schemaName}\\`](#${schemaName.toLowerCase()})`,\n ];\n if (resolved.description) {\n lines.push(resolved.description);\n }\n // Avoid deep recursion by default, just link and show description.\n // If more detail is needed, the linked definition should provide it.\n return lines;\n }\n\n #allOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**All of (Intersection):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Constraint ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`)); // Indent sub-schema docs\n });\n return lines;\n }\n\n #anyOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**Any of (Union):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Option ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`));\n });\n return lines;\n }\n\n #oneOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**One of (Exclusive Union):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Option ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`));\n });\n return lines;\n }\n\n #enum(schema: SchemaObject): string[] {\n const lines = [`**Type:** \\`${schema.type || 'unknown'}\\` (enum)`];\n if (schema.description) lines.push(schema.description);\n lines.push('**Allowed values:**');\n lines.push(\n ...(schema.enum || []).map((val) => `- \\`${JSON.stringify(val)}\\``),\n );\n if (schema.default !== undefined) {\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n }\n return lines;\n }\n\n #normal(type: string, schema: SchemaObject, nullable: boolean): string[] {\n const lines: string[] = [];\n const nullableSuffix = nullable ? ' (nullable)' : '';\n const description = schema.description ? [schema.description] : [];\n\n switch (type) {\n case 'string':\n lines.push(\n `**Type:** \\`string\\`${schema.format ? ` (format: ${schema.format})` : ''}${nullableSuffix}`,\n );\n lines.push(...description);\n if (schema.minLength !== undefined)\n lines.push(`- Minimum length: ${schema.minLength}`);\n if (schema.maxLength !== undefined)\n lines.push(`- Maximum length: ${schema.maxLength}`);\n if (schema.pattern !== undefined)\n lines.push(`- Pattern: \\`${schema.pattern}\\``);\n break;\n case 'number':\n case 'integer':\n lines.push(\n `**Type:** \\`${type}\\`${schema.format ? ` (format: ${schema.format})` : ''}${nullableSuffix}`,\n );\n lines.push(...description);\n // Add number constraints (OpenAPI 3.1)\n if (schema.minimum !== undefined) {\n // Check if exclusiveMinimum is a number (OAS 3.1)\n const exclusiveMin = typeof schema.exclusiveMinimum === 'number';\n lines.push(\n `- Minimum: ${schema.minimum}${exclusiveMin ? ' (exclusive)' : ''}`,\n );\n if (exclusiveMin) {\n lines.push(\n `- Must be strictly greater than: ${schema.exclusiveMinimum}`,\n );\n }\n } else if (typeof schema.exclusiveMinimum === 'number') {\n lines.push(\n `- Must be strictly greater than: ${schema.exclusiveMinimum}`,\n );\n }\n\n if (schema.maximum !== undefined) {\n // Check if exclusiveMaximum is a number (OAS 3.1)\n const exclusiveMax = typeof schema.exclusiveMaximum === 'number';\n lines.push(\n `- Maximum: ${schema.maximum}${exclusiveMax ? ' (exclusive)' : ''}`,\n );\n if (exclusiveMax) {\n lines.push(\n `- Must be strictly less than: ${schema.exclusiveMaximum}`,\n );\n }\n } else if (typeof schema.exclusiveMaximum === 'number') {\n lines.push(\n `- Must be strictly less than: ${schema.exclusiveMaximum}`,\n );\n }\n if (schema.multipleOf !== undefined)\n lines.push(`- Must be a multiple of: ${schema.multipleOf}`);\n break;\n case 'boolean':\n lines.push(`**Type:** \\`boolean\\`${nullableSuffix}`);\n lines.push(...description);\n break;\n case 'object':\n lines.push(`**Type:** \\`object\\`${nullableSuffix}`);\n lines.push(...description);\n lines.push(...this.#object(schema));\n break;\n case 'array':\n lines.push(`**Type:** \\`array\\`${nullableSuffix}`);\n lines.push(...description);\n lines.push(...this.#array(schema));\n break;\n case 'null':\n lines.push(`**Type:** \\`null\\``);\n lines.push(...description);\n break;\n default:\n lines.push(`**Type:** \\`${type}\\`${nullableSuffix}`);\n lines.push(...description);\n }\n if (schema.default !== undefined) {\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n }\n return lines.filter((l) => l); // Filter out empty description lines\n }\n\n /**\n * Handle schemas by resolving references and delegating to appropriate handler\n */\n public handle(schemaOrRef: SchemaObject | ReferenceObject): string[] {\n if (isRef(schemaOrRef)) {\n return this.#ref(schemaOrRef.$ref);\n }\n\n const schema = schemaOrRef;\n\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.#allOf(schema.allOf);\n }\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.#anyOf(schema.anyOf);\n }\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.#oneOf(schema.oneOf);\n }\n\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.#enum(schema);\n }\n\n let types = coerceTypes(schema);\n let nullable = false; // Default to false\n\n if (types.includes('null')) {\n nullable = true;\n types = types.filter((t) => t !== 'null');\n }\n\n if (types.length === 0) {\n if (schema.properties || schema.additionalProperties) {\n types = ['object'];\n } else if (schema.items) {\n types = ['array'];\n }\n }\n\n if (types.length === 0) {\n const lines = ['**Type:** `unknown`'];\n if (schema.description) lines.push(schema.description);\n if (schema.default !== undefined)\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n return lines;\n }\n\n // Handle single type (potentially nullable)\n if (types.length === 1) {\n return this.#normal(types[0], schema, nullable);\n }\n\n // Handle union of multiple non-null types (potentially nullable overall)\n const typeString = types.join(' | ');\n const nullableSuffix = nullable ? ' (nullable)' : '';\n const lines = [`**Type:** \\`${typeString}\\`${nullableSuffix}`];\n if (schema.description) lines.push(schema.description);\n if (schema.default !== undefined)\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n return lines;\n }\n\n /** The documentation of a request body, one block per content type. */\n requestBody(requestBody: RequestBodyObject): string[] {\n const lines: string[] = [];\n if (requestBody.description) {\n lines.push(requestBody.description);\n }\n\n const contentEntries = Object.entries(requestBody.content);\n if (contentEntries.length > 1) {\n for (const [contentType, mediaType] of contentEntries) {\n lines.push(`<details>`);\n lines.push(`<summary>Content Type: \\`${contentType}\\`</summary>`);\n lines.push('');\n if (mediaType.schema) {\n lines.push(...this.handle(mediaType.schema));\n }\n lines.push('');\n lines.push(`</details>`);\n }\n return lines;\n }\n\n const [[contentType, mediaType]] = contentEntries;\n lines.push(`Content Type: \\`${contentType}\\``);\n if (mediaType.schema) {\n lines.push(...this.handle(mediaType.schema));\n }\n return lines;\n }\n\n /** A table of the operation's path, query, header and cookie parameters. */\n parameters(parameters: readonly ParameterObject[]): string[] {\n if (parameters.length === 0) {\n return [];\n }\n return [\n [\n '| Name | In | Type | Required | Description |',\n '|------|----|------|----------|-------------|',\n ...parameters.map((parameter) =>\n [\n '',\n `\\`${parameter.name}\\``,\n parameter.in,\n parameter.schema\n ? this.handle(parameter.schema)[0].replace('**Type:** ', '')\n : '',\n parameter.required ? 'Yes' : 'No',\n (parameter.description ?? '').replaceAll('\\n', ' '),\n '',\n ]\n .map((cell) => cell.replaceAll('|', '\\\\|'))\n .join(' | ')\n .trim(),\n ),\n ].join('\\n'),\n ];\n }\n}\n", "import type { ServerObject } from 'openapi3-ts/oas31';\n\nexport function expandServerUrls(servers: ServerObject[]): string[] {\n return servers.flatMap((server) => {\n const variables = server.variables;\n if (!variables || Object.keys(variables).length === 0) {\n return [server.url];\n }\n\n const entries = Object.entries(variables);\n const valueSets = entries.map(([, variable]) => {\n const enumValues = variable.enum?.map(String);\n return enumValues?.length ? enumValues : [String(variable.default)];\n });\n\n const combinations = valueSets.reduce<string[][]>(\n (acc, values) => acc.flatMap((combo) => values.map((v) => [...combo, v])),\n [[]],\n );\n\n return combinations.map((combo) => {\n let url = server.url;\n for (let i = 0; i < entries.length; i++) {\n url = url.replaceAll(`{${entries[i][0]}}`, combo[i]);\n }\n return url;\n });\n });\n}\n", "import type { SchemaObject } from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nimport {\n type OpenAPISecuritySchemeObject,\n isEmpty,\n pascalcase,\n resolveRef,\n} from '@sdk-it/core';\nimport { type Generator } from '@sdk-it/readme';\nimport {\n type IR,\n type OperationEntry,\n type OperationPagination,\n type TunedOperationObject,\n forEachOperation,\n operationInputs,\n} from '@sdk-it/spec';\n\nimport { SnippetEmitter } from './emitters/snippet.ts';\nimport type { TypeScriptGeneratorOptions } from './options.ts';\nimport { expandServerUrls } from './server-urls.ts';\n\nexport class TypeScriptSnippet implements Generator {\n #spec: IR;\n #snippetEmitter: SnippetEmitter;\n #clientName: string;\n #packageName: string;\n constructor(spec: IR, settings: TypeScriptGeneratorOptions) {\n this.#spec = spec;\n this.#snippetEmitter = new SnippetEmitter(spec);\n this.#clientName = pascalcase(settings.name.trim());\n this.#packageName = settings.packageName;\n }\n succinct(entry: OperationEntry, operation: TunedOperationObject) {\n const payload = this.#render(this.#example(operation));\n\n const success = Object.entries(operation.responses).find(([status]) =>\n status.startsWith('2'),\n )?.[1];\n if (success?.['x-body'] === 'stream') {\n return this.#stream(entry, payload);\n }\n if (operation['x-pagination']) {\n return this.#pagination(entry, payload);\n }\n return this.#normal(entry, payload);\n }\n\n /** An input the operation's preferred input schema accepts: its required fields, and the fields that declare an example or a default. */\n #example(operation: TunedOperationObject) {\n const [preferred] = operationInputs(this.#spec, operation);\n return this.#snippetEmitter.handle(preferred.schema);\n }\n\n /**\n * The operation's example input with its first required field set to a value\n * of a type the field does not accept, so the client refuses it with a\n * `ParseError`; undefined when no such value exists.\n */\n #invalidInput(operation: TunedOperationObject) {\n const [preferred] = operationInputs(this.#spec, operation);\n const [field] = preferred.schema.required ?? [];\n const property =\n field === undefined ? undefined : preferred.schema.properties?.[field];\n const example = this.#example(operation);\n if (property === undefined || !isRecord(example)) {\n return undefined;\n }\n const value = wrongTypeValue(\n resolveRef<SchemaObject>(this.#spec, property),\n );\n if (value === undefined) {\n return undefined;\n }\n const key = JSON.stringify(field);\n return this.#render({ ...example, [field]: value })\n .split('\\n')\n .flatMap((line) =>\n line.startsWith(` ${key}:`)\n ? [\n ` // @ts-expect-error ${key} does not accept ${JSON.stringify(value)}`,\n line,\n ]\n : [line],\n )\n .join('\\n');\n }\n\n #render(example: unknown) {\n return JSON.stringify(\n example,\n (key, value) => {\n if (value?.startsWith && value.startsWith('new')) {\n return `__REPLACE_${Math.random().toString(36).substring(2, 11)}__${value}__REPLACE_END__`;\n }\n return value;\n },\n 2,\n ).replace(/\"__REPLACE_[^\"]*__([^\"]*?)__REPLACE_END__\"/g, '$1');\n }\n\n #pagination(entry: OperationEntry, payload: string) {\n return {\n content: `const controller = new AbortController();\\nconst result = await ${camelcase(this.#clientName)}.request('${endpointOf(entry)}', ${payload}, { signal: controller.signal });`,\n footer: `for await (const page of result.iterPages({ signal: controller.signal })) {\\n\\t\\tconsole.log(page);\\n}`,\n };\n }\n\n #normal(entry: OperationEntry, payload: string) {\n return {\n content: `const result = ${this.#toRequest(entry, payload)}`,\n footer: 'console.log(result);',\n };\n }\n\n #stream(entry: OperationEntry, payload: string) {\n return {\n content: `const stream = ${this.#toRequest(entry, payload)}`,\n footer: `for await (const chunk of stream) {\\n\\t\\tconsole.log(chunk);\\n}`,\n };\n }\n\n #toRequest(entry: OperationEntry, payload: string) {\n return `await ${camelcase(this.#clientName)}.request('${endpointOf(entry)}', ${payload});`;\n }\n\n snippet(\n entry: OperationEntry,\n operation: TunedOperationObject,\n config: { frame?: boolean } = {},\n ) {\n const payload = this.succinct(entry, operation);\n const content: string[] = [\n this.client(),\n '',\n payload.content,\n '',\n payload.footer,\n ];\n if (config.frame !== false) {\n return createCodeBlock('typescript', content);\n }\n return content.join('\\n');\n }\n\n #authentication() {\n const names = new Set<string>();\n for (const requirement of this.#spec.security ?? []) {\n for (const name of Object.keys(requirement)) names.add(name);\n }\n forEachOperation(this.#spec, (_entry, operation) => {\n for (const requirement of operation.security ?? []) {\n for (const name of Object.keys(requirement)) names.add(name);\n }\n });\n return [...names].flatMap((name) => {\n // Requirement names may be external URI references with no local scheme.\n const scheme = this.#spec.components.securitySchemes[name];\n return scheme\n ? [\n {\n name,\n scheme: resolveRef<OpenAPISecuritySchemeObject>(\n this.#spec,\n scheme,\n ),\n },\n ]\n : [];\n });\n }\n\n #credentialExample(\n scheme: OpenAPISecuritySchemeObject,\n ): string | boolean | { username: string; password: string } {\n if (scheme.type === 'mutualTLS') return true;\n if (scheme.type === 'http' && scheme.scheme?.toLowerCase() === 'basic') {\n return { username: 'user', password: 'password' };\n }\n if (scheme.type === 'apiKey') return 'test_api_key_1234567890abcdef';\n return 'test_access_token_1234567890abcdef';\n }\n\n client() {\n const client = this.#clientSetup();\n return client.use ? `${client.import}\\n\\n${client.use}` : client.import;\n }\n\n /** The client setup with `names` imported beside the client. */\n #clientWith(names: string[]) {\n const client = this.#clientSetup();\n return [\n `import { ${[client.name, ...names].join(', ')} } from '${this.#packageName}';`,\n ...(client.use ? ['', client.use] : []),\n ];\n }\n\n #clientSetup() {\n const servers = expandServerUrls(this.#spec.servers ?? []);\n const options: Record<string, unknown> = {};\n if (servers.length !== 1) {\n options.baseUrl = servers[0] ?? 'http://localhost:3000';\n }\n\n const authOptions = this.#authentication();\n if (!isEmpty(authOptions)) {\n const [firstAuth] = authOptions;\n options.credentials = {\n [firstAuth.name]: this.#credentialExample(firstAuth.scheme),\n };\n }\n\n return this.#constructClient(options);\n }\n\n /** The default instance when the README needs no settings, else a client created with them. */\n #constructClient(options: Record<string, unknown>) {\n const instance = camelcase(this.#clientName);\n if (isEmpty(options)) {\n return {\n name: instance,\n import: `import { ${instance} } from '${this.#packageName}';`,\n use: '',\n };\n }\n return {\n name: `create${this.#clientName}`,\n import: `import { create${this.#clientName} } from '${this.#packageName}';`,\n use: `const ${instance} = create${this.#clientName}({\\n\\t\\t${Object.entries(\n options,\n )\n .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)\n .join(',\\n\\t\\t')}\\n\\t});`,\n };\n }\n\n clientInstallDocs(): string {\n const sections: string[] = [];\n\n sections.push('## Installation');\n sections.push('');\n sections.push(\n createCodeBlock('bash', [`npm install ${this.#packageName}`]),\n );\n sections.push('');\n\n sections.push('## Basic Usage');\n sections.push('');\n sections.push(createCodeBlock('typescript', [this.client()]));\n\n return sections.join('\\n');\n }\n\n configurationOptions(): {\n sections: string[];\n hasServers: boolean;\n baseUrl: string;\n hasApiKey: boolean;\n } {\n const sections: string[] = [];\n const hasServers = Boolean(\n this.#spec.servers && this.#spec.servers.length > 0,\n );\n const baseUrl =\n expandServerUrls(this.#spec.servers ?? [])[0] ||\n 'https://api.example.com';\n\n const authOptions = this.#authentication();\n const hasApiKey = !isEmpty(authOptions);\n\n sections.push('### Configuration Options');\n sections.push('');\n sections.push('| Option | Type | Required | Description |');\n sections.push('|--------|------|----------|-------------|');\n sections.push(\n '| `fetch` | `fetch compatible` | No | Fetch implementation to use for HTTP requests |',\n );\n\n if (hasServers) {\n sections.push(\n '| `baseUrl` | `string | (() => string | Promise<string>)` | No | API base URL (default: `' +\n baseUrl +\n '`) |',\n );\n }\n\n if (hasApiKey) {\n sections.push(\n '| `credentials` | `Record<string, SecurityCredential>` | No | Credentials keyed by the exact OpenAPI security scheme name |',\n );\n }\n\n return { sections, hasServers, baseUrl, hasApiKey };\n }\n\n clientSetupDocs(): string {\n const sections: string[] = [];\n\n // Use the dedicated install docs method\n sections.push(this.clientInstallDocs());\n sections.push('');\n\n // Use the configuration options method\n const config = this.configurationOptions();\n sections.push(...config.sections);\n sections.push('');\n\n // Add configuration update documentation\n sections.push(this.configurationUpdateDocs());\n\n return sections.join('\\n');\n }\n\n paginationDocs(): string {\n const paginated = this.#paginatedOperations();\n const [first] = paginated;\n if (!first) {\n return '';\n }\n const { entry, operation } = first;\n const payload = this.#render(this.#example(operation));\n const request = this.#pagination(entry, payload);\n const sections = [\n '## Pagination',\n '',\n 'A paginated endpoint resolves to a page: the response body, plus `hasNextPage()`, `getNextPage()` and `iterPages()`. `for await` over the request or the page yields every item across pages:',\n '',\n createCodeBlock('typescript', [\n this.client(),\n '',\n request.content,\n 'console.log(result); // the response body of the first page',\n '',\n 'if (result.hasNextPage()) {',\n ' const next = await result.getNextPage({ signal: controller.signal });',\n ' console.log(next);',\n '}',\n '',\n '// Or iterate through every page, each fetch cancellable',\n request.footer,\n ]),\n '',\n '### Iterating Through All Items',\n '',\n createCodeBlock('typescript', [\n this.client(),\n '',\n `for await (const item of ${camelcase(this.#clientName)}.request('${endpointOf(entry)}', ${payload})) {`,\n ' console.log(item);',\n '}',\n ]),\n '',\n '### Pagination Strategies',\n '',\n ...paginated.map(\n ({ entry, pagination }) =>\n `- \\`${endpointOf(entry)}\\`: ${paginationStrategy(pagination)}`,\n ),\n ];\n return sections.join('\\n');\n }\n\n /** The first paginated operation of each pagination type, in README order. */\n #paginatedOperations() {\n const paginated = new Map<\n OperationPagination['type'],\n {\n entry: OperationEntry;\n operation: TunedOperationObject;\n pagination: OperationPagination;\n }\n >();\n forEachOperation(this.#spec, (entry, operation) => {\n const pagination = operation['x-pagination'];\n if (pagination && !paginated.has(pagination.type)) {\n paginated.set(pagination.type, { entry, operation, pagination });\n }\n });\n return [...paginated.values()];\n }\n\n /** The operation the README lists first. */\n #firstOperation() {\n let first:\n { entry: OperationEntry; operation: TunedOperationObject } | undefined;\n forEachOperation(this.#spec, (entry, operation) => {\n first ??= { entry, operation };\n });\n return first;\n }\n\n errorHandlingDocs(): string {\n const sections: string[] = [];\n const first = this.#firstOperation();\n\n sections.push('## Error Handling');\n sections.push('');\n sections.push(\n 'The SDK provides structured error handling with typed HTTP error responses.',\n );\n sections.push('');\n\n if (first) {\n const { entry, operation } = first;\n const payload = this.#render(this.#example(operation));\n sections.push('### Error Response Types');\n sections.push('');\n sections.push(\n 'All API errors extend from `APIError` and include the HTTP status code, the response headers and the response body:',\n );\n sections.push('');\n sections.push(\n createCodeBlock('typescript', [\n ...this.#clientWith([\n 'BadRequest',\n 'Unauthorized',\n 'NotFound',\n 'TooManyRequests',\n 'InternalServerError',\n 'ParseError',\n ]),\n '',\n 'try {',\n ` const result = ${this.#toRequest(entry, payload)}`,\n ' console.log(result);',\n '} catch (error) {',\n ' if (error instanceof BadRequest) {',\n ' console.error(\"Bad request:\", error.data);',\n ' console.log(\"Status:\", error.status); // 400',\n ' } else if (error instanceof Unauthorized) {',\n ' console.error(\"Authentication failed:\", error.data);',\n ' console.log(\"Status:\", error.status); // 401',\n ' } else if (error instanceof NotFound) {',\n ' console.error(\"Resource not found:\", error.data);',\n ' console.log(\"Status:\", error.status); // 404',\n ' } else if (error instanceof TooManyRequests) {',\n ' console.error(\"Rate limited:\", error.data);',\n ' console.log(\"Retry after:\", error.headers.get(\\'Retry-After\\'));',\n ' } else if (error instanceof InternalServerError) {',\n ' console.error(\"Server error:\", error.data);',\n ' console.log(\"Status:\", error.status); // 500',\n ' } else if (error instanceof ParseError) {',\n ' console.error(\"Input validation failed:\", error.data);',\n ' }',\n '}',\n ]),\n );\n sections.push('');\n }\n\n sections.push('### Available Error Classes');\n sections.push('');\n sections.push('#### Input Validation Errors');\n sections.push(\n '- `ParseError` - Request input validation failed against API schema',\n );\n sections.push('');\n sections.push('#### Client Errors (4xx)');\n sections.push('- `BadRequest` (400) - Invalid request data');\n sections.push('- `Unauthorized` (401) - Authentication required');\n sections.push('- `PaymentRequired` (402) - Payment required');\n sections.push('- `Forbidden` (403) - Access denied');\n sections.push('- `NotFound` (404) - Resource not found');\n sections.push('- `MethodNotAllowed` (405) - HTTP method not allowed');\n sections.push('- `NotAcceptable` (406) - Content type not acceptable');\n sections.push('- `Conflict` (409) - Resource conflict');\n sections.push('- `Gone` (410) - Resource no longer available');\n sections.push('- `PreconditionFailed` (412) - Precondition failed');\n sections.push('- `PayloadTooLarge` (413) - Request payload too large');\n sections.push('- `UnsupportedMediaType` (415) - Unsupported content type');\n sections.push('- `UnprocessableEntity` (422) - Validation errors');\n sections.push('- `TooManyRequests` (429) - Rate limit exceeded');\n sections.push('');\n\n sections.push('#### Server Errors (5xx)');\n sections.push('- `InternalServerError` (500) - Server error');\n sections.push('- `NotImplemented` (501) - Not implemented');\n sections.push('- `BadGateway` (502) - Bad gateway');\n sections.push('- `ServiceUnavailable` (503) - Service unavailable');\n sections.push('- `GatewayTimeout` (504) - Gateway timeout');\n\n if (!first) {\n return sections.join('\\n');\n }\n const { entry, operation } = first;\n\n const invalidInput = this.#invalidInput(operation);\n if (invalidInput !== undefined) {\n sections.push('');\n sections.push('### Input Validation Errors');\n sections.push('');\n sections.push(\n 'When request input fails validation against the API schema, a `ParseError` is thrown before the request is sent:',\n );\n sections.push('');\n sections.push(\n createCodeBlock('typescript', [\n ...this.#clientWith(['ParseError']),\n '',\n 'try {',\n ` const result = ${this.#toRequest(entry, invalidInput)}`,\n ' console.log(result);',\n '} catch (error) {',\n ' if (error instanceof ParseError) {',\n ' for (const [fieldName, issues] of Object.entries(error.data.fieldErrors)) {',\n \" console.log(`${fieldName}: ${(issues ?? []).map((issue) => issue.message).join(', ')}`);\",\n ' }',\n ' if (error.data.formErrors.length > 0) {',\n \" console.log(`Form errors: ${error.data.formErrors.map((issue) => issue.message).join(', ')}`);\",\n ' }',\n ' }',\n '}',\n ]),\n );\n sections.push('');\n sections.push(\n \"`ParseError` contains detailed validation information using Zod's flattened error format, providing specific field-level and form-level validation messages.\",\n );\n }\n\n sections.push('');\n sections.push('### Rate Limiting');\n sections.push('');\n sections.push(\n 'A `TooManyRequests` error carries the response headers, so a `Retry-After` header tells when to retry:',\n );\n sections.push('');\n sections.push(\n createCodeBlock('typescript', [\n ...this.#clientWith(['TooManyRequests']),\n '',\n 'try {',\n ` const result = ${this.#toRequest(entry, this.#render(this.#example(operation)))}`,\n ' console.log(result);',\n '} catch (error) {',\n ' if (error instanceof TooManyRequests) {',\n \" console.log(`Rate limited. Retry after: ${error.headers.get('Retry-After')}`);\",\n ' }',\n '}',\n ]),\n );\n\n return sections.join('\\n');\n }\n\n authenticationDocs(): string {\n const authOptions = this.#authentication();\n\n if (isEmpty(authOptions)) {\n return '';\n }\n\n const only = authOptions.length === 1;\n const sections: string[] = [\n '## Authentication',\n '',\n only\n ? 'The SDK requires authentication to access the API. Configure your client with the required credentials:'\n : 'The SDK supports the following authentication methods:',\n '',\n ];\n\n for (const { name, scheme } of authOptions) {\n sections.push(`### ${authenticationHeading(name, scheme, only)}`);\n sections.push('');\n if (isBearer(scheme)) {\n sections.push(\n 'Pass your bearer token directly - the \"Bearer\" prefix is automatically added:',\n );\n sections.push('');\n }\n const client = this.#constructClient({\n credentials: { [name]: this.#credentialExample(scheme) },\n });\n sections.push(\n createCodeBlock('typescript', [client.import, '', client.use]),\n );\n sections.push('');\n }\n\n return sections.join('\\n');\n }\n\n generalUsageDocs(): string {\n const sections: string[] = [];\n\n return sections.join('\\n');\n }\n\n configurationUpdateDocs(): string {\n const sections: string[] = [];\n const authOptions = this.#authentication();\n\n sections.push('### Updating Configuration');\n sections.push('');\n sections.push(\n 'You can update client configuration after initialization using the `setOptions` method:',\n );\n sections.push('');\n\n const initialClientOptions: Record<string, unknown> = {\n baseUrl: 'https://api.production-service.com',\n };\n\n if (!isEmpty(authOptions)) {\n const [primaryAuth] = authOptions;\n initialClientOptions.credentials = {\n [primaryAuth.name]: this.#credentialExample(primaryAuth.scheme),\n };\n }\n\n const initialClientSetup = this.#constructClient(initialClientOptions);\n\n const configurationUpdateCode = [\n initialClientSetup.import,\n '',\n '// Initial client setup',\n initialClientSetup.use,\n '',\n '// Later, update specific options',\n `${camelcase(this.#clientName)}.setOptions({`,\n \" baseUrl: 'https://api.staging-service.com',\",\n ];\n\n if (!isEmpty(authOptions)) {\n const [primaryAuth] = authOptions;\n configurationUpdateCode.push(\n ` credentials: ${JSON.stringify({\n [primaryAuth.name]: this.#credentialExample(primaryAuth.scheme),\n })}`,\n );\n }\n\n configurationUpdateCode.push('});');\n\n sections.push(createCodeBlock('typescript', configurationUpdateCode));\n sections.push('');\n sections.push(\n 'The `setOptions` method validates the provided options and only updates the specified fields, leaving other configuration unchanged.',\n );\n\n return sections.join('\\n');\n }\n}\n\nfunction isBearer(scheme: OpenAPISecuritySchemeObject) {\n return scheme.type === 'http' && scheme.scheme?.toLowerCase() === 'bearer';\n}\n\nfunction authenticationHeading(\n name: string,\n scheme: OpenAPISecuritySchemeObject,\n only: boolean,\n) {\n if (isBearer(scheme)) {\n return only ? 'Bearer Token' : 'Bearer Token Authentication';\n }\n if (scheme.type === 'apiKey' && scheme.in === 'header') {\n return only ? 'API Key (Header)' : 'API Key Authentication (Header)';\n }\n if (scheme.type === 'apiKey' && scheme.in === 'query') {\n return only\n ? 'API Key (Query Parameter)'\n : 'API Key Authentication (Query Parameter)';\n }\n return only ? name : `${name} Authentication`;\n}\n\nfunction createCodeBlock(language: string, content: string[]) {\n return ['```' + language, ...content, '```'].join('\\n');\n}\n\nfunction endpointOf(entry: OperationEntry) {\n return `${entry.method.toUpperCase()} ${entry.path}`;\n}\n\nfunction paginationStrategy(pagination: OperationPagination) {\n switch (pagination.type) {\n case 'offset':\n return `offset pagination, with the \\`${pagination.offsetParamName}\\` and \\`${pagination.limitParamName}\\` parameters.`;\n case 'page':\n return `page pagination, with the \\`${pagination.pageNumberParamName}\\` and \\`${pagination.pageSizeParamName}\\` parameters.`;\n case 'cursor':\n return `cursor pagination, with the \\`${pagination.cursorParamName}\\` and \\`${pagination.limitParamName}\\` parameters.`;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** A value whose type `schema` does not accept; undefined when it accepts every candidate or names no type. */\nfunction wrongTypeValue(schema: SchemaObject) {\n const types: string[] = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n if (\n types.length === 0 ||\n schema.format === 'binary' ||\n schema.format === 'byte' ||\n schema.contentEncoding === 'binary'\n ) {\n return undefined;\n }\n const candidates = [\n { value: 123, types: ['number', 'integer'] },\n { value: 'text', types: ['string'] },\n { value: true, types: ['boolean'] },\n ];\n return candidates.find((candidate) =>\n candidate.types.every((type) => !types.includes(type)),\n )?.value;\n}\n", "import type { ReferenceObject, SchemaObject } from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, resolveRef } from '@sdk-it/core';\nimport type { IR } from '@sdk-it/spec';\n\n/**\n * Generate example values for OpenAPI schemas\n * This emitter creates sample input payloads for API documentation and code snippets\n */\nexport class SnippetEmitter {\n private spec: IR;\n public generatedRefs = new Set<string>();\n private cache = new Map<string, unknown>();\n\n constructor(spec: IR) {\n this.spec = spec;\n }\n\n public object(\n schema: SchemaObject | ReferenceObject,\n ): Record<string, unknown> {\n const schemaObj = resolveRef(this.spec, schema);\n const result: Record<string, unknown> = {};\n const properties = schemaObj.properties || {};\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const isRequired = (schemaObj.required ?? []).includes(propName);\n const resolvedProp = resolveRef(this.spec, propSchema);\n\n if (\n isRequired ||\n resolvedProp.example !== undefined ||\n resolvedProp.default !== undefined\n ) {\n result[propName] = this.handle(propSchema);\n }\n }\n\n if (\n schemaObj.additionalProperties &&\n typeof schemaObj.additionalProperties === 'object'\n ) {\n result['additionalPropExample'] = this.handle(\n schemaObj.additionalProperties,\n );\n }\n\n return result;\n }\n\n public array(schema: SchemaObject | ReferenceObject): unknown[] {\n const schemaObj = resolveRef(this.spec, schema);\n const itemsSchema = schemaObj.items;\n if (!itemsSchema) {\n return [];\n }\n\n const count = Math.min(schemaObj.minItems ?? 1, 2);\n const result: unknown[] = [];\n\n for (let i = 0; i < count; i++) {\n result.push(this.handle(itemsSchema));\n }\n\n return result;\n }\n\n public string(schema: SchemaObject): string {\n if (schema.example !== undefined) return String(schema.example);\n if (schema.default !== undefined) return String(schema.default);\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n return `2025-07-17T09:08:00.097Z`;\n case 'date':\n return `2025-07-17`;\n case 'time':\n return `09:08:00.097Z`;\n case 'email':\n return 'user@example.com';\n case 'uuid':\n return '123e4567-e89b-12d3-a456-426614174000';\n case 'uri':\n case 'url':\n return 'https://example.com';\n case 'ipv4':\n return '192.168.1.1';\n case 'ipv6':\n return '2001:0db8:85a3:0000:0000:8a2e:0370:7334';\n case 'hostname':\n return 'example.com';\n case 'binary':\n case 'byte':\n return `new Blob(['example'], { type: 'text/plain' })`;\n default:\n if (schema.enum && schema.enum.length > 0) {\n return String(schema.enum[0]);\n }\n return schema.pattern ? `string matching ${schema.pattern}` : 'example';\n }\n }\n\n public number(schema: SchemaObject): number {\n if (schema.example !== undefined) return Number(schema.example);\n if (schema.default !== undefined) return Number(schema.default);\n\n let value: number;\n if (typeof schema.exclusiveMinimum === 'number') {\n value = schema.exclusiveMinimum + 1;\n } else if (typeof schema.minimum === 'number') {\n value = schema.minimum;\n } else {\n value = schema.type === 'integer' ? 42 : 42.42;\n }\n\n if (\n typeof schema.exclusiveMaximum === 'number' &&\n value >= schema.exclusiveMaximum\n ) {\n value = schema.exclusiveMaximum - 1;\n } else if (typeof schema.maximum === 'number' && value > schema.maximum) {\n value = schema.maximum;\n }\n\n if (\n typeof schema.multipleOf === 'number' &&\n value % schema.multipleOf !== 0\n ) {\n value = Math.floor(value / schema.multipleOf) * schema.multipleOf;\n }\n\n return schema.type === 'integer' ? Math.floor(value) : value;\n }\n\n public boolean(schema: SchemaObject): boolean {\n if (schema.example !== undefined) return Boolean(schema.example);\n if (schema.default !== undefined) return Boolean(schema.default);\n return true;\n }\n\n public null(): null {\n return null;\n }\n\n public ref($ref: string): unknown {\n const parts = $ref.split('/');\n const refKey = parts.at(-1) || '';\n\n if (this.cache.has($ref)) {\n return this.cache.get($ref);\n }\n\n this.cache.set($ref, { _ref: refKey });\n\n const resolved = followRef<SchemaObject>(this.spec, $ref);\n const result = this.handle(resolved);\n\n this.cache.set($ref, result);\n return result;\n }\n\n public allOf(schemas: (SchemaObject | ReferenceObject)[]): unknown {\n const initial: Record<string, unknown> = {};\n return schemas.reduce<Record<string, unknown>>((result, schema) => {\n const example = this.handle(schema);\n if (typeof example === 'object' && example !== null) {\n return { ...result, ...example };\n }\n return result;\n }, initial);\n }\n\n public anyOf(schemas: (SchemaObject | ReferenceObject)[]): unknown {\n if (schemas.length === 0) return {};\n return this.handle(schemas[0]);\n }\n\n public oneOf(schemas: (SchemaObject | ReferenceObject)[]): unknown {\n if (schemas.length === 0) return {};\n return this.handle(schemas[0]);\n }\n\n public enum(schema: SchemaObject): unknown {\n return Array.isArray(schema.enum) && schema.enum.length > 0\n ? schema.enum[0]\n : undefined;\n }\n\n public handle(schemaOrRef: SchemaObject | ReferenceObject): unknown {\n if (isRef(schemaOrRef)) {\n return this.ref(schemaOrRef.$ref);\n }\n\n const schema = resolveRef(this.spec, schemaOrRef);\n\n if (schema.example !== undefined) {\n return schema.example;\n }\n\n if (schema.default !== undefined) {\n return schema.default;\n }\n\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf);\n }\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf);\n }\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf);\n }\n\n if (schema.enum && Array.isArray(schema.enum) && schema.enum.length > 0) {\n return this.enum(schema);\n }\n\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n if (types.length === 0) {\n if (schema.properties || schema.additionalProperties) {\n return this.object(schema);\n } else if (schema.items) {\n return this.array(schema);\n }\n return 'example';\n }\n\n const primaryType = types.find((t) => t !== 'null') || types[0];\n\n switch (primaryType) {\n case 'string':\n return this.string(schema);\n case 'number':\n case 'integer':\n return this.number(schema);\n case 'boolean':\n return this.boolean(schema);\n case 'object':\n return this.object(schema);\n case 'array':\n return this.array(schema);\n case 'null':\n return this.null();\n default:\n return 'unknown';\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,aAAAA,kBAAiB;AAE1B,SAAS,kBAAkB;;;ACF3B,SAAS,aAAAC,kBAAiB;;;ACA1B,SAAS,iBAAiB;AAE1B,SAAS,mBAAmB;AAOrB,SAAS,gBAAgB,OAAe;AAC7C,SAAO,YAAY,UAAU,KAAK,CAAC;AACrC;;;AC4CO,SAAS,eACd,gBACY;AACZ,SAAO;AAAA,IACL,OAAO,CAAC,aAAa,GAAG,cAAc,IAAI,QAAQ;AAAA,IAClD,OAAO,CAAC,OAAO,eAAe,GAAG,gBAAgB,KAAK,CAAC,IAAI,UAAU;AAAA,IACrE,QAA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AAO;AAAA,UACL,YAAY,SAAS,cAAc,WAAW,eAAe,SAAS,CAAC,CAAC;AAAA,QAC1E;AAAA,MACF;AAAA,IACF;AACA,WAAO,KAAK,OAAO;AACnB,WAAO;AAAA,MACL,CAAC,kBAAkB,eAAe,IAAI,CAAC,OAAO,OAAO,KAAK,IAAI,CAAC;AAAA,MAC/D,GAAG;AAAA,IACL;AAAA,EACF,GAAG,CAAC,CAAC;AAEP,SAAO;AAAA,IACL,GAAG,OAAO,YAAY,OAAO;AAAA,IAC7B,GAAG;AAAA,EACL;AACF;",
|
|
6
|
+
"names": ["camelcase", "camelcase", "camelcase", "camelcase", "join", "isRef", "parseRef", "forEachOperation", "inputName", "camelcase", "inputName", "carriesBinary", "forEachOperation", "inputEndpoint", "inputName", "operationInputs", "forEachOperation", "createTools", "tools", "operationInputs", "carriesBinary", "inputName", "inputEndpoint", "forEachOperation", "inputEndpoint", "operationInputs", "followRef", "isEmpty", "isRef", "parseRef", "isInlinable", "appendOptional", "type", "forEachOperation", "operationInputs", "inputEndpoint", "pascalcase", "sanitizeTag", "clientName", "pascalcase", "sanitizeTag", "isEmpty", "forEachOperation", "operationInputs", "followRef", "isRef", "lines", "contentType", "mediaType", "forEachOperation", "operationInputs", "isEmpty", "camelcase", "isEmpty", "pascalcase", "resolveRef", "forEachOperation", "operationInputs", "followRef", "isRef", "resolveRef", "pascalcase", "operationInputs", "resolveRef", "camelcase", "forEachOperation", "isEmpty", "entry", "operation", "isRef", "forEachOperation", "parseRef", "join"]
|
|
7
7
|
}
|