zenko 0.2.2-beta.2 → 0.3.0-beta.2
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/cli.cjs +1 -1
- package/dist/cli.d.cts +1 -1
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +1 -2
- package/dist/index.d.cts +45 -41
- package/dist/index.d.mts +63 -0
- package/dist/index.mjs +1 -2
- package/dist/treaty-DM77ZhDU.d.mts +68 -0
- package/dist/treaty-NM6Hf8S8.d.cts +68 -0
- package/dist/treaty-generator-B2DqCcuW.mjs +8 -0
- package/dist/treaty-generator-Byq49esG.cjs +8 -0
- package/dist/treaty.cjs +2 -0
- package/dist/treaty.d.cts +2 -0
- package/dist/treaty.d.mts +2 -0
- package/dist/treaty.mjs +2 -0
- package/dist/types-BM-Q_QIk.d.cts +19 -0
- package/dist/types-ByqlZjPK.d.mts +19 -0
- package/dist/types.cjs +0 -0
- package/dist/types.d.cts +2 -0
- package/dist/types.d.mts +2 -0
- package/dist/types.mjs +1 -0
- package/package.json +28 -11
- package/dist/chunk-GD63CEJN.cjs +0 -11
- package/dist/chunk-VHYJGQUS.mjs +0 -11
- package/dist/cli.d.ts +0 -1
- package/dist/index.d.ts +0 -59
package/dist/cli.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require(`./treaty-generator-Byq49esG.cjs`);let l=require(`fs`);l=s(l);let u=require(`path`);u=s(u);let d=require(`url`);function f(e){return e.positional[0]===`treaty`?{...e,command:`treaty`,positional:e.positional.slice(1)}:{...e,command:`generate`}}async function p(){let e=f(m(process.argv.slice(2)));if(e.showHelp){h(),process.exit(0);return}try{if(e.command===`treaty`){if(e.configPath){console.error(`❌ Error: zenko treaty does not support --config`),process.exit(1);return}if(e.positional.length!==2){h(),process.exit(1);return}let[t,n]=e.positional;if(!t||!n){h(),process.exit(1);return}await g({inputFile:t,outputFile:n});return}if(!e.configPath&&e.positional.length===0){h(),process.exit(1);return}if(e.configPath)await v(e);else{if(e.positional.length!==2){h(),process.exit(1);return}let[t,n]=e.positional;if(!t||!n){h(),process.exit(1);return}await C({inputFile:t,outputFile:n,strictDates:e.strictDates,strictNumeric:e.strictNumeric})}}catch(e){console.error(`❌ Error:`,e),process.exit(1)}}function m(e){let t={showHelp:!1,strictDates:!1,strictNumeric:!1,positional:[]};for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`-h`||r===`--help`){t.showHelp=!0;continue}if(r===`--strict-dates`){t.strictDates=!0;continue}if(r===`--strict-numeric`){t.strictNumeric=!0;continue}if(r===`--config`||r===`-c`){let r=e[n+1];if(!r)throw Error(`--config flag requires a file path`);t.configPath=r,n+=1;continue}t.positional.push(r)}return t}function h(){console.log(`Usage:`),console.log(` zenko <input-file> <output-file> [options]`),console.log(` zenko treaty <generated-ts-file> <output-file>`),console.log(` zenko --config <config-file> [options]`),console.log(``),console.log(`Options:`),console.log(` -h, --help Show this help message`),console.log(` --strict-dates Use ISO datetime parsing (can be set per config entry)`),console.log(` --strict-numeric Preserve numeric min/max bounds (can be set per config entry)`),console.log(` -c, --config Path to config file (JSON, YAML, or JS module)`),console.log(``),console.log(`Config file format:`),console.log(` {"types"?: { emit?, helpers?, helpersOutput?, optionalType?, treeShake? }, "schemas": [{ input, output, strictDates?, strictNumeric?, dateTimeOffset?, types? }] }`)}async function g(e){let t=u.resolve(e.inputFile),n=u.resolve(e.outputFile),r=await c.t({inputFile:t,importPath:_(u.dirname(n),t)});l.mkdirSync(u.dirname(n),{recursive:!0}),l.writeFileSync(n,r,{encoding:`utf8`}),console.log(`✅ Generated treaty client in ${n}`)}function _(e,t){let n=u.relative(e,t).replace(/\\/g,`/`);return n.startsWith(`.`)||(n=`./${n}`),n.replace(/\.tsx?$/,``)}async function v(e){let t=e.configPath,n=u.resolve(t),r=await y(n);b(r);let i=u.dirname(n),a=r.types;for(let t of r.schemas){let n=x(t.input,i),r=x(t.output,i),o=S(a,t.types);await C({inputFile:n,outputFile:r,strictDates:t.strictDates??e.strictDates,strictNumeric:t.strictNumeric??e.strictNumeric,dateTimeOffset:t.dateTimeOffset,typesConfig:o,operationIds:t.operationIds,openEnums:t.openEnums}),t.treatyOutput&&await g({inputFile:r,outputFile:x(t.treatyOutput,i)})}}async function y(e){let t=u.extname(e).toLowerCase();if(t===`.json`){let t=l.readFileSync(e,`utf8`);return JSON.parse(t)}if(t===`.yaml`||t===`.yml`){let t=l.readFileSync(e,`utf8`);return Bun.YAML.parse(t)}let n=await import((0,d.pathToFileURL)(e).href);return n.default??n.config??n}function b(e){if(!e||typeof e!=`object`)throw Error(`Config file must export an object`);if(!Array.isArray(e.schemas))throw Error(`Config file must contain a 'schemas' array`);for(let t of e.schemas){if(!t||typeof t!=`object`)throw Error(`Each schema entry must be an object`);if(typeof t.input!=`string`||typeof t.output!=`string`)throw Error(`Each schema entry requires 'input' and 'output' paths`)}}function x(e,t){return u.isAbsolute(e)?e:u.join(t,e)}function S(e,t){if(!(!e&&!t))return{...e,...t}}async function C(e){let{inputFile:t,outputFile:n,strictDates:r,strictNumeric:i,dateTimeOffset:a,typesConfig:o,operationIds:s,openEnums:d}=e,f=u.resolve(t),p=u.resolve(n),m=w(f),h=c.i(m,{strictDates:r,strictNumeric:i,dateTimeOffset:a,types:o,operationIds:s,openEnums:d});if(l.mkdirSync(u.dirname(p),{recursive:!0}),l.writeFileSync(p,h.output),console.log(`✅ Generated TypeScript types in ${p}`),console.log(`📄 Processed ${Object.keys(m.paths||{}).length} paths`),m.webhooks&&console.log(`🪝 Processed ${Object.keys(m.webhooks).length} webhooks`),h.helperFile){let e=u.isAbsolute(h.helperFile.path)?h.helperFile.path:u.resolve(u.dirname(p),h.helperFile.path),t=u.resolve(p);if(t===u.resolve(e)){console.warn(`⚠️ Skipping helper file generation: would overwrite main output at ${t}`);return}l.mkdirSync(u.dirname(e),{recursive:!0}),l.writeFileSync(e,h.helperFile.content,{encoding:`utf8`}),console.log(`📦 Generated helper types in ${e}`)}}function w(e){if(!l.existsSync(e))throw Error(`Input file not found: ${e}`);let t=l.readFileSync(e,`utf8`);return e.endsWith(`.yaml`)||e.endsWith(`.yml`)?Bun.YAML.parse(t):JSON.parse(t)}p().catch(e=>{console.error(`❌ Error:`,e),process.exit(1)}),exports.t=s;
|
|
3
3
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export { };
|
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
package/dist/cli.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{i as e,t}from"./treaty-generator-B2DqCcuW.mjs";import*as n from"fs";import*as r from"path";import{pathToFileURL as i}from"url";function a(e){return e.positional[0]===`treaty`?{...e,command:`treaty`,positional:e.positional.slice(1)}:{...e,command:`generate`}}async function o(){let e=a(s(process.argv.slice(2)));if(e.showHelp){c(),process.exit(0);return}try{if(e.command===`treaty`){if(e.configPath){console.error(`❌ Error: zenko treaty does not support --config`),process.exit(1);return}if(e.positional.length!==2){c(),process.exit(1);return}let[t,n]=e.positional;if(!t||!n){c(),process.exit(1);return}await l({inputFile:t,outputFile:n});return}if(!e.configPath&&e.positional.length===0){c(),process.exit(1);return}if(e.configPath)await d(e);else{if(e.positional.length!==2){c(),process.exit(1);return}let[t,n]=e.positional;if(!t||!n){c(),process.exit(1);return}await g({inputFile:t,outputFile:n,strictDates:e.strictDates,strictNumeric:e.strictNumeric})}}catch(e){console.error(`❌ Error:`,e),process.exit(1)}}function s(e){let t={showHelp:!1,strictDates:!1,strictNumeric:!1,positional:[]};for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`-h`||r===`--help`){t.showHelp=!0;continue}if(r===`--strict-dates`){t.strictDates=!0;continue}if(r===`--strict-numeric`){t.strictNumeric=!0;continue}if(r===`--config`||r===`-c`){let r=e[n+1];if(!r)throw Error(`--config flag requires a file path`);t.configPath=r,n+=1;continue}t.positional.push(r)}return t}function c(){console.log(`Usage:`),console.log(` zenko <input-file> <output-file> [options]`),console.log(` zenko treaty <generated-ts-file> <output-file>`),console.log(` zenko --config <config-file> [options]`),console.log(``),console.log(`Options:`),console.log(` -h, --help Show this help message`),console.log(` --strict-dates Use ISO datetime parsing (can be set per config entry)`),console.log(` --strict-numeric Preserve numeric min/max bounds (can be set per config entry)`),console.log(` -c, --config Path to config file (JSON, YAML, or JS module)`),console.log(``),console.log(`Config file format:`),console.log(` {"types"?: { emit?, helpers?, helpersOutput?, optionalType?, treeShake? }, "schemas": [{ input, output, strictDates?, strictNumeric?, dateTimeOffset?, types? }] }`)}async function l(e){let i=r.resolve(e.inputFile),a=r.resolve(e.outputFile),o=await t({inputFile:i,importPath:u(r.dirname(a),i)});n.mkdirSync(r.dirname(a),{recursive:!0}),n.writeFileSync(a,o,{encoding:`utf8`}),console.log(`✅ Generated treaty client in ${a}`)}function u(e,t){let n=r.relative(e,t).replace(/\\/g,`/`);return n.startsWith(`.`)||(n=`./${n}`),n.replace(/\.tsx?$/,``)}async function d(e){let t=e.configPath,n=r.resolve(t),i=await f(n);p(i);let a=r.dirname(n),o=i.types;for(let t of i.schemas){let n=m(t.input,a),r=m(t.output,a),i=h(o,t.types);await g({inputFile:n,outputFile:r,strictDates:t.strictDates??e.strictDates,strictNumeric:t.strictNumeric??e.strictNumeric,dateTimeOffset:t.dateTimeOffset,typesConfig:i,operationIds:t.operationIds,openEnums:t.openEnums}),t.treatyOutput&&await l({inputFile:r,outputFile:m(t.treatyOutput,a)})}}async function f(e){let t=r.extname(e).toLowerCase();if(t===`.json`){let t=n.readFileSync(e,`utf8`);return JSON.parse(t)}if(t===`.yaml`||t===`.yml`){let t=n.readFileSync(e,`utf8`);return Bun.YAML.parse(t)}let a=await import(i(e).href);return a.default??a.config??a}function p(e){if(!e||typeof e!=`object`)throw Error(`Config file must export an object`);if(!Array.isArray(e.schemas))throw Error(`Config file must contain a 'schemas' array`);for(let t of e.schemas){if(!t||typeof t!=`object`)throw Error(`Each schema entry must be an object`);if(typeof t.input!=`string`||typeof t.output!=`string`)throw Error(`Each schema entry requires 'input' and 'output' paths`)}}function m(e,t){return r.isAbsolute(e)?e:r.join(t,e)}function h(e,t){if(!(!e&&!t))return{...e,...t}}async function g(t){let{inputFile:i,outputFile:a,strictDates:o,strictNumeric:s,dateTimeOffset:c,typesConfig:l,operationIds:u,openEnums:d}=t,f=r.resolve(i),p=r.resolve(a),m=_(f),h=e(m,{strictDates:o,strictNumeric:s,dateTimeOffset:c,types:l,operationIds:u,openEnums:d});if(n.mkdirSync(r.dirname(p),{recursive:!0}),n.writeFileSync(p,h.output),console.log(`✅ Generated TypeScript types in ${p}`),console.log(`📄 Processed ${Object.keys(m.paths||{}).length} paths`),m.webhooks&&console.log(`🪝 Processed ${Object.keys(m.webhooks).length} webhooks`),h.helperFile){let e=r.isAbsolute(h.helperFile.path)?h.helperFile.path:r.resolve(r.dirname(p),h.helperFile.path),t=r.resolve(p);if(t===r.resolve(e)){console.warn(`⚠️ Skipping helper file generation: would overwrite main output at ${t}`);return}n.mkdirSync(r.dirname(e),{recursive:!0}),n.writeFileSync(e,h.helperFile.content,{encoding:`utf8`}),console.log(`📦 Generated helper types in ${e}`)}}function _(e){if(!n.existsSync(e))throw Error(`Input file not found: ${e}`);let t=n.readFileSync(e,`utf8`);return e.endsWith(`.yaml`)||e.endsWith(`.yml`)?Bun.YAML.parse(t):JSON.parse(t)}o().catch(e=>{console.error(`❌ Error:`,e),process.exit(1)});export{};
|
|
3
3
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./treaty-generator-Byq49esG.cjs`),t=require(`./treaty.cjs`);exports.createTreatyClient=t.createTreatyClient,exports.generate=e.r,exports.generateTreatyModule=e.t,exports.generateTreatyModuleFromMetadata=e.n;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,35 +1,39 @@
|
|
|
1
|
+
import { a as PathFn, i as OperationErrors, n as HeaderFn, r as OperationDefinition, s as SecurityRequirement } from "./types-BM-Q_QIk.cjs";
|
|
2
|
+
import { a as RouteNode, i as TreatyRoutesConstraint, n as LeafCall, r as TreatyClient, s as TreatyResult, t as createTreatyClient } from "./treaty-NM6Hf8S8.cjs";
|
|
3
|
+
|
|
4
|
+
//#region src/zenko.d.ts
|
|
1
5
|
type OpenAPISpec = {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
6
|
+
openapi: string;
|
|
7
|
+
info: unknown;
|
|
8
|
+
paths: Record<string, Record<string, unknown>>;
|
|
9
|
+
webhooks?: Record<string, Record<string, unknown>>;
|
|
10
|
+
security?: Record<string, string[]>[];
|
|
11
|
+
components?: {
|
|
12
|
+
schemas?: Record<string, unknown>;
|
|
13
|
+
parameters?: Record<string, unknown>;
|
|
14
|
+
securitySchemes?: Record<string, unknown>;
|
|
15
|
+
};
|
|
12
16
|
};
|
|
13
17
|
type TypesHelperMode = "package" | "inline" | "file";
|
|
14
18
|
type TypesConfig = {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
emit?: boolean;
|
|
20
|
+
helpers?: TypesHelperMode;
|
|
21
|
+
helpersOutput?: string;
|
|
22
|
+
treeShake?: boolean;
|
|
23
|
+
optionalType?: "optional" | "nullable" | "nullish";
|
|
24
|
+
operationTypeSuffix?: string;
|
|
21
25
|
};
|
|
22
26
|
type EnumConfig = {
|
|
23
|
-
|
|
24
|
-
|
|
27
|
+
open?: boolean | string[];
|
|
28
|
+
unknownPrefix?: string;
|
|
25
29
|
};
|
|
26
30
|
type GenerateOptions = {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
strictDates?: boolean;
|
|
32
|
+
strictNumeric?: boolean;
|
|
33
|
+
dateTimeOffset?: boolean | string[];
|
|
34
|
+
types?: TypesConfig;
|
|
35
|
+
operationIds?: string[];
|
|
36
|
+
openEnums?: boolean | string[] | EnumConfig;
|
|
33
37
|
};
|
|
34
38
|
/**
|
|
35
39
|
* Generates TypeScript client code from an OpenAPI specification.
|
|
@@ -39,21 +43,21 @@ type GenerateOptions = {
|
|
|
39
43
|
* @returns Generated TypeScript code as a string.
|
|
40
44
|
*/
|
|
41
45
|
declare function generate(spec: OpenAPISpec, options?: GenerateOptions): string;
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
type
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;
|
|
48
|
-
type SecurityRequirement = Readonly<Record<string, readonly string[]>>;
|
|
49
|
-
type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {
|
|
50
|
-
method: TMethod;
|
|
51
|
-
path: TPath;
|
|
52
|
-
request?: TRequest;
|
|
53
|
-
response?: TResponse;
|
|
54
|
-
headers?: THeaders;
|
|
55
|
-
errors?: TErrors;
|
|
56
|
-
security?: TSecurity;
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/utils/treaty-tree.d.ts
|
|
48
|
+
type OperationMeta = {
|
|
49
|
+
method: string;
|
|
50
|
+
path: string;
|
|
57
51
|
};
|
|
58
|
-
|
|
59
|
-
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/treaty-generator.d.ts
|
|
54
|
+
declare function generateTreatyModuleFromMetadata(metadata: Record<string, OperationMeta>, options: {
|
|
55
|
+
importPath: string;
|
|
56
|
+
}): string;
|
|
57
|
+
declare function generateTreatyModule(options: {
|
|
58
|
+
inputFile: string;
|
|
59
|
+
importPath: string;
|
|
60
|
+
}): Promise<string>;
|
|
61
|
+
//#endregion
|
|
62
|
+
export { type GenerateOptions, type HeaderFn, type LeafCall, type OpenAPISpec, type OperationDefinition, type OperationErrors, type PathFn, type RouteNode, type SecurityRequirement, type TreatyClient, type TreatyResult, type TreatyRoutesConstraint, type TypesConfig, createTreatyClient, generate, generateTreatyModule, generateTreatyModuleFromMetadata };
|
|
63
|
+
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { a as PathFn, i as OperationErrors, n as HeaderFn, r as OperationDefinition, s as SecurityRequirement } from "./types-ByqlZjPK.mjs";
|
|
2
|
+
import { a as RouteNode, i as TreatyRoutesConstraint, n as LeafCall, r as TreatyClient, s as TreatyResult, t as createTreatyClient } from "./treaty-DM77ZhDU.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/zenko.d.ts
|
|
5
|
+
type OpenAPISpec = {
|
|
6
|
+
openapi: string;
|
|
7
|
+
info: unknown;
|
|
8
|
+
paths: Record<string, Record<string, unknown>>;
|
|
9
|
+
webhooks?: Record<string, Record<string, unknown>>;
|
|
10
|
+
security?: Record<string, string[]>[];
|
|
11
|
+
components?: {
|
|
12
|
+
schemas?: Record<string, unknown>;
|
|
13
|
+
parameters?: Record<string, unknown>;
|
|
14
|
+
securitySchemes?: Record<string, unknown>;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
type TypesHelperMode = "package" | "inline" | "file";
|
|
18
|
+
type TypesConfig = {
|
|
19
|
+
emit?: boolean;
|
|
20
|
+
helpers?: TypesHelperMode;
|
|
21
|
+
helpersOutput?: string;
|
|
22
|
+
treeShake?: boolean;
|
|
23
|
+
optionalType?: "optional" | "nullable" | "nullish";
|
|
24
|
+
operationTypeSuffix?: string;
|
|
25
|
+
};
|
|
26
|
+
type EnumConfig = {
|
|
27
|
+
open?: boolean | string[];
|
|
28
|
+
unknownPrefix?: string;
|
|
29
|
+
};
|
|
30
|
+
type GenerateOptions = {
|
|
31
|
+
strictDates?: boolean;
|
|
32
|
+
strictNumeric?: boolean;
|
|
33
|
+
dateTimeOffset?: boolean | string[];
|
|
34
|
+
types?: TypesConfig;
|
|
35
|
+
operationIds?: string[];
|
|
36
|
+
openEnums?: boolean | string[] | EnumConfig;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Generates TypeScript client code from an OpenAPI specification.
|
|
40
|
+
*
|
|
41
|
+
* @param spec - The OpenAPI specification object.
|
|
42
|
+
* @param options - Configuration options controlling code generation behavior.
|
|
43
|
+
* @returns Generated TypeScript code as a string.
|
|
44
|
+
*/
|
|
45
|
+
declare function generate(spec: OpenAPISpec, options?: GenerateOptions): string;
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/utils/treaty-tree.d.ts
|
|
48
|
+
type OperationMeta = {
|
|
49
|
+
method: string;
|
|
50
|
+
path: string;
|
|
51
|
+
};
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/treaty-generator.d.ts
|
|
54
|
+
declare function generateTreatyModuleFromMetadata(metadata: Record<string, OperationMeta>, options: {
|
|
55
|
+
importPath: string;
|
|
56
|
+
}): string;
|
|
57
|
+
declare function generateTreatyModule(options: {
|
|
58
|
+
inputFile: string;
|
|
59
|
+
importPath: string;
|
|
60
|
+
}): Promise<string>;
|
|
61
|
+
//#endregion
|
|
62
|
+
export { type GenerateOptions, type HeaderFn, type LeafCall, type OpenAPISpec, type OperationDefinition, type OperationErrors, type PathFn, type RouteNode, type SecurityRequirement, type TreatyClient, type TreatyResult, type TreatyRoutesConstraint, type TypesConfig, createTreatyClient, generate, generateTreatyModule, generateTreatyModuleFromMetadata };
|
|
63
|
+
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=index.mjs.map
|
|
1
|
+
import{n as e,r as t,t as n}from"./treaty-generator-B2DqCcuW.mjs";import{createTreatyClient as r}from"./treaty.mjs";export{r as createTreatyClient,t as generate,n as generateTreatyModule,e as generateTreatyModuleFromMetadata};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { i as OperationErrors, o as RequestMethod, r as OperationDefinition, s as SecurityRequirement, t as AnyHeaderFn } from "./types-ByqlZjPK.mjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/treaty-types.d.ts
|
|
5
|
+
/** Nested route tree: segments, `:param` keys, and HTTP method leaves (see `isLeaf` in treaty runtime). */
|
|
6
|
+
type RouteNode = Record<string, unknown>;
|
|
7
|
+
type TreatySuccess<T> = {
|
|
8
|
+
data: T;
|
|
9
|
+
error: null;
|
|
10
|
+
response: Response;
|
|
11
|
+
status: number;
|
|
12
|
+
headers: Headers;
|
|
13
|
+
};
|
|
14
|
+
type TreatyFailure = {
|
|
15
|
+
data: null;
|
|
16
|
+
error: {
|
|
17
|
+
status: number;
|
|
18
|
+
body: unknown;
|
|
19
|
+
};
|
|
20
|
+
response: Response;
|
|
21
|
+
status: number;
|
|
22
|
+
headers: Headers;
|
|
23
|
+
};
|
|
24
|
+
type TreatyResult<T> = TreatySuccess<T> | TreatyFailure;
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/treaty-infer.d.ts
|
|
27
|
+
type AnyOperationDefinition = OperationDefinition<RequestMethod, (...args: any[]) => string, unknown, unknown, AnyHeaderFn | undefined, OperationErrors | undefined, readonly SecurityRequirement[] | undefined>;
|
|
28
|
+
type TreatyMethodOptions = RequestInit & {
|
|
29
|
+
query?: Record<string, unknown>;
|
|
30
|
+
headers?: Record<string, string>;
|
|
31
|
+
};
|
|
32
|
+
type InferZodOutput<Schema> = Schema extends z.ZodType ? z.infer<Schema> : unknown;
|
|
33
|
+
type InferZodInput<Schema> = Schema extends z.ZodType ? z.input<Schema> : unknown;
|
|
34
|
+
type SuccessData<Op extends AnyOperationDefinition> = NonNullable<Op["response"]> extends z.ZodType ? InferZodOutput<NonNullable<Op["response"]>> : unknown;
|
|
35
|
+
/**
|
|
36
|
+
* Structural check: `Op["method"] extends "get" | "head"` is wrong when `method` is
|
|
37
|
+
* typed as `RequestMethod` (union) — it would match the GET branch incorrectly.
|
|
38
|
+
*/
|
|
39
|
+
type LeafCall<Op extends AnyOperationDefinition> = Op extends {
|
|
40
|
+
method: "get" | "head";
|
|
41
|
+
} ? (opts?: {
|
|
42
|
+
query?: Record<string, unknown>;
|
|
43
|
+
headers?: Record<string, string>;
|
|
44
|
+
}) => Promise<TreatyResult<SuccessData<Op>>> : Op extends {
|
|
45
|
+
request: infer Req;
|
|
46
|
+
} ? Req extends z.ZodType ? (body: InferZodInput<Req>, init?: TreatyMethodOptions) => Promise<TreatyResult<SuccessData<Op>>> : (body?: unknown, init?: TreatyMethodOptions) => Promise<TreatyResult<SuccessData<Op>>> : (body?: unknown, init?: TreatyMethodOptions) => Promise<TreatyResult<SuccessData<Op>>>;
|
|
47
|
+
type LeafMethods<R> = { [K in keyof R as K extends symbol ? never : R[K] extends AnyOperationDefinition ? K : never]: R[K] extends AnyOperationDefinition ? LeafCall<R[K]> : never };
|
|
48
|
+
type DynamicParamKey<R> = Extract<keyof R, `:${string}`>;
|
|
49
|
+
type ParamRecord<K extends `:${string}`> = K extends `:${infer Name}` ? { [P in Name]: string | number } : never;
|
|
50
|
+
type DynamicBranch<R> = [DynamicParamKey<R>] extends [never] ? unknown : DynamicParamKey<R> extends infer K extends `:${string}` ? K extends keyof R ? (params: ParamRecord<K>) => TreatyClient<R[K]> : never : unknown;
|
|
51
|
+
type StaticSegmentChildren<R> = { [K in keyof R as K extends symbol ? never : K extends `:${string}` ? never : R[K] extends AnyOperationDefinition ? never : R[K] extends Record<string, unknown> ? K : never]: R[K] extends Record<string, unknown> ? TreatyClient<R[K]> : never };
|
|
52
|
+
/**
|
|
53
|
+
* Inferred Eden-style client for a nested `treatyRoutes` object whose leaves are
|
|
54
|
+
* {@link OperationDefinition} values (Zod-typed `request` / `response`).
|
|
55
|
+
*/
|
|
56
|
+
type TreatyClient<R> = LeafMethods<R> & StaticSegmentChildren<R> & DynamicBranch<R>;
|
|
57
|
+
/** Permissive input constraint for `createTreatyClient` — inference comes from `routes`. */
|
|
58
|
+
type TreatyRoutesConstraint = Record<string, unknown>;
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/treaty.d.ts
|
|
61
|
+
declare function createTreatyClient<const R extends TreatyRoutesConstraint>(config: {
|
|
62
|
+
baseUrl: string;
|
|
63
|
+
routes: R;
|
|
64
|
+
fetch?: typeof fetch;
|
|
65
|
+
}): TreatyClient<R>;
|
|
66
|
+
//#endregion
|
|
67
|
+
export { RouteNode as a, TreatySuccess as c, TreatyRoutesConstraint as i, LeafCall as n, TreatyFailure as o, TreatyClient as r, TreatyResult as s, createTreatyClient as t };
|
|
68
|
+
//# sourceMappingURL=treaty-DM77ZhDU.d.mts.map
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { i as OperationErrors, o as RequestMethod, r as OperationDefinition, s as SecurityRequirement, t as AnyHeaderFn } from "./types-BM-Q_QIk.cjs";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/treaty-types.d.ts
|
|
5
|
+
/** Nested route tree: segments, `:param` keys, and HTTP method leaves (see `isLeaf` in treaty runtime). */
|
|
6
|
+
type RouteNode = Record<string, unknown>;
|
|
7
|
+
type TreatySuccess<T> = {
|
|
8
|
+
data: T;
|
|
9
|
+
error: null;
|
|
10
|
+
response: Response;
|
|
11
|
+
status: number;
|
|
12
|
+
headers: Headers;
|
|
13
|
+
};
|
|
14
|
+
type TreatyFailure = {
|
|
15
|
+
data: null;
|
|
16
|
+
error: {
|
|
17
|
+
status: number;
|
|
18
|
+
body: unknown;
|
|
19
|
+
};
|
|
20
|
+
response: Response;
|
|
21
|
+
status: number;
|
|
22
|
+
headers: Headers;
|
|
23
|
+
};
|
|
24
|
+
type TreatyResult<T> = TreatySuccess<T> | TreatyFailure;
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region src/treaty-infer.d.ts
|
|
27
|
+
type AnyOperationDefinition = OperationDefinition<RequestMethod, (...args: any[]) => string, unknown, unknown, AnyHeaderFn | undefined, OperationErrors | undefined, readonly SecurityRequirement[] | undefined>;
|
|
28
|
+
type TreatyMethodOptions = RequestInit & {
|
|
29
|
+
query?: Record<string, unknown>;
|
|
30
|
+
headers?: Record<string, string>;
|
|
31
|
+
};
|
|
32
|
+
type InferZodOutput<Schema> = Schema extends z.ZodType ? z.infer<Schema> : unknown;
|
|
33
|
+
type InferZodInput<Schema> = Schema extends z.ZodType ? z.input<Schema> : unknown;
|
|
34
|
+
type SuccessData<Op extends AnyOperationDefinition> = NonNullable<Op["response"]> extends z.ZodType ? InferZodOutput<NonNullable<Op["response"]>> : unknown;
|
|
35
|
+
/**
|
|
36
|
+
* Structural check: `Op["method"] extends "get" | "head"` is wrong when `method` is
|
|
37
|
+
* typed as `RequestMethod` (union) — it would match the GET branch incorrectly.
|
|
38
|
+
*/
|
|
39
|
+
type LeafCall<Op extends AnyOperationDefinition> = Op extends {
|
|
40
|
+
method: "get" | "head";
|
|
41
|
+
} ? (opts?: {
|
|
42
|
+
query?: Record<string, unknown>;
|
|
43
|
+
headers?: Record<string, string>;
|
|
44
|
+
}) => Promise<TreatyResult<SuccessData<Op>>> : Op extends {
|
|
45
|
+
request: infer Req;
|
|
46
|
+
} ? Req extends z.ZodType ? (body: InferZodInput<Req>, init?: TreatyMethodOptions) => Promise<TreatyResult<SuccessData<Op>>> : (body?: unknown, init?: TreatyMethodOptions) => Promise<TreatyResult<SuccessData<Op>>> : (body?: unknown, init?: TreatyMethodOptions) => Promise<TreatyResult<SuccessData<Op>>>;
|
|
47
|
+
type LeafMethods<R> = { [K in keyof R as K extends symbol ? never : R[K] extends AnyOperationDefinition ? K : never]: R[K] extends AnyOperationDefinition ? LeafCall<R[K]> : never };
|
|
48
|
+
type DynamicParamKey<R> = Extract<keyof R, `:${string}`>;
|
|
49
|
+
type ParamRecord<K extends `:${string}`> = K extends `:${infer Name}` ? { [P in Name]: string | number } : never;
|
|
50
|
+
type DynamicBranch<R> = [DynamicParamKey<R>] extends [never] ? unknown : DynamicParamKey<R> extends infer K extends `:${string}` ? K extends keyof R ? (params: ParamRecord<K>) => TreatyClient<R[K]> : never : unknown;
|
|
51
|
+
type StaticSegmentChildren<R> = { [K in keyof R as K extends symbol ? never : K extends `:${string}` ? never : R[K] extends AnyOperationDefinition ? never : R[K] extends Record<string, unknown> ? K : never]: R[K] extends Record<string, unknown> ? TreatyClient<R[K]> : never };
|
|
52
|
+
/**
|
|
53
|
+
* Inferred Eden-style client for a nested `treatyRoutes` object whose leaves are
|
|
54
|
+
* {@link OperationDefinition} values (Zod-typed `request` / `response`).
|
|
55
|
+
*/
|
|
56
|
+
type TreatyClient<R> = LeafMethods<R> & StaticSegmentChildren<R> & DynamicBranch<R>;
|
|
57
|
+
/** Permissive input constraint for `createTreatyClient` — inference comes from `routes`. */
|
|
58
|
+
type TreatyRoutesConstraint = Record<string, unknown>;
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/treaty.d.ts
|
|
61
|
+
declare function createTreatyClient<const R extends TreatyRoutesConstraint>(config: {
|
|
62
|
+
baseUrl: string;
|
|
63
|
+
routes: R;
|
|
64
|
+
fetch?: typeof fetch;
|
|
65
|
+
}): TreatyClient<R>;
|
|
66
|
+
//#endregion
|
|
67
|
+
export { RouteNode as a, TreatySuccess as c, TreatyRoutesConstraint as i, LeafCall as n, TreatyFailure as o, TreatyClient as r, TreatyResult as s, createTreatyClient as t };
|
|
68
|
+
//# sourceMappingURL=treaty-NM6Hf8S8.d.cts.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{pathToFileURL as e}from"node:url";function t(e){let t=new Set,r=new Set,i=[],a=o=>{if(t.has(o)||r.has(o))return;r.add(o);let s=e[o],c=n(s);for(let t of c)e[t]&&a(t);r.delete(o),t.add(o),i.push(o)};for(let t of Object.keys(e))a(t);return i}function n(e){let t=[],n=e=>{if(!(typeof e!=`object`||!e)){if(e.$ref&&typeof e.$ref==`string`){let n=r(e.$ref);t.push(n);return}if(Array.isArray(e))e.forEach(n);else{if(e.mapping&&typeof e.mapping==`object`)for(let n of Object.values(e.mapping))typeof n==`string`&&t.push(r(n));Object.values(e).forEach(n)}}};return n(e),[...new Set(t)]}function r(e){return(e.split(`/`).pop()||`Unknown`).replace(/\.(yml|yaml)$/i,``)}function i(e){if(!e)return!1;let t=e.at(0);return t===void 0||!/[a-zA-Z_$]/.test(t)||!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?!1:!new Set(`abstract.arguments.await.boolean.break.byte.case.catch.char.class.const.continue.debugger.default.delete.do.double.else.enum.eval.export.extends.false.final.finally.float.for.function.goto.if.implements.import.in.instanceof.int.interface.let.long.native.new.null.package.private.protected.public.return.short.static.super.switch.synchronized.this.throw.throws.transient.true.try.typeof.var.void.volatile.while.with.yield.async`.split(`.`)).has(e)}function a(e){return i(e)?e:`"${e}"`}function o(e){return e.replace(/-([a-zA-Z])/g,(e,t)=>t.toUpperCase()).replace(/-+$/,``)}function s(e){return e.charAt(0).toUpperCase()+e.slice(1)}function c(e){let t={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(t.usesOperationDefinition=!0);for(let n of e)n.errors&&u(n.errors)&&(t.usesOperationErrors=!0);return e.length>0&&!t.usesOperationErrors&&e.some(e=>!e.errors||!u(e.errors))&&(t.usesOperationErrors=!0),t}function l(e,t,n){let r=[];if(e.usesHeaderFn&&r.push(`HeaderFn`),e.usesOperationDefinition&&r.push(`OperationDefinition`),e.usesOperationErrors&&r.push(`OperationErrors`),r.length===0)return``;let i=t===`package`?`"zenko"`:`"${n}"`;return`import type { ${r.join(`, `)} } from ${i};`}function u(e){return!!(e&&Object.keys(e).length>0)}const d={"application/json":`unknown`,"text/csv":`string`,"text/plain":`string`,"application/octet-stream":`unknown`,"application/pdf":`unknown`};function f(e){let t=Object.keys(e);if(t.includes(`application/json`))return`application/json`;for(let e of t)if(e in d)return e;return t[0]||``}function p(e){let t=e.toLowerCase().split(`;`)[0]?.trim();return t?!!(t.startsWith(`text/`)||t===`application/xml`||t.startsWith(`application/`)&&t.endsWith(`+xml`)):!1}function m(e,t){if(!t||!p(e)||t.$ref)return t;let n=t.nullable===!0?{nullable:!0}:{};return t.enum?{type:`string`,enum:t.enum,...n}:{type:`string`,...n}}function h(e,t){if(e){if(e.$ref){let n=r(e.$ref),i=t.components?.parameters?.[n];if(!i)return;let{$ref:a,...o}=e;return{...i,...o}}return e}}function g(e){let t=new Map;for(let[,n]of Object.entries(e.paths||{}))for(let[,e]of Object.entries(n)){let n=e;n.operationId&&t.set(n.operationId,n)}for(let[,n]of Object.entries(e.webhooks||{}))for(let[,e]of Object.entries(n)){let n=e;n.operationId&&t.set(n.operationId,n)}return t}function _(e,t){let i=new Set,a=new Map,o=e=>{if(!e)return[];if(a.has(e))return a.get(e)??[];let t=n(e);return a.set(e,t),t},s=g(t);for(let n of e){let e=s.get(n.operationId);if(!e)continue;let a=e.requestBody?.content?.[`application/json`]?.schema;if(a?.$ref){let e=r(a.$ref);i.add(e)}else if(a){let e=o(a);for(let n of e)t.components?.schemas?.[n]&&i.add(n)}let c=e.responses||{};for(let[,e]of Object.entries(c)){let n=e?.content;if(!n)continue;let a=f(n),s=n[a]?.schema,c=m(a,s);if(c?.$ref){let e=r(c.$ref);i.add(e)}else if(c){let e=o(c);for(let n of e)t.components?.schemas?.[n]&&i.add(n)}}for(let e of n.queryParams){if(e.schema?.$ref){let t=r(e.schema.$ref);i.add(t)}if(e.schema?.items?.$ref){let t=r(e.schema.items.$ref);i.add(t)}}for(let e of n.requestHeaders||[]){if(e.schema?.$ref){let t=r(e.schema.$ref);i.add(t)}if(e.schema?.items?.$ref){let t=r(e.schema.items.$ref);i.add(t)}}let l=e.parameters||[];for(let e of l){let n=h(e,t);if(n?.schema?.$ref){let e=r(n.schema.$ref);i.add(e)}if(n?.schema?.items?.$ref){let e=r(n.schema.items.$ref);i.add(e)}}}let c=new Set,l=Array.from(i);for(;l.length>0;){let e=l.pop();if(c.has(e))continue;c.add(e);let n=t.components?.schemas?.[e];if(!n)continue;let r=o(n);for(let e of r)t.components?.schemas?.[e]&&!c.has(e)&&(i.add(e),l.push(e))}return i}function v(e,t){return t===!0?!0:Array.isArray(t)?t.includes(e):!1}function y(e,t){switch(t){case`optional`:return`${e}.optional()`;case`nullable`:return`${e}.nullable()`;case`nullish`:return`${e}.nullish()`}}function b(e,t,n,r,i,a){if(n.has(e))return``;if(n.add(e),t.enum){let n=t.enum.map(e=>`"${e}"`).join(`, `);if(v(e,r.openEnums)){let t=r.openEnumPrefix;return`const ${e}Known = [${n}] as const;\nexport const ${e} = z.enum(${e}Known).or(\n z.string().transform((v): \`${t}\${string}\` => \`${t}\${v}\`)\n);`}return`export const ${e} = z.enum([${n}]);`}if(t.allOf&&Array.isArray(t.allOf)){let n=w(t),o=n.map(t=>k(t,r,i,a,e));if(o.length===0)return`export const ${e} = z.object({});`;if(o.length===1)return`export const ${e} = ${o[0]};`;let s=n.every(e=>E(e,a))?`merge`:`and`;return`export const ${e} = ${o[0]}${o.slice(1).map(e=>`.${s}(${e})`).join(``)};`}if(t.type===`object`||t.properties)return`export const ${e} = ${ae(t,r,i,a,e)};`;if(t.type===`array`){let n=t.items??{type:`unknown`},o=k(n,r,i,a,e),s=r.strictNumeric||t.minItems!==void 0||t.maxItems!==void 0||t.uniqueItems===!0;return`export const ${e} = ${j(t,`z.array(${o})`,n,s)};`}return`export const ${e} = ${k(t,r,i,a,e,e)};`}function x(e,t,n,r,i){let a=e.map(e=>k(e,t,n,r,i));return a.length===0?`z.unknown()`:a.length===1?a[0]??`z.unknown()`:`z.union([${a.join(`, `)}])`}function S(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function ee(e,t){if(!e?.$ref)return e;let n=r(e.$ref);return t?.[n]??e}function C(e){return[`$ref`,`type`,`properties`,`required`,`additionalProperties`,`items`,`enum`,`const`,`oneOf`,`anyOf`,`not`].some(t=>e?.[t]!==void 0)}function w(e){let t=Array.isArray(e.allOf)?[...e.allOf]:[],n={...e};return delete n.allOf,C(n)&&t.push(n),t}function T(e,t,n,i,a=new Set){if(!e||a.has(e))return!1;if(a.add(e),e.$ref){let o=r(e.$ref);if((i?.get(o)||o)===t)return!0;let s=n?.[o];if(s)return T(s,t,n,i,a)}return Array.isArray(e.allOf)?e.allOf.some(e=>T(e,t,n,i,a)):Array.isArray(e.oneOf)?e.oneOf.some(e=>T(e,t,n,i,a)):Array.isArray(e.anyOf)?e.anyOf.some(e=>T(e,t,n,i,a)):e.not?T(e.not,t,n,i,a):e.items?T(e.items,t,n,i,a):e.properties?Object.values(e.properties).some(e=>T(e,t,n,i,a)):e.additionalProperties&&typeof e.additionalProperties==`object`?T(e.additionalProperties,t,n,i,a):!1}function E(e,t){let n=ee(e,t);return n?n.allOf&&Array.isArray(n.allOf)?w(n).every(e=>E(e,t)):n.type===`object`||n.properties!==void 0||n.additionalProperties!==void 0:!1}function te(e){let t=new Map;if(!e?.mapping)return t;for(let[n,i]of Object.entries(e.mapping)){if(typeof i!=`string`)continue;let e=r(i),a=t.get(e);if(a){a.values.includes(n)||a.values.push(n);continue}t.set(e,{ref:i,values:[n]})}return t}function D(e,t,n,i=new Set){if(!e||typeof e!=`object`||i.has(e))return[];if(i.add(e),e.$ref&&typeof e.$ref==`string`){let a=r(e.$ref),o=n?.[a];return o?D(o,t,n,i):[]}let a=[],o=e.properties?.[t];if(o){let e=o.const;e!==void 0&&S(e)?a.push(e):Array.isArray(o.enum)&&o.enum?.length===1&&S(o.enum?.[0])&&a.push(o.enum?.[0])}if(Array.isArray(e.allOf))for(let r of e.allOf)a.push(...D(r,t,n,i));return Array.from(new Set(a))}function O(e,t,n){return{allOf:[e,{type:`object`,properties:{[t]:{const:n}},required:[t]}]}}function ne(e,t,n,i){let a=new Set;for(let t of e)t?.$ref&&a.add(r(t.$ref));let o=[],s=!1;for(let a of e){let e=[];if(a?.$ref){let o=r(a.$ref),s=n.get(o);s?.values.length&&e.push(...s.values),e.push(...D(a,t,i))}else e.push(...D(a,t,i));let c=Array.from(new Set(e));if(c.length===0){s=!0,o.push(a);continue}for(let e of c)o.push(O(a,t,e))}for(let[e,r]of n.entries()){if(a.has(e))continue;let n={$ref:r.ref};for(let e of r.values)o.push(O(n,t,e))}return{schemas:o,hasUnmapped:s}}function re(e,t,n,r,i,a,o){let{schemas:s,hasUnmapped:c}=ne(e,t,o??new Map,i),l=s.map(e=>k(e,n,r,i,a));return l.length===0?`z.unknown()`:l.length===1?l[0]??`z.unknown()`:c?`z.union([${l.join(`, `)}])`:`z.discriminatedUnion(${JSON.stringify(t)}, [${l.join(`, `)}])`}function k(e,t,n,i,a,o){if(e.$ref){let t=r(e.$ref),o=n?.get(t)||t;return a&&(o===a||T(i?.[t],a,i,n))?`z.lazy((): z.ZodType => ${o})`:o}if(e.const!==void 0&&S(e.const))return`z.literal(${JSON.stringify(e.const)})`;if(e.enum)return e.enum.length===1?`z.literal(${JSON.stringify(e.enum[0])})`:`z.enum([${e.enum.map(e=>`"${e}"`).join(`, `)}])`;if(e.not){let r=e.not,o={...e};delete o.not;let s=C(o)?k(o,t,n,i,a):`z.any()`;return r?.type===`string`&&r.maxLength===0?`${s}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`:`${s}.refine((value) => !${k(r,t,n,i,a)}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let r=w(e),o=r.map(e=>k(e,t,n,i,a));if(o.length===0)return`z.object({})`;if(o.length===1)return o[0]??`z.object({})`;let s=r.every(e=>E(e,i))?`merge`:`and`;return`${o[0]}${o.slice(1).map(e=>`.${s}(${e})`).join(``)}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(e.discriminator?.propertyName){let r=te(e.discriminator);return re(e.oneOf,e.discriminator.propertyName,t,n,i,a,r)}return x(e.oneOf,t,n,i,a)}if(e.anyOf&&Array.isArray(e.anyOf))return x(e.anyOf,t,n,i,a);if(e.type===`object`||e.properties||e.allOf)return ae(e,t,n,i,a);switch(e.type){case`string`:return oe(e,t,o);case`boolean`:return`z.boolean()`;case`array`:{let r=e.items??{type:`unknown`},o=k(r,t,n,i,a),s=t.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return j(e,`z.array(${o})`,r,s)}case`null`:return`z.null()`;case`number`:return A(e,t);case`integer`:return ce(e,t);default:return`z.unknown()`}}function ie(e,t){if(!e||!t)return new Set;let n=new Set;for(let i of Object.values(e)){if(!i||typeof i!=`object`)continue;let e=i.discriminator?.propertyName;if(!e||!Array.isArray(i.oneOf))continue;let a=i.oneOf.some(e=>e?.$ref&&r(e.$ref)===t),o=Object.values(i.discriminator?.mapping??{}).some(e=>typeof e==`string`&&r(e)===t);(a||o)&&n.add(e)}return n}function ae(e,t,n,r,i){let o=[],s=ie(r,i),c=new Set(e.required??[]);for(let[l,u]of Object.entries(e.properties||{})){let e=c.has(l)||s.has(l),d=k(u,t,n,r,i),f=y(d,t.optionalType),p=t.optionalType===`nullable`?f:se(f,u),m=e?d:p;o.push(` ${a(l)}: ${m},`)}let l=o.length===0?`z.object({})`:`z.object({\n${o.join(`
|
|
2
|
+
`)}\n})`;return e.additionalProperties===void 0?l:e.additionalProperties===!1?`${l}.strict()`:e.additionalProperties===!0?`${l}.passthrough()`:`${l}.catchall(${k(e.additionalProperties,t,n,r,i)})`}function oe(e,t,n){if(e.format===`binary`)return`(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))`;if(t.strictDates)switch(e.format){case`date-time`:return t.dateTimeOffset===!0||Array.isArray(t.dateTimeOffset)&&n!==void 0&&t.dateTimeOffset.includes(n)?`z.string().datetime({ offset: true })`:`z.string().datetime()`;case`date`:return`z.string().date()`;case`time`:return`z.string().time()`;case`duration`:return`z.string().duration()`}let r=`z.string()`;switch(t.strictNumeric&&(typeof e.minLength==`number`&&(r+=`.min(${e.minLength})`),typeof e.maxLength==`number`&&(r+=`.max(${e.maxLength})`),e.pattern&&(r+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case`uuid`:return`${r}.uuid()`;case`email`:return`${r}.email()`;case`uri`:case`url`:return`${r}.url()`;case`ipv4`:return`${r}.ip({ version: "v4" })`;case`ipv6`:return`${r}.ip({ version: "v6" })`;default:return r}}function se(e,t){return!t||t.default===void 0||t.default===null&&!(e.includes(`.nullable()`)||e.includes(`.nullish()`)||t.type===`null`||Array.isArray(t.type)&&t.type.includes(`null`))?e:`${e}.default(${JSON.stringify(t.default)})`}function A(e,t){let n=`z.number()`;return t.strictNumeric&&(n=ue(e,n),typeof e.multipleOf==`number`&&e.multipleOf!==0&&(n+=`.refine((value) => Math.abs(value / ${e.multipleOf} - Math.round(value / ${e.multipleOf})) < Number.EPSILON, { message: "Must be a multiple of ${e.multipleOf}" })`)),n}function ce(e,t){let n=A(e,t);return n+=`.int()`,n}function j(e,t,n,r){return r?(typeof e.minItems==`number`&&(t+=`.min(${e.minItems})`),typeof e.maxItems==`number`&&(t+=`.max(${e.maxItems})`),e.uniqueItems&&le(n)&&(t+=`.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })`),t):t}function le(e){return e?.$ref?!1:new Set([`string`,`number`,`integer`,`boolean`]).has(e?.type)}function ue(e,t){return typeof e.minimum==`number`?e.exclusiveMinimum===!0?t+=`.gt(${e.minimum})`:t+=`.min(${e.minimum})`:typeof e.exclusiveMinimum==`number`&&(t+=`.gt(${e.exclusiveMinimum})`),typeof e.maximum==`number`?e.exclusiveMaximum===!0?t+=`.lt(${e.maximum})`:t+=`.max(${e.maximum})`:typeof e.exclusiveMaximum==`number`&&(t+=`.lt(${e.exclusiveMaximum})`),t}const de={400:`badRequest`,401:`unauthorized`,402:`paymentRequired`,403:`forbidden`,404:`notFound`,405:`methodNotAllowed`,406:`notAcceptable`,407:`proxyAuthenticationRequired`,408:`requestTimeout`,409:`conflict`,410:`gone`,411:`lengthRequired`,412:`preconditionFailed`,413:`payloadTooLarge`,414:`uriTooLong`,415:`unsupportedMediaType`,416:`rangeNotSatisfiable`,417:`expectationFailed`,418:`imATeapot`,421:`misdirectedRequest`,422:`unprocessableEntity`,423:`locked`,424:`failedDependency`,425:`tooEarly`,426:`upgradeRequired`,428:`preconditionRequired`,429:`tooManyRequests`,431:`requestHeaderFieldsTooLarge`,451:`unavailableForLegalReasons`,500:`internalServerError`,501:`notImplemented`,502:`badGateway`,503:`serviceUnavailable`,504:`gatewayTimeout`,505:`httpVersionNotSupported`,506:`variantAlsoNegotiates`,507:`insufficientStorage`,508:`loopDetected`,510:`notExtended`,511:`networkAuthenticationRequired`};function M(e){if(e===`default`)return`defaultError`;let t=e.trim(),n=de[t];if(n)return n;if(/^\d{3}$/.test(t))return`status${t}`;let r=t.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim();if(!r)return`unknownError`;let[i,...a]=r.split(/\s+/),o=i+a.map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``);return o?/^[a-zA-Z_$]/.test(o)?o:`status${o.charAt(0).toUpperCase()}${o.slice(1)}`:`unknownError`}function N(e){if(e===`default`)return!0;let t=Number(e);return Number.isInteger(t)?t>=400:!1}function fe(e,t){let n=[];if(e.paths)for(let[r,i]of Object.entries(e.paths))for(let[a,o]of Object.entries(i)){let s=a.toLowerCase();if(!H(s)||!o.operationId)continue;let c=F(r),l=I(o,t),{successResponse:u,errors:d,successResponses:f,errorResponses:p}=L(o,o.operationId,t),m=P(i,o,e),h=z(m),g=B(m),_=V(o,e);n.push({operationId:o.operationId,path:r,method:s,pathParams:c,queryParams:g,requestType:l,responseType:u,successResponses:f,errorResponses:p,requestHeaders:h,errors:d,security:_})}if(e.webhooks)for(let[r,i]of Object.entries(e.webhooks))for(let[a,o]of Object.entries(i)){let s=a.toLowerCase();if(!H(s)||!o.operationId)continue;let c=r,l=F(c),u=I(o,t),{successResponse:d,errors:f,successResponses:p,errorResponses:m}=L(o,o.operationId,t),h=P(i,o,e),g=z(h),_=B(h),v=V(o,e);n.push({operationId:o.operationId,path:c,method:s,pathParams:l,queryParams:_,requestType:u,responseType:d,successResponses:p,errorResponses:m,requestHeaders:g,errors:f,security:v})}return n}function P(e,t,n){let r=new Map,i=e=>{if(Array.isArray(e))for(let t of e){let e=h(t,n);if(!e)continue;let i=`${e.in}:${e.name}`;r.set(i,e)}};return i(e.parameters),i(t.parameters),Array.from(r.values())}function F(e){let t=[],n=e.match(/{([^}]+)}/g);if(n)for(let e of n){let n=e.slice(1,-1);t.push({name:n,type:`string`})}return t}function I(e,t){let n=pe(e);if(n){if(n.$ref){let e=r(n.$ref);return t?.get(e)||e}return`${s(o(e.operationId))}Request`}}function pe(e){let t=e?.requestBody?.content;if(!(!t||Object.keys(t).length===0))for(let e of[`application/json`,`multipart/form-data`,`application/x-www-form-urlencoded`]){let n=t[e]?.schema;if(n)return n}}function L(e,t,n){let r=e.responses??{},i=new Map,a=[];for(let[e,t]of Object.entries(r)){let n=t?.content;if(!n||Object.keys(n).length===0){e===`204`||/^3\d\d$/.test(e)?i.set(e,`undefined`):N(e)&&a.push({code:e,schema:`undefined`});continue}let r=f(n),o=n[r]?.schema,s=m(r,o);if(!s){let t=ve(r,e);t&&(N(e)?a.push({code:e,schema:t}):/^2\d\d$/.test(e)&&i.set(e,t));continue}if(N(e)){a.push({code:e,schema:s});continue}/^2\d\d$/.test(e)&&i.set(e,s)}return{successResponse:ge(i,t,n),errors:_e(a,t,n),successResponses:me(i,t,n),errorResponses:he(a,t,n)}}function me(e,t,n){if(e.size===0)return;let r={};for(let[i,a]of e)typeof a==`string`?r[i]=a:r[i]=R(a,`${s(o(t))}Status${i}`,n);return r}function he(e,t,n){if(e.length===0)return;let r={};for(let{code:i,schema:a}of e){let e=M(i);r[i]=R(a,`${s(o(t))}${s(e)}`,n)}return r}function ge(e,t,n){if(e.size===0)return;for(let r of[`200`,`201`,`204`]){let i=e.get(r);if(i)return typeof i==`string`?i:R(i,`${s(o(t))}Response`,n)}let[,r]=e.entries().next().value??[];if(r)return typeof r==`string`?r:R(r,`${s(o(t))}Response`,n)}function _e(e=[],t,n){if(!e.length)return;let r={};for(let{code:i,schema:a}of e){let e=M(i);r[e]=R(a,`${s(o(t))}${s(e)}`,n)}return r}function R(e,t,n){if(typeof e==`string`)return e;if(e.$ref){let t=r(e.$ref);return n?.get(t)||t}if(e.type===`array`&&e.items?.$ref){let t=r(e.items.$ref);return`z.array(${n?.get(t)||t})`}return e.allOf&&Array.isArray(e.allOf),t}function z(e){let t=[];for(let n of e??[])n.in===`header`&&t.push({name:n.name,description:n.description,schema:n.schema,required:n.required});return t}function B(e){let t=[];for(let n of e??[])n.in===`query`&&t.push({name:n.name,description:n.description,schema:n.schema,required:n.required});return t}function V(e,t){let n=e.security;if(Array.isArray(n))return n.length===0?[]:n;if(Array.isArray(t.security)&&t.security.length>0)return t.security}function H(e){switch(e){case`get`:case`put`:case`post`:case`delete`:case`options`:case`head`:case`patch`:case`trace`:return!0;default:return!1}}function ve(e,t){return t===`204`||/^3\d\d$/.test(t)?`undefined`:e in d?d[e]:`unknown`}function ye(e,t){let n=new Map,r=g(t);for(let t of e){let e=r.get(t.operationId);if(!e)continue;let i=e.requestBody;if(i&&i.content){let e=i.content,r=be(e);if(!r)continue;let a=`${s(o(t.operationId))}Request`;(!r.$ref||r.allOf||r.oneOf||r.anyOf)&&n.set(a,r)}}return n}function be(e){for(let t of[`application/json`,`multipart/form-data`,`application/x-www-form-urlencoded`]){let n=e[t]?.schema;if(n)return n}}function xe(e,t){let n=new Map,r=g(t);for(let t of e){let e=r.get(t.operationId);if(!e)continue;let i=e.responses||{};for(let[e,r]of Object.entries(i))if(/^2\d\d$/.test(e)&&r.content){let e=r.content,i=f(e),a=e[i]?.schema,c=m(i,a);if(!c)continue;let l=`${s(o(t.operationId))}Response`;(!c.$ref||c.allOf||c.oneOf||c.anyOf)&&n.set(l,c)}}return n}function Se(e,t,n,r,i){let a=ye(t,n);if(a.size>0){e.push(`// Generated Request Types`),e.push(``);for(let[t,n]of a){let a=b(t,n,new Set,i,r);e.push(a),e.push(``),e.push(`export type ${t} = z.infer<typeof ${t}>;`),e.push(``)}}}function Ce(e,t,n,r,i){let a=xe(t,n);if(a.size>0){e.push(`// Generated Response Types`),e.push(``);for(let[t,n]of a){let a=b(t,n,new Set,i,r);e.push(a),e.push(``),e.push(`export type ${t} = z.infer<typeof ${t}>;`),e.push(``)}}}function we(){let e=[];return e.push(`// Generated helper types for Zenko`),e.push(`// This file provides type definitions for operation objects and path functions`),e.push(``),e.push(`export type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string`),e.push(``),e.push(`export type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"`),e.push(``),e.push(`export type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult`),e.push(``),e.push(`export type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown)`),e.push(``),e.push(`export type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;`),e.push(``),e.push(`export type SecurityRequirement = Readonly<Record<string, readonly string[]>>`),e.push(``),e.push(`export type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {`),e.push(` method: TMethod`),e.push(` path: TPath`),e.push(` request?: TRequest`),e.push(` response?: TResponse`),e.push(` headers?: THeaders`),e.push(` errors?: TErrors`),e.push(` security?: TSecurity`),e.push(`}`),e.push(``),e.join(`
|
|
3
|
+
`)}function Te(e){return e===void 0?{open:!1,prefix:`Unknown:`}:typeof e==`boolean`||Array.isArray(e)?{open:e,prefix:`Unknown:`}:{open:e.open??!1,prefix:e.unknownPrefix??`Unknown:`}}function U(e,n={}){let r=[],s=new Set,{strictDates:c=!1,strictNumeric:l=!1,dateTimeOffset:u=!0,operationIds:d,openEnums:f=!1}=n,p=Oe({...n.types,operationTypeSuffix:n.types?.operationTypeSuffix??`Operation`}),m=Te(f),h={strictDates:c,strictNumeric:l,dateTimeOffset:u,optionalType:p.optionalType,openEnums:m.open,openEnumPrefix:m.prefix};r.push(`import { z } from "zod";`);let g=new Map;if(e.components?.schemas)for(let t of Object.keys(e.components.schemas))g.set(t,o(t));let v=fe(e,g);if(d&&d.length>0){let e=new Set(d);v=v.filter(t=>e.has(t.operationId))}if(ke(r,p,v),r.push(``),e.components?.schemas){r.push(`// Generated Zod Schemas`),r.push(``);let n=d&&d.length>0?new Set(_(v,e)):new Set(Object.keys(e.components.schemas)),i=t(e.components.schemas).filter(e=>n.has(e));for(let t of i){let n=e.components.schemas[t],i=g.get(t);r.push(b(i,n,s,h,g,e.components.schemas)),r.push(``),r.push(`export type ${i} = z.infer<typeof ${i}>;`),r.push(``)}}r.push(`// Path Functions`),r.push(`export const paths = {`);for(let e of v){let t=e.pathParams.map(e=>e.name).length>0,n=e.queryParams.length>0,s=o(e.operationId);if(!t&&!n){r.push(` ${a(s)}: () => "${e.path}",`);continue}let c=e=>{if(i(e))return e;let t=o(e);return i(t)||(t=`_${t}`),t},l=[],u=[];for(let t of e.pathParams)l.push(i(t.name)?t.name:`${a(t.name)}: ${c(t.name)}`),u.push(`${a(t.name)}: string`);for(let t of e.queryParams)l.push(i(t.name)?t.name:`${a(t.name)}: ${c(t.name)}`),u.push(`${a(t.name)}${t.required?``:`?`}: ${Fe(t)}`);let d=!t&&n&&e.queryParams.every(e=>!e.required),f=`${l.length?`{ ${l.join(`, `)} }`:`{}`}: { ${u.join(`, `)} }${d?` = {}`:``}`,p=e.path.replace(/{([^}]+)}/g,(e,t)=>`\${${c(t)}}`);if(!n){r.push(` ${a(s)}: (${f}) => \`${p}\`,`);continue}r.push(` ${a(s)}: (${f}) => {`),r.push(` const params = new URLSearchParams()`);for(let t of e.queryParams){let e=i(t.name)?t.name:c(o(t.name)),n=t.schema??{};if(n?.type===`array`){let i=Q(n.items??{},`value`);t.required?(r.push(` for (const value of ${e}) {`),r.push(` params.append("${t.name}", ${i})`),r.push(` }`)):(r.push(` if (${e} !== undefined) {`),r.push(` for (const value of ${e}) {`),r.push(` params.append("${t.name}", ${i})`),r.push(` }`),r.push(` }`));continue}let a=Q(n,e);t.required?r.push(` params.set("${t.name}", ${a})`):(r.push(` if (${e} !== undefined) {`),r.push(` params.set("${t.name}", ${a})`),r.push(` }`))}r.push(` const _searchParams = params.toString()`),r.push(` return \`${p}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),r.push(` },`)}r.push(`} as const;`),r.push(``),r.push(`// Header Schemas`),r.push(`export const headerSchemas = {`);for(let e of v){let t=o(e.operationId);if(!e.requestHeaders||e.requestHeaders.length===0){r.push(` ${a(t)}: z.object({}),`);continue}let n=e.requestHeaders.map(e=>{let t=Pe(e),n=e.required?t:y(t,h.optionalType);return` ${a(e.name)}: ${n},`}).join(`
|
|
4
|
+
`);r.push(` ${a(t)}: z.object({`),r.push(n),r.push(` }),`)}r.push(`} as const;`),r.push(``),r.push(`// Header Functions`),r.push(`export const headers = {`);for(let e of v){let t=o(e.operationId);if(!e.requestHeaders||e.requestHeaders.length===0){r.push(` ${a(t)}: () => ${i(t)?`headerSchemas.${t}`:`headerSchemas[${a(t)}]`}.parse({}),`);continue}r.push(` ${a(t)}: (params: z.input<${i(t)?`typeof headerSchemas.${t}`:`(typeof headerSchemas)[${a(t)}]`}>) => {`),r.push(` return ${i(t)?`headerSchemas.${t}`:`headerSchemas[${a(t)}]`}.parse(params)`),r.push(` },`)}if(r.push(`} as const;`),r.push(``),e.components?.securitySchemes&&Object.keys(e.components.securitySchemes).length>0){r.push(`// Security Schemes`),r.push(`export const securitySchemes = {`);for(let[t,n]of Object.entries(e.components.securitySchemes)){let e=n;r.push(` ${a(t)}: {`),r.push(` type: ${JSON.stringify(e.type)},`),e.type===`http`?(r.push(` scheme: ${JSON.stringify(String(e.scheme).toLowerCase())},`),e.bearerFormat&&r.push(` bearerFormat: ${JSON.stringify(e.bearerFormat)},`)):e.type===`apiKey`?(r.push(` name: ${JSON.stringify(e.name)},`),r.push(` in: ${JSON.stringify(e.in)},`)):e.type===`oauth2`?r.push(` flows: ${JSON.stringify(e.flows)},`):e.type===`openIdConnect`&&r.push(` openIdConnectUrl: ${JSON.stringify(e.openIdConnectUrl)},`),r.push(` },`)}r.push(`} as const;`),r.push(``)}Se(r,v,e,g,h),Ce(r,v,e,g,h),Ae(r,v,p),r.push(`// Operation Objects`);for(let e of v){let t=o(e.operationId),n=p.emit?`: ${K(t,p.operationTypeSuffix)}`:``;if(r.push(`export const ${t}${n} = {`),r.push(` method: "${e.method}",`),r.push(` path: paths.${t},`),W(r,`request`,e.requestType),W(r,`response`,e.responseType),e.requestHeaders&&e.requestHeaders.length>0&&r.push(` headers: headers.${t},`),e.security!==void 0)if(e.security.length===0)r.push(` security: [],`);else{let t=e.security.map(e=>`{ ${Object.entries(e).map(([e,t])=>`${a(e)}: ${JSON.stringify(t)}`).join(`, `)} }`);r.push(` security: [${t.join(`, `)}],`)}e.errors&&G(e.errors)&&De(r,`errors`,e.errors),r.push(`} as const;`),r.push(``)}je(r,v);let x={output:r.join(`
|
|
5
|
+
`)};return p.emit&&p.helpers===`file`&&p.helpersOutput&&(x.helperFile={path:p.helpersOutput,content:we()}),x}function Ee(e,t={}){return U(e,t).output}function W(e,t,n){n&&e.push(` ${t}: ${n},`)}function De(e,t,n){if(!(!n||Object.keys(n).length===0)){e.push(` ${t}: {`);for(let[t,r]of Object.entries(n))e.push(` ${a(t)}: ${r},`);e.push(` },`)}}function G(e){return!!(e&&Object.keys(e).length>0)}function Oe(e){let t=e?.operationTypeSuffix??`Operation`;if(t!==``&&!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(t))throw Error(`Invalid operationTypeSuffix "${t}": must be a valid TypeScript identifier suffix (letters, digits, underscores, or $). Use "" for no suffix.`);return{emit:e?.emit??!0,helpers:e?.helpers??`package`,helpersOutput:e?.helpersOutput??`./zenko-types`,treeShake:e?.treeShake??!0,optionalType:e?.optionalType??`optional`,operationTypeSuffix:t}}function K(e,t){return`${s(e)}${t}`}function ke(e,t,n){if(t.emit)switch(t.helpers){case`package`:if(t.treeShake){let t=l(c(n),`package`);t&&e.push(t)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "zenko";`);return;case`file`:if(t.treeShake){let r=l(c(n),`file`,t.helpersOutput);r&&e.push(r)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "${t.helpersOutput}";`);return;case`inline`:e.push(`type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;`),e.push(`type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";`),e.push(`type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;`),e.push(`type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);`),e.push(`type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;`),e.push(`type SecurityRequirement = Readonly<Record<string, readonly string[]>>;`),e.push(`type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {`),e.push(` method: TMethod`),e.push(` path: TPath`),e.push(` request?: TRequest`),e.push(` response?: TResponse`),e.push(` headers?: THeaders`),e.push(` errors?: TErrors`),e.push(` security?: TSecurity`),e.push(`}`),e.push(``)}}function Ae(e,t,n){if(n.emit){e.push(`// Operation Types`);for(let r of t){let t=o(r.operationId),s=K(t,n.operationTypeSuffix),c=r.requestHeaders?.length?i(t)?`typeof headers.${t}`:`(typeof headers)[${a(t)}]`:`undefined`,l=Y(r.requestType),u=Y(r.responseType),d=Me(r.errors),f=r.security===void 0?`undefined`:r.security.length===0?`readonly []`:`readonly [${r.security.map(e=>`{ ${Object.entries(e).map(([e,t])=>`readonly ${a(e)}: readonly ${JSON.stringify(t)}`).join(`; `)} }`).join(`, `)}]`;e.push(`export type ${s} = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${i(t)?`typeof paths.${t}`:`(typeof paths)[${a(t)}]`},`),e.push(` ${l},`),e.push(` ${u},`),e.push(` ${c},`),e.push(` ${d},`),e.push(` ${f}`),e.push(`>;`),e.push(``)}}}function je(e,t){e.push(`// Operation Metadata`),e.push(`export const operationMetadata = {`);for(let n of t){let t=o(n.operationId);e.push(` ${a(t)}: {`),e.push(` method: ${JSON.stringify(n.method)},`),e.push(` path: ${JSON.stringify(n.path)},`),n.successResponses&&Object.keys(n.successResponses).length>0&&e.push(` successResponses: ${JSON.stringify(n.successResponses)},`),n.errorResponses&&Object.keys(n.errorResponses).length>0&&e.push(` errorResponses: ${JSON.stringify(n.errorResponses)},`),e.push(` },`)}e.push(`} as const;`),e.push(``)}function Me(e){return!e||!G(e)?`OperationErrors`:`OperationErrors<${Ne(e)}>`}function Ne(e){return!e||Object.keys(e).length===0?`unknown`:`{ ${Object.entries(e).map(([e,t])=>`${a(e)}: ${X(t)}`).join(`; `)} }`}const q=new Set([`any`,`unknown`,`never`,`void`,`null`,`undefined`,`string`,`number`,`boolean`,`bigint`,`symbol`]),J=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Y(e){if(!e)return`undefined`;let t=e.trim();if(t===`undefined`)return`undefined`;if(q.has(t)||t.startsWith(`typeof `))return t;let n=t.match(/^z\.array\((.+)\)$/);return n?`z.ZodArray<${Y(n[1])}>`:J.test(t)?`typeof ${t}`:t}function X(e){if(!e)return`unknown`;let t=e.trim();if(q.has(t)||t.startsWith(`typeof `))return t;let n=t.match(/^z\.array\((.+)\)$/);return n?`z.ZodArray<${X(n[1])}>`:J.test(t)?`typeof ${t}`:t}function Pe(e){let t=e.schema??{};switch(t.type){case`integer`:case`number`:return`z.coerce.number()`;case`boolean`:return`z.coerce.boolean()`;case`array`:{let e=t.items??{type:`string`};return`z.array(${e.type===`integer`||e.type===`number`?`z.coerce.number()`:e.type===`boolean`?`z.coerce.boolean()`:`z.string()`})`}default:return`z.string()`}}function Fe(e){return Z(e.schema)}function Z(e){if(!e)return`string`;if(e.type===`array`)return`Array<${Z(e.items)}>`;switch(e.type){case`integer`:case`number`:return`number`;case`boolean`:return`boolean`;default:return`string`}}function Q(e,t){if(!e)return`String(${t})`;switch(e.type){case`integer`:case`number`:return`String(${t})`;case`boolean`:return`${t} ? "true" : "false"`;default:return`String(${t})`}}const Ie=new Set([`get`,`post`,`put`,`patch`,`delete`,`options`,`head`,`connect`,`trace`]);function Le(e){return e.split(`/`).filter(Boolean).map(e=>e.startsWith(`{`)&&e.endsWith(`}`)?`:${e.slice(1,-1)}`:e)}function Re(e){let t={};for(let[n,r]of Object.entries(e)){let e=Le(r.path),i=r.method.toLowerCase();if(!Ie.has(i))return{ok:!1,error:Error(`Unsupported method ${r.method} for ${n}`)};let a=ze(t,e,i,n);if(!a.ok)return a}return{ok:!0,value:t}}function ze(e,t,n,r){if(t.length===0){let t=e,i=t!==void 0&&typeof t==`object`&&t&&!Array.isArray(t)?{...t}:{};if(i[n]!==void 0){let e=`Duplicate ${n} on root for ${r} vs `,t=JSON.stringify(i[n]);return{ok:!1,error:Error(e+t)}}i[n]=r;for(let t of Object.keys(e))delete e[t];return Object.assign(e,i),{ok:!0,value:void 0}}let i=e;for(let e=0;e<t.length;e+=1){let a=t[e];if(e===t.length-1){let e=i[a],t=e!==void 0&&typeof e==`object`&&e&&!Array.isArray(e)?{...e}:{};if(t[n]!==void 0){let e=`Duplicate ${n} on ${a} for ${r} vs `,i=JSON.stringify(t[n]);return{ok:!1,error:Error(e+i)}}t[n]=r,i[a]=t}else{let e=i[a];if(e!==void 0&&typeof e!=`object`&&e!==null&&!Array.isArray(e))return{ok:!1,error:Error(`TreatyRouteTree conflict at segment ${JSON.stringify(a)}: cannot add nested path for ${n} (${r}); existing value is not an object: ${JSON.stringify(e)}`)};(e===void 0||typeof e!=`object`||!e||Array.isArray(e))&&(i[a]={}),i=i[a]}}return{ok:!0,value:void 0}}function Be(e){return Ve(e,1)}function Ve(e,t){let n=` `.repeat(t),r=[];for(let[i,o]of Object.entries(e)){let e=a(i);typeof o==`string`?r.push(`${n}${e}: ${o},`):o&&typeof o==`object`&&!Array.isArray(o)&&(r.push(`${n}${e}: {`),r.push(Ve(o,t+1)),r.push(`${n}},`))}return r.join(`
|
|
6
|
+
`)}function $(e,t){let n=Re(e);if(!n.ok)throw n.error;let r=Object.keys(e).sort(),i=Be(n.value);return[`import { createTreatyClient, type TreatyClient } from "zenko/treaty";`,`import { ${r.join(`, `)} } from ${JSON.stringify(t.importPath)};`,``,`export const treatyRoutes = {`,i,`};`,``,`export function createClient(`,` baseUrl: string,`,` init?: { fetch?: typeof fetch }`,`): TreatyClient<typeof treatyRoutes> {`,` return createTreatyClient({`,` baseUrl,`,` routes: treatyRoutes,`,` fetch: init?.fetch,`,` })`,`}`,``].join(`
|
|
7
|
+
`)}async function He(t){let n=await import(e(t.inputFile).href);if(!n.operationMetadata)throw Error(`Missing operationMetadata export in ${t.inputFile} — regenerate with the latest Zenko`);let r=n.operationMetadata;return $(r,{importPath:t.importPath})}export{U as i,$ as n,Ee as r,He as t};
|
|
8
|
+
//# sourceMappingURL=treaty-generator-B2DqCcuW.mjs.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
require(`./cli.cjs`);let e=require(`node:url`);function t(e){let t=new Set,r=new Set,i=[],a=o=>{if(t.has(o)||r.has(o))return;r.add(o);let s=e[o],c=n(s);for(let t of c)e[t]&&a(t);r.delete(o),t.add(o),i.push(o)};for(let t of Object.keys(e))a(t);return i}function n(e){let t=[],n=e=>{if(!(typeof e!=`object`||!e)){if(e.$ref&&typeof e.$ref==`string`){let n=r(e.$ref);t.push(n);return}if(Array.isArray(e))e.forEach(n);else{if(e.mapping&&typeof e.mapping==`object`)for(let n of Object.values(e.mapping))typeof n==`string`&&t.push(r(n));Object.values(e).forEach(n)}}};return n(e),[...new Set(t)]}function r(e){return(e.split(`/`).pop()||`Unknown`).replace(/\.(yml|yaml)$/i,``)}function i(e){if(!e)return!1;let t=e.at(0);return t===void 0||!/[a-zA-Z_$]/.test(t)||!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?!1:!new Set(`abstract.arguments.await.boolean.break.byte.case.catch.char.class.const.continue.debugger.default.delete.do.double.else.enum.eval.export.extends.false.final.finally.float.for.function.goto.if.implements.import.in.instanceof.int.interface.let.long.native.new.null.package.private.protected.public.return.short.static.super.switch.synchronized.this.throw.throws.transient.true.try.typeof.var.void.volatile.while.with.yield.async`.split(`.`)).has(e)}function a(e){return i(e)?e:`"${e}"`}function o(e){return e.replace(/-([a-zA-Z])/g,(e,t)=>t.toUpperCase()).replace(/-+$/,``)}function s(e){return e.charAt(0).toUpperCase()+e.slice(1)}function c(e){let t={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(t.usesOperationDefinition=!0);for(let n of e)n.errors&&u(n.errors)&&(t.usesOperationErrors=!0);return e.length>0&&!t.usesOperationErrors&&e.some(e=>!e.errors||!u(e.errors))&&(t.usesOperationErrors=!0),t}function l(e,t,n){let r=[];if(e.usesHeaderFn&&r.push(`HeaderFn`),e.usesOperationDefinition&&r.push(`OperationDefinition`),e.usesOperationErrors&&r.push(`OperationErrors`),r.length===0)return``;let i=t===`package`?`"zenko"`:`"${n}"`;return`import type { ${r.join(`, `)} } from ${i};`}function u(e){return!!(e&&Object.keys(e).length>0)}const d={"application/json":`unknown`,"text/csv":`string`,"text/plain":`string`,"application/octet-stream":`unknown`,"application/pdf":`unknown`};function f(e){let t=Object.keys(e);if(t.includes(`application/json`))return`application/json`;for(let e of t)if(e in d)return e;return t[0]||``}function p(e){let t=e.toLowerCase().split(`;`)[0]?.trim();return t?!!(t.startsWith(`text/`)||t===`application/xml`||t.startsWith(`application/`)&&t.endsWith(`+xml`)):!1}function m(e,t){if(!t||!p(e)||t.$ref)return t;let n=t.nullable===!0?{nullable:!0}:{};return t.enum?{type:`string`,enum:t.enum,...n}:{type:`string`,...n}}function h(e,t){if(e){if(e.$ref){let n=r(e.$ref),i=t.components?.parameters?.[n];if(!i)return;let{$ref:a,...o}=e;return{...i,...o}}return e}}function g(e){let t=new Map;for(let[,n]of Object.entries(e.paths||{}))for(let[,e]of Object.entries(n)){let n=e;n.operationId&&t.set(n.operationId,n)}for(let[,n]of Object.entries(e.webhooks||{}))for(let[,e]of Object.entries(n)){let n=e;n.operationId&&t.set(n.operationId,n)}return t}function _(e,t){let i=new Set,a=new Map,o=e=>{if(!e)return[];if(a.has(e))return a.get(e)??[];let t=n(e);return a.set(e,t),t},s=g(t);for(let n of e){let e=s.get(n.operationId);if(!e)continue;let a=e.requestBody?.content?.[`application/json`]?.schema;if(a?.$ref){let e=r(a.$ref);i.add(e)}else if(a){let e=o(a);for(let n of e)t.components?.schemas?.[n]&&i.add(n)}let c=e.responses||{};for(let[,e]of Object.entries(c)){let n=e?.content;if(!n)continue;let a=f(n),s=n[a]?.schema,c=m(a,s);if(c?.$ref){let e=r(c.$ref);i.add(e)}else if(c){let e=o(c);for(let n of e)t.components?.schemas?.[n]&&i.add(n)}}for(let e of n.queryParams){if(e.schema?.$ref){let t=r(e.schema.$ref);i.add(t)}if(e.schema?.items?.$ref){let t=r(e.schema.items.$ref);i.add(t)}}for(let e of n.requestHeaders||[]){if(e.schema?.$ref){let t=r(e.schema.$ref);i.add(t)}if(e.schema?.items?.$ref){let t=r(e.schema.items.$ref);i.add(t)}}let l=e.parameters||[];for(let e of l){let n=h(e,t);if(n?.schema?.$ref){let e=r(n.schema.$ref);i.add(e)}if(n?.schema?.items?.$ref){let e=r(n.schema.items.$ref);i.add(e)}}}let c=new Set,l=Array.from(i);for(;l.length>0;){let e=l.pop();if(c.has(e))continue;c.add(e);let n=t.components?.schemas?.[e];if(!n)continue;let r=o(n);for(let e of r)t.components?.schemas?.[e]&&!c.has(e)&&(i.add(e),l.push(e))}return i}function v(e,t){return t===!0?!0:Array.isArray(t)?t.includes(e):!1}function y(e,t){switch(t){case`optional`:return`${e}.optional()`;case`nullable`:return`${e}.nullable()`;case`nullish`:return`${e}.nullish()`}}function b(e,t,n,r,i,a){if(n.has(e))return``;if(n.add(e),t.enum){let n=t.enum.map(e=>`"${e}"`).join(`, `);if(v(e,r.openEnums)){let t=r.openEnumPrefix;return`const ${e}Known = [${n}] as const;\nexport const ${e} = z.enum(${e}Known).or(\n z.string().transform((v): \`${t}\${string}\` => \`${t}\${v}\`)\n);`}return`export const ${e} = z.enum([${n}]);`}if(t.allOf&&Array.isArray(t.allOf)){let n=w(t),o=n.map(t=>k(t,r,i,a,e));if(o.length===0)return`export const ${e} = z.object({});`;if(o.length===1)return`export const ${e} = ${o[0]};`;let s=n.every(e=>E(e,a))?`merge`:`and`;return`export const ${e} = ${o[0]}${o.slice(1).map(e=>`.${s}(${e})`).join(``)};`}if(t.type===`object`||t.properties)return`export const ${e} = ${ae(t,r,i,a,e)};`;if(t.type===`array`){let n=t.items??{type:`unknown`},o=k(n,r,i,a,e),s=r.strictNumeric||t.minItems!==void 0||t.maxItems!==void 0||t.uniqueItems===!0;return`export const ${e} = ${j(t,`z.array(${o})`,n,s)};`}return`export const ${e} = ${k(t,r,i,a,e,e)};`}function x(e,t,n,r,i){let a=e.map(e=>k(e,t,n,r,i));return a.length===0?`z.unknown()`:a.length===1?a[0]??`z.unknown()`:`z.union([${a.join(`, `)}])`}function S(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function ee(e,t){if(!e?.$ref)return e;let n=r(e.$ref);return t?.[n]??e}function C(e){return[`$ref`,`type`,`properties`,`required`,`additionalProperties`,`items`,`enum`,`const`,`oneOf`,`anyOf`,`not`].some(t=>e?.[t]!==void 0)}function w(e){let t=Array.isArray(e.allOf)?[...e.allOf]:[],n={...e};return delete n.allOf,C(n)&&t.push(n),t}function T(e,t,n,i,a=new Set){if(!e||a.has(e))return!1;if(a.add(e),e.$ref){let o=r(e.$ref);if((i?.get(o)||o)===t)return!0;let s=n?.[o];if(s)return T(s,t,n,i,a)}return Array.isArray(e.allOf)?e.allOf.some(e=>T(e,t,n,i,a)):Array.isArray(e.oneOf)?e.oneOf.some(e=>T(e,t,n,i,a)):Array.isArray(e.anyOf)?e.anyOf.some(e=>T(e,t,n,i,a)):e.not?T(e.not,t,n,i,a):e.items?T(e.items,t,n,i,a):e.properties?Object.values(e.properties).some(e=>T(e,t,n,i,a)):e.additionalProperties&&typeof e.additionalProperties==`object`?T(e.additionalProperties,t,n,i,a):!1}function E(e,t){let n=ee(e,t);return n?n.allOf&&Array.isArray(n.allOf)?w(n).every(e=>E(e,t)):n.type===`object`||n.properties!==void 0||n.additionalProperties!==void 0:!1}function te(e){let t=new Map;if(!e?.mapping)return t;for(let[n,i]of Object.entries(e.mapping)){if(typeof i!=`string`)continue;let e=r(i),a=t.get(e);if(a){a.values.includes(n)||a.values.push(n);continue}t.set(e,{ref:i,values:[n]})}return t}function D(e,t,n,i=new Set){if(!e||typeof e!=`object`||i.has(e))return[];if(i.add(e),e.$ref&&typeof e.$ref==`string`){let a=r(e.$ref),o=n?.[a];return o?D(o,t,n,i):[]}let a=[],o=e.properties?.[t];if(o){let e=o.const;e!==void 0&&S(e)?a.push(e):Array.isArray(o.enum)&&o.enum?.length===1&&S(o.enum?.[0])&&a.push(o.enum?.[0])}if(Array.isArray(e.allOf))for(let r of e.allOf)a.push(...D(r,t,n,i));return Array.from(new Set(a))}function O(e,t,n){return{allOf:[e,{type:`object`,properties:{[t]:{const:n}},required:[t]}]}}function ne(e,t,n,i){let a=new Set;for(let t of e)t?.$ref&&a.add(r(t.$ref));let o=[],s=!1;for(let a of e){let e=[];if(a?.$ref){let o=r(a.$ref),s=n.get(o);s?.values.length&&e.push(...s.values),e.push(...D(a,t,i))}else e.push(...D(a,t,i));let c=Array.from(new Set(e));if(c.length===0){s=!0,o.push(a);continue}for(let e of c)o.push(O(a,t,e))}for(let[e,r]of n.entries()){if(a.has(e))continue;let n={$ref:r.ref};for(let e of r.values)o.push(O(n,t,e))}return{schemas:o,hasUnmapped:s}}function re(e,t,n,r,i,a,o){let{schemas:s,hasUnmapped:c}=ne(e,t,o??new Map,i),l=s.map(e=>k(e,n,r,i,a));return l.length===0?`z.unknown()`:l.length===1?l[0]??`z.unknown()`:c?`z.union([${l.join(`, `)}])`:`z.discriminatedUnion(${JSON.stringify(t)}, [${l.join(`, `)}])`}function k(e,t,n,i,a,o){if(e.$ref){let t=r(e.$ref),o=n?.get(t)||t;return a&&(o===a||T(i?.[t],a,i,n))?`z.lazy((): z.ZodType => ${o})`:o}if(e.const!==void 0&&S(e.const))return`z.literal(${JSON.stringify(e.const)})`;if(e.enum)return e.enum.length===1?`z.literal(${JSON.stringify(e.enum[0])})`:`z.enum([${e.enum.map(e=>`"${e}"`).join(`, `)}])`;if(e.not){let r=e.not,o={...e};delete o.not;let s=C(o)?k(o,t,n,i,a):`z.any()`;return r?.type===`string`&&r.maxLength===0?`${s}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`:`${s}.refine((value) => !${k(r,t,n,i,a)}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let r=w(e),o=r.map(e=>k(e,t,n,i,a));if(o.length===0)return`z.object({})`;if(o.length===1)return o[0]??`z.object({})`;let s=r.every(e=>E(e,i))?`merge`:`and`;return`${o[0]}${o.slice(1).map(e=>`.${s}(${e})`).join(``)}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(e.discriminator?.propertyName){let r=te(e.discriminator);return re(e.oneOf,e.discriminator.propertyName,t,n,i,a,r)}return x(e.oneOf,t,n,i,a)}if(e.anyOf&&Array.isArray(e.anyOf))return x(e.anyOf,t,n,i,a);if(e.type===`object`||e.properties||e.allOf)return ae(e,t,n,i,a);switch(e.type){case`string`:return oe(e,t,o);case`boolean`:return`z.boolean()`;case`array`:{let r=e.items??{type:`unknown`},o=k(r,t,n,i,a),s=t.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return j(e,`z.array(${o})`,r,s)}case`null`:return`z.null()`;case`number`:return A(e,t);case`integer`:return ce(e,t);default:return`z.unknown()`}}function ie(e,t){if(!e||!t)return new Set;let n=new Set;for(let i of Object.values(e)){if(!i||typeof i!=`object`)continue;let e=i.discriminator?.propertyName;if(!e||!Array.isArray(i.oneOf))continue;let a=i.oneOf.some(e=>e?.$ref&&r(e.$ref)===t),o=Object.values(i.discriminator?.mapping??{}).some(e=>typeof e==`string`&&r(e)===t);(a||o)&&n.add(e)}return n}function ae(e,t,n,r,i){let o=[],s=ie(r,i),c=new Set(e.required??[]);for(let[l,u]of Object.entries(e.properties||{})){let e=c.has(l)||s.has(l),d=k(u,t,n,r,i),f=y(d,t.optionalType),p=t.optionalType===`nullable`?f:se(f,u),m=e?d:p;o.push(` ${a(l)}: ${m},`)}let l=o.length===0?`z.object({})`:`z.object({\n${o.join(`
|
|
2
|
+
`)}\n})`;return e.additionalProperties===void 0?l:e.additionalProperties===!1?`${l}.strict()`:e.additionalProperties===!0?`${l}.passthrough()`:`${l}.catchall(${k(e.additionalProperties,t,n,r,i)})`}function oe(e,t,n){if(e.format===`binary`)return`(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))`;if(t.strictDates)switch(e.format){case`date-time`:return t.dateTimeOffset===!0||Array.isArray(t.dateTimeOffset)&&n!==void 0&&t.dateTimeOffset.includes(n)?`z.string().datetime({ offset: true })`:`z.string().datetime()`;case`date`:return`z.string().date()`;case`time`:return`z.string().time()`;case`duration`:return`z.string().duration()`}let r=`z.string()`;switch(t.strictNumeric&&(typeof e.minLength==`number`&&(r+=`.min(${e.minLength})`),typeof e.maxLength==`number`&&(r+=`.max(${e.maxLength})`),e.pattern&&(r+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case`uuid`:return`${r}.uuid()`;case`email`:return`${r}.email()`;case`uri`:case`url`:return`${r}.url()`;case`ipv4`:return`${r}.ip({ version: "v4" })`;case`ipv6`:return`${r}.ip({ version: "v6" })`;default:return r}}function se(e,t){return!t||t.default===void 0||t.default===null&&!(e.includes(`.nullable()`)||e.includes(`.nullish()`)||t.type===`null`||Array.isArray(t.type)&&t.type.includes(`null`))?e:`${e}.default(${JSON.stringify(t.default)})`}function A(e,t){let n=`z.number()`;return t.strictNumeric&&(n=ue(e,n),typeof e.multipleOf==`number`&&e.multipleOf!==0&&(n+=`.refine((value) => Math.abs(value / ${e.multipleOf} - Math.round(value / ${e.multipleOf})) < Number.EPSILON, { message: "Must be a multiple of ${e.multipleOf}" })`)),n}function ce(e,t){let n=A(e,t);return n+=`.int()`,n}function j(e,t,n,r){return r?(typeof e.minItems==`number`&&(t+=`.min(${e.minItems})`),typeof e.maxItems==`number`&&(t+=`.max(${e.maxItems})`),e.uniqueItems&&le(n)&&(t+=`.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })`),t):t}function le(e){return e?.$ref?!1:new Set([`string`,`number`,`integer`,`boolean`]).has(e?.type)}function ue(e,t){return typeof e.minimum==`number`?e.exclusiveMinimum===!0?t+=`.gt(${e.minimum})`:t+=`.min(${e.minimum})`:typeof e.exclusiveMinimum==`number`&&(t+=`.gt(${e.exclusiveMinimum})`),typeof e.maximum==`number`?e.exclusiveMaximum===!0?t+=`.lt(${e.maximum})`:t+=`.max(${e.maximum})`:typeof e.exclusiveMaximum==`number`&&(t+=`.lt(${e.exclusiveMaximum})`),t}const de={400:`badRequest`,401:`unauthorized`,402:`paymentRequired`,403:`forbidden`,404:`notFound`,405:`methodNotAllowed`,406:`notAcceptable`,407:`proxyAuthenticationRequired`,408:`requestTimeout`,409:`conflict`,410:`gone`,411:`lengthRequired`,412:`preconditionFailed`,413:`payloadTooLarge`,414:`uriTooLong`,415:`unsupportedMediaType`,416:`rangeNotSatisfiable`,417:`expectationFailed`,418:`imATeapot`,421:`misdirectedRequest`,422:`unprocessableEntity`,423:`locked`,424:`failedDependency`,425:`tooEarly`,426:`upgradeRequired`,428:`preconditionRequired`,429:`tooManyRequests`,431:`requestHeaderFieldsTooLarge`,451:`unavailableForLegalReasons`,500:`internalServerError`,501:`notImplemented`,502:`badGateway`,503:`serviceUnavailable`,504:`gatewayTimeout`,505:`httpVersionNotSupported`,506:`variantAlsoNegotiates`,507:`insufficientStorage`,508:`loopDetected`,510:`notExtended`,511:`networkAuthenticationRequired`};function M(e){if(e===`default`)return`defaultError`;let t=e.trim(),n=de[t];if(n)return n;if(/^\d{3}$/.test(t))return`status${t}`;let r=t.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim();if(!r)return`unknownError`;let[i,...a]=r.split(/\s+/),o=i+a.map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``);return o?/^[a-zA-Z_$]/.test(o)?o:`status${o.charAt(0).toUpperCase()}${o.slice(1)}`:`unknownError`}function N(e){if(e===`default`)return!0;let t=Number(e);return Number.isInteger(t)?t>=400:!1}function fe(e,t){let n=[];if(e.paths)for(let[r,i]of Object.entries(e.paths))for(let[a,o]of Object.entries(i)){let s=a.toLowerCase();if(!H(s)||!o.operationId)continue;let c=F(r),l=I(o,t),{successResponse:u,errors:d,successResponses:f,errorResponses:p}=L(o,o.operationId,t),m=P(i,o,e),h=z(m),g=B(m),_=V(o,e);n.push({operationId:o.operationId,path:r,method:s,pathParams:c,queryParams:g,requestType:l,responseType:u,successResponses:f,errorResponses:p,requestHeaders:h,errors:d,security:_})}if(e.webhooks)for(let[r,i]of Object.entries(e.webhooks))for(let[a,o]of Object.entries(i)){let s=a.toLowerCase();if(!H(s)||!o.operationId)continue;let c=r,l=F(c),u=I(o,t),{successResponse:d,errors:f,successResponses:p,errorResponses:m}=L(o,o.operationId,t),h=P(i,o,e),g=z(h),_=B(h),v=V(o,e);n.push({operationId:o.operationId,path:c,method:s,pathParams:l,queryParams:_,requestType:u,responseType:d,successResponses:p,errorResponses:m,requestHeaders:g,errors:f,security:v})}return n}function P(e,t,n){let r=new Map,i=e=>{if(Array.isArray(e))for(let t of e){let e=h(t,n);if(!e)continue;let i=`${e.in}:${e.name}`;r.set(i,e)}};return i(e.parameters),i(t.parameters),Array.from(r.values())}function F(e){let t=[],n=e.match(/{([^}]+)}/g);if(n)for(let e of n){let n=e.slice(1,-1);t.push({name:n,type:`string`})}return t}function I(e,t){let n=pe(e);if(n){if(n.$ref){let e=r(n.$ref);return t?.get(e)||e}return`${s(o(e.operationId))}Request`}}function pe(e){let t=e?.requestBody?.content;if(!(!t||Object.keys(t).length===0))for(let e of[`application/json`,`multipart/form-data`,`application/x-www-form-urlencoded`]){let n=t[e]?.schema;if(n)return n}}function L(e,t,n){let r=e.responses??{},i=new Map,a=[];for(let[e,t]of Object.entries(r)){let n=t?.content;if(!n||Object.keys(n).length===0){e===`204`||/^3\d\d$/.test(e)?i.set(e,`undefined`):N(e)&&a.push({code:e,schema:`undefined`});continue}let r=f(n),o=n[r]?.schema,s=m(r,o);if(!s){let t=ve(r,e);t&&(N(e)?a.push({code:e,schema:t}):/^2\d\d$/.test(e)&&i.set(e,t));continue}if(N(e)){a.push({code:e,schema:s});continue}/^2\d\d$/.test(e)&&i.set(e,s)}return{successResponse:ge(i,t,n),errors:_e(a,t,n),successResponses:me(i,t,n),errorResponses:he(a,t,n)}}function me(e,t,n){if(e.size===0)return;let r={};for(let[i,a]of e)typeof a==`string`?r[i]=a:r[i]=R(a,`${s(o(t))}Status${i}`,n);return r}function he(e,t,n){if(e.length===0)return;let r={};for(let{code:i,schema:a}of e){let e=M(i);r[i]=R(a,`${s(o(t))}${s(e)}`,n)}return r}function ge(e,t,n){if(e.size===0)return;for(let r of[`200`,`201`,`204`]){let i=e.get(r);if(i)return typeof i==`string`?i:R(i,`${s(o(t))}Response`,n)}let[,r]=e.entries().next().value??[];if(r)return typeof r==`string`?r:R(r,`${s(o(t))}Response`,n)}function _e(e=[],t,n){if(!e.length)return;let r={};for(let{code:i,schema:a}of e){let e=M(i);r[e]=R(a,`${s(o(t))}${s(e)}`,n)}return r}function R(e,t,n){if(typeof e==`string`)return e;if(e.$ref){let t=r(e.$ref);return n?.get(t)||t}if(e.type===`array`&&e.items?.$ref){let t=r(e.items.$ref);return`z.array(${n?.get(t)||t})`}return e.allOf&&Array.isArray(e.allOf),t}function z(e){let t=[];for(let n of e??[])n.in===`header`&&t.push({name:n.name,description:n.description,schema:n.schema,required:n.required});return t}function B(e){let t=[];for(let n of e??[])n.in===`query`&&t.push({name:n.name,description:n.description,schema:n.schema,required:n.required});return t}function V(e,t){let n=e.security;if(Array.isArray(n))return n.length===0?[]:n;if(Array.isArray(t.security)&&t.security.length>0)return t.security}function H(e){switch(e){case`get`:case`put`:case`post`:case`delete`:case`options`:case`head`:case`patch`:case`trace`:return!0;default:return!1}}function ve(e,t){return t===`204`||/^3\d\d$/.test(t)?`undefined`:e in d?d[e]:`unknown`}function ye(e,t){let n=new Map,r=g(t);for(let t of e){let e=r.get(t.operationId);if(!e)continue;let i=e.requestBody;if(i&&i.content){let e=i.content,r=be(e);if(!r)continue;let a=`${s(o(t.operationId))}Request`;(!r.$ref||r.allOf||r.oneOf||r.anyOf)&&n.set(a,r)}}return n}function be(e){for(let t of[`application/json`,`multipart/form-data`,`application/x-www-form-urlencoded`]){let n=e[t]?.schema;if(n)return n}}function xe(e,t){let n=new Map,r=g(t);for(let t of e){let e=r.get(t.operationId);if(!e)continue;let i=e.responses||{};for(let[e,r]of Object.entries(i))if(/^2\d\d$/.test(e)&&r.content){let e=r.content,i=f(e),a=e[i]?.schema,c=m(i,a);if(!c)continue;let l=`${s(o(t.operationId))}Response`;(!c.$ref||c.allOf||c.oneOf||c.anyOf)&&n.set(l,c)}}return n}function Se(e,t,n,r,i){let a=ye(t,n);if(a.size>0){e.push(`// Generated Request Types`),e.push(``);for(let[t,n]of a){let a=b(t,n,new Set,i,r);e.push(a),e.push(``),e.push(`export type ${t} = z.infer<typeof ${t}>;`),e.push(``)}}}function Ce(e,t,n,r,i){let a=xe(t,n);if(a.size>0){e.push(`// Generated Response Types`),e.push(``);for(let[t,n]of a){let a=b(t,n,new Set,i,r);e.push(a),e.push(``),e.push(`export type ${t} = z.infer<typeof ${t}>;`),e.push(``)}}}function we(){let e=[];return e.push(`// Generated helper types for Zenko`),e.push(`// This file provides type definitions for operation objects and path functions`),e.push(``),e.push(`export type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string`),e.push(``),e.push(`export type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"`),e.push(``),e.push(`export type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult`),e.push(``),e.push(`export type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown)`),e.push(``),e.push(`export type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;`),e.push(``),e.push(`export type SecurityRequirement = Readonly<Record<string, readonly string[]>>`),e.push(``),e.push(`export type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {`),e.push(` method: TMethod`),e.push(` path: TPath`),e.push(` request?: TRequest`),e.push(` response?: TResponse`),e.push(` headers?: THeaders`),e.push(` errors?: TErrors`),e.push(` security?: TSecurity`),e.push(`}`),e.push(``),e.join(`
|
|
3
|
+
`)}function Te(e){return e===void 0?{open:!1,prefix:`Unknown:`}:typeof e==`boolean`||Array.isArray(e)?{open:e,prefix:`Unknown:`}:{open:e.open??!1,prefix:e.unknownPrefix??`Unknown:`}}function U(e,n={}){let r=[],s=new Set,{strictDates:c=!1,strictNumeric:l=!1,dateTimeOffset:u=!0,operationIds:d,openEnums:f=!1}=n,p=Oe({...n.types,operationTypeSuffix:n.types?.operationTypeSuffix??`Operation`}),m=Te(f),h={strictDates:c,strictNumeric:l,dateTimeOffset:u,optionalType:p.optionalType,openEnums:m.open,openEnumPrefix:m.prefix};r.push(`import { z } from "zod";`);let g=new Map;if(e.components?.schemas)for(let t of Object.keys(e.components.schemas))g.set(t,o(t));let v=fe(e,g);if(d&&d.length>0){let e=new Set(d);v=v.filter(t=>e.has(t.operationId))}if(ke(r,p,v),r.push(``),e.components?.schemas){r.push(`// Generated Zod Schemas`),r.push(``);let n=d&&d.length>0?new Set(_(v,e)):new Set(Object.keys(e.components.schemas)),i=t(e.components.schemas).filter(e=>n.has(e));for(let t of i){let n=e.components.schemas[t],i=g.get(t);r.push(b(i,n,s,h,g,e.components.schemas)),r.push(``),r.push(`export type ${i} = z.infer<typeof ${i}>;`),r.push(``)}}r.push(`// Path Functions`),r.push(`export const paths = {`);for(let e of v){let t=e.pathParams.map(e=>e.name).length>0,n=e.queryParams.length>0,s=o(e.operationId);if(!t&&!n){r.push(` ${a(s)}: () => "${e.path}",`);continue}let c=e=>{if(i(e))return e;let t=o(e);return i(t)||(t=`_${t}`),t},l=[],u=[];for(let t of e.pathParams)l.push(i(t.name)?t.name:`${a(t.name)}: ${c(t.name)}`),u.push(`${a(t.name)}: string`);for(let t of e.queryParams)l.push(i(t.name)?t.name:`${a(t.name)}: ${c(t.name)}`),u.push(`${a(t.name)}${t.required?``:`?`}: ${Fe(t)}`);let d=!t&&n&&e.queryParams.every(e=>!e.required),f=`${l.length?`{ ${l.join(`, `)} }`:`{}`}: { ${u.join(`, `)} }${d?` = {}`:``}`,p=e.path.replace(/{([^}]+)}/g,(e,t)=>`\${${c(t)}}`);if(!n){r.push(` ${a(s)}: (${f}) => \`${p}\`,`);continue}r.push(` ${a(s)}: (${f}) => {`),r.push(` const params = new URLSearchParams()`);for(let t of e.queryParams){let e=i(t.name)?t.name:c(o(t.name)),n=t.schema??{};if(n?.type===`array`){let i=Q(n.items??{},`value`);t.required?(r.push(` for (const value of ${e}) {`),r.push(` params.append("${t.name}", ${i})`),r.push(` }`)):(r.push(` if (${e} !== undefined) {`),r.push(` for (const value of ${e}) {`),r.push(` params.append("${t.name}", ${i})`),r.push(` }`),r.push(` }`));continue}let a=Q(n,e);t.required?r.push(` params.set("${t.name}", ${a})`):(r.push(` if (${e} !== undefined) {`),r.push(` params.set("${t.name}", ${a})`),r.push(` }`))}r.push(` const _searchParams = params.toString()`),r.push(` return \`${p}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),r.push(` },`)}r.push(`} as const;`),r.push(``),r.push(`// Header Schemas`),r.push(`export const headerSchemas = {`);for(let e of v){let t=o(e.operationId);if(!e.requestHeaders||e.requestHeaders.length===0){r.push(` ${a(t)}: z.object({}),`);continue}let n=e.requestHeaders.map(e=>{let t=Pe(e),n=e.required?t:y(t,h.optionalType);return` ${a(e.name)}: ${n},`}).join(`
|
|
4
|
+
`);r.push(` ${a(t)}: z.object({`),r.push(n),r.push(` }),`)}r.push(`} as const;`),r.push(``),r.push(`// Header Functions`),r.push(`export const headers = {`);for(let e of v){let t=o(e.operationId);if(!e.requestHeaders||e.requestHeaders.length===0){r.push(` ${a(t)}: () => ${i(t)?`headerSchemas.${t}`:`headerSchemas[${a(t)}]`}.parse({}),`);continue}r.push(` ${a(t)}: (params: z.input<${i(t)?`typeof headerSchemas.${t}`:`(typeof headerSchemas)[${a(t)}]`}>) => {`),r.push(` return ${i(t)?`headerSchemas.${t}`:`headerSchemas[${a(t)}]`}.parse(params)`),r.push(` },`)}if(r.push(`} as const;`),r.push(``),e.components?.securitySchemes&&Object.keys(e.components.securitySchemes).length>0){r.push(`// Security Schemes`),r.push(`export const securitySchemes = {`);for(let[t,n]of Object.entries(e.components.securitySchemes)){let e=n;r.push(` ${a(t)}: {`),r.push(` type: ${JSON.stringify(e.type)},`),e.type===`http`?(r.push(` scheme: ${JSON.stringify(String(e.scheme).toLowerCase())},`),e.bearerFormat&&r.push(` bearerFormat: ${JSON.stringify(e.bearerFormat)},`)):e.type===`apiKey`?(r.push(` name: ${JSON.stringify(e.name)},`),r.push(` in: ${JSON.stringify(e.in)},`)):e.type===`oauth2`?r.push(` flows: ${JSON.stringify(e.flows)},`):e.type===`openIdConnect`&&r.push(` openIdConnectUrl: ${JSON.stringify(e.openIdConnectUrl)},`),r.push(` },`)}r.push(`} as const;`),r.push(``)}Se(r,v,e,g,h),Ce(r,v,e,g,h),Ae(r,v,p),r.push(`// Operation Objects`);for(let e of v){let t=o(e.operationId),n=p.emit?`: ${K(t,p.operationTypeSuffix)}`:``;if(r.push(`export const ${t}${n} = {`),r.push(` method: "${e.method}",`),r.push(` path: paths.${t},`),W(r,`request`,e.requestType),W(r,`response`,e.responseType),e.requestHeaders&&e.requestHeaders.length>0&&r.push(` headers: headers.${t},`),e.security!==void 0)if(e.security.length===0)r.push(` security: [],`);else{let t=e.security.map(e=>`{ ${Object.entries(e).map(([e,t])=>`${a(e)}: ${JSON.stringify(t)}`).join(`, `)} }`);r.push(` security: [${t.join(`, `)}],`)}e.errors&&G(e.errors)&&De(r,`errors`,e.errors),r.push(`} as const;`),r.push(``)}je(r,v);let x={output:r.join(`
|
|
5
|
+
`)};return p.emit&&p.helpers===`file`&&p.helpersOutput&&(x.helperFile={path:p.helpersOutput,content:we()}),x}function Ee(e,t={}){return U(e,t).output}function W(e,t,n){n&&e.push(` ${t}: ${n},`)}function De(e,t,n){if(!(!n||Object.keys(n).length===0)){e.push(` ${t}: {`);for(let[t,r]of Object.entries(n))e.push(` ${a(t)}: ${r},`);e.push(` },`)}}function G(e){return!!(e&&Object.keys(e).length>0)}function Oe(e){let t=e?.operationTypeSuffix??`Operation`;if(t!==``&&!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(t))throw Error(`Invalid operationTypeSuffix "${t}": must be a valid TypeScript identifier suffix (letters, digits, underscores, or $). Use "" for no suffix.`);return{emit:e?.emit??!0,helpers:e?.helpers??`package`,helpersOutput:e?.helpersOutput??`./zenko-types`,treeShake:e?.treeShake??!0,optionalType:e?.optionalType??`optional`,operationTypeSuffix:t}}function K(e,t){return`${s(e)}${t}`}function ke(e,t,n){if(t.emit)switch(t.helpers){case`package`:if(t.treeShake){let t=l(c(n),`package`);t&&e.push(t)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "zenko";`);return;case`file`:if(t.treeShake){let r=l(c(n),`file`,t.helpersOutput);r&&e.push(r)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "${t.helpersOutput}";`);return;case`inline`:e.push(`type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;`),e.push(`type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";`),e.push(`type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;`),e.push(`type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);`),e.push(`type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;`),e.push(`type SecurityRequirement = Readonly<Record<string, readonly string[]>>;`),e.push(`type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {`),e.push(` method: TMethod`),e.push(` path: TPath`),e.push(` request?: TRequest`),e.push(` response?: TResponse`),e.push(` headers?: THeaders`),e.push(` errors?: TErrors`),e.push(` security?: TSecurity`),e.push(`}`),e.push(``)}}function Ae(e,t,n){if(n.emit){e.push(`// Operation Types`);for(let r of t){let t=o(r.operationId),s=K(t,n.operationTypeSuffix),c=r.requestHeaders?.length?i(t)?`typeof headers.${t}`:`(typeof headers)[${a(t)}]`:`undefined`,l=Y(r.requestType),u=Y(r.responseType),d=Me(r.errors),f=r.security===void 0?`undefined`:r.security.length===0?`readonly []`:`readonly [${r.security.map(e=>`{ ${Object.entries(e).map(([e,t])=>`readonly ${a(e)}: readonly ${JSON.stringify(t)}`).join(`; `)} }`).join(`, `)}]`;e.push(`export type ${s} = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${i(t)?`typeof paths.${t}`:`(typeof paths)[${a(t)}]`},`),e.push(` ${l},`),e.push(` ${u},`),e.push(` ${c},`),e.push(` ${d},`),e.push(` ${f}`),e.push(`>;`),e.push(``)}}}function je(e,t){e.push(`// Operation Metadata`),e.push(`export const operationMetadata = {`);for(let n of t){let t=o(n.operationId);e.push(` ${a(t)}: {`),e.push(` method: ${JSON.stringify(n.method)},`),e.push(` path: ${JSON.stringify(n.path)},`),n.successResponses&&Object.keys(n.successResponses).length>0&&e.push(` successResponses: ${JSON.stringify(n.successResponses)},`),n.errorResponses&&Object.keys(n.errorResponses).length>0&&e.push(` errorResponses: ${JSON.stringify(n.errorResponses)},`),e.push(` },`)}e.push(`} as const;`),e.push(``)}function Me(e){return!e||!G(e)?`OperationErrors`:`OperationErrors<${Ne(e)}>`}function Ne(e){return!e||Object.keys(e).length===0?`unknown`:`{ ${Object.entries(e).map(([e,t])=>`${a(e)}: ${X(t)}`).join(`; `)} }`}const q=new Set([`any`,`unknown`,`never`,`void`,`null`,`undefined`,`string`,`number`,`boolean`,`bigint`,`symbol`]),J=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Y(e){if(!e)return`undefined`;let t=e.trim();if(t===`undefined`)return`undefined`;if(q.has(t)||t.startsWith(`typeof `))return t;let n=t.match(/^z\.array\((.+)\)$/);return n?`z.ZodArray<${Y(n[1])}>`:J.test(t)?`typeof ${t}`:t}function X(e){if(!e)return`unknown`;let t=e.trim();if(q.has(t)||t.startsWith(`typeof `))return t;let n=t.match(/^z\.array\((.+)\)$/);return n?`z.ZodArray<${X(n[1])}>`:J.test(t)?`typeof ${t}`:t}function Pe(e){let t=e.schema??{};switch(t.type){case`integer`:case`number`:return`z.coerce.number()`;case`boolean`:return`z.coerce.boolean()`;case`array`:{let e=t.items??{type:`string`};return`z.array(${e.type===`integer`||e.type===`number`?`z.coerce.number()`:e.type===`boolean`?`z.coerce.boolean()`:`z.string()`})`}default:return`z.string()`}}function Fe(e){return Z(e.schema)}function Z(e){if(!e)return`string`;if(e.type===`array`)return`Array<${Z(e.items)}>`;switch(e.type){case`integer`:case`number`:return`number`;case`boolean`:return`boolean`;default:return`string`}}function Q(e,t){if(!e)return`String(${t})`;switch(e.type){case`integer`:case`number`:return`String(${t})`;case`boolean`:return`${t} ? "true" : "false"`;default:return`String(${t})`}}const Ie=new Set([`get`,`post`,`put`,`patch`,`delete`,`options`,`head`,`connect`,`trace`]);function Le(e){return e.split(`/`).filter(Boolean).map(e=>e.startsWith(`{`)&&e.endsWith(`}`)?`:${e.slice(1,-1)}`:e)}function Re(e){let t={};for(let[n,r]of Object.entries(e)){let e=Le(r.path),i=r.method.toLowerCase();if(!Ie.has(i))return{ok:!1,error:Error(`Unsupported method ${r.method} for ${n}`)};let a=ze(t,e,i,n);if(!a.ok)return a}return{ok:!0,value:t}}function ze(e,t,n,r){if(t.length===0){let t=e,i=t!==void 0&&typeof t==`object`&&t&&!Array.isArray(t)?{...t}:{};if(i[n]!==void 0){let e=`Duplicate ${n} on root for ${r} vs `,t=JSON.stringify(i[n]);return{ok:!1,error:Error(e+t)}}i[n]=r;for(let t of Object.keys(e))delete e[t];return Object.assign(e,i),{ok:!0,value:void 0}}let i=e;for(let e=0;e<t.length;e+=1){let a=t[e];if(e===t.length-1){let e=i[a],t=e!==void 0&&typeof e==`object`&&e&&!Array.isArray(e)?{...e}:{};if(t[n]!==void 0){let e=`Duplicate ${n} on ${a} for ${r} vs `,i=JSON.stringify(t[n]);return{ok:!1,error:Error(e+i)}}t[n]=r,i[a]=t}else{let e=i[a];if(e!==void 0&&typeof e!=`object`&&e!==null&&!Array.isArray(e))return{ok:!1,error:Error(`TreatyRouteTree conflict at segment ${JSON.stringify(a)}: cannot add nested path for ${n} (${r}); existing value is not an object: ${JSON.stringify(e)}`)};(e===void 0||typeof e!=`object`||!e||Array.isArray(e))&&(i[a]={}),i=i[a]}}return{ok:!0,value:void 0}}function Be(e){return Ve(e,1)}function Ve(e,t){let n=` `.repeat(t),r=[];for(let[i,o]of Object.entries(e)){let e=a(i);typeof o==`string`?r.push(`${n}${e}: ${o},`):o&&typeof o==`object`&&!Array.isArray(o)&&(r.push(`${n}${e}: {`),r.push(Ve(o,t+1)),r.push(`${n}},`))}return r.join(`
|
|
6
|
+
`)}function $(e,t){let n=Re(e);if(!n.ok)throw n.error;let r=Object.keys(e).sort(),i=Be(n.value);return[`import { createTreatyClient, type TreatyClient } from "zenko/treaty";`,`import { ${r.join(`, `)} } from ${JSON.stringify(t.importPath)};`,``,`export const treatyRoutes = {`,i,`};`,``,`export function createClient(`,` baseUrl: string,`,` init?: { fetch?: typeof fetch }`,`): TreatyClient<typeof treatyRoutes> {`,` return createTreatyClient({`,` baseUrl,`,` routes: treatyRoutes,`,` fetch: init?.fetch,`,` })`,`}`,``].join(`
|
|
7
|
+
`)}async function He(t){let n=await import((0,e.pathToFileURL)(t.inputFile).href);if(!n.operationMetadata)throw Error(`Missing operationMetadata export in ${t.inputFile} — regenerate with the latest Zenko`);let r=n.operationMetadata;return $(r,{importPath:t.importPath})}Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return Ee}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return He}});
|
|
8
|
+
//# sourceMappingURL=treaty-generator-Byq49esG.cjs.map
|
package/dist/treaty.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=new Set([`get`,`post`,`put`,`patch`,`delete`,`options`,`head`,`connect`,`trace`]);function t(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.method==`string`&&(typeof t.path==`function`||typeof t.path==`string`)}function n(e,t){return`${e.replace(/\/$/,``)}${t.startsWith(`/`)?t:`/${t}`}`}function r(e,t){return typeof e==`string`?e:e.length===0?e():e(t)}function i(e){return e instanceof Date?e.toISOString():typeof e==`object`&&e?JSON.stringify(e):typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}function a(e){let t=[];for(let[n,r]of Object.entries(e)){if(r==null)continue;let e=i(r);t.push(`${encodeURIComponent(n)}=${encodeURIComponent(e)}`)}return t.length?`?${t.join(`&`)}`:``}async function o(e){if((e.headers.get(`content-type`)??``).includes(`application/json`))try{return await e.json()}catch{return null}let t=await e.text();return t===``?null:t}function s(n){let{baseUrl:r,node:i,params:a,fetchImpl:o}=n;return new Proxy(()=>{},{get(n,l){if(typeof l==`symbol`||l===`then`)return;let u=i[l];if(u!==void 0)return t(u)?e.has(l)?c({baseUrl:r,leaf:u,params:a,fetchImpl:o}):void 0:s({baseUrl:r,node:u,params:a,fetchImpl:o})},apply(e,n,c){let l=c[0];if(!l||typeof l!=`object`)throw TypeError(`Expected a path parameter object`);let u=i,d=Object.keys(u).find(e=>e.startsWith(`:`));if(!d)throw TypeError(`No dynamic path segment here`);let f=u[d];if(f===void 0)throw TypeError(`Missing route segment ${d}`);let p={...a,...l};if(t(f))throw TypeError(`Unexpected leaf under dynamic segment`);return s({baseUrl:r,node:f,params:p,fetchImpl:o})}})}function c(e){let{baseUrl:t,leaf:i,params:s,fetchImpl:c}=e,l=i.method.toLowerCase(),u=l.toUpperCase(),d=l===`get`||l===`head`;return async(e,l)=>{let f=n(t,r(i.path,s)),p=d?e?.query:l?.query;p&&typeof p==`object`&&(f+=a(p));let m={...d?e?.headers:l?.headers},h;!d&&e!==void 0&&(typeof FormData<`u`&&e instanceof FormData?(h=e,delete m[`content-type`]):typeof Blob<`u`&&e instanceof Blob?(h=e,e.type&&(m[`content-type`]=e.type)):(m[`content-type`]=m[`content-type`]??`application/json`,h=typeof e==`string`||e instanceof ArrayBuffer?e:JSON.stringify(e)));let{method:g,body:_,...v}=l??{},y=await c(f,{...v,method:u,headers:Object.keys(m).length>0?new Headers(m):void 0,body:d?void 0:h}),b=await o(y);return y.ok?{data:b,error:null,response:y,status:y.status,headers:y.headers}:{data:null,error:{status:y.status,body:b},response:y,status:y.status,headers:y.headers}}}function l(e){let t=e.fetch??globalThis.fetch;return s({baseUrl:e.baseUrl,node:e.routes,params:{},fetchImpl:t})}exports.createTreatyClient=l;
|
|
2
|
+
//# sourceMappingURL=treaty.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as RouteNode, c as TreatySuccess, i as TreatyRoutesConstraint, n as LeafCall, o as TreatyFailure, r as TreatyClient, s as TreatyResult, t as createTreatyClient } from "./treaty-NM6Hf8S8.cjs";
|
|
2
|
+
export { LeafCall, RouteNode, TreatyClient, TreatyFailure, TreatyResult, TreatyRoutesConstraint, TreatySuccess, createTreatyClient };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as RouteNode, c as TreatySuccess, i as TreatyRoutesConstraint, n as LeafCall, o as TreatyFailure, r as TreatyClient, s as TreatyResult, t as createTreatyClient } from "./treaty-DM77ZhDU.mjs";
|
|
2
|
+
export { LeafCall, RouteNode, TreatyClient, TreatyFailure, TreatyResult, TreatyRoutesConstraint, TreatySuccess, createTreatyClient };
|
package/dist/treaty.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=new Set([`get`,`post`,`put`,`patch`,`delete`,`options`,`head`,`connect`,`trace`]);function t(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.method==`string`&&(typeof t.path==`function`||typeof t.path==`string`)}function n(e,t){return`${e.replace(/\/$/,``)}${t.startsWith(`/`)?t:`/${t}`}`}function r(e,t){return typeof e==`string`?e:e.length===0?e():e(t)}function i(e){return e instanceof Date?e.toISOString():typeof e==`object`&&e?JSON.stringify(e):typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}function a(e){let t=[];for(let[n,r]of Object.entries(e)){if(r==null)continue;let e=i(r);t.push(`${encodeURIComponent(n)}=${encodeURIComponent(e)}`)}return t.length?`?${t.join(`&`)}`:``}async function o(e){if((e.headers.get(`content-type`)??``).includes(`application/json`))try{return await e.json()}catch{return null}let t=await e.text();return t===``?null:t}function s(n){let{baseUrl:r,node:i,params:a,fetchImpl:o}=n;return new Proxy(()=>{},{get(n,l){if(typeof l==`symbol`||l===`then`)return;let u=i[l];if(u!==void 0)return t(u)?e.has(l)?c({baseUrl:r,leaf:u,params:a,fetchImpl:o}):void 0:s({baseUrl:r,node:u,params:a,fetchImpl:o})},apply(e,n,c){let l=c[0];if(!l||typeof l!=`object`)throw TypeError(`Expected a path parameter object`);let u=i,d=Object.keys(u).find(e=>e.startsWith(`:`));if(!d)throw TypeError(`No dynamic path segment here`);let f=u[d];if(f===void 0)throw TypeError(`Missing route segment ${d}`);let p={...a,...l};if(t(f))throw TypeError(`Unexpected leaf under dynamic segment`);return s({baseUrl:r,node:f,params:p,fetchImpl:o})}})}function c(e){let{baseUrl:t,leaf:i,params:s,fetchImpl:c}=e,l=i.method.toLowerCase(),u=l.toUpperCase(),d=l===`get`||l===`head`;return async(e,l)=>{let f=n(t,r(i.path,s)),p=d?e?.query:l?.query;p&&typeof p==`object`&&(f+=a(p));let m={...d?e?.headers:l?.headers},h;!d&&e!==void 0&&(typeof FormData<`u`&&e instanceof FormData?(h=e,delete m[`content-type`]):typeof Blob<`u`&&e instanceof Blob?(h=e,e.type&&(m[`content-type`]=e.type)):(m[`content-type`]=m[`content-type`]??`application/json`,h=typeof e==`string`||e instanceof ArrayBuffer?e:JSON.stringify(e)));let{method:g,body:_,...v}=l??{},y=await c(f,{...v,method:u,headers:Object.keys(m).length>0?new Headers(m):void 0,body:d?void 0:h}),b=await o(y);return y.ok?{data:b,error:null,response:y,status:y.status,headers:y.headers}:{data:null,error:{status:y.status,body:b},response:y,status:y.status,headers:y.headers}}}function l(e){let t=e.fetch??globalThis.fetch;return s({baseUrl:e.baseUrl,node:e.routes,params:{},fetchImpl:t})}export{l as createTreatyClient};
|
|
2
|
+
//# sourceMappingURL=treaty.mjs.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;
|
|
3
|
+
type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";
|
|
4
|
+
type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;
|
|
5
|
+
type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);
|
|
6
|
+
type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;
|
|
7
|
+
type SecurityRequirement = Readonly<Record<string, readonly string[]>>;
|
|
8
|
+
type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {
|
|
9
|
+
method: TMethod;
|
|
10
|
+
path: TPath;
|
|
11
|
+
request?: TRequest;
|
|
12
|
+
response?: TResponse;
|
|
13
|
+
headers?: THeaders;
|
|
14
|
+
errors?: TErrors;
|
|
15
|
+
security?: TSecurity;
|
|
16
|
+
};
|
|
17
|
+
//#endregion
|
|
18
|
+
export { PathFn as a, OperationErrors as i, HeaderFn as n, RequestMethod as o, OperationDefinition as r, SecurityRequirement as s, AnyHeaderFn as t };
|
|
19
|
+
//# sourceMappingURL=types-BM-Q_QIk.d.cts.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;
|
|
3
|
+
type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";
|
|
4
|
+
type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;
|
|
5
|
+
type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);
|
|
6
|
+
type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;
|
|
7
|
+
type SecurityRequirement = Readonly<Record<string, readonly string[]>>;
|
|
8
|
+
type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {
|
|
9
|
+
method: TMethod;
|
|
10
|
+
path: TPath;
|
|
11
|
+
request?: TRequest;
|
|
12
|
+
response?: TResponse;
|
|
13
|
+
headers?: THeaders;
|
|
14
|
+
errors?: TErrors;
|
|
15
|
+
security?: TSecurity;
|
|
16
|
+
};
|
|
17
|
+
//#endregion
|
|
18
|
+
export { PathFn as a, OperationErrors as i, HeaderFn as n, RequestMethod as o, OperationDefinition as r, SecurityRequirement as s, AnyHeaderFn as t };
|
|
19
|
+
//# sourceMappingURL=types-ByqlZjPK.d.mts.map
|
package/dist/types.cjs
ADDED
|
File without changes
|
package/dist/types.d.cts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as PathFn, i as OperationErrors, n as HeaderFn, o as RequestMethod, r as OperationDefinition, s as SecurityRequirement, t as AnyHeaderFn } from "./types-BM-Q_QIk.cjs";
|
|
2
|
+
export { AnyHeaderFn, HeaderFn, OperationDefinition, OperationErrors, PathFn, RequestMethod, SecurityRequirement };
|
package/dist/types.d.mts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as PathFn, i as OperationErrors, n as HeaderFn, o as RequestMethod, r as OperationDefinition, s as SecurityRequirement, t as AnyHeaderFn } from "./types-ByqlZjPK.mjs";
|
|
2
|
+
export { AnyHeaderFn, HeaderFn, OperationDefinition, OperationErrors, PathFn, RequestMethod, SecurityRequirement };
|
package/dist/types.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zenko",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0-beta.2",
|
|
4
4
|
"description": "Generate TypeScript types and path functions from OpenAPI specs",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"api",
|
|
@@ -29,33 +29,49 @@
|
|
|
29
29
|
"README.md",
|
|
30
30
|
"dist/**/*.cjs",
|
|
31
31
|
"dist/**/*.d.cts",
|
|
32
|
+
"dist/**/*.d.mts",
|
|
32
33
|
"dist/**/*.d.ts",
|
|
33
34
|
"dist/**/*.mjs"
|
|
34
35
|
],
|
|
35
36
|
"type": "module",
|
|
36
37
|
"main": "dist/index.cjs",
|
|
37
38
|
"module": "dist/index.mjs",
|
|
38
|
-
"types": "dist/index.d.
|
|
39
|
+
"types": "./dist/index.d.mts",
|
|
39
40
|
"exports": {
|
|
40
41
|
".": {
|
|
41
|
-
"types":
|
|
42
|
-
|
|
42
|
+
"types": {
|
|
43
|
+
"import": "./dist/index.d.mts",
|
|
44
|
+
"require": "./dist/index.d.cts"
|
|
45
|
+
},
|
|
46
|
+
"bun": "./dist/index.mjs",
|
|
43
47
|
"import": "./dist/index.mjs",
|
|
44
48
|
"require": "./dist/index.cjs"
|
|
45
49
|
},
|
|
46
50
|
"./types": {
|
|
47
|
-
"types":
|
|
48
|
-
|
|
51
|
+
"types": {
|
|
52
|
+
"import": "./dist/types.d.mts",
|
|
53
|
+
"require": "./dist/types.d.cts"
|
|
54
|
+
},
|
|
55
|
+
"bun": "./dist/types.mjs",
|
|
49
56
|
"import": "./dist/types.mjs",
|
|
50
57
|
"require": "./dist/types.cjs"
|
|
58
|
+
},
|
|
59
|
+
"./treaty": {
|
|
60
|
+
"types": {
|
|
61
|
+
"import": "./dist/treaty.d.mts",
|
|
62
|
+
"require": "./dist/treaty.d.cts"
|
|
63
|
+
},
|
|
64
|
+
"bun": "./dist/treaty.mjs",
|
|
65
|
+
"import": "./dist/treaty.mjs",
|
|
66
|
+
"require": "./dist/treaty.cjs"
|
|
51
67
|
}
|
|
52
68
|
},
|
|
53
69
|
"publishConfig": {
|
|
54
70
|
"access": "public"
|
|
55
71
|
},
|
|
56
72
|
"scripts": {
|
|
57
|
-
"build": "
|
|
58
|
-
"build:watch": "
|
|
73
|
+
"build": "tsdown",
|
|
74
|
+
"build:watch": "tsdown --watch",
|
|
59
75
|
"test": "bun test",
|
|
60
76
|
"coverage": "bun test --coverage",
|
|
61
77
|
"prepublishOnly": "bun run build",
|
|
@@ -63,13 +79,14 @@
|
|
|
63
79
|
},
|
|
64
80
|
"dependencies": {},
|
|
65
81
|
"devDependencies": {
|
|
66
|
-
"@types/bun": "1.3.
|
|
82
|
+
"@types/bun": "1.3.11",
|
|
67
83
|
"@zenko/specs": "workspace:*",
|
|
68
|
-
"
|
|
84
|
+
"tsdown": "0.21.7",
|
|
69
85
|
"typescript": "5.9.3"
|
|
70
86
|
},
|
|
71
87
|
"peerDependencies": {
|
|
72
|
-
"typescript": "^5"
|
|
88
|
+
"typescript": "^5",
|
|
89
|
+
"zod": "^4"
|
|
73
90
|
},
|
|
74
91
|
"peerDependenciesMeta": {
|
|
75
92
|
"typescript": {
|
package/dist/chunk-GD63CEJN.cjs
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }function ne(e){let n=new Set,t=new Set,r=[],o=i=>{if(n.has(i)||t.has(i))return;t.add(i);let s=e[i],a=Z(s);for(let p of a)e[p]&&o(p);t.delete(i),n.add(i),r.push(i)};for(let i of Object.keys(e))o(i);return r}function Z(e){let n=[],t=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=O(r.$ref);n.push(o);return}if(Array.isArray(r))r.forEach(t);else{if(r.mapping&&typeof r.mapping=="object")for(let o of Object.values(r.mapping))typeof o=="string"&&n.push(O(o));Object.values(r).forEach(t)}}};return t(e),[...new Set(n)]}function O(e){return(e.split("/").pop()||"Unknown").replace(/\.(yml|yaml)$/i,"")}function A(e){if(!e)return!1;let n=e.at(0);return n===void 0||!/[a-zA-Z_$]/.test(n)||!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?!1:!new Set(["abstract","arguments","await","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","eval","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","let","long","native","new","null","package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with","yield","async"]).has(e)}function S(e){return A(e)?e:`"${e}"`}function T(e){return e.replace(/-([a-zA-Z])/g,(n,t)=>t.toUpperCase()).replace(/-+$/,"")}function P(e){return e.charAt(0).toUpperCase()+e.slice(1)}function G(e){let n={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(n.usesOperationDefinition=!0);for(let t of e)t.errors&&te(t.errors)&&(n.usesOperationErrors=!0);return e.length>0&&!n.usesOperationErrors&&e.some(r=>!r.errors||!te(r.errors))&&(n.usesOperationErrors=!0),n}function U(e,n,t){let r=[];if(e.usesHeaderFn&&r.push("HeaderFn"),e.usesOperationDefinition&&r.push("OperationDefinition"),e.usesOperationErrors&&r.push("OperationErrors"),r.length===0)return"";let o=n==="package"?'"zenko"':`"${t}"`;return`import type { ${r.join(", ")} } from ${o};`}function te(e){return!!(e&&Object.keys(e).length>0)}var C={"application/json":"unknown","text/csv":"string","text/plain":"string","application/octet-stream":"unknown","application/pdf":"unknown"};function v(e){let n=Object.keys(e);if(n.includes("application/json"))return"application/json";for(let t of n)if(t in C)return t;return n[0]||""}function je(e){let n=_optionalChain([e, 'access', _2 => _2.toLowerCase, 'call', _3 => _3(), 'access', _4 => _4.split, 'call', _5 => _5(";"), 'access', _6 => _6[0], 'optionalAccess', _7 => _7.trim, 'call', _8 => _8()]);return n?!!(n.startsWith("text/")||n==="application/xml"||n.startsWith("application/")&&n.endsWith("+xml")):!1}function E(e,n){if(!n||!je(e)||n.$ref)return n;let t=n.nullable===!0?{nullable:!0}:{};return n.enum?{type:"string",enum:n.enum,...t}:{type:"string",...t}}function H(e,n){if(e){if(e.$ref){let t=O(e.$ref),r=_optionalChain([n, 'access', _9 => _9.components, 'optionalAccess', _10 => _10.parameters, 'optionalAccess', _11 => _11[t]]);if(!r)return;let{$ref:o,...i}=e;return{...r,...i}}return e}}function N(e){let n=new Map;for(let[,t]of Object.entries(e.paths||{}))for(let[,r]of Object.entries(t)){let o=r;o.operationId&&n.set(o.operationId,o)}for(let[,t]of Object.entries(e.webhooks||{}))for(let[,r]of Object.entries(t)){let o=r;o.operationId&&n.set(o.operationId,o)}return n}function re(e,n){let t=new Set,r=new Map,o=p=>{if(!p)return[];if(r.has(p))return _nullishCoalesce(r.get(p), () => ([]));let u=Z(p);return r.set(p,u),u},i=N(n);for(let p of e){let u=i.get(p.operationId);if(!u)continue;let d=_optionalChain([u, 'access', _12 => _12.requestBody, 'optionalAccess', _13 => _13.content, 'optionalAccess', _14 => _14["application/json"], 'optionalAccess', _15 => _15.schema]);if(_optionalChain([d, 'optionalAccess', _16 => _16.$ref])){let c=O(d.$ref);t.add(c)}else if(d){let c=o(d);for(let y of c)_optionalChain([n, 'access', _17 => _17.components, 'optionalAccess', _18 => _18.schemas, 'optionalAccess', _19 => _19[y]])&&t.add(y)}let g=u.responses||{};for(let[,c]of Object.entries(g)){let y=_optionalChain([c, 'optionalAccess', _20 => _20.content]);if(!y)continue;let f=v(y),h=_optionalChain([y, 'access', _21 => _21[f], 'optionalAccess', _22 => _22.schema]),$=E(f,h);if(_optionalChain([$, 'optionalAccess', _23 => _23.$ref])){let x=O($.$ref);t.add(x)}else if($){let x=o($);for(let w of x)_optionalChain([n, 'access', _24 => _24.components, 'optionalAccess', _25 => _25.schemas, 'optionalAccess', _26 => _26[w]])&&t.add(w)}}for(let c of p.queryParams){if(_optionalChain([c, 'access', _27 => _27.schema, 'optionalAccess', _28 => _28.$ref])){let y=O(c.schema.$ref);t.add(y)}if(_optionalChain([c, 'access', _29 => _29.schema, 'optionalAccess', _30 => _30.items, 'optionalAccess', _31 => _31.$ref])){let y=O(c.schema.items.$ref);t.add(y)}}for(let c of p.requestHeaders||[]){if(_optionalChain([c, 'access', _32 => _32.schema, 'optionalAccess', _33 => _33.$ref])){let y=O(c.schema.$ref);t.add(y)}if(_optionalChain([c, 'access', _34 => _34.schema, 'optionalAccess', _35 => _35.items, 'optionalAccess', _36 => _36.$ref])){let y=O(c.schema.items.$ref);t.add(y)}}let l=u.parameters||[];for(let c of l){let y=H(c,n);if(_optionalChain([y, 'optionalAccess', _37 => _37.schema, 'optionalAccess', _38 => _38.$ref])){let f=O(y.schema.$ref);t.add(f)}if(_optionalChain([y, 'optionalAccess', _39 => _39.schema, 'optionalAccess', _40 => _40.items, 'optionalAccess', _41 => _41.$ref])){let f=O(y.schema.items.$ref);t.add(f)}}}let s=new Set,a=Array.from(t);for(;a.length>0;){let p=a.pop();if(s.has(p))continue;s.add(p);let u=_optionalChain([n, 'access', _42 => _42.components, 'optionalAccess', _43 => _43.schemas, 'optionalAccess', _44 => _44[p]]);if(!u)continue;let d=o(u);for(let g of d)_optionalChain([n, 'access', _45 => _45.components, 'optionalAccess', _46 => _46.schemas, 'optionalAccess', _47 => _47[g]])&&!s.has(g)&&(t.add(g),a.push(g))}return t}function Ne(e,n){return n===!0?!0:Array.isArray(n)?n.includes(e):!1}function B(e,n){switch(n){case"optional":return`${e}.optional()`;case"nullable":return`${e}.nullable()`;case"nullish":return`${e}.nullish()`}}function M(e,n,t,r,o,i){if(t.has(e))return"";if(t.add(e),n.enum){let s=n.enum.map(a=>`"${a}"`).join(", ");if(Ne(e,r.openEnums)){let a=r.openEnumPrefix;return`const ${e}Known = [${s}] as const;
|
|
2
|
-
export const ${e} = z.enum(${e}Known).or(
|
|
3
|
-
z.string().transform((v): \`${a}\${string}\` => \`${a}\${v}\`)
|
|
4
|
-
);`}return`export const ${e} = z.enum([${s}]);`}if(n.allOf&&Array.isArray(n.allOf)){let s=_(n),a=s.map(l=>R(l,r,o,i,e));if(a.length===0)return`export const ${e} = z.object({});`;if(a.length===1)return`export const ${e} = ${a[0]};`;let u=s.every(l=>J(l,i))?"merge":"and",d=a[0],g=a.slice(1).map(l=>`.${u}(${l})`).join("");return`export const ${e} = ${d}${g};`}if(n.type==="object"||n.properties)return`export const ${e} = ${ae(n,r,o,i,e)};`;if(n.type==="array"){let s=_nullishCoalesce(n.items, () => ({type:"unknown"})),a=R(s,r,o,i,e),p=r.strictNumeric||n.minItems!==void 0||n.maxItems!==void 0||n.uniqueItems===!0,u=ue(n,`z.array(${a})`,s,p);return`export const ${e} = ${u};`}return`export const ${e} = ${R(n,r,o,i,e,e)};`}function oe(e,n,t,r,o){let i=e.map(s=>R(s,n,t,r,o));return i.length===0?"z.unknown()":i.length===1?_nullishCoalesce(i[0], () => ("z.unknown()")):`z.union([${i.join(", ")}])`}function V(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Me(e,n){if(!_optionalChain([e, 'optionalAccess', _48 => _48.$ref]))return e;let t=O(e.$ref);return _nullishCoalesce(_optionalChain([n, 'optionalAccess', _49 => _49[t]]), () => (e))}function ie(e){return["$ref","type","properties","required","additionalProperties","items","enum","const","oneOf","anyOf","not"].some(t=>_optionalChain([e, 'optionalAccess', _50 => _50[t]])!==void 0)}function _(e){let n=Array.isArray(e.allOf)?[...e.allOf]:[],t={...e};return delete t.allOf,ie(t)&&n.push(t),n}function I(e,n,t,r,o=new Set){if(!e||o.has(e))return!1;if(o.add(e),e.$ref){let i=O(e.$ref);if((_optionalChain([r, 'optionalAccess', _51 => _51.get, 'call', _52 => _52(i)])||i)===n)return!0;let a=_optionalChain([t, 'optionalAccess', _53 => _53[i]]);if(a)return I(a,n,t,r,o)}return Array.isArray(e.allOf)?e.allOf.some(i=>I(i,n,t,r,o)):Array.isArray(e.oneOf)?e.oneOf.some(i=>I(i,n,t,r,o)):Array.isArray(e.anyOf)?e.anyOf.some(i=>I(i,n,t,r,o)):e.not?I(e.not,n,t,r,o):e.items?I(e.items,n,t,r,o):e.properties?Object.values(e.properties).some(i=>I(i,n,t,r,o)):e.additionalProperties&&typeof e.additionalProperties=="object"?I(e.additionalProperties,n,t,r,o):!1}function J(e,n){let t=Me(e,n);return t?t.allOf&&Array.isArray(t.allOf)?_(t).every(o=>J(o,n)):t.type==="object"||t.properties!==void 0||t.additionalProperties!==void 0:!1}function Ce(e){let n=new Map;if(!_optionalChain([e, 'optionalAccess', _54 => _54.mapping]))return n;for(let[t,r]of Object.entries(e.mapping)){if(typeof r!="string")continue;let o=O(r),i=n.get(o);if(i){i.values.includes(t)||i.values.push(t);continue}n.set(o,{ref:r,values:[t]})}return n}function D(e,n,t,r=new Set){if(!e||typeof e!="object"||r.has(e))return[];if(r.add(e),e.$ref&&typeof e.$ref=="string"){let s=O(e.$ref),a=_optionalChain([t, 'optionalAccess', _55 => _55[s]]);return a?D(a,n,t,r):[]}let o=[],i=_optionalChain([e, 'access', _56 => _56.properties, 'optionalAccess', _57 => _57[n]]);if(i){let s=i.const;s!==void 0&&V(s)?o.push(s):Array.isArray(i.enum)&&_optionalChain([i, 'access', _58 => _58.enum, 'optionalAccess', _59 => _59.length])===1&&V(_optionalChain([i, 'access', _60 => _60.enum, 'optionalAccess', _61 => _61[0]]))&&o.push(_optionalChain([i, 'access', _62 => _62.enum, 'optionalAccess', _63 => _63[0]]))}if(Array.isArray(e.allOf))for(let s of e.allOf)o.push(...D(s,n,t,r));return Array.from(new Set(o))}function se(e,n,t){return{allOf:[e,{type:"object",properties:{[n]:{const:t}},required:[n]}]}}function He(e,n,t,r){let o=new Set;for(let a of e)_optionalChain([a, 'optionalAccess', _64 => _64.$ref])&&o.add(O(a.$ref));let i=[],s=!1;for(let a of e){let p=[];if(_optionalChain([a, 'optionalAccess', _65 => _65.$ref])){let d=O(a.$ref),g=t.get(d);_optionalChain([g, 'optionalAccess', _66 => _66.values, 'access', _67 => _67.length])&&p.push(...g.values),p.push(...D(a,n,r))}else p.push(...D(a,n,r));let u=Array.from(new Set(p));if(u.length===0){s=!0,i.push(a);continue}for(let d of u)i.push(se(a,n,d))}for(let[a,p]of t.entries()){if(o.has(a))continue;let u={$ref:p.ref};for(let d of p.values)i.push(se(u,n,d))}return{schemas:i,hasUnmapped:s}}function De(e,n,t,r,o,i,s){let{schemas:a,hasUnmapped:p}=He(e,n,_nullishCoalesce(s, () => (new Map)),o),u=a.map(d=>R(d,t,r,o,i));return u.length===0?"z.unknown()":u.length===1?_nullishCoalesce(u[0], () => ("z.unknown()")):p?`z.union([${u.join(", ")}])`:`z.discriminatedUnion(${JSON.stringify(n)}, [${u.join(", ")}])`}function R(e,n,t,r,o,i){if(e.$ref){let s=O(e.$ref),a=_optionalChain([t, 'optionalAccess', _68 => _68.get, 'call', _69 => _69(s)])||s;return o&&(a===o||I(_optionalChain([r, 'optionalAccess', _70 => _70[s]]),o,r,t))?`z.lazy((): z.ZodType => ${a})`:a}if(e.const!==void 0&&V(e.const))return`z.literal(${JSON.stringify(e.const)})`;if(e.enum)return e.enum.length===1?`z.literal(${JSON.stringify(e.enum[0])})`:`z.enum([${e.enum.map(a=>`"${a}"`).join(", ")}])`;if(e.not){let s=e.not,a={...e};delete a.not;let p=ie(a)?R(a,n,t,r,o):"z.any()";if(_optionalChain([s, 'optionalAccess', _71 => _71.type])==="string"&&s.maxLength===0)return`${p}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`;let u=R(s,n,t,r,o);return`${p}.refine((value) => !${u}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let s=_(e),a=s.map(l=>R(l,n,t,r,o));if(a.length===0)return"z.object({})";if(a.length===1)return _nullishCoalesce(a[0], () => ("z.object({})"));let u=s.every(l=>J(l,r))?"merge":"and",d=a[0],g=a.slice(1).map(l=>`.${u}(${l})`).join("");return`${d}${g}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(_optionalChain([e, 'access', _72 => _72.discriminator, 'optionalAccess', _73 => _73.propertyName])){let s=Ce(e.discriminator);return De(e.oneOf,e.discriminator.propertyName,n,t,r,o,s)}return oe(e.oneOf,n,t,r,o)}if(e.anyOf&&Array.isArray(e.anyOf))return oe(e.anyOf,n,t,r,o);if(e.type==="object"||e.properties||e.allOf)return ae(e,n,t,r,o);switch(e.type){case"string":return Le(e,n,i);case"boolean":return"z.boolean()";case"array":{let s=_nullishCoalesce(e.items, () => ({type:"unknown"})),a=R(s,n,t,r,o),p=n.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return ue(e,`z.array(${a})`,s,p)}case"null":return"z.null()";case"number":return pe(e,n);case"integer":return Ge(e,n);default:return"z.unknown()"}}function Fe(e,n){if(!e||!n)return new Set;let t=new Set;for(let r of Object.values(e)){if(!r||typeof r!="object")continue;let o=_optionalChain([r, 'access', _74 => _74.discriminator, 'optionalAccess', _75 => _75.propertyName]);if(!o||!Array.isArray(r.oneOf))continue;let s=r.oneOf.some(u=>_optionalChain([u, 'optionalAccess', _76 => _76.$ref])&&O(u.$ref)===n),p=Object.values(_nullishCoalesce(_optionalChain([r, 'access', _77 => _77.discriminator, 'optionalAccess', _78 => _78.mapping]), () => ({}))).some(u=>typeof u=="string"&&O(u)===n);(s||p)&&t.add(o)}return t}function ae(e,n,t,r,o){let i=[],s=Fe(r,o),a=new Set(_nullishCoalesce(e.required, () => ([])));for(let[d,g]of Object.entries(e.properties||{})){let l=a.has(d)||s.has(d),c=R(g,n,t,r,o),y=B(c,n.optionalType),f=n.optionalType!=="nullable"?Ze(y,g):y,h=l?c:f;i.push(` ${S(d)}: ${h},`)}let p=i.length===0?"z.object({})":`z.object({
|
|
5
|
-
${i.join(`
|
|
6
|
-
`)}
|
|
7
|
-
})`;if(e.additionalProperties===void 0)return p;if(e.additionalProperties===!1)return`${p}.strict()`;if(e.additionalProperties===!0)return`${p}.passthrough()`;let u=R(e.additionalProperties,n,t,r,o);return`${p}.catchall(${u})`}function Le(e,n,t){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(n.strictDates)switch(e.format){case"date-time":return n.dateTimeOffset===!0||Array.isArray(n.dateTimeOffset)&&t!==void 0&&n.dateTimeOffset.includes(t)?"z.string().datetime({ offset: true })":"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let r="z.string()";switch(n.strictNumeric&&(typeof e.minLength=="number"&&(r+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(r+=`.max(${e.maxLength})`),e.pattern&&(r+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${r}.uuid()`;case"email":return`${r}.email()`;case"uri":case"url":return`${r}.url()`;case"ipv4":return`${r}.ip({ version: "v4" })`;case"ipv6":return`${r}.ip({ version: "v6" })`;default:return r}}function Ze(e,n){return!n||n.default===void 0||n.default===null&&!(e.includes(".nullable()")||e.includes(".nullish()")||n.type==="null"||Array.isArray(n.type)&&n.type.includes("null"))?e:`${e}.default(${JSON.stringify(n.default)})`}function pe(e,n){let t="z.number()";return n.strictNumeric&&(t=Ve(e,t),typeof e.multipleOf=="number"&&e.multipleOf!==0&&(t+=`.refine((value) => Math.abs(value / ${e.multipleOf} - Math.round(value / ${e.multipleOf})) < Number.EPSILON, { message: "Must be a multiple of ${e.multipleOf}" })`)),t}function Ge(e,n){let t=pe(e,n);return t+=".int()",t}function ue(e,n,t,r){return r&&(typeof e.minItems=="number"&&(n+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(n+=`.max(${e.maxItems})`),e.uniqueItems&&Ue(t)&&(n+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),n}function Ue(e){return _optionalChain([e, 'optionalAccess', _79 => _79.$ref])?!1:new Set(["string","number","integer","boolean"]).has(_optionalChain([e, 'optionalAccess', _80 => _80.type]))}function Ve(e,n){return typeof e.minimum=="number"?e.exclusiveMinimum===!0?n+=`.gt(${e.minimum})`:n+=`.min(${e.minimum})`:typeof e.exclusiveMinimum=="number"&&(n+=`.gt(${e.exclusiveMinimum})`),typeof e.maximum=="number"?e.exclusiveMaximum===!0?n+=`.lt(${e.maximum})`:n+=`.max(${e.maximum})`:typeof e.exclusiveMaximum=="number"&&(n+=`.lt(${e.exclusiveMaximum})`),n}var Be={400:"badRequest",401:"unauthorized",402:"paymentRequired",403:"forbidden",404:"notFound",405:"methodNotAllowed",406:"notAcceptable",407:"proxyAuthenticationRequired",408:"requestTimeout",409:"conflict",410:"gone",411:"lengthRequired",412:"preconditionFailed",413:"payloadTooLarge",414:"uriTooLong",415:"unsupportedMediaType",416:"rangeNotSatisfiable",417:"expectationFailed",418:"imATeapot",421:"misdirectedRequest",422:"unprocessableEntity",423:"locked",424:"failedDependency",425:"tooEarly",426:"upgradeRequired",428:"preconditionRequired",429:"tooManyRequests",431:"requestHeaderFieldsTooLarge",451:"unavailableForLegalReasons",500:"internalServerError",501:"notImplemented",502:"badGateway",503:"serviceUnavailable",504:"gatewayTimeout",505:"httpVersionNotSupported",506:"variantAlsoNegotiates",507:"insufficientStorage",508:"loopDetected",510:"notExtended",511:"networkAuthenticationRequired"};function fe(e){if(e==="default")return"defaultError";let n=e.trim(),t=Be[n];if(t)return t;if(/^\d{3}$/.test(n))return`status${n}`;let r=n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();if(!r)return"unknownError";let o=r.split(/\s+/),[i,...s]=o,a=i+s.map(p=>p.charAt(0).toUpperCase()+p.slice(1)).join("");return a?/^[a-zA-Z_$]/.test(a)?a:`status${a.charAt(0).toUpperCase()}${a.slice(1)}`:"unknownError"}function F(e){if(e==="default")return!0;let n=Number(e);return Number.isInteger(n)?n>=400:!1}function Oe(e,n){let t=[];if(e.paths)for(let[r,o]of Object.entries(e.paths))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!$e(a)||!s.operationId)continue;let p=de(r),u=le(s,n),{successResponse:d,errors:g}=ye(s,s.operationId,n),l=ce(o,s,e),c=me(l),y=ge(l),f=he(s,e);t.push({operationId:s.operationId,path:r,method:a,pathParams:p,queryParams:y,requestType:u,responseType:d,requestHeaders:c,errors:g,security:f})}if(e.webhooks)for(let[r,o]of Object.entries(e.webhooks))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!$e(a)||!s.operationId)continue;let p=r,u=de(p),d=le(s,n),{successResponse:g,errors:l}=ye(s,s.operationId,n),c=ce(o,s,e),y=me(c),f=ge(c),h=he(s,e);t.push({operationId:s.operationId,path:p,method:a,pathParams:u,queryParams:f,requestType:d,responseType:g,requestHeaders:y,errors:l,security:h})}return t}function ce(e,n,t){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let a=H(s,t);if(!a)continue;let p=`${a.in}:${a.name}`;r.set(p,a)}};return o(e.parameters),o(n.parameters),Array.from(r.values())}function de(e){let n=[],t=e.match(/{([^}]+)}/g);if(t)for(let r of t){let o=r.slice(1,-1);n.push({name:o,type:"string"})}return n}function le(e,n){let t=_e(e);if(!t)return;if(t.$ref){let o=O(t.$ref);return _optionalChain([n, 'optionalAccess', _81 => _81.get, 'call', _82 => _82(o)])||o}return`${P(T(e.operationId))}Request`}function _e(e){let n=_optionalChain([e, 'optionalAccess', _83 => _83.requestBody, 'optionalAccess', _84 => _84.content]);if(!n||Object.keys(n).length===0)return;let t=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let r of t){let o=_optionalChain([n, 'access', _85 => _85[r], 'optionalAccess', _86 => _86.schema]);if(o)return o}}function ye(e,n,t){let r=_nullishCoalesce(e.responses, () => ({})),o=new Map,i=[];for(let[p,u]of Object.entries(r)){let d=_optionalChain([u, 'optionalAccess', _87 => _87.content]);if(!d||Object.keys(d).length===0){p==="204"||/^3\d\d$/.test(p)?o.set(p,"undefined"):F(p)&&i.push({code:p,schema:"undefined"});continue}let g=v(d),l=_optionalChain([d, 'access', _88 => _88[g], 'optionalAccess', _89 => _89.schema]),c=E(g,l);if(!c){let y=We(g,p);y&&(F(p)?i.push({code:p,schema:y}):/^2\d\d$/.test(p)&&o.set(p,y));continue}if(F(p)){i.push({code:p,schema:c});continue}/^2\d\d$/.test(p)&&o.set(p,c)}let s=Je(o,n,t),a=Qe(i,n,t);return{successResponse:s,errors:a}}function Je(e,n,t){if(e.size===0)return;let r=["200","201","204"];for(let i of r){let s=e.get(i);if(s)return typeof s=="string"?s:Q(s,`${P(T(n))}Response`,t)}let[,o]=_nullishCoalesce(e.entries().next().value, () => ([]));if(o)return typeof o=="string"?o:Q(o,`${P(T(n))}Response`,t)}function Qe(e=[],n,t){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=fe(o),a=Q(i,`${P(T(n))}${P(s)}`,t);r[s]=a}return r}function Q(e,n,t){if(typeof e=="string")return e;if(e.$ref){let r=O(e.$ref);return _optionalChain([t, 'optionalAccess', _90 => _90.get, 'call', _91 => _91(r)])||r}if(e.type==="array"&&_optionalChain([e, 'access', _92 => _92.items, 'optionalAccess', _93 => _93.$ref])){let r=O(e.items.$ref);return`z.array(${_optionalChain([t, 'optionalAccess', _94 => _94.get, 'call', _95 => _95(r)])||r})`}return e.allOf&&Array.isArray(e.allOf),n}function me(e){let n=[];for(let t of _nullishCoalesce(e, () => ([])))t.in==="header"&&n.push({name:t.name,description:t.description,schema:t.schema,required:t.required});return n}function ge(e){let n=[];for(let t of _nullishCoalesce(e, () => ([])))t.in==="query"&&n.push({name:t.name,description:t.description,schema:t.schema,required:t.required});return n}function he(e,n){let t=e.security;if(Array.isArray(t))return t.length===0?[]:t;if(Array.isArray(n.security)&&n.security.length>0)return n.security}function $e(e){switch(e){case"get":case"put":case"post":case"delete":case"options":case"head":case"patch":case"trace":return!0;default:return!1}}function We(e,n){return n==="204"||/^3\d\d$/.test(n)?"undefined":e in C?C[e]:"unknown"}function Se(e,n){let t=new Map,r=N(n);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.requestBody;if(s&&s.content){let a=s.content,p=Ke(a);if(!p)continue;let u=`${P(T(o.operationId))}Request`;(!p.$ref||p.allOf||p.oneOf||p.anyOf)&&t.set(u,p)}}return t}function Ke(e){let n=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let t of n){let r=_optionalChain([e, 'access', _96 => _96[t], 'optionalAccess', _97 => _97.schema]);if(r)return r}}function Te(e,n){let t=new Map,r=N(n);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.responses||{};for(let[a,p]of Object.entries(s))if(/^2\d\d$/.test(a)&&p.content){let u=p.content,d=v(u),g=_optionalChain([u, 'access', _98 => _98[d], 'optionalAccess', _99 => _99.schema]),l=E(d,g);if(!l)continue;let c=`${P(T(o.operationId))}Response`;(!l.$ref||l.allOf||l.oneOf||l.anyOf)&&t.set(c,l)}}return t}function xe(e,n,t,r,o){let i=Se(n,t);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,a]of i){let p=M(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function we(e,n,t,r,o){let i=Te(n,t);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,a]of i){let p=M(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function be(){let e=[];return e.push("// Generated helper types for Zenko"),e.push("// This file provides type definitions for operation objects and path functions"),e.push(""),e.push("export type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string"),e.push(""),e.push('export type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"'),e.push(""),e.push("export type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult"),e.push(""),e.push("export type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown)"),e.push(""),e.push("export type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push(""),e.push("export type SecurityRequirement = Readonly<Record<string, readonly string[]>>"),e.push(""),e.push("export type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push(""),e.join(`
|
|
8
|
-
`)}function Ye(e){return e===void 0?{open:!1,prefix:"Unknown:"}:typeof e=="boolean"?{open:e,prefix:"Unknown:"}:Array.isArray(e)?{open:e,prefix:"Unknown:"}:{open:_nullishCoalesce(e.open, () => (!1)),prefix:_nullishCoalesce(e.unknownPrefix, () => ("Unknown:"))}}function Xe(e,n={}){let t=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,dateTimeOffset:s=!0,operationIds:a,openEnums:p=!1}=n,u=nn({...n.types,operationTypeSuffix:_nullishCoalesce(_optionalChain([n, 'access', _100 => _100.types, 'optionalAccess', _101 => _101.operationTypeSuffix]), () => ("Operation"))}),d=Ye(p),g={strictDates:o,strictNumeric:i,dateTimeOffset:s,optionalType:u.optionalType,openEnums:d.open,openEnumPrefix:d.prefix};t.push('import { z } from "zod";');let l=new Map;if(_optionalChain([e, 'access', _102 => _102.components, 'optionalAccess', _103 => _103.schemas]))for(let f of Object.keys(e.components.schemas))l.set(f,T(f));let c=Oe(e,l);if(a&&a.length>0){let f=new Set(a);c=c.filter(h=>f.has(h.operationId))}if(tn(t,u,c),t.push(""),_optionalChain([e, 'access', _104 => _104.components, 'optionalAccess', _105 => _105.schemas])){t.push("// Generated Zod Schemas"),t.push("");let f=a&&a.length>0?new Set(re(c,e)):new Set(Object.keys(e.components.schemas)),h=ne(e.components.schemas).filter($=>f.has($));for(let $ of h){let x=e.components.schemas[$],w=l.get($);t.push(M(w,x,r,g,l,e.components.schemas)),t.push(""),t.push(`export type ${w} = z.infer<typeof ${w}>;`),t.push("")}}t.push("// Path Functions"),t.push("export const paths = {");for(let f of c){let $=f.pathParams.map(m=>m.name).length>0,x=f.queryParams.length>0,w=T(f.operationId);if(!$&&!x){t.push(` ${S(w)}: () => "${f.path}",`);continue}let q=m=>{if(A(m))return m;let k=T(m);return A(k)||(k=`_${k}`),k},z=[],j=[];for(let m of f.pathParams)z.push(A(m.name)?m.name:`${S(m.name)}: ${q(m.name)}`),j.push(`${S(m.name)}: string`);for(let m of f.queryParams)z.push(A(m.name)?m.name:`${S(m.name)}: ${q(m.name)}`),j.push(`${S(m.name)}${m.required?"":"?"}: ${pn(m)}`);let Ee=!$&&x&&f.queryParams.every(m=>!m.required),K=`${z.length?`{ ${z.join(", ")} }`:"{}"}: { ${j.join(", ")} }${Ee?" = {}":""}`,Y=f.path.replace(/{([^}]+)}/g,(m,k)=>`\${${q(k)}}`);if(!x){t.push(` ${S(w)}: (${K}) => \`${Y}\`,`);continue}t.push(` ${S(w)}: (${K}) => {`),t.push(" const params = new URLSearchParams()");for(let m of f.queryParams){let k=A(m.name)?m.name:q(T(m.name)),L=_nullishCoalesce(m.schema, () => ({}));if(_optionalChain([L, 'optionalAccess', _106 => _106.type])==="array"){let ee=Ae(_nullishCoalesce(L.items, () => ({})),"value");m.required?(t.push(` for (const value of ${k}) {`),t.push(` params.append("${m.name}", ${ee})`),t.push(" }")):(t.push(` if (${k} !== undefined) {`),t.push(` for (const value of ${k}) {`),t.push(` params.append("${m.name}", ${ee})`),t.push(" }"),t.push(" }"));continue}let X=Ae(L,k);m.required?t.push(` params.set("${m.name}", ${X})`):(t.push(` if (${k} !== undefined) {`),t.push(` params.set("${m.name}", ${X})`),t.push(" }"))}t.push(" const _searchParams = params.toString()"),t.push(` return \`${Y}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),t.push(" },")}t.push("} as const;"),t.push(""),t.push("// Header Schemas"),t.push("export const headerSchemas = {");for(let f of c){let h=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${S(h)}: z.object({}),`);continue}let $=f.requestHeaders.map(x=>{let w=an(x),q=x.required?w:B(w,g.optionalType);return` ${S(x.name)}: ${q},`}).join(`
|
|
9
|
-
`);t.push(` ${S(h)}: z.object({`),t.push($),t.push(" }),")}t.push("} as const;"),t.push(""),t.push("// Header Functions"),t.push("export const headers = {");for(let f of c){let h=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${S(h)}: () => ${A(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse({}),`);continue}t.push(` ${S(h)}: (params: z.input<${A(h)?`typeof headerSchemas.${h}`:`(typeof headerSchemas)[${S(h)}]`}>) => {`),t.push(` return ${A(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse(params)`),t.push(" },")}if(t.push("} as const;"),t.push(""),_optionalChain([e, 'access', _107 => _107.components, 'optionalAccess', _108 => _108.securitySchemes])&&Object.keys(e.components.securitySchemes).length>0){t.push("// Security Schemes"),t.push("export const securitySchemes = {");for(let[f,h]of Object.entries(e.components.securitySchemes)){let $=h;t.push(` ${S(f)}: {`),t.push(` type: ${JSON.stringify($.type)},`),$.type==="http"?(t.push(` scheme: ${JSON.stringify(String($.scheme).toLowerCase())},`),$.bearerFormat&&t.push(` bearerFormat: ${JSON.stringify($.bearerFormat)},`)):$.type==="apiKey"?(t.push(` name: ${JSON.stringify($.name)},`),t.push(` in: ${JSON.stringify($.in)},`)):$.type==="oauth2"?t.push(` flows: ${JSON.stringify($.flows)},`):$.type==="openIdConnect"&&t.push(` openIdConnectUrl: ${JSON.stringify($.openIdConnectUrl)},`),t.push(" },")}t.push("} as const;"),t.push("")}xe(t,c,e,l,g),we(t,c,e,l,g),rn(t,c,u),t.push("// Operation Objects");for(let f of c){let h=T(f.operationId),$=u.emit?`: ${Re(h,u.operationTypeSuffix)}`:"";if(t.push(`export const ${h}${$} = {`),t.push(` method: "${f.method}",`),t.push(` path: paths.${h},`),ke(t,"request",f.requestType),ke(t,"response",f.responseType),f.requestHeaders&&f.requestHeaders.length>0&&t.push(` headers: headers.${h},`),f.security!==void 0)if(f.security.length===0)t.push(" security: [],");else{let x=f.security.map(w=>`{ ${Object.entries(w).map(([z,j])=>`${S(z)}: ${JSON.stringify(j)}`).join(", ")} }`);t.push(` security: [${x.join(", ")}],`)}f.errors&&Pe(f.errors)&&en(t,"errors",f.errors),t.push("} as const;"),t.push("")}let y={output:t.join(`
|
|
10
|
-
`)};return u.emit&&u.helpers==="file"&&u.helpersOutput&&(y.helperFile={path:u.helpersOutput,content:be()}),y}function it(e,n={}){return Xe(e,n).output}function ke(e,n,t){t&&e.push(` ${n}: ${t},`)}function en(e,n,t){if(!(!t||Object.keys(t).length===0)){e.push(` ${n}: {`);for(let[r,o]of Object.entries(t))e.push(` ${S(r)}: ${o},`);e.push(" },")}}function Pe(e){return!!(e&&Object.keys(e).length>0)}function nn(e){let n=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _109 => _109.operationTypeSuffix]), () => ("Operation"));if(n!==""&&!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n))throw new Error(`Invalid operationTypeSuffix "${n}": must be a valid TypeScript identifier suffix (letters, digits, underscores, or $). Use "" for no suffix.`);return{emit:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _110 => _110.emit]), () => (!0)),helpers:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _111 => _111.helpers]), () => ("package")),helpersOutput:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _112 => _112.helpersOutput]), () => ("./zenko-types")),treeShake:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _113 => _113.treeShake]), () => (!0)),optionalType:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _114 => _114.optionalType]), () => ("optional")),operationTypeSuffix:n}}function Re(e,n){return`${P(e)}${n}`}function tn(e,n,t){if(n.emit)switch(n.helpers){case"package":if(n.treeShake){let r=G(t),o=U(r,"package");o&&e.push(o)}else e.push('import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "zenko";');return;case"file":if(n.treeShake){let r=G(t),o=U(r,"file",n.helpersOutput);o&&e.push(o)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "${n.helpersOutput}";`);return;case"inline":e.push("type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;"),e.push('type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";'),e.push("type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;"),e.push("type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);"),e.push("type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push("type SecurityRequirement = Readonly<Record<string, readonly string[]>>;"),e.push("type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push("")}}function rn(e,n,t){if(t.emit){e.push("// Operation Types");for(let r of n){let o=T(r.operationId),i=Re(o,t.operationTypeSuffix),s=_optionalChain([r, 'access', _115 => _115.requestHeaders, 'optionalAccess', _116 => _116.length])?A(o)?`typeof headers.${o}`:`(typeof headers)[${S(o)}]`:"undefined",a=W(r.requestType),p=W(r.responseType),u=on(r.errors),d=r.security===void 0?"undefined":r.security.length===0?"readonly []":`readonly [${r.security.map(l=>`{ ${Object.entries(l).map(([y,f])=>`readonly ${S(y)}: readonly ${JSON.stringify(f)}`).join("; ")} }`).join(", ")}]`;e.push(`export type ${i} = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${A(o)?`typeof paths.${o}`:`(typeof paths)[${S(o)}]`},`),e.push(` ${a},`),e.push(` ${p},`),e.push(` ${s},`),e.push(` ${u},`),e.push(` ${d}`),e.push(">;"),e.push("")}}}function on(e){return!e||!Pe(e)?"OperationErrors":`OperationErrors<${sn(e)}>`}function sn(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=S(r),s=ze(o);return`${i}: ${s}`}).join("; ")} }`}var Ie=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),qe=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function W(e){if(!e)return"undefined";let n=e.trim();if(n==="undefined")return"undefined";if(Ie.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${W(t[1])}>`:qe.test(n)?`typeof ${n}`:n}function ze(e){if(!e)return"unknown";let n=e.trim();if(Ie.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${ze(t[1])}>`:qe.test(n)?`typeof ${n}`:n}function an(e){let n=_nullishCoalesce(e.schema, () => ({}));switch(n.type){case"integer":case"number":return"z.coerce.number()";case"boolean":return"z.coerce.boolean()";case"array":{let r=_nullishCoalesce(n.items, () => ({type:"string"}));return`z.array(${r.type==="integer"||r.type==="number"?"z.coerce.number()":r.type==="boolean"?"z.coerce.boolean()":"z.string()"})`}default:return"z.string()"}}function pn(e){return ve(e.schema)}function ve(e){if(!e)return"string";if(e.type==="array")return`Array<${ve(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function Ae(e,n){if(!e)return`String(${n})`;switch(e.type){case"integer":case"number":return`String(${n})`;case"boolean":return`${n} ? "true" : "false"`;default:return`String(${n})`}}exports.a = Xe; exports.b = it;
|
|
11
|
-
//# sourceMappingURL=chunk-GD63CEJN.cjs.map
|
package/dist/chunk-VHYJGQUS.mjs
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
function te(e){let n=new Set,t=new Set,r=[],o=i=>{if(n.has(i)||t.has(i))return;t.add(i);let s=e[i],a=G(s);for(let p of a)e[p]&&o(p);t.delete(i),n.add(i),r.push(i)};for(let i of Object.keys(e))o(i);return r}function G(e){let n=[],t=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=O(r.$ref);n.push(o);return}if(Array.isArray(r))r.forEach(t);else{if(r.mapping&&typeof r.mapping=="object")for(let o of Object.values(r.mapping))typeof o=="string"&&n.push(O(o));Object.values(r).forEach(t)}}};return t(e),[...new Set(n)]}function O(e){return(e.split("/").pop()||"Unknown").replace(/\.(yml|yaml)$/i,"")}function P(e){if(!e)return!1;let n=e.at(0);return n===void 0||!/[a-zA-Z_$]/.test(n)||!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?!1:!new Set(["abstract","arguments","await","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","eval","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","let","long","native","new","null","package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with","yield","async"]).has(e)}function S(e){return P(e)?e:`"${e}"`}function T(e){return e.replace(/-([a-zA-Z])/g,(n,t)=>t.toUpperCase()).replace(/-+$/,"")}function R(e){return e.charAt(0).toUpperCase()+e.slice(1)}function U(e){let n={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(n.usesOperationDefinition=!0);for(let t of e)t.errors&&re(t.errors)&&(n.usesOperationErrors=!0);return e.length>0&&!n.usesOperationErrors&&e.some(r=>!r.errors||!re(r.errors))&&(n.usesOperationErrors=!0),n}function V(e,n,t){let r=[];if(e.usesHeaderFn&&r.push("HeaderFn"),e.usesOperationDefinition&&r.push("OperationDefinition"),e.usesOperationErrors&&r.push("OperationErrors"),r.length===0)return"";let o=n==="package"?'"zenko"':`"${t}"`;return`import type { ${r.join(", ")} } from ${o};`}function re(e){return!!(e&&Object.keys(e).length>0)}var H={"application/json":"unknown","text/csv":"string","text/plain":"string","application/octet-stream":"unknown","application/pdf":"unknown"};function E(e){let n=Object.keys(e);if(n.includes("application/json"))return"application/json";for(let t of n)if(t in H)return t;return n[0]||""}function Ne(e){let n=e.toLowerCase().split(";")[0]?.trim();return n?!!(n.startsWith("text/")||n==="application/xml"||n.startsWith("application/")&&n.endsWith("+xml")):!1}function j(e,n){if(!n||!Ne(e)||n.$ref)return n;let t=n.nullable===!0?{nullable:!0}:{};return n.enum?{type:"string",enum:n.enum,...t}:{type:"string",...t}}function D(e,n){if(e){if(e.$ref){let t=O(e.$ref),r=n.components?.parameters?.[t];if(!r)return;let{$ref:o,...i}=e;return{...r,...i}}return e}}function M(e){let n=new Map;for(let[,t]of Object.entries(e.paths||{}))for(let[,r]of Object.entries(t)){let o=r;o.operationId&&n.set(o.operationId,o)}for(let[,t]of Object.entries(e.webhooks||{}))for(let[,r]of Object.entries(t)){let o=r;o.operationId&&n.set(o.operationId,o)}return n}function oe(e,n){let t=new Set,r=new Map,o=p=>{if(!p)return[];if(r.has(p))return r.get(p)??[];let u=G(p);return r.set(p,u),u},i=M(n);for(let p of e){let u=i.get(p.operationId);if(!u)continue;let d=u.requestBody?.content?.["application/json"]?.schema;if(d?.$ref){let c=O(d.$ref);t.add(c)}else if(d){let c=o(d);for(let y of c)n.components?.schemas?.[y]&&t.add(y)}let g=u.responses||{};for(let[,c]of Object.entries(g)){let y=c?.content;if(!y)continue;let f=E(y),h=y[f]?.schema,$=j(f,h);if($?.$ref){let x=O($.$ref);t.add(x)}else if($){let x=o($);for(let w of x)n.components?.schemas?.[w]&&t.add(w)}}for(let c of p.queryParams){if(c.schema?.$ref){let y=O(c.schema.$ref);t.add(y)}if(c.schema?.items?.$ref){let y=O(c.schema.items.$ref);t.add(y)}}for(let c of p.requestHeaders||[]){if(c.schema?.$ref){let y=O(c.schema.$ref);t.add(y)}if(c.schema?.items?.$ref){let y=O(c.schema.items.$ref);t.add(y)}}let l=u.parameters||[];for(let c of l){let y=D(c,n);if(y?.schema?.$ref){let f=O(y.schema.$ref);t.add(f)}if(y?.schema?.items?.$ref){let f=O(y.schema.items.$ref);t.add(f)}}}let s=new Set,a=Array.from(t);for(;a.length>0;){let p=a.pop();if(s.has(p))continue;s.add(p);let u=n.components?.schemas?.[p];if(!u)continue;let d=o(u);for(let g of d)n.components?.schemas?.[g]&&!s.has(g)&&(t.add(g),a.push(g))}return t}function Me(e,n){return n===!0?!0:Array.isArray(n)?n.includes(e):!1}function _(e,n){switch(n){case"optional":return`${e}.optional()`;case"nullable":return`${e}.nullable()`;case"nullish":return`${e}.nullish()`}}function C(e,n,t,r,o,i){if(t.has(e))return"";if(t.add(e),n.enum){let s=n.enum.map(a=>`"${a}"`).join(", ");if(Me(e,r.openEnums)){let a=r.openEnumPrefix;return`const ${e}Known = [${s}] as const;
|
|
2
|
-
export const ${e} = z.enum(${e}Known).or(
|
|
3
|
-
z.string().transform((v): \`${a}\${string}\` => \`${a}\${v}\`)
|
|
4
|
-
);`}return`export const ${e} = z.enum([${s}]);`}if(n.allOf&&Array.isArray(n.allOf)){let s=J(n),a=s.map(l=>I(l,r,o,i,e));if(a.length===0)return`export const ${e} = z.object({});`;if(a.length===1)return`export const ${e} = ${a[0]};`;let u=s.every(l=>Q(l,i))?"merge":"and",d=a[0],g=a.slice(1).map(l=>`.${u}(${l})`).join("");return`export const ${e} = ${d}${g};`}if(n.type==="object"||n.properties)return`export const ${e} = ${pe(n,r,o,i,e)};`;if(n.type==="array"){let s=n.items??{type:"unknown"},a=I(s,r,o,i,e),p=r.strictNumeric||n.minItems!==void 0||n.maxItems!==void 0||n.uniqueItems===!0,u=fe(n,`z.array(${a})`,s,p);return`export const ${e} = ${u};`}return`export const ${e} = ${I(n,r,o,i,e,e)};`}function se(e,n,t,r,o){let i=e.map(s=>I(s,n,t,r,o));return i.length===0?"z.unknown()":i.length===1?i[0]??"z.unknown()":`z.union([${i.join(", ")}])`}function B(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ce(e,n){if(!e?.$ref)return e;let t=O(e.$ref);return n?.[t]??e}function ae(e){return["$ref","type","properties","required","additionalProperties","items","enum","const","oneOf","anyOf","not"].some(t=>e?.[t]!==void 0)}function J(e){let n=Array.isArray(e.allOf)?[...e.allOf]:[],t={...e};return delete t.allOf,ae(t)&&n.push(t),n}function q(e,n,t,r,o=new Set){if(!e||o.has(e))return!1;if(o.add(e),e.$ref){let i=O(e.$ref);if((r?.get(i)||i)===n)return!0;let a=t?.[i];if(a)return q(a,n,t,r,o)}return Array.isArray(e.allOf)?e.allOf.some(i=>q(i,n,t,r,o)):Array.isArray(e.oneOf)?e.oneOf.some(i=>q(i,n,t,r,o)):Array.isArray(e.anyOf)?e.anyOf.some(i=>q(i,n,t,r,o)):e.not?q(e.not,n,t,r,o):e.items?q(e.items,n,t,r,o):e.properties?Object.values(e.properties).some(i=>q(i,n,t,r,o)):e.additionalProperties&&typeof e.additionalProperties=="object"?q(e.additionalProperties,n,t,r,o):!1}function Q(e,n){let t=Ce(e,n);return t?t.allOf&&Array.isArray(t.allOf)?J(t).every(o=>Q(o,n)):t.type==="object"||t.properties!==void 0||t.additionalProperties!==void 0:!1}function He(e){let n=new Map;if(!e?.mapping)return n;for(let[t,r]of Object.entries(e.mapping)){if(typeof r!="string")continue;let o=O(r),i=n.get(o);if(i){i.values.includes(t)||i.values.push(t);continue}n.set(o,{ref:r,values:[t]})}return n}function F(e,n,t,r=new Set){if(!e||typeof e!="object"||r.has(e))return[];if(r.add(e),e.$ref&&typeof e.$ref=="string"){let s=O(e.$ref),a=t?.[s];return a?F(a,n,t,r):[]}let o=[],i=e.properties?.[n];if(i){let s=i.const;s!==void 0&&B(s)?o.push(s):Array.isArray(i.enum)&&i.enum?.length===1&&B(i.enum?.[0])&&o.push(i.enum?.[0])}if(Array.isArray(e.allOf))for(let s of e.allOf)o.push(...F(s,n,t,r));return Array.from(new Set(o))}function ie(e,n,t){return{allOf:[e,{type:"object",properties:{[n]:{const:t}},required:[n]}]}}function De(e,n,t,r){let o=new Set;for(let a of e)a?.$ref&&o.add(O(a.$ref));let i=[],s=!1;for(let a of e){let p=[];if(a?.$ref){let d=O(a.$ref),g=t.get(d);g?.values.length&&p.push(...g.values),p.push(...F(a,n,r))}else p.push(...F(a,n,r));let u=Array.from(new Set(p));if(u.length===0){s=!0,i.push(a);continue}for(let d of u)i.push(ie(a,n,d))}for(let[a,p]of t.entries()){if(o.has(a))continue;let u={$ref:p.ref};for(let d of p.values)i.push(ie(u,n,d))}return{schemas:i,hasUnmapped:s}}function Fe(e,n,t,r,o,i,s){let{schemas:a,hasUnmapped:p}=De(e,n,s??new Map,o),u=a.map(d=>I(d,t,r,o,i));return u.length===0?"z.unknown()":u.length===1?u[0]??"z.unknown()":p?`z.union([${u.join(", ")}])`:`z.discriminatedUnion(${JSON.stringify(n)}, [${u.join(", ")}])`}function I(e,n,t,r,o,i){if(e.$ref){let s=O(e.$ref),a=t?.get(s)||s;return o&&(a===o||q(r?.[s],o,r,t))?`z.lazy((): z.ZodType => ${a})`:a}if(e.const!==void 0&&B(e.const))return`z.literal(${JSON.stringify(e.const)})`;if(e.enum)return e.enum.length===1?`z.literal(${JSON.stringify(e.enum[0])})`:`z.enum([${e.enum.map(a=>`"${a}"`).join(", ")}])`;if(e.not){let s=e.not,a={...e};delete a.not;let p=ae(a)?I(a,n,t,r,o):"z.any()";if(s?.type==="string"&&s.maxLength===0)return`${p}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`;let u=I(s,n,t,r,o);return`${p}.refine((value) => !${u}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let s=J(e),a=s.map(l=>I(l,n,t,r,o));if(a.length===0)return"z.object({})";if(a.length===1)return a[0]??"z.object({})";let u=s.every(l=>Q(l,r))?"merge":"and",d=a[0],g=a.slice(1).map(l=>`.${u}(${l})`).join("");return`${d}${g}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(e.discriminator?.propertyName){let s=He(e.discriminator);return Fe(e.oneOf,e.discriminator.propertyName,n,t,r,o,s)}return se(e.oneOf,n,t,r,o)}if(e.anyOf&&Array.isArray(e.anyOf))return se(e.anyOf,n,t,r,o);if(e.type==="object"||e.properties||e.allOf)return pe(e,n,t,r,o);switch(e.type){case"string":return Ze(e,n,i);case"boolean":return"z.boolean()";case"array":{let s=e.items??{type:"unknown"},a=I(s,n,t,r,o),p=n.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return fe(e,`z.array(${a})`,s,p)}case"null":return"z.null()";case"number":return ue(e,n);case"integer":return Ue(e,n);default:return"z.unknown()"}}function Le(e,n){if(!e||!n)return new Set;let t=new Set;for(let r of Object.values(e)){if(!r||typeof r!="object")continue;let o=r.discriminator?.propertyName;if(!o||!Array.isArray(r.oneOf))continue;let s=r.oneOf.some(u=>u?.$ref&&O(u.$ref)===n),p=Object.values(r.discriminator?.mapping??{}).some(u=>typeof u=="string"&&O(u)===n);(s||p)&&t.add(o)}return t}function pe(e,n,t,r,o){let i=[],s=Le(r,o),a=new Set(e.required??[]);for(let[d,g]of Object.entries(e.properties||{})){let l=a.has(d)||s.has(d),c=I(g,n,t,r,o),y=_(c,n.optionalType),f=n.optionalType!=="nullable"?Ge(y,g):y,h=l?c:f;i.push(` ${S(d)}: ${h},`)}let p=i.length===0?"z.object({})":`z.object({
|
|
5
|
-
${i.join(`
|
|
6
|
-
`)}
|
|
7
|
-
})`;if(e.additionalProperties===void 0)return p;if(e.additionalProperties===!1)return`${p}.strict()`;if(e.additionalProperties===!0)return`${p}.passthrough()`;let u=I(e.additionalProperties,n,t,r,o);return`${p}.catchall(${u})`}function Ze(e,n,t){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(n.strictDates)switch(e.format){case"date-time":return n.dateTimeOffset===!0||Array.isArray(n.dateTimeOffset)&&t!==void 0&&n.dateTimeOffset.includes(t)?"z.string().datetime({ offset: true })":"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let r="z.string()";switch(n.strictNumeric&&(typeof e.minLength=="number"&&(r+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(r+=`.max(${e.maxLength})`),e.pattern&&(r+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${r}.uuid()`;case"email":return`${r}.email()`;case"uri":case"url":return`${r}.url()`;case"ipv4":return`${r}.ip({ version: "v4" })`;case"ipv6":return`${r}.ip({ version: "v6" })`;default:return r}}function Ge(e,n){return!n||n.default===void 0||n.default===null&&!(e.includes(".nullable()")||e.includes(".nullish()")||n.type==="null"||Array.isArray(n.type)&&n.type.includes("null"))?e:`${e}.default(${JSON.stringify(n.default)})`}function ue(e,n){let t="z.number()";return n.strictNumeric&&(t=Be(e,t),typeof e.multipleOf=="number"&&e.multipleOf!==0&&(t+=`.refine((value) => Math.abs(value / ${e.multipleOf} - Math.round(value / ${e.multipleOf})) < Number.EPSILON, { message: "Must be a multiple of ${e.multipleOf}" })`)),t}function Ue(e,n){let t=ue(e,n);return t+=".int()",t}function fe(e,n,t,r){return r&&(typeof e.minItems=="number"&&(n+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(n+=`.max(${e.maxItems})`),e.uniqueItems&&Ve(t)&&(n+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),n}function Ve(e){return e?.$ref?!1:new Set(["string","number","integer","boolean"]).has(e?.type)}function Be(e,n){return typeof e.minimum=="number"?e.exclusiveMinimum===!0?n+=`.gt(${e.minimum})`:n+=`.min(${e.minimum})`:typeof e.exclusiveMinimum=="number"&&(n+=`.gt(${e.exclusiveMinimum})`),typeof e.maximum=="number"?e.exclusiveMaximum===!0?n+=`.lt(${e.maximum})`:n+=`.max(${e.maximum})`:typeof e.exclusiveMaximum=="number"&&(n+=`.lt(${e.exclusiveMaximum})`),n}var _e={400:"badRequest",401:"unauthorized",402:"paymentRequired",403:"forbidden",404:"notFound",405:"methodNotAllowed",406:"notAcceptable",407:"proxyAuthenticationRequired",408:"requestTimeout",409:"conflict",410:"gone",411:"lengthRequired",412:"preconditionFailed",413:"payloadTooLarge",414:"uriTooLong",415:"unsupportedMediaType",416:"rangeNotSatisfiable",417:"expectationFailed",418:"imATeapot",421:"misdirectedRequest",422:"unprocessableEntity",423:"locked",424:"failedDependency",425:"tooEarly",426:"upgradeRequired",428:"preconditionRequired",429:"tooManyRequests",431:"requestHeaderFieldsTooLarge",451:"unavailableForLegalReasons",500:"internalServerError",501:"notImplemented",502:"badGateway",503:"serviceUnavailable",504:"gatewayTimeout",505:"httpVersionNotSupported",506:"variantAlsoNegotiates",507:"insufficientStorage",508:"loopDetected",510:"notExtended",511:"networkAuthenticationRequired"};function ce(e){if(e==="default")return"defaultError";let n=e.trim(),t=_e[n];if(t)return t;if(/^\d{3}$/.test(n))return`status${n}`;let r=n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();if(!r)return"unknownError";let o=r.split(/\s+/),[i,...s]=o,a=i+s.map(p=>p.charAt(0).toUpperCase()+p.slice(1)).join("");return a?/^[a-zA-Z_$]/.test(a)?a:`status${a.charAt(0).toUpperCase()}${a.slice(1)}`:"unknownError"}function L(e){if(e==="default")return!0;let n=Number(e);return Number.isInteger(n)?n>=400:!1}function Se(e,n){let t=[];if(e.paths)for(let[r,o]of Object.entries(e.paths))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!Oe(a)||!s.operationId)continue;let p=le(r),u=ye(s,n),{successResponse:d,errors:g}=me(s,s.operationId,n),l=de(o,s,e),c=ge(l),y=he(l),f=$e(s,e);t.push({operationId:s.operationId,path:r,method:a,pathParams:p,queryParams:y,requestType:u,responseType:d,requestHeaders:c,errors:g,security:f})}if(e.webhooks)for(let[r,o]of Object.entries(e.webhooks))for(let[i,s]of Object.entries(o)){let a=i.toLowerCase();if(!Oe(a)||!s.operationId)continue;let p=r,u=le(p),d=ye(s,n),{successResponse:g,errors:l}=me(s,s.operationId,n),c=de(o,s,e),y=ge(c),f=he(c),h=$e(s,e);t.push({operationId:s.operationId,path:p,method:a,pathParams:u,queryParams:f,requestType:d,responseType:g,requestHeaders:y,errors:l,security:h})}return t}function de(e,n,t){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let a=D(s,t);if(!a)continue;let p=`${a.in}:${a.name}`;r.set(p,a)}};return o(e.parameters),o(n.parameters),Array.from(r.values())}function le(e){let n=[],t=e.match(/{([^}]+)}/g);if(t)for(let r of t){let o=r.slice(1,-1);n.push({name:o,type:"string"})}return n}function ye(e,n){let t=Je(e);if(!t)return;if(t.$ref){let o=O(t.$ref);return n?.get(o)||o}return`${R(T(e.operationId))}Request`}function Je(e){let n=e?.requestBody?.content;if(!n||Object.keys(n).length===0)return;let t=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let r of t){let o=n[r]?.schema;if(o)return o}}function me(e,n,t){let r=e.responses??{},o=new Map,i=[];for(let[p,u]of Object.entries(r)){let d=u?.content;if(!d||Object.keys(d).length===0){p==="204"||/^3\d\d$/.test(p)?o.set(p,"undefined"):L(p)&&i.push({code:p,schema:"undefined"});continue}let g=E(d),l=d[g]?.schema,c=j(g,l);if(!c){let y=Ke(g,p);y&&(L(p)?i.push({code:p,schema:y}):/^2\d\d$/.test(p)&&o.set(p,y));continue}if(L(p)){i.push({code:p,schema:c});continue}/^2\d\d$/.test(p)&&o.set(p,c)}let s=Qe(o,n,t),a=We(i,n,t);return{successResponse:s,errors:a}}function Qe(e,n,t){if(e.size===0)return;let r=["200","201","204"];for(let i of r){let s=e.get(i);if(s)return typeof s=="string"?s:W(s,`${R(T(n))}Response`,t)}let[,o]=e.entries().next().value??[];if(o)return typeof o=="string"?o:W(o,`${R(T(n))}Response`,t)}function We(e=[],n,t){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=ce(o),a=W(i,`${R(T(n))}${R(s)}`,t);r[s]=a}return r}function W(e,n,t){if(typeof e=="string")return e;if(e.$ref){let r=O(e.$ref);return t?.get(r)||r}if(e.type==="array"&&e.items?.$ref){let r=O(e.items.$ref);return`z.array(${t?.get(r)||r})`}return e.allOf&&Array.isArray(e.allOf),n}function ge(e){let n=[];for(let t of e??[])t.in==="header"&&n.push({name:t.name,description:t.description,schema:t.schema,required:t.required});return n}function he(e){let n=[];for(let t of e??[])t.in==="query"&&n.push({name:t.name,description:t.description,schema:t.schema,required:t.required});return n}function $e(e,n){let t=e.security;if(Array.isArray(t))return t.length===0?[]:t;if(Array.isArray(n.security)&&n.security.length>0)return n.security}function Oe(e){switch(e){case"get":case"put":case"post":case"delete":case"options":case"head":case"patch":case"trace":return!0;default:return!1}}function Ke(e,n){return n==="204"||/^3\d\d$/.test(n)?"undefined":e in H?H[e]:"unknown"}function Te(e,n){let t=new Map,r=M(n);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.requestBody;if(s&&s.content){let a=s.content,p=Ye(a);if(!p)continue;let u=`${R(T(o.operationId))}Request`;(!p.$ref||p.allOf||p.oneOf||p.anyOf)&&t.set(u,p)}}return t}function Ye(e){let n=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let t of n){let r=e[t]?.schema;if(r)return r}}function xe(e,n){let t=new Map,r=M(n);for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.responses||{};for(let[a,p]of Object.entries(s))if(/^2\d\d$/.test(a)&&p.content){let u=p.content,d=E(u),g=u[d]?.schema,l=j(d,g);if(!l)continue;let c=`${R(T(o.operationId))}Response`;(!l.$ref||l.allOf||l.oneOf||l.anyOf)&&t.set(c,l)}}return t}function we(e,n,t,r,o){let i=Te(n,t);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,a]of i){let p=C(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function be(e,n,t,r,o){let i=xe(n,t);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,a]of i){let p=C(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function ke(){let e=[];return e.push("// Generated helper types for Zenko"),e.push("// This file provides type definitions for operation objects and path functions"),e.push(""),e.push("export type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string"),e.push(""),e.push('export type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"'),e.push(""),e.push("export type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult"),e.push(""),e.push("export type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown)"),e.push(""),e.push("export type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push(""),e.push("export type SecurityRequirement = Readonly<Record<string, readonly string[]>>"),e.push(""),e.push("export type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push(""),e.join(`
|
|
8
|
-
`)}function Xe(e){return e===void 0?{open:!1,prefix:"Unknown:"}:typeof e=="boolean"?{open:e,prefix:"Unknown:"}:Array.isArray(e)?{open:e,prefix:"Unknown:"}:{open:e.open??!1,prefix:e.unknownPrefix??"Unknown:"}}function en(e,n={}){let t=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,dateTimeOffset:s=!0,operationIds:a,openEnums:p=!1}=n,u=tn({...n.types,operationTypeSuffix:n.types?.operationTypeSuffix??"Operation"}),d=Xe(p),g={strictDates:o,strictNumeric:i,dateTimeOffset:s,optionalType:u.optionalType,openEnums:d.open,openEnumPrefix:d.prefix};t.push('import { z } from "zod";');let l=new Map;if(e.components?.schemas)for(let f of Object.keys(e.components.schemas))l.set(f,T(f));let c=Se(e,l);if(a&&a.length>0){let f=new Set(a);c=c.filter(h=>f.has(h.operationId))}if(rn(t,u,c),t.push(""),e.components?.schemas){t.push("// Generated Zod Schemas"),t.push("");let f=a&&a.length>0?new Set(oe(c,e)):new Set(Object.keys(e.components.schemas)),h=te(e.components.schemas).filter($=>f.has($));for(let $ of h){let x=e.components.schemas[$],w=l.get($);t.push(C(w,x,r,g,l,e.components.schemas)),t.push(""),t.push(`export type ${w} = z.infer<typeof ${w}>;`),t.push("")}}t.push("// Path Functions"),t.push("export const paths = {");for(let f of c){let $=f.pathParams.map(m=>m.name).length>0,x=f.queryParams.length>0,w=T(f.operationId);if(!$&&!x){t.push(` ${S(w)}: () => "${f.path}",`);continue}let z=m=>{if(P(m))return m;let A=T(m);return P(A)||(A=`_${A}`),A},v=[],N=[];for(let m of f.pathParams)v.push(P(m.name)?m.name:`${S(m.name)}: ${z(m.name)}`),N.push(`${S(m.name)}: string`);for(let m of f.queryParams)v.push(P(m.name)?m.name:`${S(m.name)}: ${z(m.name)}`),N.push(`${S(m.name)}${m.required?"":"?"}: ${un(m)}`);let je=!$&&x&&f.queryParams.every(m=>!m.required),Y=`${v.length?`{ ${v.join(", ")} }`:"{}"}: { ${N.join(", ")} }${je?" = {}":""}`,X=f.path.replace(/{([^}]+)}/g,(m,A)=>`\${${z(A)}}`);if(!x){t.push(` ${S(w)}: (${Y}) => \`${X}\`,`);continue}t.push(` ${S(w)}: (${Y}) => {`),t.push(" const params = new URLSearchParams()");for(let m of f.queryParams){let A=P(m.name)?m.name:z(T(m.name)),Z=m.schema??{};if(Z?.type==="array"){let ne=Pe(Z.items??{},"value");m.required?(t.push(` for (const value of ${A}) {`),t.push(` params.append("${m.name}", ${ne})`),t.push(" }")):(t.push(` if (${A} !== undefined) {`),t.push(` for (const value of ${A}) {`),t.push(` params.append("${m.name}", ${ne})`),t.push(" }"),t.push(" }"));continue}let ee=Pe(Z,A);m.required?t.push(` params.set("${m.name}", ${ee})`):(t.push(` if (${A} !== undefined) {`),t.push(` params.set("${m.name}", ${ee})`),t.push(" }"))}t.push(" const _searchParams = params.toString()"),t.push(` return \`${X}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),t.push(" },")}t.push("} as const;"),t.push(""),t.push("// Header Schemas"),t.push("export const headerSchemas = {");for(let f of c){let h=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${S(h)}: z.object({}),`);continue}let $=f.requestHeaders.map(x=>{let w=pn(x),z=x.required?w:_(w,g.optionalType);return` ${S(x.name)}: ${z},`}).join(`
|
|
9
|
-
`);t.push(` ${S(h)}: z.object({`),t.push($),t.push(" }),")}t.push("} as const;"),t.push(""),t.push("// Header Functions"),t.push("export const headers = {");for(let f of c){let h=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${S(h)}: () => ${P(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse({}),`);continue}t.push(` ${S(h)}: (params: z.input<${P(h)?`typeof headerSchemas.${h}`:`(typeof headerSchemas)[${S(h)}]`}>) => {`),t.push(` return ${P(h)?`headerSchemas.${h}`:`headerSchemas[${S(h)}]`}.parse(params)`),t.push(" },")}if(t.push("} as const;"),t.push(""),e.components?.securitySchemes&&Object.keys(e.components.securitySchemes).length>0){t.push("// Security Schemes"),t.push("export const securitySchemes = {");for(let[f,h]of Object.entries(e.components.securitySchemes)){let $=h;t.push(` ${S(f)}: {`),t.push(` type: ${JSON.stringify($.type)},`),$.type==="http"?(t.push(` scheme: ${JSON.stringify(String($.scheme).toLowerCase())},`),$.bearerFormat&&t.push(` bearerFormat: ${JSON.stringify($.bearerFormat)},`)):$.type==="apiKey"?(t.push(` name: ${JSON.stringify($.name)},`),t.push(` in: ${JSON.stringify($.in)},`)):$.type==="oauth2"?t.push(` flows: ${JSON.stringify($.flows)},`):$.type==="openIdConnect"&&t.push(` openIdConnectUrl: ${JSON.stringify($.openIdConnectUrl)},`),t.push(" },")}t.push("} as const;"),t.push("")}we(t,c,e,l,g),be(t,c,e,l,g),on(t,c,u),t.push("// Operation Objects");for(let f of c){let h=T(f.operationId),$=u.emit?`: ${Ie(h,u.operationTypeSuffix)}`:"";if(t.push(`export const ${h}${$} = {`),t.push(` method: "${f.method}",`),t.push(` path: paths.${h},`),Ae(t,"request",f.requestType),Ae(t,"response",f.responseType),f.requestHeaders&&f.requestHeaders.length>0&&t.push(` headers: headers.${h},`),f.security!==void 0)if(f.security.length===0)t.push(" security: [],");else{let x=f.security.map(w=>`{ ${Object.entries(w).map(([v,N])=>`${S(v)}: ${JSON.stringify(N)}`).join(", ")} }`);t.push(` security: [${x.join(", ")}],`)}f.errors&&Re(f.errors)&&nn(t,"errors",f.errors),t.push("} as const;"),t.push("")}let y={output:t.join(`
|
|
10
|
-
`)};return u.emit&&u.helpers==="file"&&u.helpersOutput&&(y.helperFile={path:u.helpersOutput,content:ke()}),y}function at(e,n={}){return en(e,n).output}function Ae(e,n,t){t&&e.push(` ${n}: ${t},`)}function nn(e,n,t){if(!(!t||Object.keys(t).length===0)){e.push(` ${n}: {`);for(let[r,o]of Object.entries(t))e.push(` ${S(r)}: ${o},`);e.push(" },")}}function Re(e){return!!(e&&Object.keys(e).length>0)}function tn(e){let n=e?.operationTypeSuffix??"Operation";if(n!==""&&!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n))throw new Error(`Invalid operationTypeSuffix "${n}": must be a valid TypeScript identifier suffix (letters, digits, underscores, or $). Use "" for no suffix.`);return{emit:e?.emit??!0,helpers:e?.helpers??"package",helpersOutput:e?.helpersOutput??"./zenko-types",treeShake:e?.treeShake??!0,optionalType:e?.optionalType??"optional",operationTypeSuffix:n}}function Ie(e,n){return`${R(e)}${n}`}function rn(e,n,t){if(n.emit)switch(n.helpers){case"package":if(n.treeShake){let r=U(t),o=V(r,"package");o&&e.push(o)}else e.push('import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "zenko";');return;case"file":if(n.treeShake){let r=U(t),o=V(r,"file",n.helpersOutput);o&&e.push(o)}else e.push(`import type { PathFn, HeaderFn, OperationDefinition, OperationErrors } from "${n.helpersOutput}";`);return;case"inline":e.push("type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;"),e.push('type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";'),e.push("type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;"),e.push("type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);"),e.push("type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;"),e.push("type SecurityRequirement = Readonly<Record<string, readonly string[]>>;"),e.push("type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {"),e.push(" method: TMethod"),e.push(" path: TPath"),e.push(" request?: TRequest"),e.push(" response?: TResponse"),e.push(" headers?: THeaders"),e.push(" errors?: TErrors"),e.push(" security?: TSecurity"),e.push("}"),e.push("")}}function on(e,n,t){if(t.emit){e.push("// Operation Types");for(let r of n){let o=T(r.operationId),i=Ie(o,t.operationTypeSuffix),s=r.requestHeaders?.length?P(o)?`typeof headers.${o}`:`(typeof headers)[${S(o)}]`:"undefined",a=K(r.requestType),p=K(r.responseType),u=sn(r.errors),d=r.security===void 0?"undefined":r.security.length===0?"readonly []":`readonly [${r.security.map(l=>`{ ${Object.entries(l).map(([y,f])=>`readonly ${S(y)}: readonly ${JSON.stringify(f)}`).join("; ")} }`).join(", ")}]`;e.push(`export type ${i} = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${P(o)?`typeof paths.${o}`:`(typeof paths)[${S(o)}]`},`),e.push(` ${a},`),e.push(` ${p},`),e.push(` ${s},`),e.push(` ${u},`),e.push(` ${d}`),e.push(">;"),e.push("")}}}function sn(e){return!e||!Re(e)?"OperationErrors":`OperationErrors<${an(e)}>`}function an(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=S(r),s=ve(o);return`${i}: ${s}`}).join("; ")} }`}var qe=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),ze=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function K(e){if(!e)return"undefined";let n=e.trim();if(n==="undefined")return"undefined";if(qe.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${K(t[1])}>`:ze.test(n)?`typeof ${n}`:n}function ve(e){if(!e)return"unknown";let n=e.trim();if(qe.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${ve(t[1])}>`:ze.test(n)?`typeof ${n}`:n}function pn(e){let n=e.schema??{};switch(n.type){case"integer":case"number":return"z.coerce.number()";case"boolean":return"z.coerce.boolean()";case"array":{let r=n.items??{type:"string"};return`z.array(${r.type==="integer"||r.type==="number"?"z.coerce.number()":r.type==="boolean"?"z.coerce.boolean()":"z.string()"})`}default:return"z.string()"}}function un(e){return Ee(e.schema)}function Ee(e){if(!e)return"string";if(e.type==="array")return`Array<${Ee(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function Pe(e,n){if(!e)return`String(${n})`;switch(e.type){case"integer":case"number":return`String(${n})`;case"boolean":return`${n} ? "true" : "false"`;default:return`String(${n})`}}export{en as a,at as b};
|
|
11
|
-
//# sourceMappingURL=chunk-VHYJGQUS.mjs.map
|
package/dist/cli.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
package/dist/index.d.ts
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
type OpenAPISpec = {
|
|
2
|
-
openapi: string;
|
|
3
|
-
info: unknown;
|
|
4
|
-
paths: Record<string, Record<string, unknown>>;
|
|
5
|
-
webhooks?: Record<string, Record<string, unknown>>;
|
|
6
|
-
security?: Record<string, string[]>[];
|
|
7
|
-
components?: {
|
|
8
|
-
schemas?: Record<string, unknown>;
|
|
9
|
-
parameters?: Record<string, unknown>;
|
|
10
|
-
securitySchemes?: Record<string, unknown>;
|
|
11
|
-
};
|
|
12
|
-
};
|
|
13
|
-
type TypesHelperMode = "package" | "inline" | "file";
|
|
14
|
-
type TypesConfig = {
|
|
15
|
-
emit?: boolean;
|
|
16
|
-
helpers?: TypesHelperMode;
|
|
17
|
-
helpersOutput?: string;
|
|
18
|
-
treeShake?: boolean;
|
|
19
|
-
optionalType?: "optional" | "nullable" | "nullish";
|
|
20
|
-
operationTypeSuffix?: string;
|
|
21
|
-
};
|
|
22
|
-
type EnumConfig = {
|
|
23
|
-
open?: boolean | string[];
|
|
24
|
-
unknownPrefix?: string;
|
|
25
|
-
};
|
|
26
|
-
type GenerateOptions = {
|
|
27
|
-
strictDates?: boolean;
|
|
28
|
-
strictNumeric?: boolean;
|
|
29
|
-
dateTimeOffset?: boolean | string[];
|
|
30
|
-
types?: TypesConfig;
|
|
31
|
-
operationIds?: string[];
|
|
32
|
-
openEnums?: boolean | string[] | EnumConfig;
|
|
33
|
-
};
|
|
34
|
-
/**
|
|
35
|
-
* Generates TypeScript client code from an OpenAPI specification.
|
|
36
|
-
*
|
|
37
|
-
* @param spec - The OpenAPI specification object.
|
|
38
|
-
* @param options - Configuration options controlling code generation behavior.
|
|
39
|
-
* @returns Generated TypeScript code as a string.
|
|
40
|
-
*/
|
|
41
|
-
declare function generate(spec: OpenAPISpec, options?: GenerateOptions): string;
|
|
42
|
-
|
|
43
|
-
type PathFn<TArgs extends unknown[] = []> = (...args: TArgs) => string;
|
|
44
|
-
type RequestMethod = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";
|
|
45
|
-
type HeaderFn<TArgs extends unknown[] = [], TResult = Record<string, unknown> | Record<string, never>> = (...args: TArgs) => TResult;
|
|
46
|
-
type AnyHeaderFn = HeaderFn<any, unknown> | (() => unknown);
|
|
47
|
-
type OperationErrors<TError = unknown> = TError extends Record<string, unknown> ? TError : Record<string, TError>;
|
|
48
|
-
type SecurityRequirement = Readonly<Record<string, readonly string[]>>;
|
|
49
|
-
type OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | undefined = undefined, TSecurity extends readonly SecurityRequirement[] | undefined = undefined> = {
|
|
50
|
-
method: TMethod;
|
|
51
|
-
path: TPath;
|
|
52
|
-
request?: TRequest;
|
|
53
|
-
response?: TResponse;
|
|
54
|
-
headers?: THeaders;
|
|
55
|
-
errors?: TErrors;
|
|
56
|
-
security?: TSecurity;
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
export { type GenerateOptions, type HeaderFn, type OpenAPISpec, type OperationDefinition, type OperationErrors, type PathFn, type SecurityRequirement, type TypesConfig, generate };
|