oas-truth 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -0
- package/dist/index.d.ts +96 -2
- package/dist/index.js +376 -10
- package/package.json +8 -3
package/README.md
CHANGED
|
@@ -28,6 +28,29 @@ if (result.ok) {
|
|
|
28
28
|
- TypeSpec files (`.tsp`) are compiled with `@typespec/compiler` and then bundled
|
|
29
29
|
- Returns `{ ok: true, value } | { ok: false, error }` (never throws)
|
|
30
30
|
|
|
31
|
+
## Component schemas
|
|
32
|
+
|
|
33
|
+
`makeSchemasCode` emits one file: the library import and every `components.schemas` declaration, in
|
|
34
|
+
dependency order. `makeSchemaDeclarations` returns the same declarations one by one (`name`,
|
|
35
|
+
`varName`, `fileName`, `importLine`, `code`) so a host can split a file per schema.
|
|
36
|
+
|
|
37
|
+
Recursive `$ref` cycles keep a helper type so the const can be annotated (`z.ZodType<NodeType>`,
|
|
38
|
+
`v.GenericSchema<NodeType>`, `Schema.Codec<NodeType>`). That helper matches what the library
|
|
39
|
+
infers — `| undefined` on Valibot and Effect optionals, `readonly` arrays on Effect — so it
|
|
40
|
+
type-checks under `exactOptionalPropertyTypes`. Arktype cycles become
|
|
41
|
+
`scope({...}).export().Member`; that declaration's `importLine` is then
|
|
42
|
+
`import { type, scope } from 'arktype'`. `schemaImportLine` is the same function
|
|
43
|
+
`makeSchemasCode` uses when the declarations stay in one file.
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { makeAdapter, makeSchemaDeclarations } from 'oas-truth'
|
|
47
|
+
|
|
48
|
+
const declarations = makeSchemaDeclarations(schemas, makeAdapter('arktype'))
|
|
49
|
+
// a cyclic file: import { type, scope } from 'arktype'
|
|
50
|
+
// a non-cyclic file: import { type } from 'arktype'
|
|
51
|
+
const source = `${declarations[0]?.importLine}\n\n${declarations[0]?.code}`
|
|
52
|
+
```
|
|
53
|
+
|
|
31
54
|
## License
|
|
32
55
|
|
|
33
56
|
[MIT](https://github.com/nakita628/oas-truth/blob/main/LICENSE)
|
package/dist/index.d.ts
CHANGED
|
@@ -502,6 +502,24 @@ export type Callbacks = {
|
|
|
502
502
|
//#region src/adapter/index.d.ts
|
|
503
503
|
export type ParamIn = 'query' | 'path';
|
|
504
504
|
export type SchemaLib = 'zod' | 'valibot' | 'arktype' | 'effect' | 'typebox';
|
|
505
|
+
/**
|
|
506
|
+
* Flags `renderImport` uses when the schemas builder needs more than the
|
|
507
|
+
* library's default line — Arktype `scope` for a `$ref` cycle, TypeBox
|
|
508
|
+
* `Static` when type aliases are exported.
|
|
509
|
+
*/
|
|
510
|
+
export type RenderImportOptions = {
|
|
511
|
+
readonly cyclic?: boolean;
|
|
512
|
+
readonly exportTypes?: boolean;
|
|
513
|
+
};
|
|
514
|
+
/**
|
|
515
|
+
* How this library's inferred object type differs from a Zod-shaped
|
|
516
|
+
* `prop?: T` literal, so the TS7022 helper matches `cyclicAnnotation` under
|
|
517
|
+
* `exactOptionalPropertyTypes`. Omitted properties keep the Zod form.
|
|
518
|
+
*/
|
|
519
|
+
export type CyclicTypeStyle = {
|
|
520
|
+
readonly optionalUndefined?: boolean;
|
|
521
|
+
readonly readonlyArrays?: boolean;
|
|
522
|
+
};
|
|
505
523
|
/**
|
|
506
524
|
* The minimal surface the component generators consume from a validator
|
|
507
525
|
* adapter. Each library's full adapter (carrying `toNamedExport`,
|
|
@@ -514,12 +532,24 @@ export type SchemaLib = 'zod' | 'valibot' | 'arktype' | 'effect' | 'typebox';
|
|
|
514
532
|
* expression — e.g. hono-openapi wrapping it in `resolver(...)` — supplies it;
|
|
515
533
|
* omitting it leaves the expression untouched (identity), so the shared library
|
|
516
534
|
* stays framework-agnostic.
|
|
535
|
+
*
|
|
536
|
+
* Cycle handling lives next to each library: `wrapLazy` re-wraps a `$ref`
|
|
537
|
+
* inside a strongly connected component (Zod, Valibot, Effect);
|
|
538
|
+
* `cyclicAnnotation` is the TS7022 annotation on that declaration;
|
|
539
|
+
* `cyclicTypeStyle` is the helper type that annotation names;
|
|
540
|
+
* `renderCyclic` post-processes the `$defs` container TypeBox and Arktype
|
|
541
|
+
* need (`Type.Cyclic` is already the expression; Arktype extracts `scope`).
|
|
517
542
|
*/
|
|
518
543
|
export type ComponentAdapter = {
|
|
519
|
-
readonly renderImport: () => string;
|
|
544
|
+
readonly renderImport: (options?: RenderImportOptions) => string;
|
|
520
545
|
readonly toExpression: (schema: Schema, paramIn?: ParamIn) => string;
|
|
521
546
|
readonly renderTypeInfer: (constName: string) => string;
|
|
522
547
|
readonly wrapSchema?: (expr: string) => string;
|
|
548
|
+
readonly wrapLazy?: (varName: string) => string;
|
|
549
|
+
readonly cyclicAnnotation?: (typeName: string) => string;
|
|
550
|
+
readonly cyclicTypeStyle?: CyclicTypeStyle;
|
|
551
|
+
readonly renderCyclic?: (varName: string, containerExpr: string, externals: readonly string[]) => string;
|
|
552
|
+
readonly reservedTypeNames?: readonly string[];
|
|
523
553
|
};
|
|
524
554
|
export declare function makeAdapter(lib: SchemaLib): ComponentAdapter;
|
|
525
555
|
//#endregion
|
|
@@ -579,6 +609,70 @@ export declare function makeRequestBodiesCode(components: Components, adapter: C
|
|
|
579
609
|
//#region src/generator/components/responses.d.ts
|
|
580
610
|
export declare function makeResponsesCode(components: Components, adapter: ComponentAdapter, readonly: boolean): string;
|
|
581
611
|
//#endregion
|
|
612
|
+
//#region src/generator/components/schemas.d.ts
|
|
613
|
+
type SchemasOptions = {
|
|
614
|
+
readonly exportTypes?: boolean;
|
|
615
|
+
readonly readonly?: boolean;
|
|
616
|
+
/**
|
|
617
|
+
* How to name the exported type alias. `const` (default) matches the other
|
|
618
|
+
* builders (`UserSchema`); `key` uses the OpenAPI key (`User`).
|
|
619
|
+
*/
|
|
620
|
+
readonly typeAlias?: 'const' | 'key';
|
|
621
|
+
/**
|
|
622
|
+
* Shape of the TS7022 helper type. `'library'` (default) matches what the
|
|
623
|
+
* validator infers, so `v.GenericSchema<Helper>` / `Schema.Codec<Helper>`
|
|
624
|
+
* type-check under `exactOptionalPropertyTypes`. `'literal'` is the
|
|
625
|
+
* Zod-shaped `prop?: T` form for every library.
|
|
626
|
+
*/
|
|
627
|
+
readonly cyclicTypeStyle?: 'library' | 'literal';
|
|
628
|
+
/**
|
|
629
|
+
* Host hook around each declaration expression — e.g. hono-openapi ref
|
|
630
|
+
* registration. Applied after cycle handling.
|
|
631
|
+
*/
|
|
632
|
+
readonly wrapDeclaration?: (expr: string, name: string) => string;
|
|
633
|
+
};
|
|
634
|
+
type SchemaDeclaration = {
|
|
635
|
+
readonly name: string;
|
|
636
|
+
readonly varName: string;
|
|
637
|
+
readonly fileName: string;
|
|
638
|
+
/**
|
|
639
|
+
* The library import this declaration needs when written to its own file.
|
|
640
|
+
* An Arktype cycle that is only `scope({...}).export().Member` gets
|
|
641
|
+
* `import { type, scope } from 'arktype'`; a non-cyclic file stays
|
|
642
|
+
* `import { type } from 'arktype'`.
|
|
643
|
+
*/
|
|
644
|
+
readonly importLine: string;
|
|
645
|
+
readonly code: string;
|
|
646
|
+
};
|
|
647
|
+
/**
|
|
648
|
+
* The import line a schemas file needs. `cyclic` is true when this file (or
|
|
649
|
+
* the bundled document) contains an Arktype `scope` / TypeBox container
|
|
650
|
+
* cycle — split files that are only `scope({...}).export().Member` still
|
|
651
|
+
* have to import `scope`.
|
|
652
|
+
*/
|
|
653
|
+
export declare function schemaImportLine(adapter: ComponentAdapter, options?: SchemasOptions, cyclic?: boolean): string;
|
|
654
|
+
/**
|
|
655
|
+
* One `export const <X>Schema=...` declaration per `components.schemas` entry,
|
|
656
|
+
* in dependency-first order. Only references inside a `$ref` cycle are lazy
|
|
657
|
+
* (and their declarations get the annotation TypeScript needs); every other
|
|
658
|
+
* reference is a plain identifier, declared earlier.
|
|
659
|
+
*/
|
|
660
|
+
export declare function makeSchemaDeclarations(schemas: {
|
|
661
|
+
readonly [k: string]: Schema;
|
|
662
|
+
}, adapter: ComponentAdapter, options?: SchemasOptions): {
|
|
663
|
+
name: string;
|
|
664
|
+
varName: string;
|
|
665
|
+
fileName: string;
|
|
666
|
+
importLine: string;
|
|
667
|
+
code: string;
|
|
668
|
+
}[];
|
|
669
|
+
/**
|
|
670
|
+
* The import line and every `components.schemas` declaration, in dependency
|
|
671
|
+
* order. Returns `''` when schemas are missing or empty.
|
|
672
|
+
*/
|
|
673
|
+
export declare function makeSchemasCode(components: Components, adapter: ComponentAdapter, options?: SchemasOptions): string;
|
|
674
|
+
//#endregion
|
|
582
675
|
//#region src/generator/components/security-schemes.d.ts
|
|
583
676
|
export declare function makeSecuritySchemesCode(components: Components, readonly: boolean): string;
|
|
584
|
-
//#endregion
|
|
677
|
+
//#endregion
|
|
678
|
+
export type { SchemaDeclaration, SchemasOptions };
|
package/dist/index.js
CHANGED
|
@@ -70,6 +70,20 @@ function stripZodLazy(code) {
|
|
|
70
70
|
function stripValibotLazy(code) {
|
|
71
71
|
return code.replaceAll(/v\.lazy\(\(\)\s*=>\s*(\w+Schema)\)/gu, "$1");
|
|
72
72
|
}
|
|
73
|
+
/** Inline `Schema.suspend(() => XSchema)` back to the bare `XSchema` reference. */
|
|
74
|
+
function stripEffectSuspend(code) {
|
|
75
|
+
return code.replaceAll(/Schema\.suspend\(\(\)\s*=>\s*(\w+Schema)\)/gu, "$1");
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Arktype's `$defs` document becomes `const types = scope({...}).export()` plus
|
|
79
|
+
* a selected member. The schemas builder needs the `scope` body so it can alias
|
|
80
|
+
* references that leave the cycle.
|
|
81
|
+
*/
|
|
82
|
+
function renderArktypeCyclic(varName, containerExpr, externals) {
|
|
83
|
+
const body = containerExpr.match(/scope\(\{([\s\S]*)\}\)\.export\(\)/u)?.[1];
|
|
84
|
+
if (body === void 0) return containerExpr;
|
|
85
|
+
return `scope({${[...externals.map((ref) => `${ref}:${ref}`), body].join(",")}}).export().${varName}`;
|
|
86
|
+
}
|
|
73
87
|
function makeZodAdapter() {
|
|
74
88
|
return {
|
|
75
89
|
toExpression(schema, paramIn) {
|
|
@@ -85,6 +99,12 @@ function makeZodAdapter() {
|
|
|
85
99
|
},
|
|
86
100
|
renderTypeInfer(constName) {
|
|
87
101
|
return `export type ${constName}=z.infer<typeof ${constName}>`;
|
|
102
|
+
},
|
|
103
|
+
wrapLazy(varName) {
|
|
104
|
+
return `z.lazy(() => ${varName})`;
|
|
105
|
+
},
|
|
106
|
+
cyclicAnnotation(typeName) {
|
|
107
|
+
return `z.ZodType<${typeName}>`;
|
|
88
108
|
}
|
|
89
109
|
};
|
|
90
110
|
}
|
|
@@ -103,7 +123,14 @@ function makeValibotAdapter() {
|
|
|
103
123
|
},
|
|
104
124
|
renderTypeInfer(constName) {
|
|
105
125
|
return `export type ${constName}=v.InferOutput<typeof ${constName}>`;
|
|
106
|
-
}
|
|
126
|
+
},
|
|
127
|
+
wrapLazy(varName) {
|
|
128
|
+
return `v.lazy(() => ${varName})`;
|
|
129
|
+
},
|
|
130
|
+
cyclicAnnotation(typeName) {
|
|
131
|
+
return `v.GenericSchema<${typeName}>`;
|
|
132
|
+
},
|
|
133
|
+
cyclicTypeStyle: { optionalUndefined: true }
|
|
107
134
|
};
|
|
108
135
|
}
|
|
109
136
|
function makeArktypeAdapter() {
|
|
@@ -116,12 +143,14 @@ function makeArktypeAdapter() {
|
|
|
116
143
|
...paramIn && { paramIn }
|
|
117
144
|
}));
|
|
118
145
|
},
|
|
119
|
-
renderImport() {
|
|
120
|
-
return "import { type } from 'arktype'";
|
|
146
|
+
renderImport(options) {
|
|
147
|
+
return options?.cyclic === true ? "import { type, scope } from 'arktype'" : "import { type } from 'arktype'";
|
|
121
148
|
},
|
|
122
149
|
renderTypeInfer(constName) {
|
|
123
150
|
return `export type ${constName}=typeof ${constName}.infer`;
|
|
124
|
-
}
|
|
151
|
+
},
|
|
152
|
+
renderCyclic: renderArktypeCyclic,
|
|
153
|
+
reservedTypeNames: ["type", "scope"]
|
|
125
154
|
};
|
|
126
155
|
}
|
|
127
156
|
function makeTypeboxAdapter() {
|
|
@@ -134,12 +163,17 @@ function makeTypeboxAdapter() {
|
|
|
134
163
|
...paramIn && { paramIn }
|
|
135
164
|
}));
|
|
136
165
|
},
|
|
137
|
-
renderImport() {
|
|
138
|
-
return "import { Type } from '@sinclair/typebox'";
|
|
166
|
+
renderImport(options) {
|
|
167
|
+
return options?.exportTypes === true ? "import { Type, type Static } from '@sinclair/typebox'" : "import { Type } from '@sinclair/typebox'";
|
|
139
168
|
},
|
|
140
169
|
renderTypeInfer(constName) {
|
|
141
170
|
return `export type ${constName}=Static<typeof ${constName}>`;
|
|
142
|
-
}
|
|
171
|
+
},
|
|
172
|
+
reservedTypeNames: [
|
|
173
|
+
"Type",
|
|
174
|
+
"Static",
|
|
175
|
+
"Codec"
|
|
176
|
+
]
|
|
143
177
|
};
|
|
144
178
|
}
|
|
145
179
|
function makeEffectAdapter() {
|
|
@@ -150,14 +184,25 @@ function makeEffectAdapter() {
|
|
|
150
184
|
openapi: true,
|
|
151
185
|
readonly: false,
|
|
152
186
|
...paramIn && { paramIn }
|
|
153
|
-
}));
|
|
187
|
+
}), stripEffectSuspend);
|
|
154
188
|
},
|
|
155
189
|
renderImport() {
|
|
156
190
|
return "import { Schema } from 'effect'";
|
|
157
191
|
},
|
|
158
192
|
renderTypeInfer(constName) {
|
|
159
193
|
return `export type ${constName}=Schema.Schema.Type<typeof ${constName}>`;
|
|
160
|
-
}
|
|
194
|
+
},
|
|
195
|
+
wrapLazy(varName) {
|
|
196
|
+
return `Schema.suspend(() => ${varName})`;
|
|
197
|
+
},
|
|
198
|
+
cyclicAnnotation(typeName) {
|
|
199
|
+
return `Schema.Codec<${typeName}>`;
|
|
200
|
+
},
|
|
201
|
+
cyclicTypeStyle: {
|
|
202
|
+
optionalUndefined: true,
|
|
203
|
+
readonlyArrays: true
|
|
204
|
+
},
|
|
205
|
+
reservedTypeNames: ["Schema", "Effect"]
|
|
161
206
|
};
|
|
162
207
|
}
|
|
163
208
|
//#endregion
|
|
@@ -404,6 +449,327 @@ function makeResponsesCode(components, adapter, readonly) {
|
|
|
404
449
|
return exports.join(";");
|
|
405
450
|
}
|
|
406
451
|
//#endregion
|
|
452
|
+
//#region src/helper/graph.ts
|
|
453
|
+
/** Every `components.schemas` name a schema reaches through `$ref`, at any depth. */
|
|
454
|
+
function collectSchemaRefs(node) {
|
|
455
|
+
if (Array.isArray(node)) return node.flatMap(collectSchemaRefs);
|
|
456
|
+
if (!isRecord(node)) return [];
|
|
457
|
+
return [...typeof node.$ref === "string" && node.$ref.startsWith("#/components/schemas/") ? [schemaRefToName(node.$ref)] : [], ...Object.values(node).flatMap(collectSchemaRefs)];
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Strongly connected components over the `$ref` graph. A component is closed
|
|
461
|
+
* only after every component it reaches, so the flattened result is a
|
|
462
|
+
* dependency-first declaration order; `cycles` maps each member of a recursive
|
|
463
|
+
* component (a mutual cycle, or a schema that refers to itself) to its whole
|
|
464
|
+
* group.
|
|
465
|
+
*/
|
|
466
|
+
function analyzeSchemas(schemas) {
|
|
467
|
+
const edges = new Map(Object.entries(schemas).map(([name, schema]) => [name, [...new Set(collectSchemaRefs(schema))].filter((ref) => ref in schemas)]));
|
|
468
|
+
const index = /* @__PURE__ */ new Map();
|
|
469
|
+
const low = /* @__PURE__ */ new Map();
|
|
470
|
+
const stack = [];
|
|
471
|
+
const onStack = /* @__PURE__ */ new Set();
|
|
472
|
+
const components = [];
|
|
473
|
+
const connect = (name) => {
|
|
474
|
+
index.set(name, index.size);
|
|
475
|
+
low.set(name, index.size - 1);
|
|
476
|
+
stack.push(name);
|
|
477
|
+
onStack.add(name);
|
|
478
|
+
for (const next of edges.get(name) ?? []) {
|
|
479
|
+
if (!index.has(next)) connect(next);
|
|
480
|
+
if (onStack.has(next)) low.set(name, Math.min(low.get(name) ?? 0, low.get(next) ?? 0));
|
|
481
|
+
}
|
|
482
|
+
if (low.get(name) === index.get(name)) {
|
|
483
|
+
const group = stack.splice(stack.lastIndexOf(name));
|
|
484
|
+
for (const member of group) onStack.delete(member);
|
|
485
|
+
components.push(group);
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
for (const name of edges.keys()) if (!index.has(name)) connect(name);
|
|
489
|
+
const cycles = new Map(components.filter((group) => group.length > 1 || (edges.get(group[0] ?? "") ?? []).includes(group[0] ?? "")).flatMap((group) => group.map((name) => [name, group])));
|
|
490
|
+
return {
|
|
491
|
+
order: components.flat(),
|
|
492
|
+
cycles
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
function makeTypeString(schema, self, infer, readonly, style) {
|
|
496
|
+
const recurse = (s) => makeTypeString(s, self, infer, readonly, style);
|
|
497
|
+
const ro = readonly ? "readonly " : "";
|
|
498
|
+
if (schema.$ref) {
|
|
499
|
+
const name = schemaRefToName(schema.$ref);
|
|
500
|
+
return name === self.name ? self.typeName : infer(name);
|
|
501
|
+
}
|
|
502
|
+
const union = schema.oneOf ?? schema.anyOf;
|
|
503
|
+
if (union && union.length > 0) return `(${union.map(recurse).join("|")})`;
|
|
504
|
+
if (schema.allOf && schema.allOf.length > 0) return `(${schema.allOf.map(recurse).join("&")})`;
|
|
505
|
+
if (schema.enum && schema.enum.length > 0) return schema.enum.map((v) => JSON.stringify(v)).join("|");
|
|
506
|
+
if (schema.const !== void 0) return JSON.stringify(schema.const);
|
|
507
|
+
const types = schema.type === void 0 ? ["object"] : [schema.type].flat();
|
|
508
|
+
const nullable = schema.nullable === true || types.includes("null");
|
|
509
|
+
const arrayRo = readonly || style.readonlyArrays === true ? "readonly " : "";
|
|
510
|
+
const optionalUndef = style.optionalUndefined === true ? "|undefined" : "";
|
|
511
|
+
const base = types.filter((type) => type !== "null").map((type) => {
|
|
512
|
+
if (type === "string") return "string";
|
|
513
|
+
if (type === "number" || type === "integer") return "number";
|
|
514
|
+
if (type === "boolean") return "boolean";
|
|
515
|
+
if (type === "array") {
|
|
516
|
+
const items = schema.items;
|
|
517
|
+
const item = isRecord(items) ? recurse(items) : "unknown";
|
|
518
|
+
return `${arrayRo}(${item})[]`;
|
|
519
|
+
}
|
|
520
|
+
if (type === "object") {
|
|
521
|
+
const props = Object.entries(schema.properties ?? {}).map(([key, prop]) => {
|
|
522
|
+
const required = schema.required?.includes(key) === true;
|
|
523
|
+
return `${ro}${JSON.stringify(key)}${required ? "" : "?"}:${recurse(prop)}${required ? "" : optionalUndef}`;
|
|
524
|
+
});
|
|
525
|
+
const extra = isRecord(schema.additionalProperties) ? [`${ro}[key:string]:${recurse(schema.additionalProperties)}`] : props.length === 0 ? [`${ro}[key:string]:unknown`] : [];
|
|
526
|
+
return `{${[...props, ...extra].join(";")}}`;
|
|
527
|
+
}
|
|
528
|
+
return "unknown";
|
|
529
|
+
}).join("|");
|
|
530
|
+
if (!nullable) return base || "unknown";
|
|
531
|
+
return base ? `(${base}|null)` : "null";
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* The TypeScript shape of a recursive schema, so its declaration can carry an
|
|
535
|
+
* explicit `z.ZodType<XType>` / `v.GenericSchema<XType>` annotation (TS7022).
|
|
536
|
+
* References to other schemas go through their inferred types. `style` is the
|
|
537
|
+
* library's inferred object type (Valibot `| undefined`, Effect `readonly`
|
|
538
|
+
* arrays) so the annotation type-checks under `exactOptionalPropertyTypes`.
|
|
539
|
+
*/
|
|
540
|
+
function makeCyclicType(name, typeName, schema, infer, readonly, style = {}) {
|
|
541
|
+
return `type ${typeName}=${makeTypeString(schema, {
|
|
542
|
+
name,
|
|
543
|
+
typeName
|
|
544
|
+
}, infer, readonly, style)}`;
|
|
545
|
+
}
|
|
546
|
+
//#endregion
|
|
547
|
+
//#region src/helper/identifiers.ts
|
|
548
|
+
/**
|
|
549
|
+
* Identifier rewriting on generated source without a parser: skip quoted
|
|
550
|
+
* strings so identifier-shaped text inside descriptions and `Type.Ref('X')`
|
|
551
|
+
* keys is never mistaken for a reference. The schemas builder only applies
|
|
552
|
+
* this to libraries whose cycle form is a lazy wrapper (Zod, Valibot, Effect),
|
|
553
|
+
* where a schema name appears as an identifier.
|
|
554
|
+
*/
|
|
555
|
+
function readQuoted(source, start) {
|
|
556
|
+
const quote = source[start] ?? "";
|
|
557
|
+
let i = start + 1;
|
|
558
|
+
while (i < source.length) {
|
|
559
|
+
const ch = source[i];
|
|
560
|
+
if (ch === "\\") {
|
|
561
|
+
i += 2;
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
if (ch === quote) return {
|
|
565
|
+
text: source.slice(start, i + 1),
|
|
566
|
+
end: i + 1
|
|
567
|
+
};
|
|
568
|
+
i += 1;
|
|
569
|
+
}
|
|
570
|
+
return {
|
|
571
|
+
text: source.slice(start),
|
|
572
|
+
end: source.length
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
function isIdentStart(ch) {
|
|
576
|
+
return /[A-Za-z_$]/u.test(ch);
|
|
577
|
+
}
|
|
578
|
+
function isIdentPart(ch) {
|
|
579
|
+
return /[A-Za-z0-9_$]/u.test(ch);
|
|
580
|
+
}
|
|
581
|
+
/** Rewrites every identifier in `names` with `wrap(name)`, leaving strings intact. */
|
|
582
|
+
function wrapReferences(expr, names, wrap) {
|
|
583
|
+
if (names.size === 0) return expr;
|
|
584
|
+
let result = "";
|
|
585
|
+
let i = 0;
|
|
586
|
+
while (i < expr.length) {
|
|
587
|
+
const ch = expr[i] ?? "";
|
|
588
|
+
if (ch === "\"" || ch === "'" || ch === "`") {
|
|
589
|
+
const quoted = readQuoted(expr, i);
|
|
590
|
+
result += quoted.text;
|
|
591
|
+
i = quoted.end;
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
if (isIdentStart(ch)) {
|
|
595
|
+
const start = i;
|
|
596
|
+
i += 1;
|
|
597
|
+
while (i < expr.length && isIdentPart(expr[i] ?? "")) i += 1;
|
|
598
|
+
const ident = expr.slice(start, i);
|
|
599
|
+
result += names.has(ident) ? wrap(ident) : ident;
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
result += ch;
|
|
603
|
+
i += 1;
|
|
604
|
+
}
|
|
605
|
+
return result;
|
|
606
|
+
}
|
|
607
|
+
//#endregion
|
|
608
|
+
//#region src/generator/components/schemas.ts
|
|
609
|
+
/** `name`, or the first of `name2`, `name3`, … not in `used`. */
|
|
610
|
+
function claimName(name, used, i = 2) {
|
|
611
|
+
if (!used.has(name)) return name;
|
|
612
|
+
return used.has(`${name}${i}`) ? claimName(name, used, i + 1) : `${name}${i}`;
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* `toIdentifierPascalCase` folds `user` and `User` into one identifier; later
|
|
616
|
+
* colliders get a numeric suffix so no declaration is lost. A `$ref` to a later
|
|
617
|
+
* collider still resolves to the first declaration.
|
|
618
|
+
*/
|
|
619
|
+
function makeSchemaIdentifiers(schemas) {
|
|
620
|
+
return Object.keys(schemas).reduce((acc, key) => acc.set(key, claimName(toIdentifierPascalCase(key), new Set(acc.values()))), /* @__PURE__ */ new Map());
|
|
621
|
+
}
|
|
622
|
+
/** Keys whose value is a subschema (or a list of them) and keys whose value maps names to subschemas. */
|
|
623
|
+
const SUBSCHEMA_KEYS = /* @__PURE__ */ new Set([
|
|
624
|
+
"items",
|
|
625
|
+
"prefixItems",
|
|
626
|
+
"additionalProperties",
|
|
627
|
+
"allOf",
|
|
628
|
+
"anyOf",
|
|
629
|
+
"oneOf",
|
|
630
|
+
"not",
|
|
631
|
+
"if",
|
|
632
|
+
"then",
|
|
633
|
+
"else",
|
|
634
|
+
"contains",
|
|
635
|
+
"propertyNames",
|
|
636
|
+
"unevaluatedItems",
|
|
637
|
+
"unevaluatedProperties",
|
|
638
|
+
"contentSchema"
|
|
639
|
+
]);
|
|
640
|
+
const SUBSCHEMA_MAP_KEYS = /* @__PURE__ */ new Set([
|
|
641
|
+
"properties",
|
|
642
|
+
"patternProperties",
|
|
643
|
+
"dependentSchemas",
|
|
644
|
+
"$defs"
|
|
645
|
+
]);
|
|
646
|
+
function isSchema(value) {
|
|
647
|
+
return isRecord(value);
|
|
648
|
+
}
|
|
649
|
+
/** Rewrites a schema bottom-up with `fn`, following only subschemas (never example or default values). */
|
|
650
|
+
function mapSchema(schema, fn) {
|
|
651
|
+
const map = (value) => isSchema(value) ? mapSchema(value, fn) : value;
|
|
652
|
+
const node = Object.fromEntries(Object.entries(schema).map(([key, value]) => {
|
|
653
|
+
if (SUBSCHEMA_KEYS.has(key)) return [key, Array.isArray(value) ? value.map(map) : map(value)];
|
|
654
|
+
if (SUBSCHEMA_MAP_KEYS.has(key) && isRecord(value)) return [key, Object.fromEntries(Object.entries(value).map(([k, v]) => [k, map(v)]))];
|
|
655
|
+
return [key, value];
|
|
656
|
+
}));
|
|
657
|
+
return fn(isSchema(node) ? node : schema);
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* `readonly` as the declarative `x-readonly` extension on every object and array,
|
|
661
|
+
* which schema-to-library turns into each library's readonly form.
|
|
662
|
+
*/
|
|
663
|
+
function markReadonly(schema) {
|
|
664
|
+
return mapSchema(schema, (node) => {
|
|
665
|
+
const types = new Set([node.type].flat());
|
|
666
|
+
return types.has("object") || types.has("array") ? {
|
|
667
|
+
...node,
|
|
668
|
+
"x-readonly": true
|
|
669
|
+
} : node;
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* TypeBox and Arktype cannot express a cycle with standalone `const`s: the group
|
|
674
|
+
* becomes one `Type.Cyclic(...)` / `scope(...)` container and each member selects
|
|
675
|
+
* its entry. schema-to-library builds the container from a `$defs` document.
|
|
676
|
+
*/
|
|
677
|
+
function makeCyclicContainer(varName, group, schemas, identifiers, adapter) {
|
|
678
|
+
const groupIdentifiers = new Map(group.map((name) => [name, identifiers.get(name) ?? name]));
|
|
679
|
+
const localize = (node) => {
|
|
680
|
+
const ident = node.$ref ? groupIdentifiers.get(schemaRefToName(node.$ref)) : void 0;
|
|
681
|
+
if (ident === void 0) return node;
|
|
682
|
+
const local = Object.fromEntries([...Object.entries(node), ["$ref", `#/$defs/${ident}Schema`]]);
|
|
683
|
+
return isSchema(local) ? local : node;
|
|
684
|
+
};
|
|
685
|
+
const $defs = Object.fromEntries(group.map((name) => [`${groupIdentifiers.get(name)}Schema`, mapSchema(schemas[name] ?? {}, localize)]));
|
|
686
|
+
return adapter.toExpression({
|
|
687
|
+
title: varName,
|
|
688
|
+
$defs
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* The import line a schemas file needs. `cyclic` is true when this file (or
|
|
693
|
+
* the bundled document) contains an Arktype `scope` / TypeBox container
|
|
694
|
+
* cycle — split files that are only `scope({...}).export().Member` still
|
|
695
|
+
* have to import `scope`.
|
|
696
|
+
*/
|
|
697
|
+
function schemaImportLine(adapter, options, cyclic = false) {
|
|
698
|
+
const exportTypes = options?.exportTypes === true;
|
|
699
|
+
if (!cyclic && !exportTypes) return adapter.renderImport();
|
|
700
|
+
return adapter.renderImport({
|
|
701
|
+
...cyclic && { cyclic: true },
|
|
702
|
+
...exportTypes && { exportTypes: true }
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
function exportedTypeName(ident, varName, adapter, options) {
|
|
706
|
+
if (options?.typeAlias !== "key") return varName;
|
|
707
|
+
return (adapter.reservedTypeNames ?? []).includes(ident) ? `${ident}Type` : ident;
|
|
708
|
+
}
|
|
709
|
+
function fileNameOf(ident) {
|
|
710
|
+
return `${ident.charAt(0).toLowerCase()}${ident.slice(1)}`;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* One `export const <X>Schema=...` declaration per `components.schemas` entry,
|
|
714
|
+
* in dependency-first order. Only references inside a `$ref` cycle are lazy
|
|
715
|
+
* (and their declarations get the annotation TypeScript needs); every other
|
|
716
|
+
* reference is a plain identifier, declared earlier.
|
|
717
|
+
*/
|
|
718
|
+
function makeSchemaDeclarations(schemas, adapter, options) {
|
|
719
|
+
const prepared = Object.fromEntries(Object.entries(schemas).map(([name, schema]) => [name, options?.readonly === true ? markReadonly(schema) : schema]));
|
|
720
|
+
const identifiers = makeSchemaIdentifiers(schemas);
|
|
721
|
+
const { order, cycles } = analyzeSchemas(schemas);
|
|
722
|
+
const taken = /* @__PURE__ */ new Set([
|
|
723
|
+
...identifiers.values(),
|
|
724
|
+
...[...identifiers.values()].map((ident) => `${ident}Schema`),
|
|
725
|
+
...adapter.reservedTypeNames ?? []
|
|
726
|
+
]);
|
|
727
|
+
const infer = (varName) => adapter.renderTypeInfer(varName).replace(`export type ${varName}=`, "");
|
|
728
|
+
const style = options?.cyclicTypeStyle === "literal" ? {} : adapter.cyclicTypeStyle ?? {};
|
|
729
|
+
return order.map((name) => {
|
|
730
|
+
const schema = prepared[name] ?? {};
|
|
731
|
+
const ident = identifiers.get(name) ?? toIdentifierPascalCase(name);
|
|
732
|
+
const varName = `${ident}Schema`;
|
|
733
|
+
const group = cycles.get(name);
|
|
734
|
+
const arktypeReadonly = adapter.renderCyclic !== void 0 && options?.readonly === true;
|
|
735
|
+
const container = group && adapter.wrapLazy === void 0 ? makeCyclicContainer(varName, group, arktypeReadonly ? schemas : prepared, identifiers, adapter) : void 0;
|
|
736
|
+
const peers = group ?? [];
|
|
737
|
+
const rendered = container === void 0 ? void 0 : adapter.renderCyclic?.(varName, container, [...new Set(peers.flatMap((peer) => collectSchemaRefs(schemas[peer])))].flatMap((ref) => peers.includes(ref) || !identifiers.has(ref) ? [] : [`${identifiers.get(ref)}Schema`])) ?? container;
|
|
738
|
+
const expression = (rendered && arktypeReadonly ? `${rendered}.readonly()` : rendered) ?? adapter.toExpression({
|
|
739
|
+
...schema,
|
|
740
|
+
title: varName
|
|
741
|
+
});
|
|
742
|
+
const body = adapter.wrapLazy ? wrapReferences(expression, new Set((group ?? []).map((peer) => `${identifiers.get(peer)}Schema`)), adapter.wrapLazy) : expression;
|
|
743
|
+
const value = options?.wrapDeclaration ? options.wrapDeclaration(body, name) : body;
|
|
744
|
+
const helper = group && adapter.cyclicAnnotation ? claimName(`${ident}Type`, taken) : void 0;
|
|
745
|
+
const annotationText = helper ? adapter.cyclicAnnotation?.(helper) : void 0;
|
|
746
|
+
const usesHelper = helper !== void 0 && annotationText?.includes(helper) === true;
|
|
747
|
+
if (helper && usesHelper) taken.add(helper);
|
|
748
|
+
const typeDef = helper && usesHelper ? `${makeCyclicType(name, helper, schema, (ref) => infer(`${identifiers.get(ref) ?? toIdentifierPascalCase(ref)}Schema`), options?.readonly === true, style)}\n\n` : "";
|
|
749
|
+
const annotation = annotationText === void 0 ? "" : `:${annotationText}`;
|
|
750
|
+
const typeExport = options?.exportTypes === true ? `\n\nexport type ${exportedTypeName(ident, varName, adapter, options)}=${infer(varName)}` : "";
|
|
751
|
+
const containerCycle = group !== void 0 && adapter.wrapLazy === void 0;
|
|
752
|
+
return {
|
|
753
|
+
name,
|
|
754
|
+
varName,
|
|
755
|
+
fileName: fileNameOf(ident),
|
|
756
|
+
importLine: schemaImportLine(adapter, options, containerCycle),
|
|
757
|
+
code: `${typeDef}export const ${varName}${annotation}=${value}${typeExport}`
|
|
758
|
+
};
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* The import line and every `components.schemas` declaration, in dependency
|
|
763
|
+
* order. Returns `''` when schemas are missing or empty.
|
|
764
|
+
*/
|
|
765
|
+
function makeSchemasCode(components, adapter, options) {
|
|
766
|
+
const { schemas } = components;
|
|
767
|
+
if (!schemas) return "";
|
|
768
|
+
const declarations = makeSchemaDeclarations(schemas, adapter, options);
|
|
769
|
+
if (declarations.length === 0) return "";
|
|
770
|
+
return `${schemaImportLine(adapter, options, declarations.some((d) => d.importLine !== schemaImportLine(adapter, options)))}\n\n${declarations.map((d) => d.code).join(";")}\n`;
|
|
771
|
+
}
|
|
772
|
+
//#endregion
|
|
407
773
|
//#region src/generator/components/security-schemes.ts
|
|
408
774
|
function makeSecuritySchemesCode(components, readonly) {
|
|
409
775
|
const { securitySchemes } = components;
|
|
@@ -416,4 +782,4 @@ function makeSecuritySchemesCode(components, readonly) {
|
|
|
416
782
|
}).join(";")}\n`;
|
|
417
783
|
}
|
|
418
784
|
//#endregion
|
|
419
|
-
export { isRecord, makeAdapter, makeCallbacksCode, makeExamplesCode, makeHeadersCode, makeLinksCode, makeParametersCode, makePathItemsCode, makeRequestBodiesCode, makeResponsesCode, makeSafeKey, makeSchemaReplacements, makeSecuritySchemesCode, parseOpenAPI, schemaRefToName, toIdentifierPascalCase, toPascalCase, valueToCode };
|
|
785
|
+
export { isRecord, makeAdapter, makeCallbacksCode, makeExamplesCode, makeHeadersCode, makeLinksCode, makeParametersCode, makePathItemsCode, makeRequestBodiesCode, makeResponsesCode, makeSafeKey, makeSchemaDeclarations, makeSchemaReplacements, makeSchemasCode, makeSecuritySchemesCode, parseOpenAPI, schemaImportLine, schemaRefToName, toIdentifierPascalCase, toPascalCase, valueToCode };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oas-truth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "oas-truth is a parser from OpenAPI and TypeSpec to a typed OpenAPI document",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"openapi",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
}
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"schema-to-library": "^0.4.
|
|
31
|
+
"schema-to-library": "^0.4.1"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
34
|
"@apidevtools/swagger-parser": "^13.0.0",
|
|
@@ -39,7 +39,12 @@
|
|
|
39
39
|
"@typespec/openapi3": "1.16.0",
|
|
40
40
|
"@typespec/rest": "0.86.0",
|
|
41
41
|
"@typespec/versioning": "0.86.0",
|
|
42
|
-
"
|
|
42
|
+
"arktype": "^2.2.3",
|
|
43
|
+
"effect": "4.0.0-rc.112",
|
|
44
|
+
"typebox": "^1.3.30",
|
|
45
|
+
"typescript": "^7.0.2",
|
|
46
|
+
"valibot": "^1.5.0",
|
|
47
|
+
"zod": "^4.6.2"
|
|
43
48
|
},
|
|
44
49
|
"peerDependencies": {
|
|
45
50
|
"@apidevtools/swagger-parser": ">=12.0.0 <14.0.0",
|