zenko 0.1.13 → 0.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +122 -2
- package/dist/chunk-LY3CCZ2T.cjs +11 -0
- package/dist/chunk-VT6THCQU.mjs +11 -0
- package/dist/cli.cjs +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.mjs +1 -1
- package/package.json +36 -36
- package/dist/chunk-7VP5JZCL.cjs +0 -8
- package/dist/chunk-NZMYX32P.mjs +0 -8
package/README.md
CHANGED
|
@@ -67,9 +67,12 @@ The config file controls generation for multiple specs and can also configure ty
|
|
|
67
67
|
|
|
68
68
|
```json
|
|
69
69
|
{
|
|
70
|
+
"$schema": "https://raw.githubusercontent.com/RawToast/zenko/refs/heads/master/packages/zenko/zenko-config.schema.json",
|
|
70
71
|
"types": {
|
|
71
72
|
"emit": true,
|
|
72
|
-
"helpers": "package"
|
|
73
|
+
"helpers": "package",
|
|
74
|
+
"treeShake": true,
|
|
75
|
+
"optionalType": "optional"
|
|
73
76
|
},
|
|
74
77
|
"schemas": [
|
|
75
78
|
{
|
|
@@ -84,6 +87,16 @@ The config file controls generation for multiple specs and can also configure ty
|
|
|
84
87
|
"types": {
|
|
85
88
|
"helpers": "inline"
|
|
86
89
|
}
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
"input": "my-custom-api.yaml",
|
|
93
|
+
"output": "my-custom-api.gen.ts",
|
|
94
|
+
"operationIds": ["getUser", "createUser", "updateUser"],
|
|
95
|
+
"types": {
|
|
96
|
+
"helpers": "file",
|
|
97
|
+
"helpersOutput": "./shared/api-helpers.ts",
|
|
98
|
+
"treeShake": false
|
|
99
|
+
}
|
|
87
100
|
}
|
|
88
101
|
]
|
|
89
102
|
}
|
|
@@ -96,6 +109,110 @@ The config file controls generation for multiple specs and can also configure ty
|
|
|
96
109
|
- `helpers: "file"` imports from a custom module (`helpersOutput` path)
|
|
97
110
|
- `emit: false` disables per-operation type aliases entirely
|
|
98
111
|
|
|
112
|
+
#### Additional Type Configuration
|
|
113
|
+
|
|
114
|
+
- `treeShake: true` (default) - Only generates types used in operations
|
|
115
|
+
- `treeShake: false` - Generates all types from the schema
|
|
116
|
+
- `optionalType: "optional"` (default) - Fields can be undefined (`z.optional()`)
|
|
117
|
+
- `optionalType: "nullable"` - Fields can be null (`z.nullable()`)
|
|
118
|
+
- `optionalType: "nullish"` - Fields can be undefined or null (`z.nullish()`)
|
|
119
|
+
|
|
120
|
+
#### Selective Operations
|
|
121
|
+
|
|
122
|
+
Generate only specific operations using `operationIds`:
|
|
123
|
+
|
|
124
|
+
```json
|
|
125
|
+
{
|
|
126
|
+
"$schema": "https://raw.githubusercontent.com/RawToast/zenko/refs/heads/master/packages/zenko/zenko-config.schema.json",
|
|
127
|
+
"schemas": [
|
|
128
|
+
{
|
|
129
|
+
"input": "api.yaml",
|
|
130
|
+
"output": "api.gen.ts",
|
|
131
|
+
"operationIds": ["getUser", "createUser", "updateUser"]
|
|
132
|
+
}
|
|
133
|
+
]
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
#### Open Enums
|
|
138
|
+
|
|
139
|
+
By default, enums are "closed" - they only accept the values defined in your OpenAPI spec. Open enums allow unknown string values to pass through, which is useful when APIs may add new enum values without breaking existing clients.
|
|
140
|
+
|
|
141
|
+
Unknown values are transformed to a prefixed string (default: `` `Unknown:${value}` ``), making them easy to identify and handle.
|
|
142
|
+
|
|
143
|
+
**Basic usage:**
|
|
144
|
+
|
|
145
|
+
```json
|
|
146
|
+
{
|
|
147
|
+
"schemas": [
|
|
148
|
+
{
|
|
149
|
+
"input": "api.yaml",
|
|
150
|
+
"output": "api.gen.ts",
|
|
151
|
+
"openEnums": true
|
|
152
|
+
}
|
|
153
|
+
]
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
**Selective enums:**
|
|
158
|
+
|
|
159
|
+
```json
|
|
160
|
+
{
|
|
161
|
+
"schemas": [
|
|
162
|
+
{
|
|
163
|
+
"input": "api.yaml",
|
|
164
|
+
"output": "api.gen.ts",
|
|
165
|
+
"openEnums": ["Status", "Category"]
|
|
166
|
+
}
|
|
167
|
+
]
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
**Custom prefix:**
|
|
172
|
+
|
|
173
|
+
If `"Unknown:"` conflicts with your schema values or you prefer a different convention, use the object form:
|
|
174
|
+
|
|
175
|
+
```json
|
|
176
|
+
{
|
|
177
|
+
"schemas": [
|
|
178
|
+
{
|
|
179
|
+
"input": "api.yaml",
|
|
180
|
+
"output": "api.gen.ts",
|
|
181
|
+
"openEnums": {
|
|
182
|
+
"open": true,
|
|
183
|
+
"unknownPrefix": "unrecognized_"
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
]
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Or combine selective enums with a custom prefix:
|
|
191
|
+
|
|
192
|
+
```json
|
|
193
|
+
{
|
|
194
|
+
"openEnums": { "open": ["Status"], "unknownPrefix": "x-" }
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
**Generated output:**
|
|
199
|
+
|
|
200
|
+
```typescript
|
|
201
|
+
// Closed enum (default)
|
|
202
|
+
export const Category = z.enum(["electronics", "clothing", "books"])
|
|
203
|
+
|
|
204
|
+
// Open enum
|
|
205
|
+
const StatusKnown = ["active", "inactive", "pending"] as const
|
|
206
|
+
export const Status = z
|
|
207
|
+
.enum(StatusKnown)
|
|
208
|
+
.or(z.string().transform((v): `Unknown:${string}` => `Unknown:${v}`))
|
|
209
|
+
|
|
210
|
+
// TypeScript type includes both known and unknown values
|
|
211
|
+
type Status = "active" | "inactive" | "pending" | `Unknown:${string}`
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
**Note:** When specifying enum names in `openEnums`, use the sanitized TypeScript name (e.g., `"LinksSelf"` not `"Links-Self"`). Schema names with hyphens are converted to camelCase.
|
|
215
|
+
|
|
99
216
|
### Programmatic Usage
|
|
100
217
|
|
|
101
218
|
```typescript
|
|
@@ -230,6 +347,9 @@ if (validation.success) {
|
|
|
230
347
|
|
|
231
348
|
### Building a Generic Client
|
|
232
349
|
|
|
350
|
+
Below is an example of a generic client that can be used to run operations.
|
|
351
|
+
See [examples package](../examples/README.md) for a more complete examples with tests, using undici, fetch, ts-effect.
|
|
352
|
+
|
|
233
353
|
```typescript
|
|
234
354
|
import type { OperationDefinition } from "zenko"
|
|
235
355
|
|
|
@@ -256,7 +376,7 @@ async function runOperation<
|
|
|
256
376
|
|
|
257
377
|
### Dependency Resolution
|
|
258
378
|
|
|
259
|
-
Zenko automatically resolves schema dependencies using topological sorting, ensuring that referenced types are defined before they're used. This eliminates "used before declaration" errors.
|
|
379
|
+
Zenko automatically resolves schema dependencies using topological sorting, ensuring that referenced types are defined before they're used. This eliminates "used before declaration" errors. Alongside excessive duplicate schema generation, as found in other generators.
|
|
260
380
|
|
|
261
381
|
### Zod Integration
|
|
262
382
|
|
|
@@ -0,0 +1,11 @@
|
|
|
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 X(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=v(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 v(e){let n=[],t=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=g(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(g(o));Object.values(r).forEach(t)}}};return t(e),[...new Set(n)]}function g(e){return e.split("/").pop()||"Unknown"}function x(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 $(e){return x(e)?e:`"${e}"`}function T(e){return e.replace(/-([a-zA-Z])/g,(n,t)=>t.toUpperCase()).replace(/-+$/,"")}function k(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&&ee(t.errors)&&(n.usesOperationErrors=!0);return e.length>0&&!n.usesOperationErrors&&e.some(r=>!r.errors||!ee(r.errors))&&(n.usesOperationErrors=!0),n}function Z(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 ee(e){return!!(e&&Object.keys(e).length>0)}var N={"application/json":"unknown","text/csv":"string","text/plain":"string","application/octet-stream":"unknown","application/pdf":"unknown"};function R(e){let n=Object.keys(e);if(n.includes("application/json"))return"application/json";for(let t of n)if(t in N)return t;return n[0]||""}function Re(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 q(e,n){if(!n||!Re(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 M(e,n){if(e){if(e.$ref){let t=g(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 ne(e,n){let t=new Set,r=new Map;for(let[,s]of Object.entries(n.paths||{}))for(let[,a]of Object.entries(s)){let p=a;p.operationId&&r.set(p.operationId,p)}for(let[,s]of Object.entries(n.webhooks||{}))for(let[,a]of Object.entries(s)){let p=a;p.operationId&&r.set(p.operationId,p)}for(let s of e){let a=r.get(s.operationId);if(!a)continue;let p=_optionalChain([a, 'access', _12 => _12.requestBody, 'optionalAccess', _13 => _13.content, 'optionalAccess', _14 => _14["application/json"], 'optionalAccess', _15 => _15.schema]);if(_optionalChain([p, 'optionalAccess', _16 => _16.$ref])){let d=g(p.$ref);t.add(d)}else if(p){let d=v(p);for(let u of d)_optionalChain([n, 'access', _17 => _17.components, 'optionalAccess', _18 => _18.schemas, 'optionalAccess', _19 => _19[u]])&&t.add(u)}let c=a.responses||{};for(let[,d]of Object.entries(c)){let u=_optionalChain([d, 'optionalAccess', _20 => _20.content]);if(!u)continue;let h=R(u),f=_optionalChain([u, 'access', _21 => _21[h], 'optionalAccess', _22 => _22.schema]),m=q(h,f);if(_optionalChain([m, 'optionalAccess', _23 => _23.$ref])){let O=g(m.$ref);t.add(O)}else if(m){let O=v(m);for(let w of O)_optionalChain([n, 'access', _24 => _24.components, 'optionalAccess', _25 => _25.schemas, 'optionalAccess', _26 => _26[w]])&&t.add(w)}}for(let d of s.queryParams){if(_optionalChain([d, 'access', _27 => _27.schema, 'optionalAccess', _28 => _28.$ref])){let u=g(d.schema.$ref);t.add(u)}if(_optionalChain([d, 'access', _29 => _29.schema, 'optionalAccess', _30 => _30.items, 'optionalAccess', _31 => _31.$ref])){let u=g(d.schema.items.$ref);t.add(u)}}for(let d of s.requestHeaders||[]){if(_optionalChain([d, 'access', _32 => _32.schema, 'optionalAccess', _33 => _33.$ref])){let u=g(d.schema.$ref);t.add(u)}if(_optionalChain([d, 'access', _34 => _34.schema, 'optionalAccess', _35 => _35.items, 'optionalAccess', _36 => _36.$ref])){let u=g(d.schema.items.$ref);t.add(u)}}let l=a.parameters||[];for(let d of l){let u=M(d,n);if(_optionalChain([u, 'optionalAccess', _37 => _37.schema, 'optionalAccess', _38 => _38.$ref])){let h=g(u.schema.$ref);t.add(h)}if(_optionalChain([u, 'optionalAccess', _39 => _39.schema, 'optionalAccess', _40 => _40.items, 'optionalAccess', _41 => _41.$ref])){let h=g(u.schema.items.$ref);t.add(h)}}}let o=new Set,i=Array.from(t);for(;i.length>0;){let s=i.pop();if(o.has(s))continue;o.add(s);let a=_optionalChain([n, 'access', _42 => _42.components, 'optionalAccess', _43 => _43.schemas, 'optionalAccess', _44 => _44[s]]);if(!a)continue;let p=v(a);for(let c of p)_optionalChain([n, 'access', _45 => _45.components, 'optionalAccess', _46 => _46.schemas, 'optionalAccess', _47 => _47[c]])&&!o.has(c)&&(t.add(c),i.push(c))}return t}function qe(e,n){return n===!0?!0:Array.isArray(n)?n.includes(e):!1}function U(e,n){switch(n){case"optional":return`${e}.optional()`;case"nullable":return`${e}.nullable()`;case"nullish":return`${e}.nullish()`}}function E(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(qe(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=B(n),a=s.map(u=>P(u,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 c=s.every(u=>L(u,i))?"merge":"and",l=a[0],d=a.slice(1).map(u=>`.${c}(${u})`).join("");return`export const ${e} = ${l}${d};`}if(n.type==="object"||n.properties)return`export const ${e} = ${se(n,r,o,i,e)};`;if(n.type==="array"){let s=_nullishCoalesce(n.items, () => ({type:"unknown"})),a=P(s,r,o,i,e),p=r.strictNumeric||n.minItems!==void 0||n.maxItems!==void 0||n.uniqueItems===!0,c=ae(n,`z.array(${a})`,s,p);return`export const ${e} = ${c};`}return`export const ${e} = ${P(n,r,o,i,e)};`}function te(e,n,t,r,o){let i=e.map(s=>P(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 ve(e,n){if(!_optionalChain([e, 'optionalAccess', _48 => _48.$ref]))return e;let t=g(e.$ref);return _nullishCoalesce(_optionalChain([n, 'optionalAccess', _49 => _49[t]]), () => (e))}function oe(e){return["$ref","type","properties","required","additionalProperties","items","enum","const","oneOf","anyOf","not"].some(t=>_optionalChain([e, 'optionalAccess', _50 => _50[t]])!==void 0)}function B(e){let n=Array.isArray(e.allOf)?[...e.allOf]:[],t={...e};return delete t.allOf,oe(t)&&n.push(t),n}function A(e,n,t,r,o=new Set){if(!e||o.has(e))return!1;if(o.add(e),e.$ref){let i=g(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 A(a,n,t,r,o)}return Array.isArray(e.allOf)?e.allOf.some(i=>A(i,n,t,r,o)):Array.isArray(e.oneOf)?e.oneOf.some(i=>A(i,n,t,r,o)):Array.isArray(e.anyOf)?e.anyOf.some(i=>A(i,n,t,r,o)):e.not?A(e.not,n,t,r,o):e.items?A(e.items,n,t,r,o):e.properties?Object.values(e.properties).some(i=>A(i,n,t,r,o)):e.additionalProperties&&typeof e.additionalProperties=="object"?A(e.additionalProperties,n,t,r,o):!1}function L(e,n){let t=ve(e,n);return t?t.allOf&&Array.isArray(t.allOf)?B(t).every(o=>L(o,n)):t.type==="object"||t.properties!==void 0||t.additionalProperties!==void 0:!1}function Ee(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=g(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 C(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=g(e.$ref),a=_optionalChain([t, 'optionalAccess', _55 => _55[s]]);return a?C(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(...C(s,n,t,r));return Array.from(new Set(o))}function re(e,n,t){return{allOf:[e,{type:"object",properties:{[n]:{const:t}},required:[n]}]}}function je(e,n,t,r){let o=new Set;for(let a of e)_optionalChain([a, 'optionalAccess', _64 => _64.$ref])&&o.add(g(a.$ref));let i=[],s=!1;for(let a of e){let p=[];if(_optionalChain([a, 'optionalAccess', _65 => _65.$ref])){let l=g(a.$ref),d=t.get(l);_optionalChain([d, 'optionalAccess', _66 => _66.values, 'access', _67 => _67.length])&&p.push(...d.values),p.push(...C(a,n,r))}else p.push(...C(a,n,r));let c=Array.from(new Set(p));if(c.length===0){s=!0,i.push(a);continue}for(let l of c)i.push(re(a,n,l))}for(let[a,p]of t.entries()){if(o.has(a))continue;let c={$ref:p.ref};for(let l of p.values)i.push(re(c,n,l))}return{schemas:i,hasUnmapped:s}}function Ne(e,n,t,r,o,i,s){let{schemas:a,hasUnmapped:p}=je(e,n,_nullishCoalesce(s, () => (new Map)),o),c=a.map(l=>P(l,t,r,o,i));return c.length===0?"z.unknown()":c.length===1?_nullishCoalesce(c[0], () => ("z.unknown()")):p?`z.union([${c.join(", ")}])`:`z.discriminatedUnion(${JSON.stringify(n)}, [${c.join(", ")}])`}function P(e,n,t,r,o){if(e.$ref){let i=g(e.$ref),s=_optionalChain([t, 'optionalAccess', _68 => _68.get, 'call', _69 => _69(i)])||i;return o&&(s===o||A(_optionalChain([r, 'optionalAccess', _70 => _70[i]]),o,r,t))?`z.lazy(() => ${s})`:s}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(s=>`"${s}"`).join(", ")}])`;if(e.not){let i=e.not,s={...e};delete s.not;let a=oe(s)?P(s,n,t,r,o):"z.any()";if(_optionalChain([i, 'optionalAccess', _71 => _71.type])==="string"&&i.maxLength===0)return`${a}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`;let p=P(i,n,t,r,o);return`${a}.refine((value) => !${p}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let i=B(e),s=i.map(d=>P(d,n,t,r,o));if(s.length===0)return"z.object({})";if(s.length===1)return _nullishCoalesce(s[0], () => ("z.object({})"));let p=i.every(d=>L(d,r))?"merge":"and",c=s[0],l=s.slice(1).map(d=>`.${p}(${d})`).join("");return`${c}${l}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(_optionalChain([e, 'access', _72 => _72.discriminator, 'optionalAccess', _73 => _73.propertyName])){let i=Ee(e.discriminator);return Ne(e.oneOf,e.discriminator.propertyName,n,t,r,o,i)}return te(e.oneOf,n,t,r,o)}if(e.anyOf&&Array.isArray(e.anyOf))return te(e.anyOf,n,t,r,o);if(e.type==="object"||e.properties||e.allOf)return se(e,n,t,r,o);switch(e.type){case"string":return Ce(e,n);case"boolean":return"z.boolean()";case"array":{let i=_nullishCoalesce(e.items, () => ({type:"unknown"})),s=P(i,n,t,r,o),a=n.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return ae(e,`z.array(${s})`,i,a)}case"null":return"z.null()";case"number":return ie(e,n);case"integer":return De(e,n);default:return"z.unknown()"}}function Me(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(c=>_optionalChain([c, 'optionalAccess', _76 => _76.$ref])&&g(c.$ref)===n),p=Object.values(_nullishCoalesce(_optionalChain([r, 'access', _77 => _77.discriminator, 'optionalAccess', _78 => _78.mapping]), () => ({}))).some(c=>typeof c=="string"&&g(c)===n);(s||p)&&t.add(o)}return t}function se(e,n,t,r,o){let i=[],s=Me(r,o);for(let[c,l]of Object.entries(e.properties||{})){let d=(_nullishCoalesce(_optionalChain([e, 'access', _79 => _79.required, 'optionalAccess', _80 => _80.includes, 'call', _81 => _81(c)]), () => (!1)))||s.has(c),u=P(l,n,t,r,o),h=U(u,n.optionalType),f=n.optionalType!=="nullable"?He(h,l):h,m=d?u:f;i.push(` ${$(c)}: ${m},`)}let a=i.length===0?"z.object({})":`z.object({
|
|
5
|
+
${i.join(`
|
|
6
|
+
`)}
|
|
7
|
+
})`;if(e.additionalProperties===void 0)return a;if(e.additionalProperties===!1)return`${a}.strict()`;if(e.additionalProperties===!0)return`${a}.passthrough()`;let p=P(e.additionalProperties,n,t,r,o);return`${a}.catchall(${p})`}function Ce(e,n){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(n.strictDates)switch(e.format){case"date-time":return"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let t="z.string()";switch(n.strictNumeric&&(typeof e.minLength=="number"&&(t+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(t+=`.max(${e.maxLength})`),e.pattern&&(t+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${t}.uuid()`;case"email":return`${t}.email()`;case"uri":case"url":return`${t}.url()`;case"ipv4":return`${t}.ip({ version: "v4" })`;case"ipv6":return`${t}.ip({ version: "v6" })`;default:return t}}function He(e,n){return!n||n.default===void 0?e:`${e}.default(${JSON.stringify(n.default)})`}function ie(e,n){let t="z.number()";return n.strictNumeric&&(t=Ge(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 De(e,n){let t=ie(e,n);return t+=".int()",t}function ae(e,n,t,r){return r&&(typeof e.minItems=="number"&&(n+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(n+=`.max(${e.maxItems})`),e.uniqueItems&&Fe(t)&&(n+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),n}function Fe(e){return _optionalChain([e, 'optionalAccess', _82 => _82.$ref])?!1:new Set(["string","number","integer","boolean"]).has(_optionalChain([e, 'optionalAccess', _83 => _83.type]))}function Ge(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 Ze={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 pe(e){if(e==="default")return"defaultError";let n=e.trim(),t=Ze[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 H(e){if(e==="default")return!0;let n=Number(e);return Number.isInteger(n)?n>=400:!1}function ge(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(!ye(a)||!s.operationId)continue;let p=fe(r),c=ce(s,n),{successResponse:l,errors:d}=de(s,s.operationId,n),u=ue(o,s,e),h=le(u),f=me(u);t.push({operationId:s.operationId,path:r,method:a,pathParams:p,queryParams:f,requestType:c,responseType:l,requestHeaders:h,errors:d})}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(!ye(a)||!s.operationId)continue;let p=r,c=fe(p),l=ce(s,n),{successResponse:d,errors:u}=de(s,s.operationId,n),h=ue(o,s,e),f=le(h),m=me(h);t.push({operationId:s.operationId,path:p,method:a,pathParams:c,queryParams:m,requestType:l,responseType:d,requestHeaders:f,errors:u})}return t}function ue(e,n,t){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let a=M(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 fe(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 ce(e,n){let t=Ve(e);if(!t)return;if(t.$ref){let o=g(t.$ref);return _optionalChain([n, 'optionalAccess', _84 => _84.get, 'call', _85 => _85(o)])||o}return`${k(T(e.operationId))}Request`}function Ve(e){let n=_optionalChain([e, 'optionalAccess', _86 => _86.requestBody, 'optionalAccess', _87 => _87.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', _88 => _88[r], 'optionalAccess', _89 => _89.schema]);if(o)return o}}function de(e,n,t){let r=_nullishCoalesce(e.responses, () => ({})),o=new Map,i=[];for(let[p,c]of Object.entries(r)){let l=_optionalChain([c, 'optionalAccess', _90 => _90.content]);if(!l||Object.keys(l).length===0){p==="204"||/^3\d\d$/.test(p)?o.set(p,"undefined"):H(p)&&i.push({code:p,schema:"undefined"});continue}let d=R(l),u=_optionalChain([l, 'access', _91 => _91[d], 'optionalAccess', _92 => _92.schema]),h=q(d,u);if(!h){let f=Le(d,p);f&&(H(p)?i.push({code:p,schema:f}):/^2\d\d$/.test(p)&&o.set(p,f));continue}if(H(p)){i.push({code:p,schema:h});continue}/^2\d\d$/.test(p)&&o.set(p,h)}let s=Ue(o,n,t),a=Be(i,n,t);return{successResponse:s,errors:a}}function Ue(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:_(s,`${k(T(n))}Response`,t)}let[,o]=_nullishCoalesce(e.entries().next().value, () => ([]));if(o)return typeof o=="string"?o:_(o,`${k(T(n))}Response`,t)}function Be(e=[],n,t){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=pe(o),a=_(i,`${k(T(n))}${k(s)}`,t);r[s]=a}return r}function _(e,n,t){if(typeof e=="string")return e;if(e.$ref){let r=g(e.$ref);return _optionalChain([t, 'optionalAccess', _93 => _93.get, 'call', _94 => _94(r)])||r}if(e.type==="array"&&_optionalChain([e, 'access', _95 => _95.items, 'optionalAccess', _96 => _96.$ref])){let r=g(e.items.$ref);return`z.array(${_optionalChain([t, 'optionalAccess', _97 => _97.get, 'call', _98 => _98(r)])||r})`}return e.allOf&&Array.isArray(e.allOf),n}function le(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 me(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 ye(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 Le(e,n){return n==="204"||/^3\d\d$/.test(n)?"undefined":e in N?N[e]:"unknown"}function he(e,n){let t=new Map,r=new Map;for(let[,o]of Object.entries(n.paths||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let[,o]of Object.entries(n.webhooks||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}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=_e(a);if(!p)continue;let c=`${k(T(o.operationId))}Request`;(!p.$ref||p.allOf||p.oneOf||p.anyOf)&&t.set(c,p)}}return t}function _e(e){let n=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let t of n){let r=_optionalChain([e, 'access', _99 => _99[t], 'optionalAccess', _100 => _100.schema]);if(r)return r}}function $e(e,n){let t=new Map,r=new Map;for(let[,o]of Object.entries(n.paths||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let[,o]of Object.entries(n.webhooks||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}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 c=p.content,l=R(c),d=_optionalChain([c, 'access', _101 => _101[l], 'optionalAccess', _102 => _102.schema]),u=q(l,d);if(!u)continue;let h=`${k(T(o.operationId))}Response`;(!u.$ref||u.allOf||u.oneOf||u.anyOf)&&t.set(h,u)}}return t}function Oe(e,n,t,r,o){let i=he(n,t);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,a]of i){let p=E(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function Te(e,n,t,r,o){let i=$e(n,t);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,a]of i){let p=E(s,a,new Set,o,r);e.push(p),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),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 OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | 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("}"),e.push(""),e.join(`
|
|
8
|
+
`)}function Qe(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 We(e,n={}){let t=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,operationIds:s,openEnums:a=!1}=n,p=Ke(n.types),c=Qe(a),l={strictDates:o,strictNumeric:i,optionalType:p.optionalType,openEnums:c.open,openEnumPrefix:c.prefix};t.push('import { z } from "zod";');let d=new Map;if(_optionalChain([e, 'access', _103 => _103.components, 'optionalAccess', _104 => _104.schemas]))for(let f of Object.keys(e.components.schemas))d.set(f,T(f));let u=ge(e,d);if(s&&s.length>0){let f=new Set(s);u=u.filter(m=>f.has(m.operationId))}if(Ye(t,p,u),t.push(""),_optionalChain([e, 'access', _105 => _105.components, 'optionalAccess', _106 => _106.schemas])){t.push("// Generated Zod Schemas"),t.push("");let f;if(s&&s.length>0){let O=ne(u,e);f=Array.from(O)}else f=Object.keys(e.components.schemas);let m=X(e.components.schemas).filter(O=>f.includes(O));for(let O of m){let w=e.components.schemas[O],I=d.get(O);t.push(E(I,w,r,l,d,e.components.schemas)),t.push(""),t.push(`export type ${I} = z.infer<typeof ${I}>;`),t.push("")}}t.push("// Path Functions"),t.push("export const paths = {");for(let f of u){let O=f.pathParams.map(y=>y.name).length>0,w=f.queryParams.length>0,I=T(f.operationId);if(!O&&!w){t.push(` ${$(I)}: () => "${f.path}",`);continue}let z=y=>{if(x(y))return y;let b=T(y);return x(b)||(b=`_${b}`),b},j=[],D=[];for(let y of f.pathParams)j.push(x(y.name)?y.name:`${$(y.name)}: ${z(y.name)}`),D.push(`${$(y.name)}: string`);for(let y of f.queryParams)j.push(x(y.name)?y.name:`${$(y.name)}: ${z(y.name)}`),D.push(`${$(y.name)}${y.required?"":"?"}: ${rn(y)}`);let ze=!O&&w&&f.queryParams.every(y=>!y.required),W=`${j.length?`{ ${j.join(", ")} }`:"{}"}: { ${D.join(", ")} }${ze?" = {}":""}`,J=f.path.replace(/{([^}]+)}/g,(y,b)=>`\${${z(b)}}`);if(!w){t.push(` ${$(I)}: (${W}) => \`${J}\`,`);continue}t.push(` ${$(I)}: (${W}) => {`),t.push(" const params = new URLSearchParams()");for(let y of f.queryParams){let b=x(y.name)?y.name:z(T(y.name)),F=_nullishCoalesce(y.schema, () => ({}));if(_optionalChain([F, 'optionalAccess', _107 => _107.type])==="array"){let Y=Se(_nullishCoalesce(F.items, () => ({})),"value");y.required?(t.push(` for (const value of ${b}) {`),t.push(` params.append("${y.name}", ${Y})`),t.push(" }")):(t.push(` if (${b} !== undefined) {`),t.push(` for (const value of ${b}) {`),t.push(` params.append("${y.name}", ${Y})`),t.push(" }"),t.push(" }"));continue}let K=Se(F,b);y.required?t.push(` params.set("${y.name}", ${K})`):(t.push(` if (${b} !== undefined) {`),t.push(` params.set("${y.name}", ${K})`),t.push(" }"))}t.push(" const _searchParams = params.toString()"),t.push(` return \`${J}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),t.push(" },")}t.push("} as const;"),t.push(""),t.push("// Header Schemas"),t.push("export const headerSchemas = {");for(let f of u){let m=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${$(m)}: z.object({}),`);continue}let O=f.requestHeaders.map(w=>{let I=tn(w),z=w.required?I:U(I,l.optionalType);return` ${$(w.name)}: ${z},`}).join(`
|
|
9
|
+
`);t.push(` ${$(m)}: z.object({`),t.push(O),t.push(" }),")}t.push("} as const;"),t.push(""),t.push("// Header Functions"),t.push("export const headers = {");for(let f of u){let m=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${$(m)}: () => ${x(m)?`headerSchemas.${m}`:`headerSchemas[${$(m)}]`}.parse({}),`);continue}t.push(` ${$(m)}: (params: z.input<${x(m)?`typeof headerSchemas.${m}`:`(typeof headerSchemas)[${$(m)}]`}>) => {`),t.push(` return ${x(m)?`headerSchemas.${m}`:`headerSchemas[${$(m)}]`}.parse(params)`),t.push(" },")}t.push("} as const;"),t.push(""),Oe(t,u,e,d,l),Te(t,u,e,d,l),Xe(t,u,p),t.push("// Operation Objects");for(let f of u){let m=T(f.operationId),O=p.emit?`: ${k(m)}Operation`:"";t.push(`export const ${m}${O} = {`),t.push(` method: "${f.method}",`),t.push(` path: paths.${m},`),be(t,"request",f.requestType),be(t,"response",f.responseType),f.requestHeaders&&f.requestHeaders.length>0&&t.push(` headers: headers.${m},`),f.errors&&xe(f.errors)&&Je(t,"errors",f.errors),t.push("} as const;"),t.push("")}let h={output:t.join(`
|
|
10
|
+
`)};return p.emit&&p.helpers==="file"&&p.helpersOutput&&(h.helperFile={path:p.helpersOutput,content:we()}),h}function Yn(e,n={}){return We(e,n).output}function be(e,n,t){t&&e.push(` ${n}: ${t},`)}function Je(e,n,t){if(!(!t||Object.keys(t).length===0)){e.push(` ${n}: {`);for(let[r,o]of Object.entries(t))e.push(` ${$(r)}: ${o},`);e.push(" },")}}function xe(e){return!!(e&&Object.keys(e).length>0)}function Ke(e){return{emit:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _108 => _108.emit]), () => (!0)),helpers:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _109 => _109.helpers]), () => ("package")),helpersOutput:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _110 => _110.helpersOutput]), () => ("./zenko-types")),treeShake:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _111 => _111.treeShake]), () => (!0)),optionalType:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _112 => _112.optionalType]), () => ("optional"))}}function Ye(e,n,t){if(n.emit)switch(n.helpers){case"package":if(n.treeShake){let r=G(t),o=Z(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=Z(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 OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | 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("}"),e.push("")}}function Xe(e,n,t){if(t.emit){e.push("// Operation Types");for(let r of n){let o=T(r.operationId),i=_optionalChain([r, 'access', _113 => _113.requestHeaders, 'optionalAccess', _114 => _114.length])?x(o)?`typeof headers.${o}`:`(typeof headers)[${$(o)}]`:"undefined",s=Q(r.requestType),a=Q(r.responseType),p=en(r.errors);e.push(`export type ${k(o)}Operation = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${x(o)?`typeof paths.${o}`:`(typeof paths)[${$(o)}]`},`),e.push(` ${s},`),e.push(` ${a},`),e.push(` ${i},`),e.push(` ${p}`),e.push(">;"),e.push("")}}}function en(e){return!e||!xe(e)?"OperationErrors":`OperationErrors<${nn(e)}>`}function nn(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=$(r),s=Ie(o);return`${i}: ${s}`}).join("; ")} }`}var ke=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),Pe=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Q(e){if(!e)return"undefined";let n=e.trim();if(n==="undefined")return"undefined";if(ke.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${Q(t[1])}>`:Pe.test(n)?`typeof ${n}`:n}function Ie(e){if(!e)return"unknown";let n=e.trim();if(ke.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${Ie(t[1])}>`:Pe.test(n)?`typeof ${n}`:n}function tn(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 rn(e){return Ae(e.schema)}function Ae(e){if(!e)return"string";if(e.type==="array")return`Array<${Ae(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function Se(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 = We; exports.b = Yn;
|
|
11
|
+
//# sourceMappingURL=chunk-LY3CCZ2T.cjs.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
function ee(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=E(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 E(e){let n=[],t=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=g(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(g(o));Object.values(r).forEach(t)}}};return t(e),[...new Set(n)]}function g(e){return e.split("/").pop()||"Unknown"}function k(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 $(e){return k(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 Z(e){let n={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(n.usesOperationDefinition=!0);for(let t of e)t.errors&&ne(t.errors)&&(n.usesOperationErrors=!0);return e.length>0&&!n.usesOperationErrors&&e.some(r=>!r.errors||!ne(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 ne(e){return!!(e&&Object.keys(e).length>0)}var M={"application/json":"unknown","text/csv":"string","text/plain":"string","application/octet-stream":"unknown","application/pdf":"unknown"};function q(e){let n=Object.keys(e);if(n.includes("application/json"))return"application/json";for(let t of n)if(t in M)return t;return n[0]||""}function qe(e){let n=e.toLowerCase().split(";")[0]?.trim();return n?!!(n.startsWith("text/")||n==="application/xml"||n.startsWith("application/")&&n.endsWith("+xml")):!1}function v(e,n){if(!n||!qe(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 C(e,n){if(e){if(e.$ref){let t=g(e.$ref),r=n.components?.parameters?.[t];if(!r)return;let{$ref:o,...i}=e;return{...r,...i}}return e}}function te(e,n){let t=new Set,r=new Map;for(let[,s]of Object.entries(n.paths||{}))for(let[,a]of Object.entries(s)){let p=a;p.operationId&&r.set(p.operationId,p)}for(let[,s]of Object.entries(n.webhooks||{}))for(let[,a]of Object.entries(s)){let p=a;p.operationId&&r.set(p.operationId,p)}for(let s of e){let a=r.get(s.operationId);if(!a)continue;let p=a.requestBody?.content?.["application/json"]?.schema;if(p?.$ref){let d=g(p.$ref);t.add(d)}else if(p){let d=E(p);for(let u of d)n.components?.schemas?.[u]&&t.add(u)}let c=a.responses||{};for(let[,d]of Object.entries(c)){let u=d?.content;if(!u)continue;let h=q(u),f=u[h]?.schema,m=v(h,f);if(m?.$ref){let O=g(m.$ref);t.add(O)}else if(m){let O=E(m);for(let w of O)n.components?.schemas?.[w]&&t.add(w)}}for(let d of s.queryParams){if(d.schema?.$ref){let u=g(d.schema.$ref);t.add(u)}if(d.schema?.items?.$ref){let u=g(d.schema.items.$ref);t.add(u)}}for(let d of s.requestHeaders||[]){if(d.schema?.$ref){let u=g(d.schema.$ref);t.add(u)}if(d.schema?.items?.$ref){let u=g(d.schema.items.$ref);t.add(u)}}let l=a.parameters||[];for(let d of l){let u=C(d,n);if(u?.schema?.$ref){let h=g(u.schema.$ref);t.add(h)}if(u?.schema?.items?.$ref){let h=g(u.schema.items.$ref);t.add(h)}}}let o=new Set,i=Array.from(t);for(;i.length>0;){let s=i.pop();if(o.has(s))continue;o.add(s);let a=n.components?.schemas?.[s];if(!a)continue;let p=E(a);for(let c of p)n.components?.schemas?.[c]&&!o.has(c)&&(t.add(c),i.push(c))}return t}function ve(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 j(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(ve(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=L(n),a=s.map(u=>I(u,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 c=s.every(u=>_(u,i))?"merge":"and",l=a[0],d=a.slice(1).map(u=>`.${c}(${u})`).join("");return`export const ${e} = ${l}${d};`}if(n.type==="object"||n.properties)return`export const ${e} = ${ie(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,c=pe(n,`z.array(${a})`,s,p);return`export const ${e} = ${c};`}return`export const ${e} = ${I(n,r,o,i,e)};`}function re(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 U(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ee(e,n){if(!e?.$ref)return e;let t=g(e.$ref);return n?.[t]??e}function se(e){return["$ref","type","properties","required","additionalProperties","items","enum","const","oneOf","anyOf","not"].some(t=>e?.[t]!==void 0)}function L(e){let n=Array.isArray(e.allOf)?[...e.allOf]:[],t={...e};return delete t.allOf,se(t)&&n.push(t),n}function z(e,n,t,r,o=new Set){if(!e||o.has(e))return!1;if(o.add(e),e.$ref){let i=g(e.$ref);if((r?.get(i)||i)===n)return!0;let a=t?.[i];if(a)return z(a,n,t,r,o)}return Array.isArray(e.allOf)?e.allOf.some(i=>z(i,n,t,r,o)):Array.isArray(e.oneOf)?e.oneOf.some(i=>z(i,n,t,r,o)):Array.isArray(e.anyOf)?e.anyOf.some(i=>z(i,n,t,r,o)):e.not?z(e.not,n,t,r,o):e.items?z(e.items,n,t,r,o):e.properties?Object.values(e.properties).some(i=>z(i,n,t,r,o)):e.additionalProperties&&typeof e.additionalProperties=="object"?z(e.additionalProperties,n,t,r,o):!1}function _(e,n){let t=Ee(e,n);return t?t.allOf&&Array.isArray(t.allOf)?L(t).every(o=>_(o,n)):t.type==="object"||t.properties!==void 0||t.additionalProperties!==void 0:!1}function je(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=g(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 H(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=g(e.$ref),a=t?.[s];return a?H(a,n,t,r):[]}let o=[],i=e.properties?.[n];if(i){let s=i.const;s!==void 0&&U(s)?o.push(s):Array.isArray(i.enum)&&i.enum?.length===1&&U(i.enum?.[0])&&o.push(i.enum?.[0])}if(Array.isArray(e.allOf))for(let s of e.allOf)o.push(...H(s,n,t,r));return Array.from(new Set(o))}function oe(e,n,t){return{allOf:[e,{type:"object",properties:{[n]:{const:t}},required:[n]}]}}function Ne(e,n,t,r){let o=new Set;for(let a of e)a?.$ref&&o.add(g(a.$ref));let i=[],s=!1;for(let a of e){let p=[];if(a?.$ref){let l=g(a.$ref),d=t.get(l);d?.values.length&&p.push(...d.values),p.push(...H(a,n,r))}else p.push(...H(a,n,r));let c=Array.from(new Set(p));if(c.length===0){s=!0,i.push(a);continue}for(let l of c)i.push(oe(a,n,l))}for(let[a,p]of t.entries()){if(o.has(a))continue;let c={$ref:p.ref};for(let l of p.values)i.push(oe(c,n,l))}return{schemas:i,hasUnmapped:s}}function Me(e,n,t,r,o,i,s){let{schemas:a,hasUnmapped:p}=Ne(e,n,s??new Map,o),c=a.map(l=>I(l,t,r,o,i));return c.length===0?"z.unknown()":c.length===1?c[0]??"z.unknown()":p?`z.union([${c.join(", ")}])`:`z.discriminatedUnion(${JSON.stringify(n)}, [${c.join(", ")}])`}function I(e,n,t,r,o){if(e.$ref){let i=g(e.$ref),s=t?.get(i)||i;return o&&(s===o||z(r?.[i],o,r,t))?`z.lazy(() => ${s})`:s}if(e.const!==void 0&&U(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(s=>`"${s}"`).join(", ")}])`;if(e.not){let i=e.not,s={...e};delete s.not;let a=se(s)?I(s,n,t,r,o):"z.any()";if(i?.type==="string"&&i.maxLength===0)return`${a}.refine((value) => typeof value !== "string" || value.length > 0, { message: "Value must not be empty" })`;let p=I(i,n,t,r,o);return`${a}.refine((value) => !${p}.safeParse(value).success, { message: "Value must not match schema" })`}if(e.allOf&&Array.isArray(e.allOf)){let i=L(e),s=i.map(d=>I(d,n,t,r,o));if(s.length===0)return"z.object({})";if(s.length===1)return s[0]??"z.object({})";let p=i.every(d=>_(d,r))?"merge":"and",c=s[0],l=s.slice(1).map(d=>`.${p}(${d})`).join("");return`${c}${l}`}if(e.oneOf&&Array.isArray(e.oneOf)){if(e.discriminator?.propertyName){let i=je(e.discriminator);return Me(e.oneOf,e.discriminator.propertyName,n,t,r,o,i)}return re(e.oneOf,n,t,r,o)}if(e.anyOf&&Array.isArray(e.anyOf))return re(e.anyOf,n,t,r,o);if(e.type==="object"||e.properties||e.allOf)return ie(e,n,t,r,o);switch(e.type){case"string":return He(e,n);case"boolean":return"z.boolean()";case"array":{let i=e.items??{type:"unknown"},s=I(i,n,t,r,o),a=n.strictNumeric||e.minItems!==void 0||e.maxItems!==void 0||e.uniqueItems===!0;return pe(e,`z.array(${s})`,i,a)}case"null":return"z.null()";case"number":return ae(e,n);case"integer":return Fe(e,n);default:return"z.unknown()"}}function Ce(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(c=>c?.$ref&&g(c.$ref)===n),p=Object.values(r.discriminator?.mapping??{}).some(c=>typeof c=="string"&&g(c)===n);(s||p)&&t.add(o)}return t}function ie(e,n,t,r,o){let i=[],s=Ce(r,o);for(let[c,l]of Object.entries(e.properties||{})){let d=(e.required?.includes(c)??!1)||s.has(c),u=I(l,n,t,r,o),h=B(u,n.optionalType),f=n.optionalType!=="nullable"?De(h,l):h,m=d?u:f;i.push(` ${$(c)}: ${m},`)}let a=i.length===0?"z.object({})":`z.object({
|
|
5
|
+
${i.join(`
|
|
6
|
+
`)}
|
|
7
|
+
})`;if(e.additionalProperties===void 0)return a;if(e.additionalProperties===!1)return`${a}.strict()`;if(e.additionalProperties===!0)return`${a}.passthrough()`;let p=I(e.additionalProperties,n,t,r,o);return`${a}.catchall(${p})`}function He(e,n){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(n.strictDates)switch(e.format){case"date-time":return"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let t="z.string()";switch(n.strictNumeric&&(typeof e.minLength=="number"&&(t+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(t+=`.max(${e.maxLength})`),e.pattern&&(t+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${t}.uuid()`;case"email":return`${t}.email()`;case"uri":case"url":return`${t}.url()`;case"ipv4":return`${t}.ip({ version: "v4" })`;case"ipv6":return`${t}.ip({ version: "v6" })`;default:return t}}function De(e,n){return!n||n.default===void 0?e:`${e}.default(${JSON.stringify(n.default)})`}function ae(e,n){let t="z.number()";return n.strictNumeric&&(t=Ze(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 Fe(e,n){let t=ae(e,n);return t+=".int()",t}function pe(e,n,t,r){return r&&(typeof e.minItems=="number"&&(n+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(n+=`.max(${e.maxItems})`),e.uniqueItems&&Ge(t)&&(n+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),n}function Ge(e){return e?.$ref?!1:new Set(["string","number","integer","boolean"]).has(e?.type)}function Ze(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 Ve={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 ue(e){if(e==="default")return"defaultError";let n=e.trim(),t=Ve[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 D(e){if(e==="default")return!0;let n=Number(e);return Number.isInteger(n)?n>=400:!1}function he(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(!ge(a)||!s.operationId)continue;let p=ce(r),c=de(s,n),{successResponse:l,errors:d}=le(s,s.operationId,n),u=fe(o,s,e),h=me(u),f=ye(u);t.push({operationId:s.operationId,path:r,method:a,pathParams:p,queryParams:f,requestType:c,responseType:l,requestHeaders:h,errors:d})}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(!ge(a)||!s.operationId)continue;let p=r,c=ce(p),l=de(s,n),{successResponse:d,errors:u}=le(s,s.operationId,n),h=fe(o,s,e),f=me(h),m=ye(h);t.push({operationId:s.operationId,path:p,method:a,pathParams:c,queryParams:m,requestType:l,responseType:d,requestHeaders:f,errors:u})}return t}function fe(e,n,t){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let a=C(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 ce(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 de(e,n){let t=Ue(e);if(!t)return;if(t.$ref){let o=g(t.$ref);return n?.get(o)||o}return`${P(T(e.operationId))}Request`}function Ue(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 le(e,n,t){let r=e.responses??{},o=new Map,i=[];for(let[p,c]of Object.entries(r)){let l=c?.content;if(!l||Object.keys(l).length===0){p==="204"||/^3\d\d$/.test(p)?o.set(p,"undefined"):D(p)&&i.push({code:p,schema:"undefined"});continue}let d=q(l),u=l[d]?.schema,h=v(d,u);if(!h){let f=_e(d,p);f&&(D(p)?i.push({code:p,schema:f}):/^2\d\d$/.test(p)&&o.set(p,f));continue}if(D(p)){i.push({code:p,schema:h});continue}/^2\d\d$/.test(p)&&o.set(p,h)}let s=Be(o,n,t),a=Le(i,n,t);return{successResponse:s,errors:a}}function Be(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]=e.entries().next().value??[];if(o)return typeof o=="string"?o:Q(o,`${P(T(n))}Response`,t)}function Le(e=[],n,t){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=ue(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=g(e.$ref);return t?.get(r)||r}if(e.type==="array"&&e.items?.$ref){let r=g(e.items.$ref);return`z.array(${t?.get(r)||r})`}return e.allOf&&Array.isArray(e.allOf),n}function me(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 ye(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 ge(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 _e(e,n){return n==="204"||/^3\d\d$/.test(n)?"undefined":e in M?M[e]:"unknown"}function $e(e,n){let t=new Map,r=new Map;for(let[,o]of Object.entries(n.paths||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let[,o]of Object.entries(n.webhooks||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}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=Qe(a);if(!p)continue;let c=`${P(T(o.operationId))}Request`;(!p.$ref||p.allOf||p.oneOf||p.anyOf)&&t.set(c,p)}}return t}function Qe(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 Oe(e,n){let t=new Map,r=new Map;for(let[,o]of Object.entries(n.paths||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let[,o]of Object.entries(n.webhooks||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}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 c=p.content,l=q(c),d=c[l]?.schema,u=v(l,d);if(!u)continue;let h=`${P(T(o.operationId))}Response`;(!u.$ref||u.allOf||u.oneOf||u.anyOf)&&t.set(h,u)}}return t}function Te(e,n,t,r,o){let i=$e(n,t);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,a]of i){let p=j(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=Oe(n,t);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,a]of i){let p=j(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 OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | 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("}"),e.push(""),e.join(`
|
|
8
|
+
`)}function We(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 Je(e,n={}){let t=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,operationIds:s,openEnums:a=!1}=n,p=Ye(n.types),c=We(a),l={strictDates:o,strictNumeric:i,optionalType:p.optionalType,openEnums:c.open,openEnumPrefix:c.prefix};t.push('import { z } from "zod";');let d=new Map;if(e.components?.schemas)for(let f of Object.keys(e.components.schemas))d.set(f,T(f));let u=he(e,d);if(s&&s.length>0){let f=new Set(s);u=u.filter(m=>f.has(m.operationId))}if(Xe(t,p,u),t.push(""),e.components?.schemas){t.push("// Generated Zod Schemas"),t.push("");let f;if(s&&s.length>0){let O=te(u,e);f=Array.from(O)}else f=Object.keys(e.components.schemas);let m=ee(e.components.schemas).filter(O=>f.includes(O));for(let O of m){let w=e.components.schemas[O],A=d.get(O);t.push(j(A,w,r,l,d,e.components.schemas)),t.push(""),t.push(`export type ${A} = z.infer<typeof ${A}>;`),t.push("")}}t.push("// Path Functions"),t.push("export const paths = {");for(let f of u){let O=f.pathParams.map(y=>y.name).length>0,w=f.queryParams.length>0,A=T(f.operationId);if(!O&&!w){t.push(` ${$(A)}: () => "${f.path}",`);continue}let R=y=>{if(k(y))return y;let b=T(y);return k(b)||(b=`_${b}`),b},N=[],F=[];for(let y of f.pathParams)N.push(k(y.name)?y.name:`${$(y.name)}: ${R(y.name)}`),F.push(`${$(y.name)}: string`);for(let y of f.queryParams)N.push(k(y.name)?y.name:`${$(y.name)}: ${R(y.name)}`),F.push(`${$(y.name)}${y.required?"":"?"}: ${on(y)}`);let Re=!O&&w&&f.queryParams.every(y=>!y.required),J=`${N.length?`{ ${N.join(", ")} }`:"{}"}: { ${F.join(", ")} }${Re?" = {}":""}`,K=f.path.replace(/{([^}]+)}/g,(y,b)=>`\${${R(b)}}`);if(!w){t.push(` ${$(A)}: (${J}) => \`${K}\`,`);continue}t.push(` ${$(A)}: (${J}) => {`),t.push(" const params = new URLSearchParams()");for(let y of f.queryParams){let b=k(y.name)?y.name:R(T(y.name)),G=y.schema??{};if(G?.type==="array"){let X=xe(G.items??{},"value");y.required?(t.push(` for (const value of ${b}) {`),t.push(` params.append("${y.name}", ${X})`),t.push(" }")):(t.push(` if (${b} !== undefined) {`),t.push(` for (const value of ${b}) {`),t.push(` params.append("${y.name}", ${X})`),t.push(" }"),t.push(" }"));continue}let Y=xe(G,b);y.required?t.push(` params.set("${y.name}", ${Y})`):(t.push(` if (${b} !== undefined) {`),t.push(` params.set("${y.name}", ${Y})`),t.push(" }"))}t.push(" const _searchParams = params.toString()"),t.push(` return \`${K}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),t.push(" },")}t.push("} as const;"),t.push(""),t.push("// Header Schemas"),t.push("export const headerSchemas = {");for(let f of u){let m=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${$(m)}: z.object({}),`);continue}let O=f.requestHeaders.map(w=>{let A=rn(w),R=w.required?A:B(A,l.optionalType);return` ${$(w.name)}: ${R},`}).join(`
|
|
9
|
+
`);t.push(` ${$(m)}: z.object({`),t.push(O),t.push(" }),")}t.push("} as const;"),t.push(""),t.push("// Header Functions"),t.push("export const headers = {");for(let f of u){let m=T(f.operationId);if(!f.requestHeaders||f.requestHeaders.length===0){t.push(` ${$(m)}: () => ${k(m)?`headerSchemas.${m}`:`headerSchemas[${$(m)}]`}.parse({}),`);continue}t.push(` ${$(m)}: (params: z.input<${k(m)?`typeof headerSchemas.${m}`:`(typeof headerSchemas)[${$(m)}]`}>) => {`),t.push(` return ${k(m)?`headerSchemas.${m}`:`headerSchemas[${$(m)}]`}.parse(params)`),t.push(" },")}t.push("} as const;"),t.push(""),Te(t,u,e,d,l),we(t,u,e,d,l),en(t,u,p),t.push("// Operation Objects");for(let f of u){let m=T(f.operationId),O=p.emit?`: ${P(m)}Operation`:"";t.push(`export const ${m}${O} = {`),t.push(` method: "${f.method}",`),t.push(` path: paths.${m},`),Se(t,"request",f.requestType),Se(t,"response",f.responseType),f.requestHeaders&&f.requestHeaders.length>0&&t.push(` headers: headers.${m},`),f.errors&&ke(f.errors)&&Ke(t,"errors",f.errors),t.push("} as const;"),t.push("")}let h={output:t.join(`
|
|
10
|
+
`)};return p.emit&&p.helpers==="file"&&p.helpersOutput&&(h.helperFile={path:p.helpersOutput,content:be()}),h}function Xn(e,n={}){return Je(e,n).output}function Se(e,n,t){t&&e.push(` ${n}: ${t},`)}function Ke(e,n,t){if(!(!t||Object.keys(t).length===0)){e.push(` ${n}: {`);for(let[r,o]of Object.entries(t))e.push(` ${$(r)}: ${o},`);e.push(" },")}}function ke(e){return!!(e&&Object.keys(e).length>0)}function Ye(e){return{emit:e?.emit??!0,helpers:e?.helpers??"package",helpersOutput:e?.helpersOutput??"./zenko-types",treeShake:e?.treeShake??!0,optionalType:e?.optionalType??"optional"}}function Xe(e,n,t){if(n.emit)switch(n.helpers){case"package":if(n.treeShake){let r=Z(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=Z(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 OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | 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("}"),e.push("")}}function en(e,n,t){if(t.emit){e.push("// Operation Types");for(let r of n){let o=T(r.operationId),i=r.requestHeaders?.length?k(o)?`typeof headers.${o}`:`(typeof headers)[${$(o)}]`:"undefined",s=W(r.requestType),a=W(r.responseType),p=nn(r.errors);e.push(`export type ${P(o)}Operation = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${k(o)?`typeof paths.${o}`:`(typeof paths)[${$(o)}]`},`),e.push(` ${s},`),e.push(` ${a},`),e.push(` ${i},`),e.push(` ${p}`),e.push(">;"),e.push("")}}}function nn(e){return!e||!ke(e)?"OperationErrors":`OperationErrors<${tn(e)}>`}function tn(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=$(r),s=Ae(o);return`${i}: ${s}`}).join("; ")} }`}var Pe=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),Ie=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function W(e){if(!e)return"undefined";let n=e.trim();if(n==="undefined")return"undefined";if(Pe.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${W(t[1])}>`:Ie.test(n)?`typeof ${n}`:n}function Ae(e){if(!e)return"unknown";let n=e.trim();if(Pe.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${Ae(t[1])}>`:Ie.test(n)?`typeof ${n}`:n}function rn(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 on(e){return ze(e.schema)}function ze(e){if(!e)return"string";if(e.type==="array")return`Array<${ze(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function xe(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{Je as a,Xn as b};
|
|
11
|
+
//# sourceMappingURL=chunk-VT6THCQU.mjs.map
|
package/dist/cli.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict"; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var
|
|
2
|
+
"use strict"; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkLY3CCZ2Tcjs = require('./chunk-LY3CCZ2T.cjs');var _fs = require('fs'); var i = _interopRequireWildcard(_fs);var _path = require('path'); var n = _interopRequireWildcard(_path);var _url = require('url');async function S(){let t=process.argv.slice(2),e=E(t);if(e.showHelp||!e.configPath&&e.positional.length===0){m(),process.exit(e.showHelp?0:1);return}try{if(e.configPath)await v(e);else{if(e.positional.length!==2){m(),process.exit(1);return}let[s,o]=e.positional;if(!s||!o){m(),process.exit(1);return}await C({inputFile:s,outputFile:o,strictDates:e.strictDates,strictNumeric:e.strictNumeric})}}catch(s){console.error("\u274C Error:",s),process.exit(1)}}function E(t){let e={showHelp:!1,strictDates:!1,strictNumeric:!1,positional:[]};for(let s=0;s<t.length;s+=1){let o=t[s];if(o==="-h"||o==="--help"){e.showHelp=!0;continue}if(o==="--strict-dates"){e.strictDates=!0;continue}if(o==="--strict-numeric"){e.strictNumeric=!0;continue}if(o==="--config"||o==="-c"){let r=t[s+1];if(!r)throw new Error("--config flag requires a file path");e.configPath=r,s+=1;continue}e.positional.push(o)}return e}function m(){console.log("Usage:"),console.log(" zenko <input-file> <output-file> [options]"),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?, types? }] }')}async function v(t){let e=t.configPath,s=n.resolve(e),o=await A(s);N(o);let r=n.dirname(s),f=o.types;for(let c of o.schemas){let g=w(c.input,r),h=w(c.output,r),p=O(f,c.types);await C({inputFile:g,outputFile:h,strictDates:_nullishCoalesce(c.strictDates, () => (t.strictDates)),strictNumeric:_nullishCoalesce(c.strictNumeric, () => (t.strictNumeric)),typesConfig:p,operationIds:c.operationIds,openEnums:c.openEnums})}}async function A(t){let e=n.extname(t).toLowerCase();if(e===".json"){let r=i.readFileSync(t,"utf8");return JSON.parse(r)}if(e===".yaml"||e===".yml"){let r=i.readFileSync(t,"utf8");return Bun.YAML.parse(r)}let o=await Promise.resolve().then(() => _interopRequireWildcard(require(_url.pathToFileURL.call(void 0, t).href)));return _nullishCoalesce(_nullishCoalesce(o.default, () => (o.config)), () => (o))}function N(t){if(!t||typeof t!="object")throw new Error("Config file must export an object");if(!Array.isArray(t.schemas))throw new Error("Config file must contain a 'schemas' array");for(let e of t.schemas){if(!e||typeof e!="object")throw new Error("Each schema entry must be an object");if(typeof e.input!="string"||typeof e.output!="string")throw new Error("Each schema entry requires 'input' and 'output' paths")}}function w(t,e){return n.isAbsolute(t)?t:n.join(e,t)}function O(t,e){if(!(!t&&!e))return{...t,...e}}async function C(t){let{inputFile:e,outputFile:s,strictDates:o,strictNumeric:r,typesConfig:f,operationIds:c,openEnums:g}=t,h=n.resolve(e),p=n.resolve(s),l=P(h),a=_chunkLY3CCZ2Tcjs.a.call(void 0, l,{strictDates:o,strictNumeric:r,types:f,operationIds:c,openEnums:g});if(i.mkdirSync(n.dirname(p),{recursive:!0}),i.writeFileSync(p,a.output),console.log(`\u2705 Generated TypeScript types in ${p}`),console.log(`\u{1F4C4} Processed ${Object.keys(l.paths||{}).length} paths`),l.webhooks&&console.log(`\u{1FA9D} Processed ${Object.keys(l.webhooks).length} webhooks`),a.helperFile){let u=n.isAbsolute(a.helperFile.path)?a.helperFile.path:n.resolve(n.dirname(p),a.helperFile.path),y=n.resolve(p),b=n.resolve(u);if(y===b){console.warn(`\u26A0\uFE0F Skipping helper file generation: would overwrite main output at ${y}`);return}i.mkdirSync(n.dirname(u),{recursive:!0}),i.writeFileSync(u,a.helperFile.content,{encoding:"utf8"}),console.log(`\u{1F4E6} Generated helper types in ${u}`)}}function P(t){if(!i.existsSync(t))throw new Error(`Input file not found: ${t}`);let e=i.readFileSync(t,"utf8");return t.endsWith(".yaml")||t.endsWith(".yml")?Bun.YAML.parse(e):JSON.parse(e)}S().catch(t=>{console.error("\u274C Error:",t),process.exit(1)});
|
|
3
3
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
2
|
+
import{a as d}from"./chunk-VT6THCQU.mjs";import*as i from"fs";import*as n from"path";import{pathToFileURL as F}from"url";async function S(){let t=process.argv.slice(2),e=E(t);if(e.showHelp||!e.configPath&&e.positional.length===0){m(),process.exit(e.showHelp?0:1);return}try{if(e.configPath)await v(e);else{if(e.positional.length!==2){m(),process.exit(1);return}let[s,o]=e.positional;if(!s||!o){m(),process.exit(1);return}await C({inputFile:s,outputFile:o,strictDates:e.strictDates,strictNumeric:e.strictNumeric})}}catch(s){console.error("\u274C Error:",s),process.exit(1)}}function E(t){let e={showHelp:!1,strictDates:!1,strictNumeric:!1,positional:[]};for(let s=0;s<t.length;s+=1){let o=t[s];if(o==="-h"||o==="--help"){e.showHelp=!0;continue}if(o==="--strict-dates"){e.strictDates=!0;continue}if(o==="--strict-numeric"){e.strictNumeric=!0;continue}if(o==="--config"||o==="-c"){let r=t[s+1];if(!r)throw new Error("--config flag requires a file path");e.configPath=r,s+=1;continue}e.positional.push(o)}return e}function m(){console.log("Usage:"),console.log(" zenko <input-file> <output-file> [options]"),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?, types? }] }')}async function v(t){let e=t.configPath,s=n.resolve(e),o=await A(s);N(o);let r=n.dirname(s),f=o.types;for(let c of o.schemas){let g=w(c.input,r),h=w(c.output,r),p=O(f,c.types);await C({inputFile:g,outputFile:h,strictDates:c.strictDates??t.strictDates,strictNumeric:c.strictNumeric??t.strictNumeric,typesConfig:p,operationIds:c.operationIds,openEnums:c.openEnums})}}async function A(t){let e=n.extname(t).toLowerCase();if(e===".json"){let r=i.readFileSync(t,"utf8");return JSON.parse(r)}if(e===".yaml"||e===".yml"){let r=i.readFileSync(t,"utf8");return Bun.YAML.parse(r)}let o=await import(F(t).href);return o.default??o.config??o}function N(t){if(!t||typeof t!="object")throw new Error("Config file must export an object");if(!Array.isArray(t.schemas))throw new Error("Config file must contain a 'schemas' array");for(let e of t.schemas){if(!e||typeof e!="object")throw new Error("Each schema entry must be an object");if(typeof e.input!="string"||typeof e.output!="string")throw new Error("Each schema entry requires 'input' and 'output' paths")}}function w(t,e){return n.isAbsolute(t)?t:n.join(e,t)}function O(t,e){if(!(!t&&!e))return{...t,...e}}async function C(t){let{inputFile:e,outputFile:s,strictDates:o,strictNumeric:r,typesConfig:f,operationIds:c,openEnums:g}=t,h=n.resolve(e),p=n.resolve(s),l=P(h),a=d(l,{strictDates:o,strictNumeric:r,types:f,operationIds:c,openEnums:g});if(i.mkdirSync(n.dirname(p),{recursive:!0}),i.writeFileSync(p,a.output),console.log(`\u2705 Generated TypeScript types in ${p}`),console.log(`\u{1F4C4} Processed ${Object.keys(l.paths||{}).length} paths`),l.webhooks&&console.log(`\u{1FA9D} Processed ${Object.keys(l.webhooks).length} webhooks`),a.helperFile){let u=n.isAbsolute(a.helperFile.path)?a.helperFile.path:n.resolve(n.dirname(p),a.helperFile.path),y=n.resolve(p),b=n.resolve(u);if(y===b){console.warn(`\u26A0\uFE0F Skipping helper file generation: would overwrite main output at ${y}`);return}i.mkdirSync(n.dirname(u),{recursive:!0}),i.writeFileSync(u,a.helperFile.content,{encoding:"utf8"}),console.log(`\u{1F4E6} Generated helper types in ${u}`)}}function P(t){if(!i.existsSync(t))throw new Error(`Input file not found: ${t}`);let e=i.readFileSync(t,"utf8");return t.endsWith(".yaml")||t.endsWith(".yml")?Bun.YAML.parse(e):JSON.parse(e)}S().catch(t=>{console.error("\u274C Error:",t),process.exit(1)});
|
|
3
3
|
//# sourceMappingURL=cli.mjs.map
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkLY3CCZ2Tcjs = require('./chunk-LY3CCZ2T.cjs');exports.generate = _chunkLY3CCZ2Tcjs.b;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -16,11 +16,16 @@ type TypesConfig = {
|
|
|
16
16
|
treeShake?: boolean;
|
|
17
17
|
optionalType?: "optional" | "nullable" | "nullish";
|
|
18
18
|
};
|
|
19
|
+
type EnumConfig = {
|
|
20
|
+
open?: boolean | string[];
|
|
21
|
+
unknownPrefix?: string;
|
|
22
|
+
};
|
|
19
23
|
type GenerateOptions = {
|
|
20
24
|
strictDates?: boolean;
|
|
21
25
|
strictNumeric?: boolean;
|
|
22
26
|
types?: TypesConfig;
|
|
23
27
|
operationIds?: string[];
|
|
28
|
+
openEnums?: boolean | string[] | EnumConfig;
|
|
24
29
|
};
|
|
25
30
|
/**
|
|
26
31
|
* Generates TypeScript client code from an OpenAPI specification.
|
package/dist/index.d.ts
CHANGED
|
@@ -16,11 +16,16 @@ type TypesConfig = {
|
|
|
16
16
|
treeShake?: boolean;
|
|
17
17
|
optionalType?: "optional" | "nullable" | "nullish";
|
|
18
18
|
};
|
|
19
|
+
type EnumConfig = {
|
|
20
|
+
open?: boolean | string[];
|
|
21
|
+
unknownPrefix?: string;
|
|
22
|
+
};
|
|
19
23
|
type GenerateOptions = {
|
|
20
24
|
strictDates?: boolean;
|
|
21
25
|
strictNumeric?: boolean;
|
|
22
26
|
types?: TypesConfig;
|
|
23
27
|
operationIds?: string[];
|
|
28
|
+
openEnums?: boolean | string[] | EnumConfig;
|
|
24
29
|
};
|
|
25
30
|
/**
|
|
26
31
|
* Generates TypeScript client code from an OpenAPI specification.
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as e}from"./chunk-
|
|
1
|
+
import{b as e}from"./chunk-VT6THCQU.mjs";export{e as generate};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/package.json
CHANGED
|
@@ -1,61 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zenko",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.15",
|
|
4
4
|
"description": "Generate TypeScript types and path functions from OpenAPI specs",
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
"keywords": [
|
|
6
|
+
"api",
|
|
7
|
+
"codegen",
|
|
8
|
+
"generator",
|
|
9
|
+
"openapi",
|
|
10
|
+
"swagger",
|
|
11
|
+
"typescript",
|
|
12
|
+
"zod"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/RawToast/zenko#readme",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/RawToast/zenko/issues"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"author": "RawToast",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "https://github.com/RawToast/zenko.git"
|
|
23
|
+
},
|
|
9
24
|
"bin": {
|
|
10
25
|
"zenko": "dist/cli.cjs"
|
|
11
26
|
},
|
|
12
27
|
"files": [
|
|
28
|
+
"LICENSE",
|
|
29
|
+
"README.md",
|
|
13
30
|
"dist/**/*.cjs",
|
|
14
|
-
"dist/**/*.mjs",
|
|
15
|
-
"dist/**/*.d.ts",
|
|
16
31
|
"dist/**/*.d.cts",
|
|
17
|
-
"
|
|
18
|
-
"
|
|
32
|
+
"dist/**/*.d.ts",
|
|
33
|
+
"dist/**/*.mjs"
|
|
19
34
|
],
|
|
35
|
+
"type": "module",
|
|
36
|
+
"main": "dist/index.cjs",
|
|
37
|
+
"module": "dist/index.mjs",
|
|
38
|
+
"types": "dist/index.d.ts",
|
|
20
39
|
"exports": {
|
|
21
40
|
".": {
|
|
22
|
-
"bun": "./src/zenko.ts",
|
|
23
41
|
"types": "./dist/index.d.ts",
|
|
42
|
+
"bun": "./src/zenko.ts",
|
|
24
43
|
"import": "./dist/index.mjs",
|
|
25
44
|
"require": "./dist/index.cjs"
|
|
26
45
|
},
|
|
27
46
|
"./types": {
|
|
28
|
-
"bun": "./src/types.ts",
|
|
29
47
|
"types": "./dist/types.d.ts",
|
|
48
|
+
"bun": "./src/types.ts",
|
|
30
49
|
"import": "./dist/types.mjs",
|
|
31
50
|
"require": "./dist/types.cjs"
|
|
32
51
|
}
|
|
33
52
|
},
|
|
34
|
-
"repository": {
|
|
35
|
-
"type": "git",
|
|
36
|
-
"url": "https://github.com/RawToast/zenko.git"
|
|
37
|
-
},
|
|
38
|
-
"author": "RawToast",
|
|
39
|
-
"license": "MIT",
|
|
40
|
-
"keywords": [
|
|
41
|
-
"openapi",
|
|
42
|
-
"typescript",
|
|
43
|
-
"codegen",
|
|
44
|
-
"api",
|
|
45
|
-
"generator",
|
|
46
|
-
"swagger",
|
|
47
|
-
"zod"
|
|
48
|
-
],
|
|
49
|
-
"homepage": "https://github.com/RawToast/zenko#readme",
|
|
50
|
-
"engines": {
|
|
51
|
-
"bun": ">=1.2.22"
|
|
52
|
-
},
|
|
53
53
|
"publishConfig": {
|
|
54
54
|
"access": "public"
|
|
55
55
|
},
|
|
56
|
-
"bugs": {
|
|
57
|
-
"url": "https://github.com/RawToast/zenko/issues"
|
|
58
|
-
},
|
|
59
56
|
"scripts": {
|
|
60
57
|
"build": "tsup",
|
|
61
58
|
"build:watch": "tsup --watch",
|
|
@@ -64,10 +61,11 @@
|
|
|
64
61
|
"prepublishOnly": "bun run build",
|
|
65
62
|
"check-types": "tsc --noEmit"
|
|
66
63
|
},
|
|
64
|
+
"dependencies": {},
|
|
67
65
|
"devDependencies": {
|
|
68
66
|
"@types/bun": "1.3.2",
|
|
69
|
-
"
|
|
70
|
-
"
|
|
67
|
+
"tsup": "8.5.1",
|
|
68
|
+
"typescript": "5.9.3"
|
|
71
69
|
},
|
|
72
70
|
"peerDependencies": {
|
|
73
71
|
"typescript": "^5"
|
|
@@ -77,5 +75,7 @@
|
|
|
77
75
|
"optional": true
|
|
78
76
|
}
|
|
79
77
|
},
|
|
80
|
-
"
|
|
78
|
+
"engines": {
|
|
79
|
+
"bun": ">=1.2.22"
|
|
80
|
+
}
|
|
81
81
|
}
|
package/dist/chunk-7VP5JZCL.cjs
DELETED
|
@@ -1,8 +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 L(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],u=P(s);for(let a of u)e[a]&&o(a);t.delete(i),n.add(i),r.push(i)};for(let i of Object.keys(e))o(i);return r}function P(e){let n=[],t=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=g(r.$ref);n.push(o);return}Array.isArray(r)?r.forEach(t):Object.values(r).forEach(t)}};return t(e),[...new Set(n)]}function g(e){return e.split("/").pop()||"Unknown"}function I(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 y(e){return I(e)?e:`"${e}"`}function $(e){return e.replace(/-([a-zA-Z])/g,(n,t)=>t.toUpperCase()).replace(/-+$/,"")}function w(e){return e.charAt(0).toUpperCase()+e.slice(1)}function M(e){let n={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(n.usesOperationDefinition=!0);for(let t of e)t.errors&&U(t.errors)&&(n.usesOperationErrors=!0);return e.length>0&&!n.usesOperationErrors&&e.some(r=>!r.errors||!U(r.errors))&&(n.usesOperationErrors=!0),n}function H(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 U(e){return!!(e&&Object.keys(e).length>0)}var q={"application/json":"unknown","text/csv":"string","text/plain":"string","application/octet-stream":"unknown","application/pdf":"unknown"};function z(e){let n=Object.keys(e);if(n.includes("application/json"))return"application/json";for(let t of n)if(t in q)return t;return n[0]||""}function E(e,n){if(e){if(e.$ref){let t=g(e.$ref),r=_optionalChain([n, 'access', _2 => _2.components, 'optionalAccess', _3 => _3.parameters, 'optionalAccess', _4 => _4[t]]);if(!r)return;let{$ref:o,...i}=e;return{...r,...i}}return e}}function Q(e,n){let t=new Set,r=new Map;for(let[,s]of Object.entries(n.paths||{}))for(let[,u]of Object.entries(s)){let a=u;a.operationId&&r.set(a.operationId,a)}for(let[,s]of Object.entries(n.webhooks||{}))for(let[,u]of Object.entries(s)){let a=u;a.operationId&&r.set(a.operationId,a)}for(let s of e){let u=r.get(s.operationId);if(!u)continue;let a=_optionalChain([u, 'access', _5 => _5.requestBody, 'optionalAccess', _6 => _6.content, 'optionalAccess', _7 => _7["application/json"], 'optionalAccess', _8 => _8.schema]);if(_optionalChain([a, 'optionalAccess', _9 => _9.$ref])){let f=g(a.$ref);t.add(f)}else if(a){let f=P(a);for(let p of f)_optionalChain([n, 'access', _10 => _10.components, 'optionalAccess', _11 => _11.schemas, 'optionalAccess', _12 => _12[p]])&&t.add(p)}let l=u.responses||{};for(let[,f]of Object.entries(l)){let p=_optionalChain([f, 'optionalAccess', _13 => _13.content]);if(!p)continue;let c=z(p),h=_optionalChain([p, 'access', _14 => _14[c], 'optionalAccess', _15 => _15.schema]);if(_optionalChain([h, 'optionalAccess', _16 => _16.$ref])){let O=g(h.$ref);t.add(O)}else if(h){let O=P(h);for(let T of O)_optionalChain([n, 'access', _17 => _17.components, 'optionalAccess', _18 => _18.schemas, 'optionalAccess', _19 => _19[T]])&&t.add(T)}}for(let f of s.queryParams){if(_optionalChain([f, 'access', _20 => _20.schema, 'optionalAccess', _21 => _21.$ref])){let p=g(f.schema.$ref);t.add(p)}if(_optionalChain([f, 'access', _22 => _22.schema, 'optionalAccess', _23 => _23.items, 'optionalAccess', _24 => _24.$ref])){let p=g(f.schema.items.$ref);t.add(p)}}for(let f of s.requestHeaders||[]){if(_optionalChain([f, 'access', _25 => _25.schema, 'optionalAccess', _26 => _26.$ref])){let p=g(f.schema.$ref);t.add(p)}if(_optionalChain([f, 'access', _27 => _27.schema, 'optionalAccess', _28 => _28.items, 'optionalAccess', _29 => _29.$ref])){let p=g(f.schema.items.$ref);t.add(p)}}let m=u.parameters||[];for(let f of m){let p=E(f,n);if(_optionalChain([p, 'optionalAccess', _30 => _30.schema, 'optionalAccess', _31 => _31.$ref])){let c=g(p.schema.$ref);t.add(c)}if(_optionalChain([p, 'optionalAccess', _32 => _32.schema, 'optionalAccess', _33 => _33.items, 'optionalAccess', _34 => _34.$ref])){let c=g(p.schema.items.$ref);t.add(c)}}}let o=new Set,i=Array.from(t);for(;i.length>0;){let s=i.pop();if(o.has(s))continue;o.add(s);let u=_optionalChain([n, 'access', _35 => _35.components, 'optionalAccess', _36 => _36.schemas, 'optionalAccess', _37 => _37[s]]);if(!u)continue;let a=P(u);for(let l of a)_optionalChain([n, 'access', _38 => _38.components, 'optionalAccess', _39 => _39.schemas, 'optionalAccess', _40 => _40[l]])&&!o.has(l)&&(t.add(l),i.push(l))}return t}function C(e,n){switch(n){case"optional":return`${e}.optional()`;case"nullable":return`${e}.nullable()`;case"nullish":return`${e}.nullish()`}}function k(e,n,t,r,o){if(t.has(e))return"";if(t.add(e),n.enum){let i=n.enum.map(s=>`"${s}"`).join(", ");return`export const ${e} = z.enum([${i}]);`}if(n.allOf&&Array.isArray(n.allOf)){let i=n.allOf.map(a=>R(a,r,o));if(i.length===0)return`export const ${e} = z.object({});`;if(i.length===1)return`export const ${e} = ${i[0]};`;let s=i[0],u=i.slice(1).map(a=>`.and(${a})`).join("");return`export const ${e} = ${s}${u};`}if(n.type==="object"||n.properties)return`export const ${e} = ${V(n,r,o)};`;if(n.type==="array"){let i=_nullishCoalesce(n.items, () => ({type:"unknown"})),s=R(i,r,o),u=Se(n,`z.array(${s})`,i,r.strictNumeric);return`export const ${e} = ${u};`}return`export const ${e} = ${R(n,r,o)};`}function R(e,n,t){if(e.$ref){let r=g(e.$ref);return _optionalChain([t, 'optionalAccess', _41 => _41.get, 'call', _42 => _42(r)])||r}if(e.enum)return`z.enum([${e.enum.map(o=>`"${o}"`).join(", ")}])`;if(e.allOf&&Array.isArray(e.allOf)){let r=e.allOf.map(s=>R(s,n,t));if(r.length===0)return"z.object({})";if(r.length===1)return r[0];let o=r[0],i=r.slice(1).map(s=>`.and(${s})`).join("");return`${o}${i}`}if(e.type==="object"||e.properties||e.allOf||e.oneOf||e.anyOf)return V(e,n,t);switch(e.type){case"string":return $e(e,n);case"boolean":return"z.boolean()";case"array":return`z.array(${R(_nullishCoalesce(e.items, () => ({type:"unknown"})),n,t)})`;case"null":return"z.null()";case"number":return W(e,n);case"integer":return Te(e,n);default:return"z.unknown()"}}function V(e,n,t){let r=[];for(let[o,i]of Object.entries(e.properties||{})){let s=_nullishCoalesce(_optionalChain([e, 'access', _43 => _43.required, 'optionalAccess', _44 => _44.includes, 'call', _45 => _45(o)]), () => (!1)),u=R(i,n,t),a=C(u,n.optionalType),l=n.optionalType!=="nullable"?Oe(a,i):a,m=s?u:l;r.push(` ${y(o)}: ${m},`)}return r.length===0?"z.object({})":`z.object({
|
|
2
|
-
${r.join(`
|
|
3
|
-
`)}
|
|
4
|
-
})`}function $e(e,n){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(n.strictDates)switch(e.format){case"date-time":return"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let t="z.string()";switch(n.strictNumeric&&(typeof e.minLength=="number"&&(t+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(t+=`.max(${e.maxLength})`),e.pattern&&(t+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${t}.uuid()`;case"email":return`${t}.email()`;case"uri":case"url":return`${t}.url()`;case"ipv4":return`${t}.ip({ version: "v4" })`;case"ipv6":return`${t}.ip({ version: "v6" })`;default:return t}}function Oe(e,n){return!n||n.default===void 0?e:`${e}.default(${JSON.stringify(n.default)})`}function W(e,n){let t="z.number()";return n.strictNumeric&&(t=Ie(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 Te(e,n){let t=W(e,n);return t+=".int()",t}function Se(e,n,t,r){return r&&(typeof e.minItems=="number"&&(n+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(n+=`.max(${e.maxItems})`),e.uniqueItems&&xe(t)&&(n+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),n}function xe(e){return _optionalChain([e, 'optionalAccess', _46 => _46.$ref])?!1:new Set(["string","number","integer","boolean"]).has(_optionalChain([e, 'optionalAccess', _47 => _47.type]))}function Ie(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 we={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 J(e){if(e==="default")return"defaultError";let n=e.trim(),t=we[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,u=i+s.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("");return u?/^[a-zA-Z_$]/.test(u)?u:`status${u.charAt(0).toUpperCase()}${u.slice(1)}`:"unknownError"}function v(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 u=i.toLowerCase();if(!re(u)||!s.operationId)continue;let a=K(r),l=X(s,n),{successResponse:m,errors:f}=ee(s,s.operationId,n),p=Y(o,s,e),c=te(p),h=ne(p);t.push({operationId:s.operationId,path:r,method:u,pathParams:a,queryParams:h,requestType:l,responseType:m,requestHeaders:c,errors:f})}if(e.webhooks)for(let[r,o]of Object.entries(e.webhooks))for(let[i,s]of Object.entries(o)){let u=i.toLowerCase();if(!re(u)||!s.operationId)continue;let a=r,l=K(a),m=X(s,n),{successResponse:f,errors:p}=ee(s,s.operationId,n),c=Y(o,s,e),h=te(c),O=ne(c);t.push({operationId:s.operationId,path:a,method:u,pathParams:l,queryParams:O,requestType:m,responseType:f,requestHeaders:h,errors:p})}return t}function Y(e,n,t){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let u=E(s,t);if(!u)continue;let a=`${u.in}:${u.name}`;r.set(a,u)}};return o(e.parameters),o(n.parameters),Array.from(r.values())}function K(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 X(e,n){let t=be(e);if(!t)return;if(t.$ref){let o=g(t.$ref);return _optionalChain([n, 'optionalAccess', _48 => _48.get, 'call', _49 => _49(o)])||o}return`${w($(e.operationId))}Request`}function be(e){let n=_optionalChain([e, 'optionalAccess', _50 => _50.requestBody, 'optionalAccess', _51 => _51.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', _52 => _52[r], 'optionalAccess', _53 => _53.schema]);if(o)return o}}function ee(e,n,t){let r=_nullishCoalesce(e.responses, () => ({})),o=new Map,i=[];for(let[a,l]of Object.entries(r)){let m=_optionalChain([l, 'optionalAccess', _54 => _54.content]);if(!m||Object.keys(m).length===0){a==="204"||/^3\d\d$/.test(a)?o.set(a,"undefined"):v(a)&&i.push({code:a,schema:"undefined"});continue}let f=z(m),p=_optionalChain([m, 'access', _55 => _55[f], 'optionalAccess', _56 => _56.schema]);if(!p){let c=ke(f,a);c&&(v(a)?i.push({code:a,schema:c}):/^2\d\d$/.test(a)&&o.set(a,c));continue}if(v(a)){i.push({code:a,schema:p});continue}/^2\d\d$/.test(a)&&o.set(a,p)}let s=Re(o,n,t),u=Pe(i,n,t);return{successResponse:s,errors:u}}function Re(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:F(s,`${w($(n))}Response`,t)}let[,o]=_nullishCoalesce(e.entries().next().value, () => ([]));if(o)return typeof o=="string"?o:F(o,`${w($(n))}Response`,t)}function Pe(e=[],n,t){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=J(o),u=F(i,`${w($(n))}${w(s)}`,t);r[s]=u}return r}function F(e,n,t){if(typeof e=="string")return e;if(e.$ref){let r=g(e.$ref);return _optionalChain([t, 'optionalAccess', _57 => _57.get, 'call', _58 => _58(r)])||r}if(e.type==="array"&&_optionalChain([e, 'access', _59 => _59.items, 'optionalAccess', _60 => _60.$ref])){let r=g(e.items.$ref);return`z.array(${_optionalChain([t, 'optionalAccess', _61 => _61.get, 'call', _62 => _62(r)])||r})`}return e.allOf&&Array.isArray(e.allOf),n}function te(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 ne(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 re(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 q?q[e]:"unknown"}function se(e,n){let t=new Map,r=new Map;for(let[,o]of Object.entries(n.paths||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let[,o]of Object.entries(n.webhooks||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.requestBody;if(s&&s.content){let u=s.content,a=Ae(u);if(!a)continue;let l=`${w($(o.operationId))}Request`;(!a.$ref||a.allOf||a.oneOf||a.anyOf)&&t.set(l,a)}}return t}function Ae(e){let n=["application/json","multipart/form-data","application/x-www-form-urlencoded"];for(let t of n){let r=_optionalChain([e, 'access', _63 => _63[t], 'optionalAccess', _64 => _64.schema]);if(r)return r}}function ie(e,n){let t=new Map,r=new Map;for(let[,o]of Object.entries(n.paths||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let[,o]of Object.entries(n.webhooks||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.responses||{};for(let[u,a]of Object.entries(s))if(/^2\d\d$/.test(u)&&a.content){let m=a.content["application/json"];if(m&&m.schema){let f=m.schema,p=`${w($(o.operationId))}Response`;(!f.$ref||f.allOf||f.oneOf||f.anyOf)&&t.set(p,f)}}}return t}function ae(e,n,t,r,o){let i=se(n,t);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,u]of i){let a=k(s,u,new Set,o,r);e.push(a),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function pe(e,n,t,r,o){let i=ie(n,t);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,u]of i){let a=k(s,u,new Set,o,r);e.push(a),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function ue(){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 OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | 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("}"),e.push(""),e.join(`
|
|
5
|
-
`)}function qe(e,n={}){let t=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,operationIds:s}=n,u=Ee(n.types),a={strictDates:o,strictNumeric:i,optionalType:u.optionalType};t.push('import { z } from "zod";');let l=new Map;if(_optionalChain([e, 'access', _65 => _65.components, 'optionalAccess', _66 => _66.schemas]))for(let p of Object.keys(e.components.schemas))l.set(p,$(p));let m=oe(e,l);if(s&&s.length>0){let p=new Set(s);m=m.filter(c=>p.has(c.operationId))}if(ve(t,u,m),t.push(""),_optionalChain([e, 'access', _67 => _67.components, 'optionalAccess', _68 => _68.schemas])){t.push("// Generated Zod Schemas"),t.push("");let p;if(s&&s.length>0){let h=Q(m,e);p=Array.from(h)}else p=Object.keys(e.components.schemas);let c=L(e.components.schemas).filter(h=>p.includes(h));for(let h of c){let O=e.components.schemas[h],T=l.get(h);t.push(k(T,O,r,a,l)),t.push(""),t.push(`export type ${T} = z.infer<typeof ${T}>;`),t.push("")}}t.push("// Path Functions"),t.push("export const paths = {");for(let p of m){let h=p.pathParams.map(d=>d.name).length>0,O=p.queryParams.length>0,T=$(p.operationId);if(!h&&!O){t.push(` ${y(T)}: () => "${p.path}",`);continue}let b=d=>{if(I(d))return d;let S=$(d);return I(S)||(S=`_${S}`),S},A=[],N=[];for(let d of p.pathParams)A.push(I(d.name)?d.name:`${y(d.name)}: ${b(d.name)}`),N.push(`${y(d.name)}: string`);for(let d of p.queryParams)A.push(I(d.name)?d.name:`${y(d.name)}: ${b(d.name)}`),N.push(`${y(d.name)}${d.required?"":"?"}: ${Ce(d)}`);let ge=!h&&O&&p.queryParams.every(d=>!d.required),D=`${A.length?`{ ${A.join(", ")} }`:"{}"}: { ${N.join(", ")} }${ge?" = {}":""}`,Z=p.path.replace(/{([^}]+)}/g,(d,S)=>`\${${b(S)}}`);if(!O){t.push(` ${y(T)}: (${D}) => \`${Z}\`,`);continue}t.push(` ${y(T)}: (${D}) => {`),t.push(" const params = new URLSearchParams()");for(let d of p.queryParams){let S=I(d.name)?d.name:b($(d.name)),j=_nullishCoalesce(d.schema, () => ({}));if(_optionalChain([j, 'optionalAccess', _69 => _69.type])==="array"){let _=fe(_nullishCoalesce(j.items, () => ({})),"value");d.required?(t.push(` for (const value of ${S}) {`),t.push(` params.append("${d.name}", ${_})`),t.push(" }")):(t.push(` if (${S} !== undefined) {`),t.push(` for (const value of ${S}) {`),t.push(` params.append("${d.name}", ${_})`),t.push(" }"),t.push(" }"));continue}let B=fe(j,S);d.required?t.push(` params.set("${d.name}", ${B})`):(t.push(` if (${S} !== undefined) {`),t.push(` params.set("${d.name}", ${B})`),t.push(" }"))}t.push(" const _searchParams = params.toString()"),t.push(` return \`${Z}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),t.push(" },")}t.push("} as const;"),t.push(""),t.push("// Header Schemas"),t.push("export const headerSchemas = {");for(let p of m){let c=$(p.operationId);if(!p.requestHeaders||p.requestHeaders.length===0){t.push(` ${y(c)}: z.object({}),`);continue}let h=p.requestHeaders.map(O=>{let T=He(O),b=O.required?T:C(T,a.optionalType);return` ${y(O.name)}: ${b},`}).join(`
|
|
6
|
-
`);t.push(` ${y(c)}: z.object({`),t.push(h),t.push(" }),")}t.push("} as const;"),t.push(""),t.push("// Header Functions"),t.push("export const headers = {");for(let p of m){let c=$(p.operationId);if(!p.requestHeaders||p.requestHeaders.length===0){t.push(` ${y(c)}: () => ${I(c)?`headerSchemas.${c}`:`headerSchemas[${y(c)}]`}.parse({}),`);continue}t.push(` ${y(c)}: (params: z.input<${I(c)?`typeof headerSchemas.${c}`:`(typeof headerSchemas)[${y(c)}]`}>) => {`),t.push(` return ${I(c)?`headerSchemas.${c}`:`headerSchemas[${y(c)}]`}.parse(params)`),t.push(" },")}t.push("} as const;"),t.push(""),ae(t,m,e,l,a),pe(t,m,e,l,a),Ne(t,m,u),t.push("// Operation Objects");for(let p of m){let c=$(p.operationId),h=u.emit?`: ${w(c)}Operation`:"";t.push(`export const ${c}${h} = {`),t.push(` method: "${p.method}",`),t.push(` path: paths.${c},`),ce(t,"request",p.requestType),ce(t,"response",p.responseType),p.requestHeaders&&p.requestHeaders.length>0&&t.push(` headers: headers.${c},`),p.errors&&de(p.errors)&&ze(t,"errors",p.errors),t.push("} as const;"),t.push("")}let f={output:t.join(`
|
|
7
|
-
`)};return u.emit&&u.helpers==="file"&&u.helpersOutput&&(f.helperFile={path:u.helpersOutput,content:ue()}),f}function zt(e,n={}){return qe(e,n).output}function ce(e,n,t){t&&e.push(` ${n}: ${t},`)}function ze(e,n,t){if(!(!t||Object.keys(t).length===0)){e.push(` ${n}: {`);for(let[r,o]of Object.entries(t))e.push(` ${y(r)}: ${o},`);e.push(" },")}}function de(e){return!!(e&&Object.keys(e).length>0)}function Ee(e){return{emit:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _70 => _70.emit]), () => (!0)),helpers:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _71 => _71.helpers]), () => ("package")),helpersOutput:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _72 => _72.helpersOutput]), () => ("./zenko-types")),treeShake:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _73 => _73.treeShake]), () => (!0)),optionalType:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _74 => _74.optionalType]), () => ("optional"))}}function ve(e,n,t){if(n.emit)switch(n.helpers){case"package":if(n.treeShake){let r=M(t),o=H(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=M(t),o=H(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 OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | 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("}"),e.push("")}}function Ne(e,n,t){if(t.emit){e.push("// Operation Types");for(let r of n){let o=$(r.operationId),i=_optionalChain([r, 'access', _75 => _75.requestHeaders, 'optionalAccess', _76 => _76.length])?I(o)?`typeof headers.${o}`:`(typeof headers)[${y(o)}]`:"undefined",s=G(r.requestType),u=G(r.responseType),a=je(r.errors);e.push(`export type ${w(o)}Operation = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${I(o)?`typeof paths.${o}`:`(typeof paths)[${y(o)}]`},`),e.push(` ${s},`),e.push(` ${u},`),e.push(` ${i},`),e.push(` ${a}`),e.push(">;"),e.push("")}}}function je(e){return!e||!de(e)?"OperationErrors":`OperationErrors<${Me(e)}>`}function Me(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=y(r),s=he(o);return`${i}: ${s}`}).join("; ")} }`}var me=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),le=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function G(e){if(!e)return"undefined";let n=e.trim();if(n==="undefined")return"undefined";if(me.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${G(t[1])}>`:le.test(n)?`typeof ${n}`:n}function he(e){if(!e)return"unknown";let n=e.trim();if(me.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${he(t[1])}>`:le.test(n)?`typeof ${n}`:n}function He(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 Ce(e){return ye(e.schema)}function ye(e){if(!e)return"string";if(e.type==="array")return`Array<${ye(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function fe(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 = qe; exports.b = zt;
|
|
8
|
-
//# sourceMappingURL=chunk-7VP5JZCL.cjs.map
|
package/dist/chunk-NZMYX32P.mjs
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
function U(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],u=k(s);for(let a of u)e[a]&&o(a);t.delete(i),n.add(i),r.push(i)};for(let i of Object.keys(e))o(i);return r}function k(e){let n=[],t=r=>{if(!(typeof r!="object"||r===null)){if(r.$ref&&typeof r.$ref=="string"){let o=g(r.$ref);n.push(o);return}Array.isArray(r)?r.forEach(t):Object.values(r).forEach(t)}};return t(e),[...new Set(n)]}function g(e){return e.split("/").pop()||"Unknown"}function w(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 y(e){return w(e)?e:`"${e}"`}function $(e){return e.replace(/-([a-zA-Z])/g,(n,t)=>t.toUpperCase()).replace(/-+$/,"")}function b(e){return e.charAt(0).toUpperCase()+e.slice(1)}function H(e){let n={usesHeaderFn:!1,usesOperationDefinition:!1,usesOperationErrors:!1};e.length>0&&(n.usesOperationDefinition=!0);for(let t of e)t.errors&&Q(t.errors)&&(n.usesOperationErrors=!0);return e.length>0&&!n.usesOperationErrors&&e.some(r=>!r.errors||!Q(r.errors))&&(n.usesOperationErrors=!0),n}function C(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 Q(e){return!!(e&&Object.keys(e).length>0)}var z={"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 z)return t;return n[0]||""}function v(e,n){if(e){if(e.$ref){let t=g(e.$ref),r=n.components?.parameters?.[t];if(!r)return;let{$ref:o,...i}=e;return{...r,...i}}return e}}function V(e,n){let t=new Set,r=new Map;for(let[,s]of Object.entries(n.paths||{}))for(let[,u]of Object.entries(s)){let a=u;a.operationId&&r.set(a.operationId,a)}for(let[,s]of Object.entries(n.webhooks||{}))for(let[,u]of Object.entries(s)){let a=u;a.operationId&&r.set(a.operationId,a)}for(let s of e){let u=r.get(s.operationId);if(!u)continue;let a=u.requestBody?.content?.["application/json"]?.schema;if(a?.$ref){let f=g(a.$ref);t.add(f)}else if(a){let f=k(a);for(let p of f)n.components?.schemas?.[p]&&t.add(p)}let l=u.responses||{};for(let[,f]of Object.entries(l)){let p=f?.content;if(!p)continue;let c=E(p),h=p[c]?.schema;if(h?.$ref){let O=g(h.$ref);t.add(O)}else if(h){let O=k(h);for(let T of O)n.components?.schemas?.[T]&&t.add(T)}}for(let f of s.queryParams){if(f.schema?.$ref){let p=g(f.schema.$ref);t.add(p)}if(f.schema?.items?.$ref){let p=g(f.schema.items.$ref);t.add(p)}}for(let f of s.requestHeaders||[]){if(f.schema?.$ref){let p=g(f.schema.$ref);t.add(p)}if(f.schema?.items?.$ref){let p=g(f.schema.items.$ref);t.add(p)}}let m=u.parameters||[];for(let f of m){let p=v(f,n);if(p?.schema?.$ref){let c=g(p.schema.$ref);t.add(c)}if(p?.schema?.items?.$ref){let c=g(p.schema.items.$ref);t.add(c)}}}let o=new Set,i=Array.from(t);for(;i.length>0;){let s=i.pop();if(o.has(s))continue;o.add(s);let u=n.components?.schemas?.[s];if(!u)continue;let a=k(u);for(let l of a)n.components?.schemas?.[l]&&!o.has(l)&&(t.add(l),i.push(l))}return t}function F(e,n){switch(n){case"optional":return`${e}.optional()`;case"nullable":return`${e}.nullable()`;case"nullish":return`${e}.nullish()`}}function A(e,n,t,r,o){if(t.has(e))return"";if(t.add(e),n.enum){let i=n.enum.map(s=>`"${s}"`).join(", ");return`export const ${e} = z.enum([${i}]);`}if(n.allOf&&Array.isArray(n.allOf)){let i=n.allOf.map(a=>P(a,r,o));if(i.length===0)return`export const ${e} = z.object({});`;if(i.length===1)return`export const ${e} = ${i[0]};`;let s=i[0],u=i.slice(1).map(a=>`.and(${a})`).join("");return`export const ${e} = ${s}${u};`}if(n.type==="object"||n.properties)return`export const ${e} = ${W(n,r,o)};`;if(n.type==="array"){let i=n.items??{type:"unknown"},s=P(i,r,o),u=xe(n,`z.array(${s})`,i,r.strictNumeric);return`export const ${e} = ${u};`}return`export const ${e} = ${P(n,r,o)};`}function P(e,n,t){if(e.$ref){let r=g(e.$ref);return t?.get(r)||r}if(e.enum)return`z.enum([${e.enum.map(o=>`"${o}"`).join(", ")}])`;if(e.allOf&&Array.isArray(e.allOf)){let r=e.allOf.map(s=>P(s,n,t));if(r.length===0)return"z.object({})";if(r.length===1)return r[0];let o=r[0],i=r.slice(1).map(s=>`.and(${s})`).join("");return`${o}${i}`}if(e.type==="object"||e.properties||e.allOf||e.oneOf||e.anyOf)return W(e,n,t);switch(e.type){case"string":return Oe(e,n);case"boolean":return"z.boolean()";case"array":return`z.array(${P(e.items??{type:"unknown"},n,t)})`;case"null":return"z.null()";case"number":return J(e,n);case"integer":return Se(e,n);default:return"z.unknown()"}}function W(e,n,t){let r=[];for(let[o,i]of Object.entries(e.properties||{})){let s=e.required?.includes(o)??!1,u=P(i,n,t),a=F(u,n.optionalType),l=n.optionalType!=="nullable"?Te(a,i):a,m=s?u:l;r.push(` ${y(o)}: ${m},`)}return r.length===0?"z.object({})":`z.object({
|
|
2
|
-
${r.join(`
|
|
3
|
-
`)}
|
|
4
|
-
})`}function Oe(e,n){if(e.format==="binary")return'(typeof Blob === "undefined" ? z.unknown() : z.instanceof(Blob))';if(n.strictDates)switch(e.format){case"date-time":return"z.string().datetime()";case"date":return"z.string().date()";case"time":return"z.string().time()";case"duration":return"z.string().duration()"}let t="z.string()";switch(n.strictNumeric&&(typeof e.minLength=="number"&&(t+=`.min(${e.minLength})`),typeof e.maxLength=="number"&&(t+=`.max(${e.maxLength})`),e.pattern&&(t+=`.regex(new RegExp(${JSON.stringify(e.pattern)}))`)),e.format){case"uuid":return`${t}.uuid()`;case"email":return`${t}.email()`;case"uri":case"url":return`${t}.url()`;case"ipv4":return`${t}.ip({ version: "v4" })`;case"ipv6":return`${t}.ip({ version: "v6" })`;default:return t}}function Te(e,n){return!n||n.default===void 0?e:`${e}.default(${JSON.stringify(n.default)})`}function J(e,n){let t="z.number()";return n.strictNumeric&&(t=we(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 Se(e,n){let t=J(e,n);return t+=".int()",t}function xe(e,n,t,r){return r&&(typeof e.minItems=="number"&&(n+=`.min(${e.minItems})`),typeof e.maxItems=="number"&&(n+=`.max(${e.maxItems})`),e.uniqueItems&&Ie(t)&&(n+='.refine((items) => new Set(items).size === items.length, { message: "Items must be unique" })')),n}function Ie(e){return e?.$ref?!1:new Set(["string","number","integer","boolean"]).has(e?.type)}function we(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 Y(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,u=i+s.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("");return u?/^[a-zA-Z_$]/.test(u)?u:`status${u.charAt(0).toUpperCase()}${u.slice(1)}`:"unknownError"}function N(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 u=i.toLowerCase();if(!oe(u)||!s.operationId)continue;let a=X(r),l=ee(s,n),{successResponse:m,errors:f}=te(s,s.operationId,n),p=K(o,s,e),c=ne(p),h=re(p);t.push({operationId:s.operationId,path:r,method:u,pathParams:a,queryParams:h,requestType:l,responseType:m,requestHeaders:c,errors:f})}if(e.webhooks)for(let[r,o]of Object.entries(e.webhooks))for(let[i,s]of Object.entries(o)){let u=i.toLowerCase();if(!oe(u)||!s.operationId)continue;let a=r,l=X(a),m=ee(s,n),{successResponse:f,errors:p}=te(s,s.operationId,n),c=K(o,s,e),h=ne(c),O=re(c);t.push({operationId:s.operationId,path:a,method:u,pathParams:l,queryParams:O,requestType:m,responseType:f,requestHeaders:h,errors:p})}return t}function K(e,n,t){let r=new Map,o=i=>{if(Array.isArray(i))for(let s of i){let u=v(s,t);if(!u)continue;let a=`${u.in}:${u.name}`;r.set(a,u)}};return o(e.parameters),o(n.parameters),Array.from(r.values())}function X(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 ee(e,n){let t=Re(e);if(!t)return;if(t.$ref){let o=g(t.$ref);return n?.get(o)||o}return`${b($(e.operationId))}Request`}function Re(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 te(e,n,t){let r=e.responses??{},o=new Map,i=[];for(let[a,l]of Object.entries(r)){let m=l?.content;if(!m||Object.keys(m).length===0){a==="204"||/^3\d\d$/.test(a)?o.set(a,"undefined"):N(a)&&i.push({code:a,schema:"undefined"});continue}let f=E(m),p=m[f]?.schema;if(!p){let c=Ae(f,a);c&&(N(a)?i.push({code:a,schema:c}):/^2\d\d$/.test(a)&&o.set(a,c));continue}if(N(a)){i.push({code:a,schema:p});continue}/^2\d\d$/.test(a)&&o.set(a,p)}let s=Pe(o,n,t),u=ke(i,n,t);return{successResponse:s,errors:u}}function Pe(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:G(s,`${b($(n))}Response`,t)}let[,o]=e.entries().next().value??[];if(o)return typeof o=="string"?o:G(o,`${b($(n))}Response`,t)}function ke(e=[],n,t){if(!e.length)return;let r={};for(let{code:o,schema:i}of e){let s=Y(o),u=G(i,`${b($(n))}${b(s)}`,t);r[s]=u}return r}function G(e,n,t){if(typeof e=="string")return e;if(e.$ref){let r=g(e.$ref);return t?.get(r)||r}if(e.type==="array"&&e.items?.$ref){let r=g(e.items.$ref);return`z.array(${t?.get(r)||r})`}return e.allOf&&Array.isArray(e.allOf),n}function ne(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 re(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 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 Ae(e,n){return n==="204"||/^3\d\d$/.test(n)?"undefined":e in z?z[e]:"unknown"}function ie(e,n){let t=new Map,r=new Map;for(let[,o]of Object.entries(n.paths||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let[,o]of Object.entries(n.webhooks||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.requestBody;if(s&&s.content){let u=s.content,a=qe(u);if(!a)continue;let l=`${b($(o.operationId))}Request`;(!a.$ref||a.allOf||a.oneOf||a.anyOf)&&t.set(l,a)}}return t}function qe(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 ae(e,n){let t=new Map,r=new Map;for(let[,o]of Object.entries(n.paths||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let[,o]of Object.entries(n.webhooks||{}))for(let[,i]of Object.entries(o)){let s=i;s.operationId&&r.set(s.operationId,s)}for(let o of e){let i=r.get(o.operationId);if(!i)continue;let s=i.responses||{};for(let[u,a]of Object.entries(s))if(/^2\d\d$/.test(u)&&a.content){let m=a.content["application/json"];if(m&&m.schema){let f=m.schema,p=`${b($(o.operationId))}Response`;(!f.$ref||f.allOf||f.oneOf||f.anyOf)&&t.set(p,f)}}}return t}function pe(e,n,t,r,o){let i=ie(n,t);if(i.size>0){e.push("// Generated Request Types"),e.push("");for(let[s,u]of i){let a=A(s,u,new Set,o,r);e.push(a),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function ue(e,n,t,r,o){let i=ae(n,t);if(i.size>0){e.push("// Generated Response Types"),e.push("");for(let[s,u]of i){let a=A(s,u,new Set,o,r);e.push(a),e.push(""),e.push(`export type ${s} = z.infer<typeof ${s}>;`),e.push("")}}}function ce(){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 OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | 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("}"),e.push(""),e.join(`
|
|
5
|
-
`)}function ze(e,n={}){let t=[],r=new Set,{strictDates:o=!1,strictNumeric:i=!1,operationIds:s}=n,u=ve(n.types),a={strictDates:o,strictNumeric:i,optionalType:u.optionalType};t.push('import { z } from "zod";');let l=new Map;if(e.components?.schemas)for(let p of Object.keys(e.components.schemas))l.set(p,$(p));let m=se(e,l);if(s&&s.length>0){let p=new Set(s);m=m.filter(c=>p.has(c.operationId))}if(Ne(t,u,m),t.push(""),e.components?.schemas){t.push("// Generated Zod Schemas"),t.push("");let p;if(s&&s.length>0){let h=V(m,e);p=Array.from(h)}else p=Object.keys(e.components.schemas);let c=U(e.components.schemas).filter(h=>p.includes(h));for(let h of c){let O=e.components.schemas[h],T=l.get(h);t.push(A(T,O,r,a,l)),t.push(""),t.push(`export type ${T} = z.infer<typeof ${T}>;`),t.push("")}}t.push("// Path Functions"),t.push("export const paths = {");for(let p of m){let h=p.pathParams.map(d=>d.name).length>0,O=p.queryParams.length>0,T=$(p.operationId);if(!h&&!O){t.push(` ${y(T)}: () => "${p.path}",`);continue}let R=d=>{if(w(d))return d;let S=$(d);return w(S)||(S=`_${S}`),S},q=[],j=[];for(let d of p.pathParams)q.push(w(d.name)?d.name:`${y(d.name)}: ${R(d.name)}`),j.push(`${y(d.name)}: string`);for(let d of p.queryParams)q.push(w(d.name)?d.name:`${y(d.name)}: ${R(d.name)}`),j.push(`${y(d.name)}${d.required?"":"?"}: ${Fe(d)}`);let $e=!h&&O&&p.queryParams.every(d=>!d.required),Z=`${q.length?`{ ${q.join(", ")} }`:"{}"}: { ${j.join(", ")} }${$e?" = {}":""}`,B=p.path.replace(/{([^}]+)}/g,(d,S)=>`\${${R(S)}}`);if(!O){t.push(` ${y(T)}: (${Z}) => \`${B}\`,`);continue}t.push(` ${y(T)}: (${Z}) => {`),t.push(" const params = new URLSearchParams()");for(let d of p.queryParams){let S=w(d.name)?d.name:R($(d.name)),M=d.schema??{};if(M?.type==="array"){let L=de(M.items??{},"value");d.required?(t.push(` for (const value of ${S}) {`),t.push(` params.append("${d.name}", ${L})`),t.push(" }")):(t.push(` if (${S} !== undefined) {`),t.push(` for (const value of ${S}) {`),t.push(` params.append("${d.name}", ${L})`),t.push(" }"),t.push(" }"));continue}let _=de(M,S);d.required?t.push(` params.set("${d.name}", ${_})`):(t.push(` if (${S} !== undefined) {`),t.push(` params.set("${d.name}", ${_})`),t.push(" }"))}t.push(" const _searchParams = params.toString()"),t.push(` return \`${B}\${_searchParams ? \`?\${_searchParams}\` : ""}\``),t.push(" },")}t.push("} as const;"),t.push(""),t.push("// Header Schemas"),t.push("export const headerSchemas = {");for(let p of m){let c=$(p.operationId);if(!p.requestHeaders||p.requestHeaders.length===0){t.push(` ${y(c)}: z.object({}),`);continue}let h=p.requestHeaders.map(O=>{let T=Ce(O),R=O.required?T:F(T,a.optionalType);return` ${y(O.name)}: ${R},`}).join(`
|
|
6
|
-
`);t.push(` ${y(c)}: z.object({`),t.push(h),t.push(" }),")}t.push("} as const;"),t.push(""),t.push("// Header Functions"),t.push("export const headers = {");for(let p of m){let c=$(p.operationId);if(!p.requestHeaders||p.requestHeaders.length===0){t.push(` ${y(c)}: () => ${w(c)?`headerSchemas.${c}`:`headerSchemas[${y(c)}]`}.parse({}),`);continue}t.push(` ${y(c)}: (params: z.input<${w(c)?`typeof headerSchemas.${c}`:`(typeof headerSchemas)[${y(c)}]`}>) => {`),t.push(` return ${w(c)?`headerSchemas.${c}`:`headerSchemas[${y(c)}]`}.parse(params)`),t.push(" },")}t.push("} as const;"),t.push(""),pe(t,m,e,l,a),ue(t,m,e,l,a),je(t,m,u),t.push("// Operation Objects");for(let p of m){let c=$(p.operationId),h=u.emit?`: ${b(c)}Operation`:"";t.push(`export const ${c}${h} = {`),t.push(` method: "${p.method}",`),t.push(` path: paths.${c},`),fe(t,"request",p.requestType),fe(t,"response",p.responseType),p.requestHeaders&&p.requestHeaders.length>0&&t.push(` headers: headers.${c},`),p.errors&&me(p.errors)&&Ee(t,"errors",p.errors),t.push("} as const;"),t.push("")}let f={output:t.join(`
|
|
7
|
-
`)};return u.emit&&u.helpers==="file"&&u.helpersOutput&&(f.helperFile={path:u.helpersOutput,content:ce()}),f}function Et(e,n={}){return ze(e,n).output}function fe(e,n,t){t&&e.push(` ${n}: ${t},`)}function Ee(e,n,t){if(!(!t||Object.keys(t).length===0)){e.push(` ${n}: {`);for(let[r,o]of Object.entries(t))e.push(` ${y(r)}: ${o},`);e.push(" },")}}function me(e){return!!(e&&Object.keys(e).length>0)}function ve(e){return{emit:e?.emit??!0,helpers:e?.helpers??"package",helpersOutput:e?.helpersOutput??"./zenko-types",treeShake:e?.treeShake??!0,optionalType:e?.optionalType??"optional"}}function Ne(e,n,t){if(n.emit)switch(n.helpers){case"package":if(n.treeShake){let r=H(t),o=C(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=H(t),o=C(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 OperationDefinition<TMethod extends RequestMethod, TPath extends (...args: any[]) => string, TRequest = undefined, TResponse = undefined, THeaders extends AnyHeaderFn | undefined = undefined, TErrors extends OperationErrors | 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("}"),e.push("")}}function je(e,n,t){if(t.emit){e.push("// Operation Types");for(let r of n){let o=$(r.operationId),i=r.requestHeaders?.length?w(o)?`typeof headers.${o}`:`(typeof headers)[${y(o)}]`:"undefined",s=D(r.requestType),u=D(r.responseType),a=Me(r.errors);e.push(`export type ${b(o)}Operation = OperationDefinition<`),e.push(` "${r.method}",`),e.push(` ${w(o)?`typeof paths.${o}`:`(typeof paths)[${y(o)}]`},`),e.push(` ${s},`),e.push(` ${u},`),e.push(` ${i},`),e.push(` ${a}`),e.push(">;"),e.push("")}}}function Me(e){return!e||!me(e)?"OperationErrors":`OperationErrors<${He(e)}>`}function He(e){return!e||Object.keys(e).length===0?"unknown":`{ ${Object.entries(e).map(([r,o])=>{let i=y(r),s=ye(o);return`${i}: ${s}`}).join("; ")} }`}var le=new Set(["any","unknown","never","void","null","undefined","string","number","boolean","bigint","symbol"]),he=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function D(e){if(!e)return"undefined";let n=e.trim();if(n==="undefined")return"undefined";if(le.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${D(t[1])}>`:he.test(n)?`typeof ${n}`:n}function ye(e){if(!e)return"unknown";let n=e.trim();if(le.has(n)||n.startsWith("typeof "))return n;let t=n.match(/^z\.array\((.+)\)$/);return t?`z.ZodArray<${ye(t[1])}>`:he.test(n)?`typeof ${n}`:n}function Ce(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 Fe(e){return ge(e.schema)}function ge(e){if(!e)return"string";if(e.type==="array")return`Array<${ge(e.items)}>`;switch(e.type){case"integer":case"number":return"number";case"boolean":return"boolean";default:return"string"}}function de(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{ze as a,Et as b};
|
|
8
|
-
//# sourceMappingURL=chunk-NZMYX32P.mjs.map
|