@sdk-it/typescript 0.39.0 → 0.41.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/dist/index.js +169 -59
- package/dist/index.js.map +3 -3
- package/dist/lib/client.d.ts.map +1 -1
- package/dist/lib/emitters/zod.d.ts.map +1 -1
- package/dist/lib/generate.d.ts +3 -1
- package/dist/lib/generate.d.ts.map +1 -1
- package/dist/lib/generator.d.ts.map +1 -1
- package/dist/lib/options.d.ts +1 -0
- package/dist/lib/options.d.ts.map +1 -1
- package/dist/lib/sdk.d.ts +1 -1
- package/dist/lib/sdk.d.ts.map +1 -1
- package/dist/lib/server-urls.d.ts +3 -0
- package/dist/lib/server-urls.d.ts.map +1 -0
- package/dist/lib/status-map.d.ts.map +1 -1
- package/dist/lib/typescript-snippet.d.ts.map +1 -1
- package/package.json +4 -4
- package/dist/connect.d.ts +0 -1
- package/dist/connect.d.ts.map +0 -1
- package/dist/global.d.js +0 -1
- package/dist/global.d.js.map +0 -7
- package/dist/lib/connect.d.ts +0 -162
- package/dist/lib/connect.d.ts.map +0 -1
- package/dist/lib/readme-generator.d.ts +0 -8
- package/dist/lib/readme-generator.d.ts.map +0 -1
- package/dist/lib/statusMap.d.ts +0 -2
- package/dist/lib/statusMap.d.ts.map +0 -1
- package/dist/lib/utils.d.ts +0 -17
- package/dist/lib/utils.d.ts.map +0 -1
- package/dist/lib/watcher.d.ts +0 -2
- package/dist/lib/watcher.d.ts.map +0 -1
- package/dist/src/index.js +0 -5
- package/dist/src/index.js.map +0 -7
- package/dist/src/lib/agent/ai-sdk.js +0 -60
- package/dist/src/lib/agent/ai-sdk.js.map +0 -7
- package/dist/src/lib/agent/openai-agents.js +0 -42
- package/dist/src/lib/agent/openai-agents.js.map +0 -7
- package/dist/src/lib/client.js +0 -152
- package/dist/src/lib/client.js.map +0 -7
- package/dist/src/lib/emitters/interface.js +0 -169
- package/dist/src/lib/emitters/interface.js.map +0 -7
- package/dist/src/lib/emitters/snippet.js +0 -191
- package/dist/src/lib/emitters/snippet.js.map +0 -7
- package/dist/src/lib/emitters/zod.js +0 -271
- package/dist/src/lib/emitters/zod.js.map +0 -7
- package/dist/src/lib/generate.js +0 -382
- package/dist/src/lib/generate.js.map +0 -7
- package/dist/src/lib/generator.js +0 -268
- package/dist/src/lib/generator.js.map +0 -7
- package/dist/src/lib/import-utilities.js +0 -56
- package/dist/src/lib/import-utilities.js.map +0 -7
- package/dist/src/lib/options.js +0 -3
- package/dist/src/lib/options.js.map +0 -7
- package/dist/src/lib/readme/prop.emitter.js +0 -283
- package/dist/src/lib/readme/prop.emitter.js.map +0 -7
- package/dist/src/lib/readme/readme.js +0 -105
- package/dist/src/lib/readme/readme.js.map +0 -7
- package/dist/src/lib/sdk.js +0 -236
- package/dist/src/lib/sdk.js.map +0 -7
- package/dist/src/lib/status-map.js +0 -28
- package/dist/src/lib/status-map.js.map +0 -7
- package/dist/src/lib/style.js +0 -1
- package/dist/src/lib/style.js.map +0 -7
- package/dist/src/lib/typescript-snippet.js +0 -738
- package/dist/src/lib/typescript-snippet.js.map +0 -7
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/generate.ts", "../src/lib/agent/ai-sdk.ts", "../src/lib/agent/openai-agents.ts", "../src/lib/agent/utils.txt", "../src/lib/client.ts", "../src/lib/emitters/zod.ts", "../src/lib/emitters/interface.ts", "../src/lib/generator.ts", "../src/lib/sdk.ts", "../src/lib/import-utilities.ts", "../src/lib/status-map.ts", "../src/lib/styles/github/endpoints.txt", "../src/lib/http/dispatcher.txt", "../src/lib/http/interceptors.txt", "../src/lib/http/parse-response.txt", "../src/lib/http/parser.txt", "../src/lib/http/request.txt", "../src/lib/http/response.txt", "../src/lib/paginations/cursor-pagination.txt", "../src/lib/paginations/offset-pagination.txt", "../src/lib/paginations/page-pagination.txt", "../src/lib/readme/readme.ts", "../src/lib/readme/prop.emitter.ts", "../src/lib/typescript-snippet.ts", "../src/lib/emitters/snippet.ts"],
|
|
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 type { OpenAPIObject } from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { methods, 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 cleanFiles,\n readWriteMetadata,\n sanitizeTag,\n securityToOptions,\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 { 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 { TypeScriptSnippet } from './typescript-snippet.ts';\n\nfunction security(spec: IR) {\n const security = spec.security || [];\n const components = spec.components || {};\n const securitySchemes = components.securitySchemes || {};\n const paths = Object.values(spec.paths ?? {});\n\n const options = securityToOptions(spec, security, securitySchemes);\n\n for (const it of paths) {\n for (const method of methods) {\n const operation = it[method];\n if (!operation) {\n continue;\n }\n Object.assign(\n options,\n securityToOptions(\n spec,\n operation.security || [],\n securitySchemes,\n 'input',\n ),\n );\n }\n }\n return options;\n}\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: OpenAPIObject,\n settings: TypeScriptGeneratorOptions,\n) {\n const spec = toIR(\n {\n spec: openapi,\n responses: { flattenErrorResponses: true },\n pagination: settings.pagination,\n },\n false,\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 = 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 '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 { 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 });\n\n await settings.writer(output, {\n 'client.ts': backend({\n name: clientName,\n servers: (spec.servers ?? []).map((server) => server.url) || [],\n options: security(spec),\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 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: '^3.25.76',\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 module: 'ESNext',\n noEmit: true,\n strict: true,\n allowImportingTsExtensions: true,\n verbatimModuleSyntax: true,\n baseUrl: '.',\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\nfunction serializeModels(spec: IR) {\n const filesMap: Record<string, string[]> = {};\n const files: Record<string, string> = {};\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 stream = (schema as any)['x-stream'];\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 = 'ReadableStream';\n if (!stream) {\n const serializer = new TypeScriptEmitter(spec);\n typeContent = serializer.handle(schema, true);\n }\n\n const fileContent = [\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.experimental_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.ZodTypeAny>;\n\n for (const [key, value] of Object.entries(shape)) {\n if (value instanceof z.ZodOptional) {\n // Make optional properties also nullable\n newShape[key] = value._def.innerType.nullable().optional();\n } else {\n // Keep non-optional properties as they are\n newShape[key] = value;\n }\n }\n\n return z.object(newShape);\n}", "import { toLitObject } from '@sdk-it/core';\n\nimport { toZod } from './emitters/zod.ts';\nimport type { Spec } from './sdk.ts';\n\nexport default (spec: Omit<Spec, 'operations'>) => {\n const defaultHeaders = `{${spec.options\n .filter((value) => value.in === 'header')\n .map(\n (value) =>\n `'${value.name}': options['${value['x-optionName'] ?? value.name}']`,\n )\n .join(',\\n')}}`;\n const defaultInputs = `{${spec.options\n .filter((value) => value.in === 'input')\n .map(\n (value) =>\n `'${value.name}': options['${value['x-optionName'] ?? value.name}']`,\n )\n .join(',\\n')}}`;\n\n /**\n * Map of option name to zod schema (as string)\n * Usually stuff like token, apiKey and so on.\n */\n const globalOptions = Object.fromEntries(\n spec.options.map((value) => [\n `'${value['x-optionName'] ?? value.name}'`,\n { schema: toZod(value.schema, value.required) },\n ]),\n );\n\n const specOptions: Record<string, { schema: string }> = {\n ...globalOptions,\n ...(globalOptions[\"'token'\"]\n ? {\n \"'token'\": {\n schema: `z.union([z.string(),z.function().returns(z.union([z.string(), z.promise(z.string())])),]).optional()\n .transform(async (token) => {\n if (!token) return undefined;\n if (typeof token === 'function') {\n token = await Promise.resolve(token());\n }\n return \\`Bearer \\${token}\\`;\n })`,\n },\n }\n : {}),\n fetch: {\n schema: 'fetchType',\n },\n baseUrl: {\n schema: spec.servers.length\n ? `z.enum(servers).default(servers[0])`\n : 'z.string()',\n },\n headers: {\n schema: 'z.record(z.string()).optional()',\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\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 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(it) {\n if (it instanceof APIResponse) {\n return it.data as InferData<E>;\n }\n return it as InferData<E>;\n });\n }\n\n async prepare<const E extends keyof typeof schemas>(\n endpoint: E,\n input: z.input<(typeof schemas)[E]['schema']>,\n options?: { headers?: HeadersInit },\n ): Promise<RequestConfig & {\n parse: (response: Response) => ReturnType<typeof parse>;\n }> {\n const clientOptions = await optionsSchema.parseAsync(this.options);\n const route = schemas[endpoint];\n const interceptors = [\n createHeadersInterceptor(\n await this.defaultHeaders(),\n options?.headers ?? {},\n ),\n createBaseUrlInterceptor(clientOptions.baseUrl),\n ];\n const parsedInput = parseInput(route.schema, input);\n\n let config = route.toRequest(parsedInput as never);\n for (const interceptor of interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n const prepared = { ...config, parse: (response: Response) => parse(route.output, response, (d) => d) as never };\n return prepared as any;\n }\n\n async defaultHeaders() {\n const options = await optionsSchema.parseAsync(this.options);\n return {\n ...${defaultHeaders},\n ...options.headers,\n };\n }\n\n async defaultInputs() {\n const options = await optionsSchema.parseAsync(this.options);\n return ${defaultInputs}\n }\n\n setOptions(options: Partial<${spec.name}Options>) {\n this.options = {\n ...this.options,\n ...options,\n };\n }\n\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 options?: { signal?: AbortSignal; headers?: HeadersInit },\n): Promise<Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>> {\n const route = schemas[endpoint];\n const withDefaultInputs = Object.assign(\n {},\n await client.defaultInputs(),\n input,\n );\n const parsedInput = parseInput(route.schema, withDefaultInputs);\n const clientOptions = await optionsSchema.parseAsync(client.options);\n const result = await route.dispatch(parsedInput as never, {\n fetch: clientOptions.fetch,\n interceptors: [\n createHeadersInterceptor(\n await client.defaultHeaders(),\n options?.headers ?? {},\n ),\n createBaseUrlInterceptor(clientOptions.baseUrl),\n ],\n signal: options?.signal,\n });\n return result as Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>;\n}\n\n\n`;\n};\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, parseRef, pascalcase } 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: OpenAPIObject;\n #onRef?: OnRefCallback;\n\n constructor(spec: OpenAPIObject, 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 return `${this.string(schema)}${this.#suffixes(JSON.stringify(schema.default), required, nullable)}`;\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 `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 return `z.union([${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 if (type === 'integer') {\n // Zod doesn\u2019t have a direct enum for numbers, so we use union of literals\n return `z.union([${values.map((val) => `z.literal(${val})`).join(', ')}])`;\n }\n\n return `z.enum([${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 = '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 base = 'z.instanceof(Blob)';\n return base;\n }\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n base = 'z.string().datetime()';\n break;\n case 'date':\n base = 'z.coerce.date()';\n break;\n case 'time':\n base =\n 'z.string() /* optionally add .regex(...) for HH:MM:SS format */';\n break;\n case 'email':\n base = 'z.string().email()';\n break;\n case 'uuid':\n base = 'z.string().uuid()';\n break;\n case 'url':\n case 'uri':\n base = 'z.string().url()';\n break;\n case 'ipv4':\n base = 'z.string().ip({version: \"v4\"})';\n break;\n case 'ipv6':\n base = 'z.string().ip({version: \"v6\"})';\n break;\n case 'phone':\n base = 'z.string() /* or add .regex(...) for phone formats */';\n break;\n case 'byte':\n case 'binary':\n base = 'z.instanceof(Blob)';\n break;\n case 'int64':\n // JS numbers can't reliably store int64, consider z.bigint() or keep as string\n base = 'z.string() /* or z.bigint() if your app can handle it */';\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 defaultValue = schema.default;\n let base = 'z.number()';\n if (schema.format === 'int64') {\n base = 'z.bigint()';\n if (schema.default !== undefined) {\n defaultValue = `BigInt(${schema.default})`;\n }\n }\n\n if (schema.format === 'int32') {\n // 32-bit 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 +=\n schema.format === 'int64'\n ? `.min(BigInt(${schema.minimum}))`\n : `.min(${schema.minimum})`;\n }\n if (typeof schema.maximum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.max(BigInt(${schema.maximum}))`\n : `.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 };\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 // 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 // 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(realTypes[0], schema, required, true);\n }\n // If multiple different types, build a union\n const subSchemas = types.map((t) => this.normal(t, schema, false));\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\nexport function toZod(schema: SchemaObject, required?: boolean): string {\n const emitter = new ZodEmitter({} as OpenAPIObject);\n const schemaStr = emitter.handle(schema, required ?? false);\n if (schema['x-prefix']) {\n const prefix = schema['x-prefix'];\n if (required === false) {\n return (\n schemaStr +\n `.transform((val) => (val ? \\`${prefix}\\${val}\\` : undefined))`\n );\n } else {\n return schemaStr + `.transform((val) => \\`${prefix}\\${val}\\`)`;\n }\n }\n return schemaStr;\n}\n", "import type {\n ReferenceObject,\n SchemaObject\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, parseRef, pascalcase } 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)}: ${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 // For TypeScript we use union types for anyOf/oneOf\n const oneOfTypes = schemas.map((sub) => this.handle(sub, true));\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 = 'Date';\n break;\n case 'binary':\n case 'byte':\n type = 'Blob';\n break;\n case 'int64':\n type = 'bigint';\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 const type = schema.format === 'int64' ? 'bigint' : 'number';\n return appendOptional(type, 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 // 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, false);\n return appendOptional(`${tsType} | null`, required);\n }\n\n // Multiple different types\n const typeResults = types.map((t) => this.normal(t, schema, false));\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 OpenAPIObject,\n ParameterObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { followRef, isEmpty, isRef, resolveRef, sortArray } 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, config.spec, 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 return [\n [\n join('api', `${spinalcase(name)}.ts`),\n `${[\n `import z from 'zod';`,\n `import * as http from '${config.makeImport('../http/response')}';`,\n `import * as outputs from '${config.makeImport('../outputs/index')}';`,\n `import { toRequest, json, urlencoded, empty, formdata, type HeadersInit } from '${config.makeImport('../http/request')}';`,\n `import { chunked, buffered } from \"${config.makeImport('../http/parse-response')}\";`,\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 '\\n',\n )}\\nexport default {\\n${endpoint.flatMap((it) => it.schemas).join(',\\n')}\\n}`,\n ],\n ];\n })\n .flat(),\n ),\n },\n };\n}\n\nfunction toProps(\n spec: OpenAPIObject,\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 { OpenAPIObject, ResponseObject } from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nimport { isEmpty, pascalcase } from '@sdk-it/core';\nimport {\n type IR,\n type OperationPagination,\n type OurParameter,\n type TunedOperationObject,\n isStreamingContentType,\n isTextContentType,\n parseJsonContentType,\n sanitizeTag,\n} from '@sdk-it/spec';\n\nimport { TypeScriptEmitter } from './emitters/interface.ts';\nimport { type MakeImportFn } from './import-utilities.ts';\nimport statusMap from './status-map.ts';\n\nexport type Parser = 'chunked' | 'buffered';\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 options: OurParameter[];\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 spec: IR,\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).flatMap((status) =>\n toHttpOutput(\n spec,\n specOperation.operationId,\n status,\n specOperation.responses[status],\n ),\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 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) : 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\nfunction paginationOperation(operation: TunedOperationObject) {\n const pagination = operation['x-pagination'] as OperationPagination;\n const data = `result.data`;\n const returnValue = `pagination`;\n if (pagination.type === 'offset') {\n const sameInputNames =\n pagination.limitParamName === 'limit' &&\n pagination.offsetParamName === 'offset';\n const initialParams = sameInputNames\n ? 'input'\n : `{...input, limit: input.${pagination.limitParamName}, offset: input.${pagination.offsetParamName}}`;\n\n const nextPageParams = sameInputNames\n ? '...nextPageParams'\n : `${pagination.offsetParamName}: nextPageParams.offset, ${pagination.limitParamName}: nextPageParams.limit`;\n const logic = `const pagination = new OffsetPagination(${initialParams}, async (nextPageParams) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n options.signal,\n );\n return {\n data: ${data}.${pagination.items},\n meta: {\n hasMore: Boolean(${data}.${pagination.hasMore}),\n },\n };\n });\n await pagination.getNextPage();\n return ${returnValue}\n `;\n return `{${logic}}}`;\n }\n if (pagination.type === 'cursor') {\n const sameInputNames = pagination.cursorParamName === 'cursor';\n const initialParams = sameInputNames\n ? 'input'\n : `{...input, cursor: input.${pagination.cursorParamName}}`;\n\n const nextPageParams = sameInputNames\n ? '...nextPageParams'\n : `${pagination.cursorParamName}: nextPageParams.cursor`;\n const logic = `\n const pagination = new CursorPagination(${initialParams}, async (nextPageParams) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n options.signal,\n );\n return {\n data: ${data}.${pagination.items},\n meta: {\n hasMore: Boolean(${data}.${pagination.hasMore}),\n },\n };\n });\n await pagination.getNextPage();\n return ${returnValue}\n `;\n return `{${logic}}}`;\n }\n if (pagination.type === 'page') {\n const sameInputNames =\n pagination.pageNumberParamName === 'page' &&\n pagination.pageSizeParamName === 'pageSize';\n const initialParams = sameInputNames\n ? 'input'\n : `{...input, page: input.${pagination.pageNumberParamName}, pageSize: input.${pagination.pageSizeParamName}}`;\n const nextPageParams = sameInputNames\n ? '...nextPageParams'\n : `${pagination.pageNumberParamName}: nextPageParams.page, ${pagination.pageSizeParamName}: nextPageParams.pageSize`;\n\n const logic = `\n const pagination = new Pagination(${initialParams}, async (nextPageParams) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n options.signal,\n );\n return {\n data: ${data}.${pagination.items},\n meta: {\n hasMore: Boolean(${data}.${pagination.hasMore}),\n },\n };\n });\n return ${returnValue}\n `;\n return `{${logic}}}`;\n }\n return normalOperation();\n}\n\nexport function toHttpOutput(\n spec: IR,\n operationName: string,\n status: string,\n response: ResponseObject,\n withGenerics = true,\n) {\n const typeScriptDeserialzer = new TypeScriptEmitter(spec);\n const interfaceName = pascalcase(sanitizeTag(response['x-response-name']));\n\n if (!isEmpty(response.content)) {\n const contentTypeResult = fromContentType(\n spec,\n typeScriptDeserialzer,\n response,\n );\n if (!contentTypeResult) {\n throw new Error(\n `No recognizable content type for response ${status} in operation ${operationName}`,\n );\n }\n const parser: Parser = contentTypeResult.parser || 'buffered';\n const outputs: string[] = [];\n const statusName = `http.${statusMap[status] || 'APIResponse'}`;\n const statusCode = +status;\n if (statusCode === 204) {\n outputs.push(statusName);\n } else {\n const generic = withGenerics ? `<outputs.${interfaceName}>` : '';\n if (status.endsWith('XX')) {\n outputs.push(`http.APIError${generic}`);\n } else {\n if (parser !== 'buffered') {\n outputs.push(`{type: ${statusName}${generic}, parser: ${parser}}`);\n } else {\n outputs.push(`${statusName}${generic}`);\n }\n }\n }\n return outputs;\n }\n return [];\n}\n\nfunction fromContentType(\n spec: OpenAPIObject,\n typeScriptDeserialzer: TypeScriptEmitter,\n response: ResponseObject,\n) {\n if ((response.headers ?? {})['Transfer-Encoding']) {\n return streamedOutput();\n }\n for (const type in response.content) {\n if (isStreamingContentType(type)) {\n return streamedOutput();\n }\n if (parseJsonContentType(type)) {\n return {\n parser: 'buffered' as const,\n responseSchema: response.content[type].schema\n ? typeScriptDeserialzer.handle(response.content[type].schema, true)\n : 'void',\n };\n }\n if (isTextContentType(type)) {\n return {\n parser: 'buffered' as const,\n responseSchema: response.content[type].schema\n ? typeScriptDeserialzer.handle(response.content[type].schema, true)\n : 'void',\n };\n }\n }\n return streamedOutput();\n}\n\nfunction streamedOutput() {\n return {\n parser: 'chunked' as const,\n responseSchema: 'ReadableStream',\n };\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", "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 '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>;\nexport type OutputType =\n | Type<APIResponse>\n | { parser: Parser; type: Type<APIResponse> };\n\nexport const fetchType = z\n .function()\n .args(z.instanceof(Request))\n .returns(z.promise(z.instanceof(Response)))\n .optional();\n\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 | null = null;\n let parser: Parser = buffered;\n for (const outputType of outputs) {\n if ('parser' in outputType) {\n parser = outputType.parser;\n if (isTypeOf(outputType.type, APIResponse)) {\n if (response.status === outputType.type.status) {\n output = outputType.type;\n break;\n }\n }\n } else if (isTypeOf(outputType, APIResponse)) {\n if (response.status === outputType.status) {\n output = outputType;\n break;\n }\n }\n }\n\n if (response.ok) {\n const apiresponse = (output || APIResponse).create(\n response.status,\n response.headers,\n mapper((await parser(response)) as ResponseData<T>),\n );\n\n return apiresponse as RebindSuccessPayload<Extract<InstanceType<T>, SuccessfulResponse<unknown>>, R>;\n }\n\n throw (output || APIError).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[], 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 let response = await (this.#fetch ?? fetch)(\n new Request(config.url, config.init),\n {\n ...config.init,\n signal: signal,\n },\n );\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 return await parse(\n outputs,\n response,\n mapper ?? ((data: ResponseData<T>) => data as unknown as R),\n );\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\nexport const logInterceptor: Interceptor = {\n before({ url, init }) {\n console.log('Request:', { url, init });\n return { url, init };\n },\n after(response) {\n console.log('Response:', response);\n return response;\n },\n};\n\n/**\n * Creates an interceptor that logs detailed information about requests and responses.\n * @param options Configuration options for the logger\n * @returns An interceptor object with before and after handlers\n */\nexport const createDetailedLogInterceptor = (options?: {\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n includeRequestBody?: boolean;\n includeResponseBody?: boolean;\n}) => {\n const logLevel = options?.logLevel || 'info';\n const includeRequestBody = options?.includeRequestBody || false;\n const includeResponseBody = options?.includeResponseBody || false;\n\n return {\n async before(request: Request) {\n const logData = {\n url: request.url,\n method: request.method,\n contentType: request.headers.get('Content-Type'),\n headers: Object.fromEntries([...request.headers.entries()]),\n };\n\n console[logLevel]('\uD83D\uDE80 Outgoing Request:', logData);\n\n if (includeRequestBody) {\n try {\n // Clone the request to avoid consuming the body stream\n const clonedRequest = request.clone();\n if (clonedRequest.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedRequest.json().catch(() => null);\n console[logLevel]('Request Body:', body);\n } else {\n const body = await clonedRequest.text().catch(() => null);\n console[logLevel]('Request Body:', body);\n }\n } catch (error) {\n console.error('Could not log request body:', error);\n }\n }\n\n return request;\n },\n\n async after(response: Response) {\n const logData = {\n status: response.status,\n statusText: response.statusText,\n url: response.url,\n headers: Object.fromEntries([...response.headers.entries()]),\n };\n\n console[logLevel]('\uD83D\uDCE5 Incoming Response:', logData);\n\n if (includeResponseBody && response.body) {\n try {\n // Clone the response to avoid consuming the body stream\n const clonedResponse = response.clone();\n if (clonedResponse.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedResponse.json().catch(() => null);\n console[logLevel]('Response Body:', body);\n } else {\n const body = await clonedResponse.text().catch(() => null);\n if (body) {\n console[logLevel]('Response Body:', body.substring(0, 500) + (body.length > 500 ? '...' : ''));\n } else {\n console[logLevel]('No response body');\n }\n }\n } catch (error) {\n console.error('Could not log response body:', error);\n }\n }\n\n return response;\n },\n };\n};\n", "import { parse } from \"fast-content-type-parse\";\n\nasync function handleChunkedResponse(response: Response, contentType: string) {\n\tconst { type } = parse(contentType);\n\n\tswitch (type) {\n\t\tcase \"application/json\": {\n\t\t\tlet buffer = \"\";\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\twhile (true) {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value);\n\t\t\t}\n\t\t\treturn JSON.parse(buffer);\n\t\t}\n\t\tcase \"text/html\":\n\t\tcase \"text/plain\": {\n\t\t\tlet buffer = \"\";\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\twhile (true) {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value);\n\t\t\t}\n\t\t\treturn buffer;\n\t\t}\n\t\tdefault:\n\t\t\treturn response.body;\n\t}\n}\n\nexport function chunked(response: Response) {\n\treturn response.body!;\n}\n\nexport async function buffered(response: Response) {\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\tif (response.status === 204) {\n\t\treturn null;\n\t}\n\n\tconst { type } = parse(contentType);\n\tswitch (type) {\n\t\tcase \"application/json\":\n\t\t\treturn response.json();\n\t\tcase \"text/plain\":\n\t\t\treturn response.text();\n\t\tcase \"text/html\":\n\t\t\treturn response.text();\n\t\tcase \"text/xml\":\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<any, any, any>> extends Error {\n public data: z.typeToFlattenedError<T, z.ZodIssue>;\n constructor(data: z.typeToFlattenedError<T, z.ZodIssue>) {\n super('Validation failed');\n this.name = 'ParseError';\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType<any, any, any>>(\n schema: T,\n input: unknown,\n): z.infer<T> {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = result.error.flatten((issue) => issue);\n throw new ParseError(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 ? '' : String(result);\n });\n}\n\ntype Input = Record<string, any>;\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 = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\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, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return {\n body: this.getBody(),\n url,\n headers: this.getHeaders(),\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, 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 body: method === 'GET' ? undefined : 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 APIResponse<\n Body,\n Status\n> {\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(status, headers, data);\n }\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(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\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", "type CursorPaginationParams = {\n cursor?: string;\n};\n\ninterface CursorMetadata extends Metadata {\n nextCursor?: string;\n}\n\ninterface Metadata {\n hasMore?: boolean;\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) => 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\n constructor(\n initialParams: PartialNullable<CursorPaginationParams>,\n fetchFn: FetchFn<T, M>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = {\n cursor: initialParams.cursor ?? undefined,\n };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n cursor: result.meta.nextCursor,\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() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\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;\n};\n", "type OffsetPaginationParams = {\n offset: number;\n limit: number;\n};\n\ninterface Metadata {\n hasMore?: boolean;\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) => 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\n constructor(\n initialParams: Partial<OffsetPaginationParams>,\n fetchFn: FetchFn<T, M>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = {\n limit: initialParams.limit ?? 0,\n offset: initialParams.offset ?? 0,\n };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\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() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\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, S extends number | bigint> = {\n page?: P;\n pageSize?: S;\n};\n\ninterface Metadata {\n hasMore?: boolean;\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,\n S extends number | bigint,\n> = (input: Partial<PaginationParams<P, S>>) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class Pagination<\n T,\n M extends Metadata,\n P extends number | bigint,\n S extends number | bigint,\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\n constructor(\n initialParams: Partial<PaginationParams<P, S>>,\n fetchFn: FetchFn<T, M, P, S>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = { ...initialParams, page: initialParams.page };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\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() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\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 OpenAPIObject,\n ReferenceObject,\n RequestBodyObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { 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: OpenAPIObject;\n\n constructor(spec: OpenAPIObject) {\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 { ResponseObject, SchemaObject } from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { isEmpty, pascalcase, resolveRef } 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 securityToOptions,\n} from '@sdk-it/spec';\n\nimport { SnippetEmitter } from './emitters/snippet.ts';\nimport type { TypeScriptGeneratorOptions } from './options.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(\n this.#spec,\n requestBody,\n operation.parameters,\n operation.security ?? [],\n );\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 result = ${this.#toRequest(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\t\\tconsole.log(page);\\n}`,\n };\n case 'offset':\n return {\n content: `const result = ${this.#toRequest(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\t\\tconsole.log(page);\\n}`,\n };\n case 'cursor':\n return {\n content: `const result = ${this.#toRequest(entry, payload)}`,\n footer: `for await (const page of result) {\\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 return securityToOptions(\n this.#spec,\n this.#spec.security ?? [],\n this.#spec.components?.securitySchemes ?? {},\n );\n }\n\n client() {\n const options: Record<string, unknown> = {\n baseUrl: this.#spec.servers?.[0]?.url ?? 'http://localhost:3000',\n };\n\n const authOptions = this.#authentication();\n if (!isEmpty(authOptions)) {\n const [firstAuth] = authOptions;\n const optionName = firstAuth['x-optionName'] ?? firstAuth.name;\n options[optionName] = firstAuth.example;\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 = this.#spec.servers?.[0]?.url || 'https://api.example.com';\n\n // Use the existing authentication method to get auth options\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` | No | API base URL (default: `' +\n baseUrl +\n '`) |',\n );\n }\n\n // Add auth options using the existing authentication structure\n for (const authOption of authOptions) {\n const optionName = authOption['x-optionName'] ?? authOption.name;\n const description =\n authOption.in === 'header' && authOption.name === 'authorization'\n ? 'Bearer token for authentication'\n : `API key for authentication (${authOption.in}: ${authOption.name})`;\n\n sections.push(`| \\`${optionName}\\` | \\`string\\` | No | ${description} |`);\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();',\n '}',\n '',\n '// Or iterate through all pages automatically',\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 // Use the existing authentication method\n const authOptions = this.#authentication();\n\n if (isEmpty(authOptions)) {\n return '';\n }\n\n const sections: string[] = [];\n\n sections.push('## Authentication');\n sections.push('');\n\n // Adapt introduction based on number of auth methods\n if (authOptions.length === 1) {\n sections.push(\n 'The SDK requires authentication to access the API. Configure your client with the required credentials:',\n );\n } else {\n sections.push('The SDK supports the following authentication methods:');\n }\n sections.push('');\n\n for (const authOption of authOptions) {\n const optionName = authOption['x-optionName'] ?? authOption.name;\n const isBearer =\n authOption.in === 'header' && authOption.name === 'authorization';\n const isApiKey =\n authOption.in === 'header' && authOption.name !== 'authorization';\n const isQueryParam = authOption.in === 'query';\n\n // Determine heading level based on number of auth methods\n const headingLevel = authOptions.length === 1 ? '###' : '###';\n\n if (isBearer) {\n const authenticationHeading =\n authOptions.length === 1\n ? 'Bearer Token'\n : 'Bearer Token Authentication';\n sections.push(`${headingLevel} ${authenticationHeading}`);\n sections.push('');\n sections.push(\n 'Pass your bearer token directly - the \"Bearer\" prefix is automatically added:',\n );\n sections.push('');\n const bearerAuthClient = this.#constructClient({\n [optionName]: 'sk_live_51234567890abcdef1234567890abcdef',\n });\n sections.push(createCodeBlock('typescript', [bearerAuthClient.use]));\n sections.push('');\n } else if (isApiKey) {\n const apiKeyHeading =\n authOptions.length === 1\n ? 'API Key (Header)'\n : 'API Key Authentication (Header)';\n sections.push(`${headingLevel} ${apiKeyHeading}`);\n sections.push('');\n const apiKeyAuthClient = this.#constructClient({\n [optionName]: 'api_key_1234567890abcdef1234567890abcdef',\n });\n sections.push(createCodeBlock('typescript', [apiKeyAuthClient.use]));\n sections.push('');\n } else if (isQueryParam) {\n const queryParamHeading =\n authOptions.length === 1\n ? 'API Key (Query Parameter)'\n : 'API Key Authentication (Query Parameter)';\n sections.push(`${headingLevel} ${queryParamHeading}`);\n sections.push('');\n const queryParamAuthClient = this.#constructClient({\n [optionName]: 'qp_key_1234567890abcdef1234567890abcdef',\n });\n sections.push(\n createCodeBlock('typescript', [queryParamAuthClient.use]),\n );\n sections.push('');\n } else {\n // Generic fallback\n const genericAuthHeading =\n authOptions.length === 1\n ? authOption.name\n : `${authOption.name} Authentication`;\n sections.push(`${headingLevel} ${genericAuthHeading}`);\n sections.push('');\n const genericAuthClient = this.#constructClient({\n [optionName]: 'auth_token_1234567890abcdef1234567890abcdef',\n });\n sections.push(createCodeBlock('typescript', [genericAuthClient.use]));\n sections.push('');\n }\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 const authOptionName = primaryAuth['x-optionName'] ?? primaryAuth.name;\n initialClientOptions[authOptionName] = 'prod_sk_1234567890abcdef';\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 const authOptionName = primaryAuth['x-optionName'] ?? primaryAuth.name;\n configurationUpdateCode.push(\n ` ${authOptionName}: 'staging_sk_abcdef1234567890'`,\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 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;AAE9B,SAAS,aAAAC,YAAW,cAAAC,mBAAkB;AAEtC,SAAS,SAAS,cAAAC,aAAY,eAAAC,oBAAmB;AACjD;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA,qBAAAC;AAAA,EACA;AAAA,OACK;;;ACrBP,SAAS,iBAAiB;AAE1B;AAAA,EAIE;AAAA,OACK;AAEA,SAAS,mBAAmB,IAAQ;AACzC,QAAM,SAQF,CAAC;AACL,mBAAiB,IAAI,CAAC,OAAO,cAAc;AACzC,UAAM,SAAS,GAAG,KAAK,KAAK,CAAC,QAAQ,IAAI,SAAS,MAAM,GAAG;AAC3D,QAAI,CAAC,QAAQ;AACX,cAAQ,KAAK,iCAAiC,MAAM,GAAG,EAAE;AACzD;AAAA,IACF;AAEA,WAAO,MAAM,GAAG,MAAM;AAAA,MACpB,OAAO,CAAC;AAAA,MACR,cAAc;AAAA,MACd,aAAa;AAAA,MACb,MAAM;AAAA,IACR;AACA,WAAO,MAAM,GAAG,EAAE,MAAM,KAAK,WAAW,OAAO,SAAS,CAAC;AACzD,WAAO,MAAM,GAAG,EAAE,eAAe,OAAO,gBAAgB;AACxD,WAAO,MAAM,GAAG,EAAE,OAAO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AAO,KAAK,MAAM;AAAA,IACpB;AACA,WAAO,UAAUA,YAAW,IAAI,CAAC,KAAK,IACpC,CAAC,GAAG,SAAS,GAAG,MAAM,EAAE,KAAK,IAAI,IAAI;AAAA,EACzC;AAEA,QAAM,UAAU,UACb,QAAQ,EACR,OAAmB,CAAC,KAAK,CAAC,MAAM,MAAM,MAAM;AAC3C,UAAM,SAAS,CAAC,0BAA0B;AAC1C,UAAM,UAAU,gBAAgB,IAAI,MAAM,MAAM;AAChD,eAAWK,WAAU,eAAe;AAClC,YAAM,eAAe,IAAI,OAAO,MAAMA,OAAM,KAAK;AACjD,UAAI,aAAa,KAAK,OAAO,KAAKA,YAAW,MAAM;AACjD,eAAO;AAAA,UACL,YAAYA,OAAM,cAAc,WAAWL,YAAWK,OAAM,CAAC,CAAC;AAAA,QAChE;AAAA,MACF;AAAA,IACF;AACA,WAAO,KAAK,OAAO;AACnB,WAAO;AAAA,MACL,CAAC,kBAAkBL,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;",
|
|
3
|
+
"sources": ["../src/lib/generate.ts", "../src/lib/agent/ai-sdk.ts", "../src/lib/agent/openai-agents.ts", "../src/lib/agent/utils.txt", "../src/lib/client.ts", "../src/lib/emitters/zod.ts", "../src/lib/emitters/interface.ts", "../src/lib/generator.ts", "../src/lib/sdk.ts", "../src/lib/import-utilities.ts", "../src/lib/status-map.ts", "../src/lib/styles/github/endpoints.txt", "../src/lib/http/dispatcher.txt", "../src/lib/http/interceptors.txt", "../src/lib/http/parse-response.txt", "../src/lib/http/parser.txt", "../src/lib/http/request.txt", "../src/lib/http/response.txt", "../src/lib/http/sse.txt", "../src/lib/paginations/cursor-pagination.txt", "../src/lib/paginations/offset-pagination.txt", "../src/lib/paginations/page-pagination.txt", "../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 { template } from 'lodash-es';\nimport { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { OpenAPIObject } from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { methods, 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 cleanFiles,\n readWriteMetadata,\n sanitizeTag,\n securityToOptions,\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 { expandServerUrls } from './server-urls.ts';\nimport { TypeScriptSnippet } from './typescript-snippet.ts';\n\nfunction security(spec: IR) {\n const security = spec.security || [];\n const components = spec.components || {};\n const securitySchemes = components.securitySchemes || {};\n const paths = Object.values(spec.paths ?? {});\n\n const options = securityToOptions(spec, security, securitySchemes);\n\n for (const it of paths) {\n for (const method of methods) {\n const operation = it[method];\n if (!operation) {\n continue;\n }\n Object.assign(\n options,\n securityToOptions(\n spec,\n operation.security || [],\n securitySchemes,\n 'input',\n ),\n );\n }\n }\n return options;\n}\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: OpenAPIObject,\n settings: TypeScriptGeneratorOptions,\n): Promise<{ packageName: string }> {\n const spec = toIR(\n {\n spec: openapi,\n responses: { flattenErrorResponses: true },\n pagination: settings.pagination,\n },\n false,\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 = settings.packageName ?? (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 });\n\n await settings.writer(output, {\n 'client.ts': backend({\n name: clientName,\n servers: expandServerUrls(spec.servers ?? []),\n options: security(spec),\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 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: '^3.25.76',\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 module: 'ESNext',\n noEmit: true,\n strict: true,\n allowImportingTsExtensions: true,\n verbatimModuleSyntax: true,\n baseUrl: '.',\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 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 stream = (schema as any)['x-stream'];\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 const isSse = (schema as any)['x-sse'];\n let typeContent = isSse ? 'SSEListener' : 'ReadableStream';\n if (!stream) {\n const serializer = new TypeScriptEmitter(spec);\n typeContent = serializer.handle(schema, true);\n }\n\n const imports: string[] = [];\n if (isSse) {\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.experimental_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.ZodTypeAny>;\n\n for (const [key, value] of Object.entries(shape)) {\n if (value instanceof z.ZodOptional) {\n // Make optional properties also nullable\n newShape[key] = value._def.innerType.nullable().optional();\n } else {\n // Keep non-optional properties as they are\n newShape[key] = value;\n }\n }\n\n return z.object(newShape);\n}", "import { toLitObject } from '@sdk-it/core';\n\nimport { toZod } from './emitters/zod.ts';\nimport type { Spec } from './sdk.ts';\n\nexport default (spec: Omit<Spec, 'operations'>) => {\n const defaultHeaders = `{${spec.options\n .filter((value) => value.in === 'header')\n .map(\n (value) =>\n `'${value.name}': options['${value['x-optionName'] ?? value.name}']`,\n )\n .join(',\\n')}}`;\n const defaultInputs = `{${spec.options\n .filter((value) => value.in === 'input')\n .map(\n (value) =>\n `'${value.name}': options['${value['x-optionName'] ?? value.name}']`,\n )\n .join(',\\n')}}`;\n\n /**\n * Map of option name to zod schema (as string)\n * Usually stuff like token, apiKey and so on.\n */\n const globalOptions = Object.fromEntries(\n spec.options.map((value) => [\n `'${value['x-optionName'] ?? value.name}'`,\n { schema: toZod(value.schema, value.required) },\n ]),\n );\n\n const specOptions: Record<string, { schema: string }> = {\n ...globalOptions,\n ...(globalOptions[\"'token'\"]\n ? {\n \"'token'\": {\n schema: `z.union([z.string(),z.function().returns(z.union([z.string(), z.promise(z.string())])),]).optional()\n .transform(async (token) => {\n if (!token) return undefined;\n if (typeof token === 'function') {\n token = await Promise.resolve(token());\n }\n return \\`Bearer \\${token}\\`;\n }).describe('Bearer token for authentication. Can be a string or a function that returns a string.')`,\n },\n }\n : {}),\n fetch: {\n schema: `fetchType.describe('Custom fetch implementation. Defaults to globalThis.fetch.')`,\n },\n baseUrl: {\n schema: spec.servers.length\n ? `z.enum(servers).default(servers[0]).describe('Base URL of the API server.')`\n : `z.string().describe('Base URL of the API server.')`,\n },\n headers: {\n schema: `z.record(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\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(it) {\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?: { 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 {\n ...${defaultHeaders},\n ...options.headers,\n };\n }\n\n async defaultInputs() {\n const options = await optionsSchema.parseAsync(this.options);\n return ${defaultInputs}\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 * Merges the client's default inputs and 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 withDefaultInputs = Object.assign(\n {},\n ${defaultInputs},\n input,\n );\n const parsedInput = options.skipValidation ? withDefaultInputs : parseInput(route.schema, withDefaultInputs);\n const result = await route.dispatch(parsedInput as never, {\n fetch: options.fetch,\n interceptors: [\n createHeadersInterceptor(\n { ...${defaultHeaders}, ...options.headers },\n requestOptions?.headers ?? {},\n ),\n createBaseUrlInterceptor(options.baseUrl),\n ],\n 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?: { 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 withDefaultInputs = Object.assign(\n {},\n ${defaultInputs},\n input,\n );\n const parsedInput = options.skipValidation ? withDefaultInputs : parseInput(route.schema, withDefaultInputs);\n const interceptors = [\n createHeadersInterceptor(\n { ...${defaultHeaders}, ...options.headers },\n requestOptions?.headers ?? {},\n ),\n createBaseUrlInterceptor(options.baseUrl),\n ];\n\n let config = route.toRequest(parsedInput as never);\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 {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, parseRef, pascalcase } 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: OpenAPIObject;\n #onRef?: OnRefCallback;\n\n constructor(spec: OpenAPIObject, 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' || schema['x-zod-type'] === 'coerce-date') && 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 `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 return `z.union([${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 if (type === 'integer') {\n // Zod doesn\u2019t have a direct enum for numbers, so we use union of literals\n return `z.union([${values.map((val) => `z.literal(${val})`).join(', ')}])`;\n }\n\n return `z.enum([${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 = '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 base = 'z.instanceof(Blob)';\n return base;\n }\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 base = 'z.string().datetime()';\n }\n break;\n case 'date':\n base = 'z.string().date()';\n break;\n case 'time':\n base =\n 'z.string() /* optionally add .regex(...) for HH:MM:SS format */';\n break;\n case 'email':\n base = 'z.string().email()';\n break;\n case 'uuid':\n base = 'z.string().uuid()';\n break;\n case 'url':\n case 'uri':\n base = 'z.string().url()';\n break;\n case 'ipv4':\n base = 'z.string().ip({version: \"v4\"})';\n break;\n case 'ipv6':\n base = 'z.string().ip({version: \"v6\"})';\n break;\n case 'phone':\n base = 'z.string() /* or add .regex(...) for phone formats */';\n break;\n case 'byte':\n case 'binary':\n base = 'z.instanceof(Blob)';\n break;\n case 'int64':\n // JS numbers can't reliably store int64, consider z.bigint() or keep as string\n base = 'z.string() /* or z.bigint() if your app can handle it */';\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 defaultValue = schema.default;\n let base: string;\n if (schema.format === 'int64') {\n base = schema['x-zod-type'] === 'coerce-bigint' ? 'z.coerce.bigint()' : 'z.bigint()';\n if (schema.default !== undefined) {\n defaultValue = `BigInt(${schema.default})`;\n }\n } else {\n base = schema['x-zod-type'] === 'coerce-number' ? 'z.coerce.number()' : 'z.number()';\n }\n\n if (schema.type === 'integer' && schema.format !== 'int64') {\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 +=\n schema.format === 'int64'\n ? `.min(BigInt(${schema.minimum}))`\n : `.min(${schema.minimum})`;\n }\n if (typeof schema.maximum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.max(BigInt(${schema.maximum}))`\n : `.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 };\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 // 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 // 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(realTypes[0], schema, required, true);\n }\n // If multiple different types, build a union\n const subSchemas = types.map((t) => this.normal(t, schema, false));\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\nexport function toZod(schema: SchemaObject, required?: boolean): string {\n const emitter = new ZodEmitter({} as OpenAPIObject);\n const schemaStr = emitter.handle(schema, required ?? false);\n if (schema['x-prefix']) {\n const prefix = schema['x-prefix'];\n if (required === false) {\n return (\n schemaStr +\n `.transform((val) => (val ? \\`${prefix}\\${val}\\` : undefined))`\n );\n } else {\n return schemaStr + `.transform((val) => \\`${prefix}\\${val}\\`)`;\n }\n }\n return schemaStr;\n}\n", "import type {\n ReferenceObject,\n SchemaObject\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, parseRef, pascalcase } 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)}: ${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 // For TypeScript we use union types for anyOf/oneOf\n const oneOfTypes = schemas.map((sub) => this.handle(sub, true));\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 case 'int64':\n type = 'bigint';\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 const type = schema.format === 'int64' ? 'bigint' : 'number';\n return appendOptional(type, 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 // 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, false);\n return appendOptional(`${tsType} | null`, required);\n }\n\n // Multiple different types\n const typeResults = types.map((t) => this.normal(t, schema, false));\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 OpenAPIObject,\n ParameterObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { followRef, isEmpty, isRef, resolveRef, sortArray } 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, config.spec, 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 return [\n [\n join('api', `${spinalcase(name)}.ts`),\n `${[\n `import z from 'zod';`,\n `import * as http from '${config.makeImport('../http/response')}';`,\n `import * as outputs from '${config.makeImport('../outputs/index')}';`,\n `import { toRequest, json, urlencoded, empty, formdata, type HeadersInit } from '${config.makeImport('../http/request')}';`,\n `import { chunked, buffered } from \"${config.makeImport('../http/parse-response')}\";`,\n `import { sse } 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 '\\n',\n )}\\nexport default {\\n${endpoint.flatMap((it) => it.schemas).join(',\\n')}\\n}`,\n ],\n ];\n })\n .flat(),\n ),\n },\n };\n}\n\nfunction toProps(\n spec: OpenAPIObject,\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 { OpenAPIObject, ResponseObject } from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nimport { isEmpty, pascalcase } from '@sdk-it/core';\nimport {\n type IR,\n type OperationPagination,\n type OurParameter,\n type TunedOperationObject,\n isBinaryContentType,\n isSseContentType,\n isStreamingContentType,\n isTextContentType,\n parseJsonContentType,\n sanitizeTag,\n} from '@sdk-it/spec';\n\nimport { TypeScriptEmitter } from './emitters/interface.ts';\nimport { type MakeImportFn } from './import-utilities.ts';\nimport statusMap from './status-map.ts';\n\nexport type Parser = 'chunked' | 'buffered' | 'sse';\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 options: OurParameter[];\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 spec: IR,\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).flatMap((status) =>\n toHttpOutput(\n spec,\n specOperation.operationId,\n status,\n specOperation.responses[status],\n ),\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 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) : 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\nfunction paginationOperation(operation: TunedOperationObject) {\n const pagination = operation['x-pagination'] as OperationPagination;\n const data = `result.data`;\n const returnValue = `pagination`;\n if (pagination.type === 'offset') {\n const sameInputNames =\n pagination.limitParamName === 'limit' &&\n pagination.offsetParamName === 'offset';\n const initialParams = sameInputNames\n ? 'input'\n : `{...input, limit: input.${pagination.limitParamName}, offset: input.${pagination.offsetParamName}}`;\n\n const nextPageParams = sameInputNames\n ? '...nextPageParams'\n : `${pagination.offsetParamName}: nextPageParams.offset, ${pagination.limitParamName}: nextPageParams.limit`;\n const logic = `const pagination = new OffsetPagination(${initialParams}, async (nextPageParams) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n options.signal,\n );\n return {\n data: ${data}.${pagination.items},\n meta: {\n hasMore: Boolean(${data}.${pagination.hasMore}),\n },\n };\n });\n await pagination.getNextPage();\n return ${returnValue}\n `;\n return `{${logic}}}`;\n }\n if (pagination.type === 'cursor') {\n const sameInputNames = pagination.cursorParamName === 'cursor';\n const initialParams = sameInputNames\n ? 'input'\n : `{...input, cursor: input.${pagination.cursorParamName}}`;\n\n const nextPageParams = sameInputNames\n ? '...nextPageParams'\n : `${pagination.cursorParamName}: nextPageParams.cursor`;\n const logic = `\n const pagination = new CursorPagination(${initialParams}, async (nextPageParams) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n options.signal,\n );\n return {\n data: ${data}.${pagination.items},\n meta: {\n hasMore: Boolean(${data}.${pagination.hasMore}),\n },\n };\n });\n await pagination.getNextPage();\n return ${returnValue}\n `;\n return `{${logic}}}`;\n }\n if (pagination.type === 'page') {\n const sameInputNames =\n pagination.pageNumberParamName === 'page' &&\n pagination.pageSizeParamName === 'pageSize';\n const initialParams = sameInputNames\n ? 'input'\n : `{...input, page: input.${pagination.pageNumberParamName}, pageSize: input.${pagination.pageSizeParamName}}`;\n const nextPageParams = sameInputNames\n ? '...nextPageParams'\n : `${pagination.pageNumberParamName}: nextPageParams.page, ${pagination.pageSizeParamName}: nextPageParams.pageSize`;\n\n const logic = `\n const pagination = new Pagination(${initialParams}, async (nextPageParams) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n options.signal,\n );\n return {\n data: ${data}.${pagination.items},\n meta: {\n hasMore: Boolean(${data}.${pagination.hasMore}),\n },\n };\n });\n return ${returnValue}\n `;\n return `{${logic}}}`;\n }\n return normalOperation();\n}\n\nexport function toHttpOutput(\n spec: IR,\n operationName: string,\n status: string,\n response: ResponseObject,\n withGenerics = true,\n) {\n const typeScriptDeserialzer = new TypeScriptEmitter(spec);\n const interfaceName = pascalcase(sanitizeTag(response['x-response-name']));\n\n if (!isEmpty(response.content)) {\n const contentTypeResult = fromContentType(\n spec,\n typeScriptDeserialzer,\n response,\n );\n if (!contentTypeResult) {\n throw new Error(\n `No recognizable content type for response ${status} in operation ${operationName}`,\n );\n }\n const parser: Parser = contentTypeResult.parser || 'buffered';\n const outputs: string[] = [];\n const statusName = `http.${statusMap[status] || 'APIResponse'}`;\n const statusCode = +status;\n if (statusCode === 204) {\n outputs.push(statusName);\n } else {\n const generic = withGenerics ? `<outputs.${interfaceName}>` : '';\n if (status.endsWith('XX')) {\n outputs.push(`http.APIError${generic}`);\n } else {\n if (parser !== 'buffered') {\n outputs.push(`{type: ${statusName}${generic}, parser: ${parser}}`);\n } else {\n outputs.push(`${statusName}${generic}`);\n }\n }\n }\n return outputs;\n }\n return [];\n}\n\nfunction fromContentType(\n spec: OpenAPIObject,\n typeScriptDeserialzer: TypeScriptEmitter,\n response: ResponseObject,\n) {\n if ((response.headers ?? {})['Transfer-Encoding']) {\n return streamedOutput();\n }\n const hasContentDisposition = hasHeader(response, 'Content-Disposition');\n for (const type in response.content) {\n const isStreaming = isStreamingContentType(type);\n const isBinary = isBinaryContentType(type) || (isStreaming && hasContentDisposition);\n // Octet-stream defaults to streaming unless Content-Disposition hints a file download.\n if (isStreaming && !hasContentDisposition) {\n return streamedOutput();\n }\n if (isBinary) {\n return {\n parser: 'buffered' as const,\n responseSchema: response.content[type].schema\n ? typeScriptDeserialzer.handle(response.content[type].schema, true)\n : 'Blob',\n };\n }\n if (parseJsonContentType(type)) {\n return {\n parser: 'buffered' as const,\n responseSchema: response.content[type].schema\n ? typeScriptDeserialzer.handle(response.content[type].schema, true)\n : 'void',\n };\n }\n if (isSseContentType(type)) {\n return {\n parser: 'sse' as const,\n responseSchema: 'SSEListener',\n };\n }\n if (isTextContentType(type)) {\n return {\n parser: 'buffered' as const,\n responseSchema: response.content[type].schema\n ? typeScriptDeserialzer.handle(response.content[type].schema, true)\n : 'void',\n };\n }\n }\n return streamedOutput();\n}\n\nfunction hasHeader(response: ResponseObject, name: string) {\n const headers = response.headers ?? {};\n const target = name.toLowerCase();\n return Object.keys(headers).some((key) => key.toLowerCase() === target);\n}\n\nfunction streamedOutput() {\n return {\n parser: 'chunked' as const,\n responseSchema: 'ReadableStream',\n };\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", "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\nexport const fetchType = z\n .function()\n .args(z.instanceof(Request))\n .returns(z.promise(z.instanceof(Response)))\n .optional();\n\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 | null = null;\n let parser: Parser = buffered;\n for (const outputType of outputs) {\n if ('parser' in outputType) {\n parser = outputType.parser;\n if (isTypeOf(outputType.type, APIResponse)) {\n if (response.status === outputType.type.status) {\n output = outputType.type;\n break;\n }\n }\n } else if (isTypeOf(outputType, APIResponse)) {\n if (response.status === outputType.status) {\n output = outputType;\n break;\n }\n }\n }\n\n if (response.ok) {\n const apiresponse = (output || APIResponse).create(\n response.status,\n response.headers,\n mapper((await parser(response)) as ResponseData<T>),\n );\n\n return apiresponse as RebindSuccessPayload<Extract<InstanceType<T>, SuccessfulResponse<unknown>>, R>;\n }\n\n throw (output || APIError).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[], 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 let response = await (this.#fetch ?? fetch)(\n new Request(config.url, config.init),\n {\n ...config.init,\n signal: signal,\n },\n );\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 return await parse(\n outputs,\n response,\n mapper ?? ((data: ResponseData<T>) => data as unknown as R),\n );\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\nexport const logInterceptor: Interceptor = {\n before({ url, init }) {\n console.log('Request:', { url, init });\n return { url, init };\n },\n after(response) {\n console.log('Response:', response);\n return response;\n },\n};\n\n/**\n * Creates an interceptor that logs detailed information about requests and responses.\n * @param options Configuration options for the logger\n * @returns An interceptor object with before and after handlers\n */\nexport const createDetailedLogInterceptor = (options?: {\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n includeRequestBody?: boolean;\n includeResponseBody?: boolean;\n}) => {\n const logLevel = options?.logLevel || 'info';\n const includeRequestBody = options?.includeRequestBody || false;\n const includeResponseBody = options?.includeResponseBody || false;\n\n return {\n async before(request: Request) {\n const logData = {\n url: request.url,\n method: request.method,\n contentType: request.headers.get('Content-Type'),\n headers: Object.fromEntries([...request.headers.entries()]),\n };\n\n console[logLevel]('\uD83D\uDE80 Outgoing Request:', logData);\n\n if (includeRequestBody) {\n try {\n // Clone the request to avoid consuming the body stream\n const clonedRequest = request.clone();\n if (clonedRequest.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedRequest.json().catch(() => null);\n console[logLevel]('Request Body:', body);\n } else {\n const body = await clonedRequest.text().catch(() => null);\n console[logLevel]('Request Body:', body);\n }\n } catch (error) {\n console.error('Could not log request body:', error);\n }\n }\n\n return request;\n },\n\n async after(response: Response) {\n const logData = {\n status: response.status,\n statusText: response.statusText,\n url: response.url,\n headers: Object.fromEntries([...response.headers.entries()]),\n };\n\n console[logLevel]('\uD83D\uDCE5 Incoming Response:', logData);\n\n if (includeResponseBody && response.body) {\n try {\n // Clone the response to avoid consuming the body stream\n const clonedResponse = response.clone();\n if (clonedResponse.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedResponse.json().catch(() => null);\n console[logLevel]('Response Body:', body);\n } else {\n const body = await clonedResponse.text().catch(() => null);\n if (body) {\n console[logLevel]('Response Body:', body.substring(0, 500) + (body.length > 500 ? '...' : ''));\n } else {\n console[logLevel]('No response body');\n }\n }\n } catch (error) {\n console.error('Could not log response body:', error);\n }\n }\n\n return response;\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\nasync function handleChunkedResponse(response: Response, contentType: string) {\n\tconst { type } = parse(contentType);\n\n\tswitch (type) {\n\t\tcase \"application/json\": {\n\t\t\tlet buffer = \"\";\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\twhile (true) {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value);\n\t\t\t}\n\t\t\treturn JSON.parse(buffer);\n\t\t}\n\t\tcase \"text/html\":\n\t\tcase \"text/plain\": {\n\t\t\tlet buffer = \"\";\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\twhile (true) {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value);\n\t\t\t}\n\t\t\treturn buffer;\n\t\t}\n\t\tdefault:\n\t\t\treturn response.body;\n\t}\n}\n\nexport function chunked(response: Response) {\n\treturn response.body!;\n}\n\nexport async function buffered(response: Response) {\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\tif (response.status === 204) {\n\t\treturn null;\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<any, any, any>> extends Error {\n public data: z.typeToFlattenedError<T, z.ZodIssue>;\n constructor(data: z.typeToFlattenedError<T, z.ZodIssue>) {\n super('Validation failed');\n this.name = 'ParseError';\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType<any, any, any>>(\n schema: T,\n input: unknown,\n): z.infer<T> {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = result.error.flatten((issue) => issue);\n throw new ParseError(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 ? '' : String(result);\n });\n}\n\ntype Input = Record<string, any>;\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 = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\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, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n return {\n body: this.getBody(),\n url,\n headers: this.getHeaders(),\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, 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 body: method === 'GET' ? undefined : 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 APIResponse<\n Body,\n Status\n> {\n static override create<T>(status: number, headers: Headers, data: T) {\n return new this(status, headers, data);\n }\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(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\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\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(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 {}\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 (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 PaginationResult<T, M extends CursorMetadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<T, M extends CursorMetadata> = (\n input: CursorPaginationParams,\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\n constructor(\n initialParams: PartialNullable<CursorPaginationParams>,\n fetchFn: FetchFn<T, M>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = {\n cursor: initialParams.cursor ?? undefined,\n };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n cursor: result.meta.nextCursor,\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() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\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;\n};\n", "type OffsetPaginationParams = {\n offset: number;\n limit: number;\n};\n\ninterface Metadata {\n hasMore?: boolean;\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) => 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\n constructor(\n initialParams: Partial<OffsetPaginationParams>,\n fetchFn: FetchFn<T, M>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = {\n limit: initialParams.limit ?? 0,\n offset: initialParams.offset ?? 0,\n };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\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() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\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, S extends number | bigint> = {\n page?: P;\n pageSize?: S;\n};\n\ninterface Metadata {\n hasMore?: boolean;\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,\n S extends number | bigint,\n> = (input: Partial<PaginationParams<P, S>>) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class Pagination<\n T,\n M extends Metadata,\n P extends number | bigint,\n S extends number | bigint,\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\n constructor(\n initialParams: Partial<PaginationParams<P, S>>,\n fetchFn: FetchFn<T, M, P, S>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = { ...initialParams, page: initialParams.page };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\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() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\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 OpenAPIObject,\n ReferenceObject,\n RequestBodyObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { 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: OpenAPIObject;\n\n constructor(spec: OpenAPIObject) {\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 { 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 { isEmpty, pascalcase, resolveRef } 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 securityToOptions,\n} from '@sdk-it/spec';\n\nimport { SnippetEmitter } from './emitters/snippet.ts';\nimport { expandServerUrls } from './server-urls.ts';\nimport type { TypeScriptGeneratorOptions } from './options.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(\n this.#spec,\n requestBody,\n operation.parameters,\n operation.security ?? [],\n );\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 result = ${this.#toRequest(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\t\\tconsole.log(page);\\n}`,\n };\n case 'offset':\n return {\n content: `const result = ${this.#toRequest(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\t\\tconsole.log(page);\\n}`,\n };\n case 'cursor':\n return {\n content: `const result = ${this.#toRequest(entry, payload)}`,\n footer: `for await (const page of result) {\\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 return securityToOptions(\n this.#spec,\n this.#spec.security ?? [],\n this.#spec.components?.securitySchemes ?? {},\n );\n }\n\n client() {\n const options: Record<string, unknown> = {\n baseUrl: expandServerUrls(this.#spec.servers ?? [])[0] ?? 'http://localhost:3000',\n };\n\n const authOptions = this.#authentication();\n if (!isEmpty(authOptions)) {\n const [firstAuth] = authOptions;\n const optionName = firstAuth['x-optionName'] ?? firstAuth.name;\n options[optionName] = firstAuth.example;\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 = expandServerUrls(this.#spec.servers ?? [])[0] || 'https://api.example.com';\n\n // Use the existing authentication method to get auth options\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` | No | API base URL (default: `' +\n baseUrl +\n '`) |',\n );\n }\n\n // Add auth options using the existing authentication structure\n for (const authOption of authOptions) {\n const optionName = authOption['x-optionName'] ?? authOption.name;\n const description =\n authOption.in === 'header' && authOption.name === 'authorization'\n ? 'Bearer token for authentication'\n : `API key for authentication (${authOption.in}: ${authOption.name})`;\n\n sections.push(`| \\`${optionName}\\` | \\`string\\` | No | ${description} |`);\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();',\n '}',\n '',\n '// Or iterate through all pages automatically',\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 // Use the existing authentication method\n const authOptions = this.#authentication();\n\n if (isEmpty(authOptions)) {\n return '';\n }\n\n const sections: string[] = [];\n\n sections.push('## Authentication');\n sections.push('');\n\n // Adapt introduction based on number of auth methods\n if (authOptions.length === 1) {\n sections.push(\n 'The SDK requires authentication to access the API. Configure your client with the required credentials:',\n );\n } else {\n sections.push('The SDK supports the following authentication methods:');\n }\n sections.push('');\n\n for (const authOption of authOptions) {\n const optionName = authOption['x-optionName'] ?? authOption.name;\n const isBearer =\n authOption.in === 'header' && authOption.name === 'authorization';\n const isApiKey =\n authOption.in === 'header' && authOption.name !== 'authorization';\n const isQueryParam = authOption.in === 'query';\n\n // Determine heading level based on number of auth methods\n const headingLevel = authOptions.length === 1 ? '###' : '###';\n\n if (isBearer) {\n const authenticationHeading =\n authOptions.length === 1\n ? 'Bearer Token'\n : 'Bearer Token Authentication';\n sections.push(`${headingLevel} ${authenticationHeading}`);\n sections.push('');\n sections.push(\n 'Pass your bearer token directly - the \"Bearer\" prefix is automatically added:',\n );\n sections.push('');\n const bearerAuthClient = this.#constructClient({\n [optionName]: 'test_51234567890abcdef1234567890abcdef',\n });\n sections.push(createCodeBlock('typescript', [bearerAuthClient.use]));\n sections.push('');\n } else if (isApiKey) {\n const apiKeyHeading =\n authOptions.length === 1\n ? 'API Key (Header)'\n : 'API Key Authentication (Header)';\n sections.push(`${headingLevel} ${apiKeyHeading}`);\n sections.push('');\n const apiKeyAuthClient = this.#constructClient({\n [optionName]: 'test_api_key_1234567890abcdef1234567890abcdef',\n });\n sections.push(createCodeBlock('typescript', [apiKeyAuthClient.use]));\n sections.push('');\n } else if (isQueryParam) {\n const queryParamHeading =\n authOptions.length === 1\n ? 'API Key (Query Parameter)'\n : 'API Key Authentication (Query Parameter)';\n sections.push(`${headingLevel} ${queryParamHeading}`);\n sections.push('');\n const queryParamAuthClient = this.#constructClient({\n [optionName]: 'test_qp_key_1234567890abcdef1234567890abcdef',\n });\n sections.push(\n createCodeBlock('typescript', [queryParamAuthClient.use]),\n );\n sections.push('');\n } else {\n // Generic fallback\n const genericAuthHeading =\n authOptions.length === 1\n ? authOption.name\n : `${authOption.name} Authentication`;\n sections.push(`${headingLevel} ${genericAuthHeading}`);\n sections.push('');\n const genericAuthClient = this.#constructClient({\n [optionName]: 'test_auth_token_1234567890abcdef1234567890abcdef',\n });\n sections.push(createCodeBlock('typescript', [genericAuthClient.use]));\n sections.push('');\n }\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 const authOptionName = primaryAuth['x-optionName'] ?? primaryAuth.name;\n initialClientOptions[authOptionName] = 'YOUR_PRODUCTION_TOKEN';\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 const authOptionName = primaryAuth['x-optionName'] ?? primaryAuth.name;\n configurationUpdateCode.push(` ${authOptionName}: 'YOUR_STAGING_TOKEN'`);\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 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;AAE9B,SAAS,aAAAC,YAAW,cAAAC,mBAAkB;AAEtC,SAAS,SAAS,cAAAC,aAAY,eAAAC,oBAAmB;AACjD;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA,qBAAAC;AAAA,EACA;AAAA,OACK;;;ACrBP,SAAS,iBAAiB;AAE1B;AAAA,EAIE;AAAA,OACK;AAEA,SAAS,mBAAmB,IAAQ;AACzC,QAAM,SAQF,CAAC;AACL,mBAAiB,IAAI,CAAC,OAAO,cAAc;AACzC,UAAM,SAAS,GAAG,KAAK,KAAK,CAAC,QAAQ,IAAI,SAAS,MAAM,GAAG;AAC3D,QAAI,CAAC,QAAQ;AACX,cAAQ,KAAK,iCAAiC,MAAM,GAAG,EAAE;AACzD;AAAA,IACF;AAEA,WAAO,MAAM,GAAG,MAAM;AAAA,MACpB,OAAO,CAAC;AAAA,MACR,cAAc;AAAA,MACd,aAAa;AAAA,MACb,MAAM;AAAA,IACR;AACA,WAAO,MAAM,GAAG,EAAE,MAAM,KAAK,WAAW,OAAO,SAAS,CAAC;AACzD,WAAO,MAAM,GAAG,EAAE,eAAe,OAAO,gBAAgB;AACxD,WAAO,MAAM,GAAG,EAAE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;AAAA,UAChE;AAAA,QACF;AAAA,MACF;AACA,aAAO,KAAK,MAAM;AAAA,IACpB;AACA,WAAO,UAAUA,YAAW,IAAI,CAAC,KAAK,IACpC,CAAC,GAAG,SAAS,GAAG,MAAM,EAAE,KAAK,IAAI,IAAI;AAAA,EACzC;AAEA,QAAM,UAAU,UACb,QAAQ,EACR,OAAmB,CAAC,KAAK,CAAC,MAAM,MAAM,MAAM;AAC3C,UAAM,SAAS,CAAC,0BAA0B;AAC1C,UAAM,UAAU,gBAAgB,IAAI,MAAM,MAAM;AAChD,eAAWK,WAAU,eAAe;AAClC,YAAM,eAAe,IAAI,OAAO,MAAMA,OAAM,KAAK;AACjD,UAAI,aAAa,KAAK,OAAO,KAAKA,YAAW,MAAM;AACjD,eAAO;AAAA,UACL,YAAYA,OAAM,cAAc,WAAWL,YAAWK,OAAM,CAAC,CAAC;AAAA,QAChE;AAAA,MACF;AAAA,IACF;AACA,WAAO,KAAK,OAAO;AACnB,WAAO;AAAA,MACL,CAAC,kBAAkBL,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
6
|
"names": ["template", "join", "camelcase", "spinalcase", "pascalcase", "toLitObject", "sanitizeTag", "securityToOptions", "camelcase", "forEachOperation", "createTool", "tools", "followRef", "isRef", "parseRef", "pascalcase", "isPrimitiveSchema", "sanitizeTag", "appendOptional", "camelcase", "spinalcase", "followRef", "isEmpty", "isRef", "forEachOperation", "camelcase", "pascalcase", "sanitizeTag", "camelcase", "pascalcase", "sanitizeTag", "isEmpty", "forEachOperation", "camelcase", "spinalcase", "isRef", "followRef", "isEmpty", "forEachOperation", "followRef", "isRef", "lines", "forEachOperation", "isEmpty", "camelcase", "spinalcase", "isEmpty", "pascalcase", "resolveRef", "forEachOperation", "followRef", "isRef", "resolveRef", "pascalcase", "spinalcase", "isEmpty", "resolveRef", "camelcase", "forEachOperation", "security", "securityToOptions", "join", "pascalcase", "spinalcase", "template", "sanitizeTag", "camelcase", "toLitObject", "schema"]
|
|
7
7
|
}
|