@sdk-it/typescript 0.16.0 → 0.17.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 +391 -83
- package/dist/index.js.map +4 -4
- package/dist/lib/client.d.ts.map +1 -1
- package/dist/lib/emitters/zod.d.ts +1 -1
- package/dist/lib/emitters/zod.d.ts.map +1 -1
- package/dist/lib/generate.d.ts.map +1 -1
- package/dist/lib/generator.d.ts +1 -2
- package/dist/lib/generator.d.ts.map +1 -1
- package/dist/lib/sdk.d.ts.map +1 -1
- package/package.json +4 -3
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/generate.ts", "../src/lib/client.ts", "../src/lib/generator.ts", "../src/lib/emitters/zod.ts", "../src/lib/sdk.ts", "../src/lib/emitters/interface.ts", "../src/lib/utils.ts", "../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/send-request.txt", "../src/lib/watcher.ts"],
|
|
4
|
-
"sourcesContent": ["import { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { OpenAPIObject } from 'openapi3-ts/oas31';\nimport { spinalcase } from 'stringcase';\n\nimport { getFolderExports, methods, writeFiles } from '@sdk-it/core';\n\nimport backend from './client.ts';\nimport { generateCode } from './generator.ts';\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 sendRequest from './http/send-request.txt';\nimport { generateInputs } from './sdk.ts';\nimport { exclude, securityToOptions } from './utils.ts';\n\nfunction security(spec: OpenAPIObject) {\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(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(operation.security || [], securitySchemes, 'input'),\n );\n }\n }\n return options;\n}\n\nexport async function generate(\n spec: OpenAPIObject,\n settings: {\n style?: 'github';\n output: string;\n useTsExtension?: boolean;\n name?: string;\n /**\n * full: generate a full project including package.json and tsconfig.json. useful for monorepo/workspaces\n * minimal: generate only the client sdk\n */\n mode?: 'full' | 'minimal';\n formatCode?: (options: {\n output: string;\n env: ReturnType<typeof npmRunPathEnv>;\n }) => void | Promise<void>;\n },\n) {\n settings.useTsExtension ??= true;\n const makeImport = (moduleSpecifier: string) => {\n return settings.useTsExtension ? `${moduleSpecifier}.ts` : moduleSpecifier;\n };\n const { commonSchemas, endpoints, groups, outputs, commonZod, clientFiles } =\n generateCode({\n spec,\n style: 'github',\n makeImport,\n });\n const output =\n settings.mode === 'full' ? join(settings.output, 'src') : settings.output;\n const options = security(spec);\n const clientName = settings.name || 'Client';\n\n // const readme = generateReadme(spec, {\n // name: name,\n // });\n\n // FIXME: inputs, outputs should be generated before hand.\n const inputFiles = generateInputs(groups, commonZod, makeImport);\n\n await writeFiles(output, {\n 'outputs/.gitkeep': '',\n 'inputs/.gitkeep': '',\n 'models/.getkeep': '',\n // 'README.md': readme,\n });\n\n await writeFiles(join(output, 'http'), {\n 'interceptors.ts': interceptors,\n 'parse-response.ts': parseResponse,\n 'send-request.ts': `import z from 'zod';\nimport type { Interceptor } from './${makeImport('interceptors')}';\nimport { buffered } from './${makeImport('parse-response')}';\nimport { parse } from './${makeImport('parser')}';\nimport type { RequestConfig } from './${makeImport('request')}';\nimport { APIResponse } from './${makeImport('response')}';\n\n${sendRequest}`,\n 'response.ts': responseTxt,\n 'parser.ts': parserTxt,\n 'request.ts': requestTxt,\n });\n\n await writeFiles(join(output, 'outputs'), outputs);\n const modelsImports = Object.entries(commonSchemas).map(([name]) => name);\n await writeFiles(output, {\n 'client.ts': backend({\n name: clientName,\n servers: (spec.servers ?? []).map((server) => server.url) || [],\n options: options,\n makeImport,\n }),\n ...clientFiles,\n ...inputFiles,\n ...endpoints,\n ...Object.fromEntries(\n Object.entries(commonSchemas).map(([name, schema]) => [\n `models/${name}.ts`,\n [\n `import { z } from 'zod';`,\n ...exclude(modelsImports, [name]).map(\n (it) => `import type { ${it} } from './${it}.ts';`,\n ),\n `export type ${name} = ${schema};`,\n ].join('\\n'),\n ]),\n ),\n });\n\n const folders = [\n getFolderExports(join(output, 'outputs'), settings.useTsExtension),\n getFolderExports(\n join(output, 'inputs'),\n settings.useTsExtension,\n ['ts'],\n (dirent) => dirent.isDirectory() && ['schemas'].includes(dirent.name),\n ),\n getFolderExports(join(output, 'api'), settings.useTsExtension),\n getFolderExports(\n join(output, 'http'),\n settings.useTsExtension,\n ['ts'],\n (dirent) => dirent.name !== 'response.ts',\n ),\n ];\n if (modelsImports.length) {\n folders.push(\n getFolderExports(join(output, 'models'), settings.useTsExtension),\n );\n }\n const [outputIndex, inputsIndex, apiIndex, httpIndex, modelsIndex] =\n await Promise.all(folders);\n await writeFiles(output, {\n 'api/index.ts': apiIndex,\n 'outputs/index.ts': outputIndex,\n 'inputs/index.ts': inputsIndex || null,\n 'http/index.ts': httpIndex,\n ...(modelsImports.length ? { 'models/index.ts': modelsIndex } : {}),\n });\n await writeFiles(output, {\n 'index.ts': await getFolderExports(output, settings.useTsExtension, ['ts']),\n });\n if (settings.mode === 'full') {\n await writeFiles(settings.output, {\n 'package.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n name: settings.name\n ? `@${spinalcase(clientName.toLowerCase())}/sdk`\n : 'sdk',\n type: 'module',\n main: './src/index.ts',\n dependencies: {\n 'fast-content-type-parse': '^3.0.0',\n zod: '^3.24.2',\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 }\n\n await settings.formatCode?.({\n output: output,\n env: npmRunPathEnv(),\n });\n}\n", "import { toLitObject } from '@sdk-it/core';\n\nimport type { Spec } from './sdk.ts';\n\nexport default (spec: Omit<Spec, 'operations'>) => {\n const optionsEntries = Object.entries(spec.options).map(\n ([key, value]) => [`'${key}'`, value] as const,\n );\n const defaultHeaders = `{${optionsEntries\n .filter(([, value]) => value.in === 'header')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const defaultInputs = `{${optionsEntries\n .filter(([, value]) => value.in === 'input')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const specOptions: Record<string, { schema: string }> = {\n ...Object.fromEntries(\n optionsEntries.map(([key, value]) => [value.optionName ?? key, value]),\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 };\n\n return `\nimport { fetchType, sendRequest } from './http/${spec.makeImport('send-request')}';\nimport z from 'zod';\nimport type { Endpoints } from './api/${spec.makeImport('schemas')}';\nimport schemas from './api/${spec.makeImport('schemas')}';\nimport {\n createBaseUrlInterceptor,\n createHeadersInterceptor,\n} from './http/${spec.makeImport('interceptors')}';\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.infer<typeof optionsSchema>;\n\nexport class ${spec.name} {\n public options: ${spec.name}Options\n constructor(options: ${spec.name}Options) {\n this.options = optionsSchema.parse(options);\n }\n\n async request<E extends keyof Endpoints>(\n endpoint: E,\n input: Endpoints[E]['input'],\n options?: { signal?: AbortSignal, headers?: HeadersInit },\n ): Promise<readonly [Endpoints[E]['output'], Endpoints[E]['error'] | null]> {\n const route = schemas[endpoint];\n return sendRequest(Object.assign(this.#defaultInputs, input), route, {\n fetch: this.options.fetch,\n interceptors: [\n createHeadersInterceptor(() => this.defaultHeaders, options?.headers ?? {}),\n createBaseUrlInterceptor(() => this.options.baseUrl),\n ],\n signal: options?.signal,\n });\n }\n\n get defaultHeaders() {\n return ${defaultHeaders}\n }\n\n get #defaultInputs() {\n return ${defaultInputs}\n }\n\n setOptions(options: Partial<${spec.name}Options>) {\n const validated = optionsSchema.partial().parse(options);\n\n for (const key of Object.keys(validated) as (keyof ${spec.name}Options)[]) {\n if (validated[key] !== undefined) {\n (this.options[key] as typeof validated[typeof key]) = validated[key]!;\n }\n }\n }\n}`;\n};\n", "import { get, merge } from 'lodash-es';\nimport { join } from 'node:path';\nimport type {\n ContentObject,\n OpenAPIObject,\n ParameterLocation,\n ParameterObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { type GenerateSdkConfig, followRef, forEachOperation, isRef } from '@sdk-it/core';\n\nimport { ZodDeserialzer } from './emitters/zod.ts';\nimport {\n type Operation,\n type OperationInput,\n type Spec,\n toEndpoint,\n} from './sdk.ts';\nimport {\n importsToString,\n mergeImports,\n securityToOptions,\n useImports,\n} from './utils.ts';\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(\n config: GenerateSdkConfig & {\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n style?: 'github';\n makeImport: (module: string) => string;\n },\n) {\n const commonZod = new Map<string, string>();\n const commonZodImports: Import[] = [];\n const zodDeserialzer = new ZodDeserialzer(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 outputs: Record<string, string> = {};\n const endpoints: Record<string, ReturnType<typeof toEndpoint>[]> = {};\n\n forEachOperation(config, (entry, operation) => {\n console.log(`Processing ${entry.method} ${entry.path}`);\n\n groups[entry.groupName] ??= [];\n endpoints[entry.groupName] ??= [];\n const inputs: Operation['inputs'] = {};\n\n const additionalProperties: ParameterObject[] = [];\n for (const param of operation.parameters ?? []) {\n if (isRef(param)) {\n throw new Error(`Found reference in parameter ${param.$ref}`);\n }\n if (!param.schema) {\n throw new Error(`Schema not found for parameter ${param.name}`);\n }\n inputs[param.name] = {\n in: param.in,\n schema: '',\n };\n additionalProperties.push(param);\n }\n\n const security = operation.security ?? [];\n const securitySchemes = config.spec.components?.securitySchemes ?? {};\n const securityOptions = securityToOptions(security, securitySchemes);\n\n Object.assign(inputs, securityOptions);\n\n additionalProperties.push(\n ...Object.entries(securityOptions).map(\n ([name, value]) =>\n ({\n name: name,\n required: false,\n schema: {\n type: 'string',\n },\n in: value.in as ParameterLocation,\n }) satisfies ParameterObject,\n ),\n );\n\n const schemas: Record<string, string> = {};\n const shortContenTypeMap: Record<string, string> = {\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 };\n let outgoingContentType: string | undefined;\n if (operation.requestBody && Object.keys(operation.requestBody).length) {\n const content: ContentObject = isRef(operation.requestBody)\n ? get(followRef(config.spec, operation.requestBody.$ref), ['content'])\n : operation.requestBody.content;\n\n for (const type in content) {\n const ctSchema = isRef(content[type].schema)\n ? followRef(config.spec, content[type].schema.$ref)\n : content[type].schema;\n if (!ctSchema) {\n console.warn(`Schema not found for ${type}`);\n continue;\n }\n\n const schema = merge({}, ctSchema, {\n required: additionalProperties\n .filter((p) => p.required)\n .map((p) => p.name),\n properties: additionalProperties.reduce<Record<string, unknown>>(\n (acc, p) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n ),\n });\n\n Object.assign(inputs, bodyInputs(config, ctSchema));\n schemas[shortContenTypeMap[type]] = zodDeserialzer.handle(schema, true);\n }\n\n // TODO: each content type should create own endpoint or force content-type header to be set as third parameter\n // we can do the same for response that have multiple content types: force accept header to be set as third parameter\n // instead of prefixing the endpoint name with the content type\n if (content['application/json']) {\n outgoingContentType = 'json';\n } else if (content['application/x-www-form-urlencoded']) {\n outgoingContentType = 'urlencoded';\n } else if (content['multipart/form-data']) {\n outgoingContentType = 'formdata';\n } else {\n outgoingContentType = 'json';\n }\n } else {\n const properties = additionalProperties.reduce<Record<string, any>>(\n (acc, p) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n );\n schemas[shortContenTypeMap['application/json']] = zodDeserialzer.handle(\n {\n type: 'object',\n required: additionalProperties\n .filter((p) => p.required)\n .map((p) => p.name),\n properties,\n },\n true,\n );\n }\n\n const endpoint = toEndpoint(\n entry.groupName,\n config.spec,\n operation,\n {\n outgoingContentType,\n name: entry.name,\n type: 'http',\n trigger: entry,\n schemas,\n inputs,\n },\n { makeImport: config.makeImport },\n );\n\n const output = [`import z from 'zod';`];\n const responses = endpoint.responses.flatMap((it) => it.responses);\n const responsesImports = endpoint.responses.flatMap((it) =>\n Object.values(it.imports),\n );\n if (responses.length) {\n output.push(\n ...responses.map((it) => `export type ${it.name} = ${it.schema};`),\n );\n } else {\n output.push(`export type ${pascalcase(entry.name + ' output')} = void;`);\n }\n\n output.unshift(...useImports(output.join(''), ...responsesImports));\n\n outputs[`${spinalcase(entry.name)}.ts`] = output.join('\\n');\n\n endpoints[entry.groupName].push(endpoint);\n\n groups[entry.groupName].push({\n name: entry.name,\n type: 'http',\n inputs,\n outgoingContentType,\n schemas,\n trigger: entry,\n });\n });\n const commonSchemas = Object.values(endpoints).reduce<Record<string, string>>(\n (acc, endpoint) => ({\n ...acc,\n ...endpoint.reduce<Record<string, string>>(\n (acc, { responses }) => ({\n ...acc,\n ...responses.reduce<Record<string, string>>(\n (acc, it) => ({ ...acc, ...it.schemas }),\n {},\n ),\n }),\n {},\n ),\n }),\n {},\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 const imports = [\n 'import z from \"zod\";',\n `import type { ParseError } from '${config.makeImport('../http/parser')}';`,\n `import type { ServerError } from '${config.makeImport('../http/response')}';`,\n `import type { OutputType, Parser, Type } from '../http/send-request.ts';`,\n ];\n return {\n groups,\n commonSchemas,\n commonZod,\n outputs,\n clientFiles: {},\n endpoints: {\n [`${join('api', config.makeImport('schemas'))}`]: `\n${imports.join('\\n')}\n${allSchemas.map((it) => it.import).join('\\n')}\n\nconst schemas = {\\n${allSchemas.map((it) => it.use).join(',\\n')}\\n};\n\n\ntype Output<T extends OutputType> = T extends {\n parser: Parser;\n type: Type<any>;\n}\n ? InstanceType<T['type']>\n : T extends Type<any>\n ? InstanceType<T>\n : never;\n\nexport type Endpoints = {\n [K in keyof typeof schemas]: {\n input: z.infer<(typeof schemas)[K]['schema']>;\n output: (typeof schemas)[K]['output'] extends [\n infer Single extends OutputType,\n ]\n ? Output<Single>\n : (typeof schemas)[K]['output'] extends readonly [\n ...infer Tuple extends OutputType[],\n ]\n ? { [I in keyof Tuple]: Output<Tuple[I]> }[number]\n : never;\n error: ServerError | ParseError<(typeof schemas)[K]['schema']>;\n };\n};\n\nexport default schemas;\n\n\n`.trim(),\n ...Object.fromEntries(\n Object.entries(endpoints)\n .map(([name, endpoint]) => {\n const imps = importsToString(\n ...mergeImports(\n ...endpoint.flatMap((it) =>\n it.responses.flatMap((it) =>\n Object.values(it.endpointImports),\n ),\n ),\n ),\n );\n // const imports = endpoint.map((it) => it.imports).flat();\n return [\n [\n join('api', config.makeImport(spinalcase(name))),\n `${[\n ...imps,\n // ...imports,\n `import z from 'zod';`,\n `import { toRequest, json, urlencoded, nobody, formdata, createUrl } 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 ].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(\n config: GenerateSdkConfig,\n ctSchema: SchemaObject | ReferenceObject,\n) {\n const props: string[] = [];\n toProps(config.spec, ctSchema, props);\n return props.reduce<Record<string, OperationInput>>(\n (acc, prop) => ({\n ...acc,\n [prop]: {\n in: 'body',\n schema: '',\n },\n }),\n {},\n );\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef, parseRef } from '@sdk-it/core';\n\ntype OnRefCallback = (ref: string, content: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into a Zod schema string,\n * adapted for OpenAPI 3.1 (fully aligned with JSON Schema 2020-12).\n */\nexport class ZodDeserialzer {\n circularRefTracker = 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 * Handle objects (properties, additionalProperties).\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 /**\n * Handle arrays (items could be a single schema or a tuple (array of schemas)).\n * In JSON Schema 2020-12, `items` can be an array \u2192 tuple style.\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => z.array(z.unknown())\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})${appendOptional(required)}`;\n }\n\n #suffixes = (defaultValue: unknown, required: boolean, nullable: boolean) => {\n return `${nullable ? '.nullable()' : ''}${appendDefault(defaultValue)}${appendOptional(required)}`;\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 = cleanRef($ref).split('/').pop()!;\n\n if (this.circularRefTracker.has(schemaName)) {\n return schemaName;\n }\n\n this.circularRefTracker.add(schemaName);\n this.#onRef?.(\n schemaName,\n this.handle(followRef(this.#spec, $ref), required),\n );\n this.circularRefTracker.delete(schemaName);\n\n return schemaName;\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 #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 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) => {\n if (isRef(sub)) {\n const { model } = parseRef(sub.$ref);\n if (this.circularRefTracker.has(model)) {\n return `${model}${appendOptional(required)}`;\n }\n }\n return this.handle(sub, true);\n });\n if (oneOfSchemas.length === 1) {\n return `${oneOfSchemas[0]}${appendOptional(required)}`;\n }\n return `z.union([${oneOfSchemas.join(', ')}])${appendOptional(required)}`;\n }\n\n enum(values: any[]) {\n if (values.length === 1) {\n return `z.literal(${values.join(', ')})`;\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 switch (schema.format) {\n case 'date-time':\n case 'datetime':\n // parse to JS Date\n base = 'z.coerce.date()';\n break;\n case 'date':\n base =\n 'z.coerce.date() /* or z.string() if you want raw date strings */';\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) /* consider base64 check if needed */';\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(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\n/**\n * Append .optional() if not required\n */\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined || typeof defaultValue !== 'undefined'\n ? `.default(${defaultValue})`\n : '';\n}\n\n// Todo: convert openapi 3.0 to 3.1 before proccesing\n", "import { get } from 'lodash-es';\nimport type {\n OpenAPIObject,\n OperationObject,\n ReferenceObject,\n ResponseObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { followRef, isRef, toLitObject } from '@sdk-it/core';\n\nimport { TypeScriptDeserialzer } from './emitters/interface.ts';\nimport { type Import, type MakeImportFn } from './utils.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, any>;\n emptyBodyAsNull?: boolean;\n stripBodyFromGetAndHead?: boolean;\n output: string;\n}\n\nexport type Options = Record<\n string,\n {\n in: string;\n schema: string;\n optionName?: string;\n }\n>;\nexport interface Spec {\n name: string;\n options: Options;\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 name: string;\n type: string;\n trigger: Record<string, any>;\n schemas: Record<string, string>;\n inputs: Record<string, OperationInput>;\n outgoingContentType?: string;\n}\n\nexport function generateInputs(\n operationsSet: Spec['operations'],\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.name} 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 const inputContent = schema;\n\n for (const schema of commonImports) {\n if (inputContent.includes(schema)) {\n imports.add(\n `import { ${schema} } from './schemas/${makeImport(spinalcase(schema))}';`,\n );\n }\n }\n output.push(inputContent);\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\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\nexport function toEndpoint(\n groupName: string,\n spec: OpenAPIObject,\n specOperation: OperationObject,\n operation: Operation,\n utils: {\n makeImport: MakeImportFn;\n },\n) {\n const schemaName = camelcase(`${operation.name} schema`);\n const schemaRef = `${camelcase(groupName)}.${schemaName}`;\n\n const inputHeaders: string[] = [];\n const inputQuery: string[] = [];\n const inputBody: string[] = [];\n const inputParams: string[] = [];\n const schemas: string[] = [];\n const responses: ReturnType<typeof handleResponse>[] = [];\n for (const [name, prop] of Object.entries(operation.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 if (prop.in === 'internal') {\n // ignore internal sources\n continue;\n } else {\n throw new Error(\n `Unknown source ${prop.in} in ${name} ${JSON.stringify(\n prop,\n )} in ${operation.name}`,\n );\n }\n }\n\n specOperation.responses ??= {};\n const outputs: string[] = [];\n\n const statusesCount =\n Object.keys(specOperation.responses).filter((status) => {\n const statusCode = +status;\n return statusCode >= 200 && statusCode < 300;\n }).length > 1;\n for (const status in specOperation.responses) {\n const response = isRef(\n specOperation.responses[status] as ResponseObject | ReferenceObject,\n )\n ? (followRef(\n spec,\n specOperation.responses[status].$ref,\n ) as ResponseObject)\n : (specOperation.responses[status] as ResponseObject);\n const handled = handleResponse(\n spec,\n operation.name,\n status,\n response,\n utils,\n true,\n // statusesCount,\n );\n responses.push(handled);\n outputs.push(...handled.outputs);\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\n const endpoint = `${typePrefix}${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;\n\n schemas.push(\n `\"${endpoint}\": {\n schema: ${schemaRef}${addTypeParser ? `.${type}` : ''},\n output:[${outputs.join(',')}],\n toRequest(input: z.infer<typeof ${schemaRef}${addTypeParser ? `.${type}` : ''}>) {\n const endpoint = '${endpoint}';\n return toRequest(endpoint, ${operation.outgoingContentType || 'nobody'}(input, {\n inputHeaders: [${inputHeaders}],\n inputQuery: [${inputQuery}],\n inputBody: [${inputBody}],\n inputParams: [${inputParams}],\n }));\n },\n }`,\n );\n }\n return { responses, schemas };\n}\n\nconst statusCodeToResponseMap: Record<string, string> = {\n '200': 'Ok',\n '201': 'Created',\n '202': 'Accepted',\n '204': 'NoContent',\n '400': 'BadRequest',\n '401': 'Unauthorized',\n '402': 'PaymentRequired',\n '403': 'Forbidden',\n '404': 'NotFound',\n '405': 'MethodNotAllowed',\n '406': 'NotAcceptable',\n '409': 'Conflict',\n '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};\nfunction handleResponse(\n spec: OpenAPIObject,\n operationName: string,\n status: string,\n response: ResponseObject,\n utils: { makeImport: MakeImportFn },\n numbered: boolean,\n) {\n const schemas: Record<string, string> = {};\n const imports: Record<string, Import> = {};\n const endpointImports: Record<string, Import> = {\n ParseError: {\n defaultImport: undefined,\n isTypeOnly: false,\n moduleSpecifier: utils.makeImport(`../http/parser`),\n namedImports: [{ isTypeOnly: false, name: 'ParseError' }],\n namespaceImport: undefined,\n },\n };\n const responses: { name: string; schema: string }[] = [];\n const outputs: string[] = [];\n const typeScriptDeserialzer = new TypeScriptDeserialzer(\n spec,\n (schemaName, zod) => {\n schemas[schemaName] = zod;\n imports[schemaName] = {\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../models/${utils.makeImport(schemaName)}`,\n namedImports: [{ isTypeOnly: true, name: schemaName }],\n namespaceImport: undefined,\n };\n },\n );\n const statusCode = +status;\n const parser: Parser = (response.headers ?? {})['Transfer-Encoding']\n ? 'chunked'\n : 'buffered';\n const statusName = statusCodeToResponseMap[status] || 'APIResponse';\n const interfaceName = pascalcase(\n operationName + ` output${numbered ? status : ''}`,\n );\n\n if (statusCode === 204) {\n outputs.push(statusName);\n } else {\n if (status.endsWith('XX')) {\n outputs.push(`APIError<${interfaceName}>`);\n } else {\n outputs.push(\n parser !== 'buffered'\n ? `{type: ${statusName}<${interfaceName}>, parser: ${parser}}`\n : `${statusName}<${interfaceName}>`,\n );\n }\n }\n const responseContent = get(response, ['content']);\n const isJson = responseContent && responseContent['application/json'];\n const responseSchema = isJson\n ? typeScriptDeserialzer.handle(\n responseContent['application/json'].schema!,\n true,\n )\n : 'void';\n responses.push({\n name: interfaceName,\n schema: responseSchema,\n });\n const statusGroup = +status.slice(0, 1);\n if (statusCode >= 400 || statusGroup >= 4) {\n endpointImports[statusCodeToResponseMap[status] ?? 'APIError'] = {\n moduleSpecifier: utils.makeImport('../http/response'),\n namedImports: [{ name: statusCodeToResponseMap[status] ?? 'APIError' }],\n };\n\n endpointImports[interfaceName] = {\n isTypeOnly: true,\n moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n namedImports: [{ isTypeOnly: true, name: interfaceName }],\n };\n } else if (\n (statusCode >= 200 && statusCode < 300) ||\n statusCode >= 2 ||\n statusGroup <= 3\n ) {\n endpointImports[statusName] = {\n moduleSpecifier: utils.makeImport('../http/response'),\n namedImports: [\n {\n isTypeOnly: false,\n name: statusName,\n },\n ],\n };\n\n endpointImports[interfaceName] = {\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n namedImports: [{ isTypeOnly: true, name: interfaceName }],\n namespaceImport: undefined,\n };\n }\n return { schemas, imports, endpointImports, responses, outputs };\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef, parseRef } from '@sdk-it/core';\n\ntype OnRefCallback = (ref: string, interfaceContent: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into TypeScript interfaces,\n */\nexport class TypeScriptDeserialzer {\n circularRefTracker = 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 #stringifyKey = (key: string): string => {\n // List of JavaScript keywords and special object properties that should be quoted\n const reservedWords = [\n 'constructor',\n 'prototype',\n 'break',\n 'case',\n 'catch',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'else',\n 'export',\n 'extends',\n 'false',\n 'finally',\n 'for',\n 'function',\n 'if',\n 'import',\n 'in',\n 'instanceof',\n 'new',\n 'null',\n 'return',\n 'super',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'while',\n 'with',\n 'yield',\n ];\n\n // Check if key is a reserved word\n if (reservedWords.includes(key)) {\n return `'${key}'`;\n }\n\n // Check if key is empty or only whitespace\n if (key.trim() === '') {\n return `'${key}'`;\n }\n\n // Check if first character is valid for identifiers\n const firstChar = key.charAt(0);\n const validFirstChar =\n (firstChar >= 'a' && firstChar <= 'z') ||\n (firstChar >= 'A' && firstChar <= 'Z') ||\n firstChar === '_' ||\n firstChar === '$';\n\n if (!validFirstChar) {\n return `'${key.replace(/'/g, \"\\\\'\")}'`;\n }\n\n // Check if the rest of the characters are valid for identifiers\n for (let i = 1; i < key.length; i++) {\n const char = key.charAt(i);\n const validChar =\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n (char >= '0' && char <= '9') ||\n char === '_' ||\n char === '$';\n\n if (!validChar) {\n return `'${key.replace(/'/g, \"\\\\'\")}'`;\n }\n }\n\n return key;\n };\n #stringifyKeyV2 = (value: string): string => {\n return `'${value}'`;\n };\n\n /**\n * Handle objects (properties)\n */\n object(schema: SchemaObject, required = false): 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 const tsType = this.handle(propSchema, isRequired);\n // Add question mark for optional properties\n return `${this.#stringifyKeyV2(key)}: ${tsType}`;\n });\n\n // Handle additionalProperties\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.join('; ')} }`;\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}[]`;\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 = cleanRef($ref).split('/').pop()!;\n\n if (this.circularRefTracker.has(schemaName)) {\n return schemaName;\n }\n\n this.circularRefTracker.add(schemaName);\n this.#onRef?.(\n schemaName,\n this.handle(followRef(this.#spec, $ref), required),\n );\n this.circularRefTracker.delete(schemaName);\n\n return 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 anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n // For TypeScript we use union types for anyOf/oneOf\n const anyOfTypes = schemas.map((sub) => this.handle(sub, true));\n return appendOptional(\n anyOfTypes.length > 1 ? `${anyOfTypes.join(' | ')}` : anyOfTypes[0],\n required,\n );\n }\n\n oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n const oneOfTypes = schemas.map((sub) => {\n if (isRef(sub)) {\n const { model } = parseRef(sub.$ref);\n if (this.circularRefTracker.has(model)) {\n return model;\n }\n }\n return this.handle(sub, false);\n });\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n\n enum(values: any[], 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 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 // 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 /**\n * Generate an interface declaration\n */\n generateInterface(\n name: string,\n schema: SchemaObject | ReferenceObject,\n ): string {\n const content = this.handle(schema, true);\n return `interface ${name} ${content}`;\n }\n}\n\n/**\n * Append \"| undefined\" if not required\n */\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\n}\n", "import type {\n ComponentsObject,\n SecurityRequirementObject,\n} from 'openapi3-ts/oas31';\n\nimport { isRef, removeDuplicates } from '@sdk-it/core';\n\nimport { type Options } from './sdk.ts';\n\nexport function securityToOptions(\n security: SecurityRequirementObject[],\n securitySchemes: ComponentsObject['securitySchemes'],\n staticIn?: string,\n) {\n securitySchemes ??= {};\n const options: Options = {};\n for (const it of security) {\n const [name] = Object.keys(it);\n if (!name) {\n // this means the operation doesn't necessarily require security\n continue;\n }\n const schema = securitySchemes[name];\n if (isRef(schema)) {\n throw new Error(`Ref security schemas are not supported`);\n }\n if (schema.type === 'http') {\n options['authorization'] = {\n in: staticIn ?? 'header',\n schema:\n 'z.string().optional().transform((val) => (val ? `Bearer ${val}` : undefined))',\n optionName: 'token',\n };\n continue;\n }\n if (schema.type === 'apiKey') {\n if (!schema.in) {\n throw new Error(`apiKey security schema must have an \"in\" field`);\n }\n if (!schema.name) {\n throw new Error(`apiKey security schema must have a \"name\" field`);\n }\n options[schema.name] = {\n in: staticIn ?? schema.in,\n schema: 'z.string().optional()',\n };\n continue;\n }\n }\n return options;\n}\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 exclude<T>(list: T[], exclude: T[]): T[] {\n return list.filter((it) => !exclude.includes(it));\n}\n\nexport function useImports(content: string, ...imports: Import[]) {\n const output: string[] = [];\n for (const it of mergeImports(...imports)) {\n const singleImport = it.defaultImport ?? it.namespaceImport;\n if (singleImport && content.includes(singleImport)) {\n output.push(importsToString(it).join('\\n'));\n } else if (it.namedImports.length) {\n for (const namedImport of it.namedImports) {\n if (content.includes(namedImport.name)) {\n output.push(importsToString(it).join('\\n'));\n }\n }\n }\n }\n return output;\n}\n\nexport type MakeImportFn = (moduleSpecifier: string) => string;\n", "import { type RequestConfig } from './request.ts';\n\nexport interface Interceptor {\n before?: (config: RequestConfig) => Promise<RequestConfig>|RequestConfig;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nexport const createHeadersInterceptor = (\n defaultHeaders: () => 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 const headers = defaultHeaders();\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 = (\n getBaseUrl: () => string,\n): Interceptor => {\n return {\n before({ init, url }) {\n const baseUrl = getBaseUrl();\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.dir('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\nexport async function handleError(response: Response) {\n\ttry {\n\t\tif (response.status >= 400 && response.status < 500) {\n\t\t\tconst body = (await response.json()) as Record<string, any>;\n\t\t\treturn {\n\t\t\t\tstatus: response.status,\n\t\t\t\tbody: body,\n\t\t\t};\n\t\t}\n\t\treturn new Error(\n\t\t\t`An error occurred while fetching the data. Status: ${response.status}`,\n\t\t);\n\t} catch (error) {\n\t\treturn error as any;\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\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>> {\n public data: z.typeToFlattenedError<T, z.ZodIssue>;\n constructor(data: z.typeToFlattenedError<T, z.ZodIssue>) {\n this.data = data;\n }\n}\n\nexport function parse<T extends z.ZodType<any, any, any>>(schema: T, input: unknown) {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = result.error.flatten((issue) => issue);\n return [null, new ParseError(error)];\n }\n return [result.data as z.infer<T>, null];\n}\n", "type Init = Omit<RequestInit, 'headers'> & { headers: Headers; };\nexport type RequestConfig = { init: Init; url: URL };\nexport type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\nexport type ContentType = 'xml' | 'json' | 'urlencoded' | 'multipart' | 'formdata';\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\nexport function createUrl(path: string, query: URLSearchParams) {\n const url = new URL(path, `local://`);\n url.search = query.toString();\n return url;\n}\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(\n input: Input,\n props: Props,\n ) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(): Serialized {\n const headers = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\n }\n\n const query = new URLSearchParams();\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n query.set(key, String(value));\n }\n }\n\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\n return {\n body: this.getBody(),\n query,\n params,\n headers: this.getHeaders(),\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n query: URLSearchParams;\n params: Record<string, any>;\n headers: Record<string, string>;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\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 }\n}\n\nclass NoBodySerializer 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 }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props).serialize();\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props).serialize();\n}\nexport function nobody(input: Input, props: Props) {\n return new NoBodySerializer(input, props).serialize();\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props).serialize();\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n input: Serialized,\n): RequestConfig {\n const [method, path] = endpoint.split(' ');\n const pathVariable = template(path, input.params);\n\n return {\n url: createUrl(pathVariable, input.query),\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 status: number;\n status: Status;\n data: Body;\n\n constructor(status: Status, data: Body) {\n this.status = status;\n this.data = data;\n }\n}\n\nexport class APIError<Body, Status extends number = number> extends APIResponse<\n Body,\n Status\n> {}\n\n// 2xx Success\nexport class Ok<T> extends APIResponse<T, 200> {\n static status = 200;\n}\nexport class Created<T> extends APIResponse<T, 201> {}\nexport class Accepted<T> extends APIResponse<T, 202> {}\nexport class NoContent extends APIResponse<null, 204> {}\n\n// 4xx Client Errors\nexport class BadRequest<T> extends APIError<T, 400> {}\nexport class Unauthorized<T = { message: string }> extends APIError<T, 401> {}\nexport class PaymentRequired<T = { message: string }> extends APIError<\n T,\n 402\n> {}\nexport class Forbidden<T = { message: string }> extends APIError<T, 403> {}\nexport class NotFound<T = { message: string }> extends APIError<T, 404> {}\nexport class MethodNotAllowed<T = { message: string }> extends APIError<\n T,\n 405\n> {}\nexport class NotAcceptable<T = { message: string }> extends APIError<T, 406> {}\nexport class Conflict<T = { message: string }> extends APIError<T, 409> {}\nexport class Gone<T = { message: string }> extends APIError<T, 410> {}\nexport class UnprocessableEntity<\n T = { message: string; errors?: Record<string, string[]> },\n> extends APIError<T, 422> {}\nexport class TooManyRequests<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 429> {}\nexport class PayloadTooLarge<T = { message: string }> extends APIError<\n T,\n 413\n> {}\nexport class UnsupportedMediaType<T = { message: string }> extends APIError<\n T,\n 415\n> {}\n\n// 5xx Server Errors\nexport class InternalServerError<T = { message: string }> extends APIError<\n T,\n 500\n> {}\nexport class NotImplemented<T = { message: string }> extends APIError<T, 501> {}\nexport class BadGateway<T = { message: string }> extends APIError<T, 502> {}\nexport class ServiceUnavailable<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 503> {}\nexport class GatewayTimeout<T = { message: string }> extends APIError<T, 504> {}\n\nexport type ClientError =\n | BadRequest<{ message: string }>\n | Unauthorized\n | PaymentRequired\n | Forbidden\n | NotFound\n | MethodNotAllowed\n | NotAcceptable\n | Conflict\n | Gone\n | UnprocessableEntity\n | TooManyRequests;\n\nexport type ServerError =\n | InternalServerError\n | NotImplemented\n | BadGateway\n | ServiceUnavailable\n | GatewayTimeout;\n\nexport type ProblematicResponse = ClientError | ServerError;\n", "export 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> };\ntype Constructor<T> = new (...args: any[]) => T;\nexport interface RequestSchema {\n schema: z.ZodType;\n toRequest: (input: any) => RequestConfig;\n output: OutputType[];\n}\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 sendRequest(\n input: unknown,\n route: RequestSchema,\n options: {\n fetch?: z.infer<typeof fetchType>;\n interceptors?: Interceptor[];\n signal?: AbortSignal;\n },\n) {\n const { interceptors = [] } = options;\n const [parsedInput, parseError] = parse(route.schema, input);\n if (parseError) {\n return [null as never, { ...parseError, kind: 'parse' } as never] as const;\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\n let response = await (options.fetch ?? fetch)(\n new Request(config.url, config.init),\n {\n ...config.init,\n signal: options.signal,\n },\n );\n\n for (let i = interceptors.length - 1; i >= 0; i--) {\n const interceptor = interceptors[i];\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n\n let output: Constructor<APIResponse> | null = APIResponse;\n let parser: Parser = buffered;\n for (const outputType of route.output) {\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 const data = new output(response.status, await parser(response));\n if (response.ok) {\n return [data as never, null] as const;\n }\n return [null as never, data as never] as const;\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", "import { watch as nodeWatch } from 'node:fs/promises';\nimport { debounceTime, from } from 'rxjs';\n\nexport function watch(path: string) {\n return from(\n nodeWatch(path, {\n persistent: true,\n recursive: true,\n }),\n ).pipe(debounceTime(400));\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,QAAAA,aAAY;AACrB,SAAS,qBAAqB;AAE9B,SAAS,cAAAC,mBAAkB;AAE3B,SAAS,kBAAkB,SAAS,kBAAkB;;;ACLtD,SAAS,mBAAmB;AAI5B,IAAO,iBAAQ,CAAC,SAAmC;AACjD,QAAM,iBAAiB,OAAO,QAAQ,KAAK,OAAO,EAAE;AAAA,IAClD,CAAC,CAAC,KAAK,KA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AE,KAAK,aAAa,GAAG,CAAC;AAC1B;",
|
|
6
|
-
"names": ["join", "spinalcase", "
|
|
3
|
+
"sources": ["../src/lib/generate.ts", "../src/lib/client.ts", "../src/lib/generator.ts", "../../spec/src/lib/operation.ts", "../src/lib/emitters/zod.ts", "../src/lib/sdk.ts", "../src/lib/emitters/interface.ts", "../src/lib/utils.ts", "../src/lib/styles/github/endpoints.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/send-request.txt", "../src/lib/watcher.ts"],
|
|
4
|
+
"sourcesContent": ["import { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { OpenAPIObject } from 'openapi3-ts/oas31';\nimport { spinalcase } from 'stringcase';\n\nimport { getFolderExports, methods, writeFiles } from '@sdk-it/core';\n\nimport backend from './client.ts';\nimport { generateCode } from './generator.ts';\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 sendRequest from './http/send-request.txt';\nimport { generateInputs } from './sdk.ts';\nimport { exclude, securityToOptions } from './utils.ts';\n\nfunction security(spec: OpenAPIObject) {\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(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(operation.security || [], securitySchemes, 'input'),\n );\n }\n }\n return options;\n}\n\nexport async function generate(\n spec: OpenAPIObject,\n settings: {\n style?: 'github';\n output: string;\n useTsExtension?: boolean;\n name?: string;\n /**\n * full: generate a full project including package.json and tsconfig.json. useful for monorepo/workspaces\n * minimal: generate only the client sdk\n */\n mode?: 'full' | 'minimal';\n formatCode?: (options: {\n output: string;\n env: ReturnType<typeof npmRunPathEnv>;\n }) => void | Promise<void>;\n },\n) {\n settings.useTsExtension ??= true;\n const makeImport = (moduleSpecifier: string) => {\n return settings.useTsExtension ? `${moduleSpecifier}.ts` : moduleSpecifier;\n };\n const { commonSchemas, endpoints, groups, outputs, commonZod } = generateCode(\n {\n spec,\n style: 'github',\n makeImport,\n },\n );\n const output =\n settings.mode === 'full' ? join(settings.output, 'src') : settings.output;\n const options = security(spec);\n const clientName = settings.name || 'Client';\n\n // const readme = generateReadme(spec, {\n // name: name,\n // });\n\n // FIXME: inputs, outputs should be generated before hand.\n const inputFiles = generateInputs(groups, commonZod, makeImport);\n\n await writeFiles(output, {\n 'outputs/.gitkeep': '',\n 'inputs/.gitkeep': '',\n 'models/.getkeep': '',\n // 'README.md': readme,\n });\n\n await writeFiles(join(output, 'http'), {\n 'interceptors.ts': `\n import { type RequestConfig } from './${makeImport('request')}';\n ${interceptors}`,\n 'parse-response.ts': parseResponse,\n 'send-request.ts': `import z from 'zod';\nimport type { Interceptor } from './${makeImport('interceptors')}';\nimport { buffered } from './${makeImport('parse-response')}';\nimport { parseInput } from './${makeImport('parser')}';\nimport type { RequestConfig } from './${makeImport('request')}';\nimport { APIError, APIResponse } from './${makeImport('response')}';\n\n${sendRequest}`,\n 'response.ts': responseTxt,\n 'parser.ts': parserTxt,\n 'request.ts': requestTxt,\n });\n\n await writeFiles(join(output, 'outputs'), outputs);\n const modelsImports = Object.entries(commonSchemas).map(([name]) => name);\n await writeFiles(output, {\n 'client.ts': backend({\n name: clientName,\n servers: (spec.servers ?? []).map((server) => server.url) || [],\n options: options,\n makeImport,\n }),\n ...inputFiles,\n ...endpoints,\n ...Object.fromEntries(\n Object.entries(commonSchemas).map(([name, schema]) => [\n `models/${name}.ts`,\n [\n `import { z } from 'zod';`,\n ...exclude(modelsImports, [name]).map(\n (it) => `import type { ${it} } from './${it}.ts';`,\n ),\n `export type ${name} = ${schema};`,\n ].join('\\n'),\n ]),\n ),\n });\n\n const folders = [\n getFolderExports(join(output, 'outputs'), settings.useTsExtension),\n getFolderExports(\n join(output, 'inputs'),\n settings.useTsExtension,\n ['ts'],\n (dirent) => dirent.isDirectory() && ['schemas'].includes(dirent.name),\n ),\n getFolderExports(join(output, 'api'), settings.useTsExtension),\n getFolderExports(\n join(output, 'http'),\n settings.useTsExtension,\n ['ts'],\n (dirent) => dirent.name !== 'response.ts',\n ),\n ];\n if (modelsImports.length) {\n folders.push(\n getFolderExports(join(output, 'models'), settings.useTsExtension),\n );\n }\n const [outputIndex, inputsIndex, apiIndex, httpIndex, modelsIndex] =\n await Promise.all(folders);\n await writeFiles(output, {\n 'api/index.ts': apiIndex,\n 'outputs/index.ts': outputIndex,\n 'inputs/index.ts': inputsIndex || null,\n 'http/index.ts': httpIndex,\n ...(modelsImports.length ? { 'models/index.ts': modelsIndex } : {}),\n });\n await writeFiles(output, {\n 'index.ts': await getFolderExports(output, settings.useTsExtension, ['ts']),\n });\n if (settings.mode === 'full') {\n await writeFiles(settings.output, {\n 'package.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n name: settings.name\n ? `@${spinalcase(clientName.toLowerCase())}/sdk`\n : 'sdk',\n type: 'module',\n main: './src/index.ts',\n dependencies: {\n 'fast-content-type-parse': '^3.0.0',\n zod: '^3.24.2',\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 }\n\n await settings.formatCode?.({\n output: output,\n env: npmRunPathEnv(),\n });\n}\n", "import { toLitObject } from '@sdk-it/core';\n\nimport type { Spec } from './sdk.ts';\n\nexport default (spec: Omit<Spec, 'operations'>) => {\n const optionsEntries = Object.entries(spec.options).map(\n ([key, value]) => [`'${key}'`, value] as const,\n );\n const defaultHeaders = `{${optionsEntries\n .filter(([, value]) => value.in === 'header')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const defaultInputs = `{${optionsEntries\n .filter(([, value]) => value.in === 'input')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const specOptions: Record<string, { schema: string }> = {\n ...Object.fromEntries(\n optionsEntries.map(([key, value]) => [value.optionName ?? key, value]),\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 };\n\n return `\nimport type { RequestConfig } from './http/${spec.makeImport('request')}';\nimport { fetchType, sendRequest, parse } from './http/${spec.makeImport('send-request')}';\nimport z from 'zod';\nimport type { Endpoints } from './api/${spec.makeImport('endpoints')}';\nimport schemas from './api/${spec.makeImport('schemas')}';\nimport {\n createBaseUrlInterceptor,\n createHeadersInterceptor,\n} from './http/${spec.makeImport('interceptors')}';\n\nimport { parseInput, type ParseError } 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.infer<typeof optionsSchema>;\n\nexport class ${spec.name} {\n public options: ${spec.name}Options\n constructor(options: ${spec.name}Options) {\n this.options = optionsSchema.parse(options);\n }\n\n async request<E extends keyof Endpoints>(\n endpoint: E,\n input: Endpoints[E]['input'],\n options?: { signal?: AbortSignal, headers?: HeadersInit },\n ): Promise<readonly [Endpoints[E]['output'], Endpoints[E]['error'] | null]> {\n const route = schemas[endpoint];\n return sendRequest(Object.assign(this.#defaultInputs, input), route, {\n fetch: this.options.fetch,\n interceptors: [\n createHeadersInterceptor(() => this.defaultHeaders, options?.headers ?? {}),\n createBaseUrlInterceptor(() => this.options.baseUrl),\n ],\n signal: options?.signal,\n });\n }\n\n async prepare<E extends keyof Endpoints>(\n endpoint: E,\n input: Endpoints[E]['input'],\n options?: { headers?: HeadersInit },\n ): Promise<\n readonly [\n RequestConfig & {\n parse: (response: Response) => ReturnType<typeof parse>;\n },\n ParseError<(typeof schemas)[E]['schema']> | null,\n ]\n > {\n const route = schemas[endpoint];\n\n const interceptors = [\n createHeadersInterceptor(\n () => this.defaultHeaders,\n options?.headers ?? {},\n ),\n createBaseUrlInterceptor(() => this.options.baseUrl),\n ];\n const [parsedInput, parseError] = parseInput(route.schema, input);\n if (parseError) {\n return [null as never, parseError as never] as const;\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 [\n { ...config, parse: (response: Response) => parse(route, response) },\n null as never,\n ] as const;\n }\n\n get defaultHeaders() {\n return ${defaultHeaders}\n }\n\n get #defaultInputs() {\n return ${defaultInputs}\n }\n\n setOptions(options: Partial<${spec.name}Options>) {\n const validated = optionsSchema.partial().parse(options);\n\n for (const key of Object.keys(validated) as (keyof ${spec.name}Options)[]) {\n if (validated[key] !== undefined) {\n (this.options[key] as typeof validated[typeof key]) = validated[key]!;\n }\n }\n }\n}`;\n};\n", "import { merge } from 'lodash-es';\nimport { join } from 'node:path';\nimport type {\n OpenAPIObject,\n ParameterLocation,\n ParameterObject,\n ReferenceObject,\n RequestBodyObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { followRef, isEmpty, isRef } from '@sdk-it/core';\nimport {\n type GenerateSdkConfig,\n forEachOperation,\n} from '@sdk-it/spec/operation.js';\n\nimport { ZodDeserialzer } from './emitters/zod.ts';\nimport {\n type Operation,\n type OperationInput,\n type Spec,\n toEndpoint,\n} from './sdk.ts';\nimport endpointsTxt from './styles/github/endpoints.txt';\nimport {\n importsToString,\n mergeImports,\n securityToOptions,\n useImports,\n} from './utils.ts';\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(\n config: GenerateSdkConfig & {\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n style?: 'github';\n makeImport: (module: string) => string;\n },\n) {\n const commonZod = new Map<string, string>();\n const commonZodImports: Import[] = [];\n const zodDeserialzer = new ZodDeserialzer(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 outputs: Record<string, string> = {};\n const endpoints: Record<string, ReturnType<typeof toEndpoint>[]> = {};\n\n forEachOperation(config, (entry, operation) => {\n console.log(`Processing ${entry.method} ${entry.path}`);\n groups[entry.groupName] ??= [];\n endpoints[entry.groupName] ??= [];\n const inputs: Operation['inputs'] = {};\n\n const additionalProperties: ParameterObject[] = [];\n for (const param of operation.parameters ?? []) {\n if (isRef(param)) {\n throw new Error(`Found reference in parameter ${param.$ref}`);\n }\n if (!param.schema) {\n throw new Error(`Schema not found for parameter ${param.name}`);\n }\n inputs[param.name] = {\n in: param.in,\n schema: '',\n };\n additionalProperties.push(param);\n }\n\n const security = operation.security ?? [];\n const securitySchemes = config.spec.components?.securitySchemes ?? {};\n const securityOptions = securityToOptions(security, securitySchemes);\n\n Object.assign(inputs, securityOptions);\n\n additionalProperties.push(\n ...Object.entries(securityOptions).map(\n ([name, value]) =>\n ({\n name: name,\n required: false,\n schema: {\n type: 'string',\n },\n in: value.in as ParameterLocation,\n }) satisfies ParameterObject,\n ),\n );\n\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 let outgoingContentType: string | undefined;\n\n if (!isEmpty(operation.requestBody)) {\n const requestBody = isRef(operation.requestBody)\n ? followRef<RequestBodyObject>(config.spec, operation.requestBody.$ref)\n : operation.requestBody;\n\n for (const type in requestBody.content) {\n const ctSchema = isRef(requestBody.content[type].schema)\n ? followRef(config.spec, requestBody.content[type].schema.$ref)\n : requestBody.content[type].schema;\n if (!ctSchema) {\n console.warn(\n `Schema not found for ${type} in ${entry.method} ${entry.path}`,\n );\n continue;\n }\n\n let objectSchema = ctSchema;\n if (objectSchema.type !== 'object') {\n objectSchema = {\n type: 'object',\n required: [requestBody.required ? '$body' : ''],\n properties: {\n $body: ctSchema,\n },\n };\n }\n\n const schema = merge({}, objectSchema, {\n required: additionalProperties\n .filter((p) => p.required)\n .map((p) => p.name),\n properties: additionalProperties.reduce<Record<string, unknown>>(\n (acc, p) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n ),\n });\n\n Object.assign(inputs, bodyInputs(config, objectSchema));\n schemas[shortContenTypeMap[type]] = zodDeserialzer.handle(schema, true);\n }\n\n // TODO: each content type should create own endpoint or force content-type header to be set as third parameter\n // we can do the same for response that have multiple content types: force accept header to be set as third parameter\n // instead of prefixing the endpoint name with the content type\n if (requestBody.content['application/json']) {\n outgoingContentType = 'json';\n } else if (requestBody.content['application/x-www-form-urlencoded']) {\n outgoingContentType = 'urlencoded';\n } else if (requestBody.content['multipart/form-data']) {\n outgoingContentType = 'formdata';\n } else {\n outgoingContentType = 'json';\n }\n } else {\n const properties = additionalProperties.reduce<Record<string, any>>(\n (acc, p) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n );\n schemas[shortContenTypeMap['application/json']] = zodDeserialzer.handle(\n {\n type: 'object',\n required: additionalProperties\n .filter((p) => p.required)\n .map((p) => p.name),\n properties,\n },\n true,\n );\n }\n\n const endpoint = toEndpoint(\n entry.groupName,\n config.spec,\n operation,\n {\n outgoingContentType,\n name: operation.operationId,\n type: 'http',\n trigger: entry,\n schemas,\n inputs,\n },\n { makeImport: config.makeImport },\n );\n\n const output = [`import z from 'zod';`];\n const responses = endpoint.responses.flatMap((it) => it.responses);\n const responsesImports = endpoint.responses.flatMap((it) =>\n Object.values(it.imports),\n );\n if (responses.length) {\n output.push(\n ...responses.map((it) => `export type ${it.name} = ${it.schema};`),\n );\n } else {\n output.push(\n `export type ${pascalcase(operation.operationId + ' output')} = void;`,\n );\n }\n\n output.unshift(...useImports(output.join(''), ...responsesImports));\n\n outputs[`${spinalcase(operation.operationId)}.ts`] = output.join('\\n');\n\n endpoints[entry.groupName].push(endpoint);\n\n groups[entry.groupName].push({\n name: operation.operationId,\n type: 'http',\n inputs,\n outgoingContentType,\n schemas,\n trigger: entry,\n });\n });\n const commonSchemas = Object.values(endpoints).reduce<Record<string, string>>(\n (acc, endpoint) => ({\n ...acc,\n ...endpoint.reduce<Record<string, string>>(\n (acc, { responses }) => ({\n ...acc,\n ...responses.reduce<Record<string, string>>(\n (acc, it) => ({ ...acc, ...it.schemas }),\n {},\n ),\n }),\n {},\n ),\n }),\n {},\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 const imports = [\n 'import z from \"zod\";',\n `import type { ParseError } from '${config.makeImport('../http/parser')}';`,\n `import type { ServerError } from '${config.makeImport('../http/response')}';`,\n `import type { OutputType, Parser, Type } from '../http/send-request.ts';`,\n ];\n return {\n groups,\n commonSchemas,\n commonZod,\n outputs,\n endpoints: {\n [join('api', 'endpoints.ts')]: `\n\n\nimport type z from 'zod';\nimport type { ParseError } from '${config.makeImport('../http/parser')}';\nimport type { ProblematicResponse, SuccessfulResponse } from '${config.makeImport(\n '../http/response',\n )}';\nimport type { OutputType, Parser, Type } from '${config.makeImport(\n '../http/send-request',\n )}';\n\nimport schemas from '${config.makeImport('./schemas')}';\n\n ${endpointsTxt}`,\n [`${join('api', 'schemas.ts')}`]:\n `${allSchemas.map((it) => it.import).join('\\n')}\n\nexport default {\\n${allSchemas.map((it) => it.use).join(',\\n')}\\n};\n\n`.trim(),\n ...Object.fromEntries(\n Object.entries(endpoints)\n .map(([name, endpoint]) => {\n const imps = importsToString(\n ...mergeImports(\n ...endpoint.flatMap((it) =>\n it.responses.flatMap((it) =>\n Object.values(it.endpointImports),\n ),\n ),\n ),\n );\n // const imports = endpoint.map((it) => it.imports).flat();\n return [\n [\n join('api', `${spinalcase(name)}.ts`),\n `${[\n ...imps,\n // ...imports,\n `import z from 'zod';`,\n `import { toRequest, json, urlencoded, nobody, formdata, createUrl } 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 ].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(\n config: GenerateSdkConfig,\n ctSchema: SchemaObject | ReferenceObject,\n) {\n const props: string[] = [];\n toProps(config.spec, ctSchema, props);\n return props.reduce<Record<string, OperationInput>>(\n (acc, prop) => ({\n ...acc,\n [prop]: {\n in: 'body',\n schema: '',\n },\n }),\n {},\n );\n}\n", "import type {\n OpenAPIObject,\n OperationObject,\n ParameterObject,\n ReferenceObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nexport const defaults: Partial<GenerateSdkConfig> &\n Required<Pick<GenerateSdkConfig, 'operationId' | 'tag'>> = {\n operationId: (operation, path, method) => {\n if (operation.operationId) {\n return camelcase(operation.operationId);\n }\n const metadata = operation['x-oaiMeta'];\n if (metadata && metadata.name) {\n return camelcase(metadata.name);\n }\n return camelcase(\n [method, ...path.replace(/[\\\\/\\\\{\\\\}]/g, ' ').split(' ')]\n .filter(Boolean)\n .join(' ')\n .trim(),\n );\n },\n tag: (operation, path) => {\n return operation.tags?.[0] || determineGenericTag(path, operation);\n },\n};\n\nexport type TunedOperationObject = OperationObject & {\n operationId: string;\n parameters: (ParameterObject | ReferenceObject)[];\n};\n\nexport interface OperationEntry {\n name?: string;\n method: string;\n path: string;\n groupName: string;\n tag: string;\n}\nexport type Operation = {\n entry: OperationEntry;\n operation: TunedOperationObject;\n};\n\nexport function forEachOperation<T>(\n config: GenerateSdkConfig,\n callback: (entry: OperationEntry, operation: TunedOperationObject) => T,\n) {\n const result: T[] = [];\n for (const [path, pathItem] of Object.entries(config.spec.paths ?? {})) {\n const { parameters = [], ...methods } = pathItem;\n\n // Convert Express-style routes (:param) to OpenAPI-style routes ({param})\n const fixedPath = path.replace(/:([^/]+)/g, '{$1}');\n\n for (const [method, operation] of Object.entries(methods) as [\n string,\n OperationObject,\n ][]) {\n const formatOperationId = config.operationId ?? defaults.operationId;\n const formatTag = config.tag ?? defaults.tag;\n const operationName = formatOperationId(operation, fixedPath, method);\n const operationTag = formatTag(operation, fixedPath);\n const metadata = operation['x-oaiMeta'] ?? {};\n result.push(\n callback(\n {\n name: metadata.name,\n method,\n path: fixedPath,\n groupName: operationTag,\n tag: operationTag,\n },\n {\n ...operation,\n parameters: [...parameters, ...(operation.parameters ?? [])],\n operationId: operationName,\n },\n ),\n );\n }\n }\n return result;\n}\n\nexport interface GenerateSdkConfig {\n spec: OpenAPIObject;\n operationId?: (\n operation: OperationObject,\n path: string,\n method: string,\n ) => string;\n tag?: (operation: OperationObject, path: string) => string;\n}\n\n// --- Function Definition (determineGenericTag, sanitizeTag, reservedKeywords, commonVerbs) ---\n/**\n * Set of reserved TypeScript keywords and common verbs potentially used as tags.\n */\nconst reservedKeywords = new Set([\n 'abstract',\n 'arguments',\n 'await',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n // Potentially problematic identifiers / Common Verbs used as tags\n 'object',\n 'string',\n 'number',\n 'any',\n 'unknown',\n 'never',\n 'get',\n 'list',\n 'create',\n 'update',\n 'delete',\n 'post',\n 'put',\n 'patch',\n 'do',\n 'send',\n 'add',\n 'remove',\n 'set',\n 'find',\n 'search',\n 'check',\n 'make', // Added make, check\n]);\n\n/**\n * Sanitizes a potential tag name (assumed to be already camelCased)\n * to avoid conflicts with reserved keywords or invalid starting characters (numbers).\n * Appends an underscore if the tag matches a reserved keyword.\n * Prepends an underscore if the tag starts with a number.\n * @param camelCasedTag The potential tag name, already camelCased.\n * @returns The sanitized tag name.\n */\nfunction sanitizeTag(camelCasedTag: string): string {\n // Prepend underscore if starts with a number\n if (/^\\d/.test(camelCasedTag)) {\n return `_${camelCasedTag}`;\n }\n // Append underscore if it's a reserved keyword\n return reservedKeywords.has(camelCasedTag)\n ? `${camelCasedTag}_`\n : camelCasedTag;\n}\n\n/**\n * Attempts to determine a generic tag for an OpenAPI operation based on path and operationId.\n * Rules and fallbacks are documented within the code.\n * @param pathString The path string.\n * @param operation The OpenAPI Operation Object.\n * @returns A sanitized, camelCased tag name string.\n */\nexport function determineGenericTag(\n pathString: string,\n operation: OperationObject,\n): string {\n const operationId = operation.operationId || '';\n const VERSION_REGEX = /^[vV]\\d+$/;\n const commonVerbs = new Set([\n // Verbs to potentially strip from operationId prefix\n 'get',\n 'list',\n 'create',\n 'update',\n 'delete',\n 'post',\n 'put',\n 'patch',\n 'do',\n 'send',\n 'add',\n 'remove',\n 'set',\n 'find',\n 'search',\n 'check',\n 'make', // Added make\n ]);\n\n const segments = pathString.split('/').filter(Boolean);\n\n const potentialCandidates = segments.filter(\n (segment) =>\n segment &&\n !segment.startsWith('{') &&\n !segment.endsWith('}') &&\n !VERSION_REGEX.test(segment),\n );\n\n // --- Heuristic 1: Last non-'@' path segment ---\n for (let i = potentialCandidates.length - 1; i >= 0; i--) {\n const segment = potentialCandidates[i];\n if (!segment.startsWith('@')) {\n // Sanitize just before returning\n return sanitizeTag(camelcase(segment));\n }\n }\n\n const canFallbackToPathSegment = potentialCandidates.length > 0;\n\n // --- Heuristic 2: OperationId parsing ---\n if (operationId) {\n const lowerOpId = operationId.toLowerCase();\n const parts = operationId\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')\n .replace(/([a-zA-Z])(\\d)/g, '$1_$2')\n .replace(/(\\d)([a-zA-Z])/g, '$1_$2')\n .toLowerCase()\n .split(/[_-\\s]+/);\n\n const validParts = parts.filter(Boolean);\n\n // Quick skip: If opId is just a verb and we can use Heuristic 3, prefer that.\n if (\n commonVerbs.has(lowerOpId) &&\n validParts.length === 1 &&\n canFallbackToPathSegment\n ) {\n // Proceed directly to Heuristic 3\n }\n // Only process if there are valid parts and the quick skip didn't happen\n else if (validParts.length > 0) {\n const firstPart = validParts[0];\n const isFirstPartVerb = commonVerbs.has(firstPart);\n\n // Case 2a: Starts with verb, has following parts\n if (isFirstPartVerb && validParts.length > 1) {\n const verbPrefixLength = firstPart.length;\n let nextPartStartIndex = -1;\n if (operationId.length > verbPrefixLength) {\n // Simplified check for next part start\n const charAfterPrefix = operationId[verbPrefixLength];\n if (charAfterPrefix >= 'A' && charAfterPrefix <= 'Z') {\n nextPartStartIndex = verbPrefixLength;\n } else if (charAfterPrefix >= '0' && charAfterPrefix <= '9') {\n nextPartStartIndex = verbPrefixLength;\n } else if (['_', '-'].includes(charAfterPrefix)) {\n nextPartStartIndex = verbPrefixLength + 1;\n } else {\n const match = operationId\n .substring(verbPrefixLength)\n .match(/[A-Z0-9]/);\n if (match && match.index !== undefined) {\n nextPartStartIndex = verbPrefixLength + match.index;\n }\n if (\n nextPartStartIndex === -1 &&\n operationId.length > verbPrefixLength\n ) {\n nextPartStartIndex = verbPrefixLength; // Default guess\n }\n }\n }\n\n if (\n nextPartStartIndex !== -1 &&\n nextPartStartIndex < operationId.length\n ) {\n const remainingOriginalSubstring =\n operationId.substring(nextPartStartIndex);\n const potentialTag = camelcase(remainingOriginalSubstring);\n if (potentialTag) {\n // Sanitize just before returning\n return sanitizeTag(potentialTag);\n }\n }\n\n // Fallback: join remaining lowercased parts\n const potentialTagJoined = camelcase(validParts.slice(1).join('_'));\n if (potentialTagJoined) {\n // Sanitize just before returning\n return sanitizeTag(potentialTagJoined);\n }\n }\n\n // Case 2b: Doesn't start with verb, or only one part (might be verb)\n const potentialTagFull = camelcase(operationId);\n if (potentialTagFull) {\n const isResultSingleVerb = validParts.length === 1 && isFirstPartVerb;\n\n // Avoid returning only a verb if Heuristic 3 is possible\n if (!(isResultSingleVerb && canFallbackToPathSegment)) {\n if (potentialTagFull.length > 0) {\n // Sanitize just before returning\n return sanitizeTag(potentialTagFull);\n }\n }\n }\n\n // Case 2c: Further fallbacks within OpId if above failed/skipped\n const firstPartCamel = camelcase(firstPart);\n if (firstPartCamel) {\n const isFirstPartCamelVerb = commonVerbs.has(firstPartCamel);\n if (\n !isFirstPartCamelVerb ||\n validParts.length === 1 ||\n !canFallbackToPathSegment\n ) {\n // Sanitize just before returning\n return sanitizeTag(firstPartCamel);\n }\n }\n if (\n isFirstPartVerb &&\n validParts.length > 1 &&\n validParts[1] &&\n canFallbackToPathSegment\n ) {\n const secondPartCamel = camelcase(validParts[1]);\n if (secondPartCamel) {\n // Sanitize just before returning\n return sanitizeTag(secondPartCamel);\n }\n }\n } // End if(validParts.length > 0) after quick skip check\n } // End if(operationId)\n\n // --- Heuristic 3: First path segment (stripping '@') ---\n if (potentialCandidates.length > 0) {\n let firstCandidate = potentialCandidates[0];\n if (firstCandidate.startsWith('@')) {\n firstCandidate = firstCandidate.substring(1);\n }\n if (firstCandidate) {\n // Sanitize just before returning\n return sanitizeTag(camelcase(firstCandidate));\n }\n }\n\n // --- Heuristic 4: Default ---\n console.warn(\n `Could not determine a suitable tag for path: ${pathString}, operationId: ${operationId}. Using 'unknown'.`,\n );\n return 'unknown'; // 'unknown' is safe\n}\n\nexport function parseJsonContentType(contentType: string | null | undefined) {\n if (!contentType) {\n return null;\n }\n\n // 1. Trim whitespace\n let mainType = contentType.trim();\n\n // 2. Remove parameters (anything after the first ';')\n const semicolonIndex = mainType.indexOf(';');\n if (semicolonIndex !== -1) {\n mainType = mainType.substring(0, semicolonIndex).trim(); // Trim potential space before ';'\n }\n\n // 3. Convert to lowercase for case-insensitive comparison\n mainType = mainType.toLowerCase();\n\n if (mainType.endsWith('/json')) {\n return mainType.split('/')[1];\n } else if (mainType.endsWith('+json')) {\n return mainType.split('+')[1];\n }\n return null;\n}\n\n/**\n * Checks if a given content type string represents Server-Sent Events (SSE).\n * Handles case-insensitivity, parameters (like charset), and leading/trailing whitespace.\n *\n * @param contentType The content type string to check (e.g., from a Content-Type header).\n * @returns True if the content type is 'text/event-stream', false otherwise.\n */\nexport function isSseContentType(\n contentType: string | null | undefined,\n): boolean {\n if (!contentType) {\n return false; // Handle null, undefined, or empty string\n }\n\n // 1. Trim whitespace from the input string\n let mainType = contentType.trim();\n\n // 2. Find the position of the first semicolon (if any) to remove parameters\n const semicolonIndex = mainType.indexOf(';');\n if (semicolonIndex !== -1) {\n // Extract the part before the semicolon and trim potential space\n mainType = mainType.substring(0, semicolonIndex).trim();\n }\n\n // 3. Convert the main type part to lowercase for case-insensitive comparison\n mainType = mainType.toLowerCase();\n\n // 4. Compare against the standard SSE MIME type\n return mainType === 'text/event-stream';\n}\n\nexport function isStreamingContentType(\n contentType: string | null | undefined,\n): boolean {\n return contentType === 'application/octet-stream';\n}\n\nexport function isSuccessStatusCode(statusCode: number | string): boolean {\n statusCode = Number(statusCode);\n return statusCode >= 200 && statusCode < 300;\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef, parseRef } from '@sdk-it/core';\n\ntype OnRefCallback = (ref: string, content: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into a Zod schema string,\n * adapted for OpenAPI 3.1 (fully aligned with JSON Schema 2020-12).\n */\nexport class ZodDeserialzer {\n circularRefTracker = 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 * Handle objects (properties, additionalProperties).\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 /**\n * Handle arrays (items could be a single schema or a tuple (array of schemas)).\n * In JSON Schema 2020-12, `items` can be an array \u2192 tuple style.\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => z.array(z.unknown())\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})${appendOptional(required)}`;\n }\n\n #suffixes = (defaultValue: unknown, required: boolean, nullable: boolean) => {\n return `${nullable ? '.nullable()' : ''}${appendDefault(defaultValue)}${appendOptional(required)}`;\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 = cleanRef($ref).split('/').pop()!;\n\n if (this.circularRefTracker.has(schemaName)) {\n return schemaName;\n }\n\n this.circularRefTracker.add(schemaName);\n this.#onRef?.(\n schemaName,\n this.handle(followRef<SchemaObject>(this.#spec, $ref), required),\n );\n this.circularRefTracker.delete(schemaName);\n\n return schemaName;\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 #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 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) => {\n if (isRef(sub)) {\n const { model } = parseRef(sub.$ref);\n if (this.circularRefTracker.has(model)) {\n return `${model}${appendOptional(required)}`;\n }\n }\n return this.handle(sub, true);\n });\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 switch (schema.format) {\n case 'date-time':\n case 'datetime':\n // parse to JS Date\n base = 'z.coerce.date()';\n break;\n case 'date':\n base =\n 'z.coerce.date() /* or z.string() if you want raw date strings */';\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\n/**\n * Append .optional() if not required\n */\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined || typeof defaultValue !== 'undefined'\n ? `.default(${defaultValue})`\n : '';\n}\n\n// Todo: convert openapi 3.0 to 3.1 before proccesing\n", "import { get } from 'lodash-es';\nimport type {\n OpenAPIObject,\n OperationObject,\n ReferenceObject,\n ResponseObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { followRef, isRef, toLitObject } from '@sdk-it/core';\n\nimport { TypeScriptDeserialzer } from './emitters/interface.ts';\nimport { type Import, type MakeImportFn } from './utils.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, any>;\n emptyBodyAsNull?: boolean;\n stripBodyFromGetAndHead?: boolean;\n output: string;\n}\n\nexport type Options = Record<\n string,\n {\n in: string;\n schema: string;\n optionName?: string;\n }\n>;\nexport interface Spec {\n name: string;\n options: Options;\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 name: string;\n type: string;\n trigger: Record<string, any>;\n schemas: Record<string, string>;\n inputs: Record<string, OperationInput>;\n outgoingContentType?: string;\n}\n\nexport function generateInputs(\n operationsSet: Spec['operations'],\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.name} 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 const inputContent = schema;\n\n for (const schema of commonImports) {\n if (inputContent.includes(schema)) {\n imports.add(\n `import { ${schema} } from './schemas/${makeImport(spinalcase(schema))}';`,\n );\n }\n }\n output.push(inputContent);\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\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\nexport function toEndpoint(\n groupName: string,\n spec: OpenAPIObject,\n specOperation: OperationObject,\n operation: Operation,\n utils: {\n makeImport: MakeImportFn;\n },\n) {\n const schemaName = camelcase(`${operation.name} schema`);\n const schemaRef = `${camelcase(groupName)}.${schemaName}`;\n\n const inputHeaders: string[] = [];\n const inputQuery: string[] = [];\n const inputBody: string[] = [];\n const inputParams: string[] = [];\n const schemas: string[] = [];\n const responses: ReturnType<typeof handleResponse>[] = [];\n for (const [name, prop] of Object.entries(operation.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 if (prop.in === 'internal') {\n // ignore internal sources\n continue;\n } else {\n throw new Error(\n `Unknown source ${prop.in} in ${name} ${JSON.stringify(\n prop,\n )} in ${operation.name}`,\n );\n }\n }\n\n specOperation.responses ??= {};\n const outputs: string[] = [];\n\n const statusesCount =\n Object.keys(specOperation.responses).filter((status) => {\n const statusCode = +status;\n return statusCode >= 200 && statusCode < 300;\n }).length > 1;\n for (const status in specOperation.responses) {\n const response = isRef(specOperation.responses[status] as ReferenceObject)\n ? followRef<ResponseObject>(spec, specOperation.responses[status].$ref)\n : (specOperation.responses[status] as ResponseObject);\n const handled = handleResponse(\n spec,\n operation.name,\n status,\n response,\n utils,\n true,\n // statusesCount,\n );\n responses.push(handled);\n outputs.push(...handled.outputs);\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\n const endpoint = `${typePrefix}${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;\n\n schemas.push(\n `\"${endpoint}\": {\n schema: ${schemaRef}${addTypeParser ? `.${type}` : ''},\n output:[${outputs.join(',')}],\n toRequest(input: z.infer<typeof ${schemaRef}${addTypeParser ? `.${type}` : ''}>) {\n const endpoint = '${endpoint}';\n return toRequest(endpoint, ${operation.outgoingContentType || 'nobody'}(input, {\n inputHeaders: [${inputHeaders}],\n inputQuery: [${inputQuery}],\n inputBody: [${inputBody}],\n inputParams: [${inputParams}],\n }));\n },\n }`,\n );\n }\n return { responses, schemas };\n}\n\nconst statusCodeToResponseMap: Record<string, string> = {\n '200': 'Ok',\n '201': 'Created',\n '202': 'Accepted',\n '204': 'NoContent',\n '400': 'BadRequest',\n '401': 'Unauthorized',\n '402': 'PaymentRequired',\n '403': 'Forbidden',\n '404': 'NotFound',\n '405': 'MethodNotAllowed',\n '406': 'NotAcceptable',\n '409': 'Conflict',\n '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};\nfunction handleResponse(\n spec: OpenAPIObject,\n operationName: string,\n status: string,\n response: ResponseObject,\n utils: { makeImport: MakeImportFn },\n numbered: boolean,\n) {\n const schemas: Record<string, string> = {};\n const imports: Record<string, Import> = {};\n const endpointImports: Record<string, Import> = {\n ParseError: {\n defaultImport: undefined,\n isTypeOnly: false,\n moduleSpecifier: utils.makeImport(`../http/parser`),\n namedImports: [{ isTypeOnly: false, name: 'ParseError' }],\n namespaceImport: undefined,\n },\n };\n const responses: { name: string; schema: string }[] = [];\n const outputs: string[] = [];\n const typeScriptDeserialzer = new TypeScriptDeserialzer(\n spec,\n (schemaName, zod) => {\n schemas[schemaName] = zod;\n imports[schemaName] = {\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../models/${utils.makeImport(schemaName)}`,\n namedImports: [{ isTypeOnly: true, name: schemaName }],\n namespaceImport: undefined,\n };\n },\n );\n const statusCode = +status;\n const parser: Parser = (response.headers ?? {})['Transfer-Encoding']\n ? 'chunked'\n : 'buffered';\n const statusName = statusCodeToResponseMap[status] || 'APIResponse';\n const interfaceName = pascalcase(\n operationName + ` output${numbered ? status : ''}`,\n );\n\n if (statusCode === 204) {\n outputs.push(statusName);\n } else {\n if (status.endsWith('XX')) {\n outputs.push(`APIError<${interfaceName}>`);\n } else {\n outputs.push(\n parser !== 'buffered'\n ? `{type: ${statusName}<${interfaceName}>, parser: ${parser}}`\n : `${statusName}<${interfaceName}>`,\n );\n }\n }\n const responseContent = get(response, ['content']);\n const isJson = responseContent && responseContent['application/json'];\n const responseSchema = isJson\n ? typeScriptDeserialzer.handle(\n responseContent['application/json'].schema!,\n true,\n )\n : 'void';\n responses.push({\n name: interfaceName,\n schema: responseSchema,\n });\n const statusGroup = +status.slice(0, 1);\n if (statusCode >= 400 || statusGroup >= 4) {\n endpointImports[statusCodeToResponseMap[status] ?? 'APIError'] = {\n moduleSpecifier: utils.makeImport('../http/response'),\n namedImports: [{ name: statusCodeToResponseMap[status] ?? 'APIError' }],\n };\n\n endpointImports[interfaceName] = {\n isTypeOnly: true,\n moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n namedImports: [{ isTypeOnly: true, name: interfaceName }],\n };\n } else if (\n (statusCode >= 200 && statusCode < 300) ||\n statusCode >= 2 ||\n statusGroup <= 3\n ) {\n endpointImports[statusName] = {\n moduleSpecifier: utils.makeImport('../http/response'),\n namedImports: [\n {\n isTypeOnly: false,\n name: statusName,\n },\n ],\n };\n\n endpointImports[interfaceName] = {\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n namedImports: [{ isTypeOnly: true, name: interfaceName }],\n namespaceImport: undefined,\n };\n }\n return { schemas, imports, endpointImports, responses, outputs };\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef, parseRef } from '@sdk-it/core';\n\ntype OnRefCallback = (ref: string, interfaceContent: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into TypeScript interfaces,\n */\nexport class TypeScriptDeserialzer {\n circularRefTracker = 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 #stringifyKey = (key: string): string => {\n // List of JavaScript keywords and special object properties that should be quoted\n const reservedWords = [\n 'constructor',\n 'prototype',\n 'break',\n 'case',\n 'catch',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'else',\n 'export',\n 'extends',\n 'false',\n 'finally',\n 'for',\n 'function',\n 'if',\n 'import',\n 'in',\n 'instanceof',\n 'new',\n 'null',\n 'return',\n 'super',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'while',\n 'with',\n 'yield',\n ];\n\n // Check if key is a reserved word\n if (reservedWords.includes(key)) {\n return `'${key}'`;\n }\n\n // Check if key is empty or only whitespace\n if (key.trim() === '') {\n return `'${key}'`;\n }\n\n // Check if first character is valid for identifiers\n const firstChar = key.charAt(0);\n const validFirstChar =\n (firstChar >= 'a' && firstChar <= 'z') ||\n (firstChar >= 'A' && firstChar <= 'Z') ||\n firstChar === '_' ||\n firstChar === '$';\n\n if (!validFirstChar) {\n return `'${key.replace(/'/g, \"\\\\'\")}'`;\n }\n\n // Check if the rest of the characters are valid for identifiers\n for (let i = 1; i < key.length; i++) {\n const char = key.charAt(i);\n const validChar =\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n (char >= '0' && char <= '9') ||\n char === '_' ||\n char === '$';\n\n if (!validChar) {\n return `'${key.replace(/'/g, \"\\\\'\")}'`;\n }\n }\n\n return key;\n };\n #stringifyKeyV2 = (value: string): string => {\n return `'${value}'`;\n };\n\n /**\n * Handle objects (properties)\n */\n object(schema: SchemaObject, required = false): 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 const tsType = this.handle(propSchema, isRequired);\n // Add question mark for optional properties\n return `${this.#stringifyKeyV2(key)}: ${tsType}`;\n });\n\n // Handle additionalProperties\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.join('; ')} }`;\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}[]`;\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 = cleanRef($ref).split('/').pop()!;\n\n if (this.circularRefTracker.has(schemaName)) {\n return schemaName;\n }\n\n this.circularRefTracker.add(schemaName);\n this.#onRef?.(\n schemaName,\n this.handle(followRef<SchemaObject>(this.#spec, $ref), required),\n );\n this.circularRefTracker.delete(schemaName);\n\n return 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 anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n // For TypeScript we use union types for anyOf/oneOf\n const anyOfTypes = schemas.map((sub) => this.handle(sub, true));\n return appendOptional(\n anyOfTypes.length > 1 ? `${anyOfTypes.join(' | ')}` : anyOfTypes[0],\n required,\n );\n }\n\n oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n const oneOfTypes = schemas.map((sub) => {\n if (isRef(sub)) {\n const { model } = parseRef(sub.$ref);\n if (this.circularRefTracker.has(model)) {\n return model;\n }\n }\n return this.handle(sub, false);\n });\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n\n enum(values: any[], 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 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 // 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 /**\n * Generate an interface declaration\n */\n generateInterface(\n name: string,\n schema: SchemaObject | ReferenceObject,\n ): string {\n const content = this.handle(schema, true);\n return `interface ${name} ${content}`;\n }\n}\n\n/**\n * Append \"| undefined\" if not required\n */\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\n}\n", "import type {\n ComponentsObject,\n SecurityRequirementObject,\n} from 'openapi3-ts/oas31';\n\nimport { isRef, removeDuplicates } from '@sdk-it/core';\n\nimport { type Options } from './sdk.ts';\n\nexport function securityToOptions(\n security: SecurityRequirementObject[],\n securitySchemes: ComponentsObject['securitySchemes'],\n staticIn?: string,\n) {\n securitySchemes ??= {};\n const options: Options = {};\n for (const it of security) {\n const [name] = Object.keys(it);\n if (!name) {\n // this means the operation doesn't necessarily require security\n continue;\n }\n const schema = securitySchemes[name];\n if (isRef(schema)) {\n throw new Error(`Ref security schemas are not supported`);\n }\n if (schema.type === 'http') {\n options['authorization'] = {\n in: staticIn ?? 'header',\n schema:\n 'z.string().optional().transform((val) => (val ? `Bearer ${val}` : undefined))',\n optionName: 'token',\n };\n continue;\n }\n if (schema.type === 'apiKey') {\n if (!schema.in) {\n throw new Error(`apiKey security schema must have an \"in\" field`);\n }\n if (!schema.name) {\n throw new Error(`apiKey security schema must have a \"name\" field`);\n }\n options[schema.name] = {\n in: staticIn ?? schema.in,\n schema: 'z.string().optional()',\n };\n continue;\n }\n }\n return options;\n}\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 exclude<T>(list: T[], exclude: T[]): T[] {\n return list.filter((it) => !exclude.includes(it));\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", "\ntype Output<T extends OutputType> = T extends {\n parser: Parser;\n type: Type<unknown>;\n}\n ? InstanceType<T['type']>\n : T extends Type<unknown>\n ? InstanceType<T>\n : never;\n\ntype Unionize<T> = T extends [infer Single extends OutputType]\n ? Output<Single>\n : T extends readonly [...infer Tuple extends OutputType[]]\n ? { [I in keyof Tuple]: Output<Tuple[I]> }[number]\n : never;\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 [K in keyof typeof schemas]: {\n input: z.infer<(typeof schemas)[K]['schema']>;\n output: EndpointOutput<K>;\n error: EndpointError<K> | ParseError<(typeof schemas)[K]['schema']>;\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 defaultHeaders: () => 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 const headers = defaultHeaders();\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 = (\n getBaseUrl: () => string,\n): Interceptor => {\n return {\n before({ init, url }) {\n const baseUrl = getBaseUrl();\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.dir('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>> {\n public data: z.typeToFlattenedError<T, z.ZodIssue>;\n constructor(data: z.typeToFlattenedError<T, z.ZodIssue>) {\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType<any, any, any>>(\n schema: T,\n input: unknown,\n) {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = result.error.flatten((issue) => issue);\n return [null, new ParseError(error)];\n }\n return [result.data as z.infer<T>, null];\n}\n", "type Init = Omit<RequestInit, 'headers'> & { headers: Headers; };\nexport type RequestConfig = { init: Init; url: URL };\nexport type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';\nexport type ContentType = 'xml' | 'json' | 'urlencoded' | 'multipart' | 'formdata';\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\nexport function createUrl(path: string, query: URLSearchParams) {\n const url = new URL(path, `local://`);\n url.search = query.toString();\n return url;\n}\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(\n input: Input,\n props: Props,\n ) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(): Serialized {\n const headers = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\n }\n\n const query = new URLSearchParams();\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n query.set(key, String(value));\n }\n }\n\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\n return {\n body: this.getBody(),\n query,\n params,\n headers: this.getHeaders(),\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n query: URLSearchParams;\n params: Record<string, any>;\n headers: Record<string, string>;\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 NoBodySerializer 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).serialize();\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props).serialize();\n}\nexport function nobody(input: Input, props: Props) {\n return new NoBodySerializer(input, props).serialize();\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props).serialize();\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n input: Serialized,\n): RequestConfig {\n const [method, path] = endpoint.split(' ');\n const pathVariable = template(path, input.params);\n\n return {\n url: createUrl(pathVariable, input.query),\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 status: number;\n status: Status;\n data: Body;\n\n constructor(status: Status, data: Body) {\n this.status = status;\n this.data = data;\n }\n\n static create<Body = unknown>(status: number, data: Body) {\n return new this(status, 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, data: T) {\n return new this(status, data);\n }\n}\n\n// 2xx Success\nexport class Ok<T> extends APIResponse<T, 200> {\n static override status = 200 as const;\n constructor(data: T) {\n super(Ok.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class Created<T> extends APIResponse<T, 201> {\n static override status = 201 as const;\n constructor(data: T) {\n super(Created.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class Accepted<T> extends APIResponse<T, 202> {\n static override status = 202 as const;\n constructor(data: T) {\n super(Accepted.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class NoContent extends APIResponse<never, 204> {\n static override status = 204 as const;\n constructor() {\n super(NoContent.status, null as never);\n }\n static override create(status: number, data: never): NoContent {\n return new this();\n }\n}\n\n// 4xx Client Errors\nexport class BadRequest<T> extends APIError<T, 400> {\n static override status = 400 as const;\n constructor(data: T) {\n super(BadRequest.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class Unauthorized<T = { message: string }> extends APIError<T, 401> {\n static override status = 401 as const;\n constructor(data: T) {\n super(Unauthorized.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class PaymentRequired<T = { message: string }> extends APIError<T, 402> {\n static override status = 402 as const;\n constructor(data: T) {\n super(PaymentRequired.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class Forbidden<T = { message: string }> extends APIError<T, 403> {\n static override status = 403 as const;\n constructor(data: T) {\n super(Forbidden.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class NotFound<T = { message: string }> extends APIError<T, 404> {\n static override status = 404 as const;\n constructor(data: T) {\n super(NotFound.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(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(data: T) {\n super(MethodNotAllowed.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class NotAcceptable<T = { message: string }> extends APIError<T, 406> {\n static override status = 406 as const;\n constructor(data: T) {\n super(NotAcceptable.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class Conflict<T = { message: string }> extends APIError<T, 409> {\n static override status = 409 as const;\n constructor(data: T) {\n super(Conflict.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class Gone<T = { message: string }> extends APIError<T, 410> {\n static override status = 410 as const;\n constructor(data: T) {\n super(Gone.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(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(data: T) {\n super(UnprocessableEntity.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(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(data: T) {\n super(TooManyRequests.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {\n static override status = 413 as const;\n constructor(data: T) {\n super(PayloadTooLarge.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(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(data: T) {\n super(UnsupportedMediaType.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(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(data: T) {\n super(InternalServerError.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class NotImplemented<T = { message: string }> extends APIError<T, 501> {\n static override status = 501 as const;\n constructor(data: T) {\n super(NotImplemented.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class BadGateway<T = { message: string }> extends APIError<T, 502> {\n static override status = 502 as const;\n constructor(data: T) {\n super(BadGateway.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(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(data: T) {\n super(ServiceUnavailable.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\nexport class GatewayTimeout<T = { message: string }> extends APIError<T, 504> {\n static override status = 504 as const;\n constructor(data: T) {\n super(GatewayTimeout.status, data);\n }\n static override create<T>(status: number, data: T) {\n return new this(data);\n }\n}\n\nexport type ClientError =\n | BadRequest<{ message: string }>\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 | 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 = Ok<unknown> | Created<unknown> | Accepted<unknown> | NoContent;", "export 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 interface RequestSchema {\n schema: z.ZodType;\n toRequest: (input: any) => RequestConfig;\n output: OutputType[];\n}\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 sendRequest(\n input: unknown,\n route: RequestSchema,\n options: {\n fetch?: z.infer<typeof fetchType>;\n interceptors?: Interceptor[];\n signal?: AbortSignal;\n },\n) {\n const { interceptors = [] } = options;\n const [parsedInput, parseError] = parseInput(route.schema, input);\n if (parseError) {\n return [null as never, parseError as never] as const;\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\n let response = await (options.fetch ?? fetch)(\n new Request(config.url, config.init),\n {\n ...config.init,\n signal: options.signal,\n },\n );\n\n for (let i = interceptors.length - 1; i >= 0; i--) {\n const interceptor = interceptors[i];\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n return await parse(route, response);\n}\n\nexport async function parse(route: RequestSchema, response: Response) {\n let output: typeof APIResponse | null = null;\n let parser: Parser = buffered;\n for (const outputType of route.output) {\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 data = (output || APIResponse).create(\n response.status,\n await parser(response),\n );\n return [data as never, null] as const;\n }\n const data = (output || APIError).create(\n response.status,\n await parser(response),\n );\n return [null as never, data as never] as const;\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", "import { watch as nodeWatch } from 'node:fs/promises';\nimport { debounceTime, from } from 'rxjs';\n\nexport function watch(path: string) {\n return from(\n nodeWatch(path, {\n persistent: true,\n recursive: true,\n }),\n ).pipe(debounceTime(400));\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,QAAAA,aAAY;AACrB,SAAS,qBAAqB;AAE9B,SAAS,cAAAC,mBAAkB;AAE3B,SAAS,kBAAkB,SAAS,kBAAkB;;;ACLtD,SAAS,mBAAmB;AAI5B,IAAO,iBAAQ,CAAC,SAAmC;AACjD,QAAM,iBAAiB,OAAO,QAAQ,KAAK,OAAO,EAAE;AAAA,IAClD,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,IAAI,GAAG,KAAK,KAAK;AAAA,EACtC;AACA,QAAM,iBAAiB,I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AAM,SAAc,CAAC;AACrB,aAAW,CAAC,MAAM,QAAQ,KAAK,OAAO,QAAQ,OAAO,KAAK,SAAS,CAAC,CAAC,GAAG;AACtE,UAAM,EAAE,aAAa,CAAC,GAAG,GAAGC,SAAQ,IAAI;AAGxC,UAAM,YAAY,KAAK,QAAQ,aAAa,MAAM;AAElD,eAAW,CAAC,QAAQ,SAAS,KAAK,OAAO,QAAQA,QAAO,GAGnD;AACH,YAAM,oBAAoB,OAAO,eAAe,SAAS;AACzD,YAAM,YAAY,OAAO,OAAO,SAAS;AACzC,YAAM,gBAAgB,kBAAkB,WAAW,WAAW,MAAM;AACpE,YAAM,eAAe,UAAU,WAAW,SAAS;AACnD,YAAM,WAAW,UAAU,WAAW,KAAK,CAAC;AAC5C,aAAO;QACL;UACE;YACE,MAAM,SAAS;YACf;YACA,MAAM;YACN,WAAW;YACX,KAAK;UACP;UACA;YACE,GAAG;YACH,YAAY,CAAC,GAAG,YAAY,GAAI,UAAU,cAAc,CAAC,CAAE;YAC3D,aAAa;UACf;QACF;MACF;IACF;EACF;AACA,SAAO;AACT;AAgBA,IAAM,mBAAmB,oBAAI,IAAI;EAC/B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AACF,CAAC;AAUD,SAAS,YAAY,eAA+B;AAElD,MAAI,MAAM,KAAK,aAAa,GAAG;AAC7B,WAAO,IAAI,aAAa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AA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,SAAS,aAAa;AAAA,IAC1B;AAAA,IACA,KAAK,cAAc;AAAA,EACrB,CAAC;AACH;;;AetNA,SAAS,SAAS,iBAAiB;AACnC,SAAS,cAAc,YAAY;AAE5B,SAAS,MAAM,MAAc;AAClC,SAAO;AAAA,IACL,UAAU,MAAM;AAAA,MACd,YAAY;AAAA,MACZ,WAAW;AAAA,IACb,CAAC;AAAA,EACH,EAAE,KAAK,aAAa,GAAG,CAAC;AAC1B;",
|
|
6
|
+
"names": ["join", "spinalcase", "camelcase", "pascalcase", "spinalcase", "followRef", "isRef", "methods", "camelcase", "followRef", "isRef", "toLitObject", "cleanRef", "followRef", "isRef", "parseRef", "appendOptional", "isRef", "security", "isRef", "it", "exclude", "camelcase", "toLitObject", "schema", "isRef", "followRef", "isRef", "security", "followRef", "pascalcase", "spinalcase", "acc", "camelcase", "it", "security", "join", "spinalcase"]
|
|
7
7
|
}
|