oas-truth 0.2.0 → 0.4.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 CHANGED
@@ -28,6 +28,41 @@ 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
+ Every other component kind has the same split: `make<Kind>Declarations` returns `{ name,
46
+ varName, fileName, code }` with no import line, and `make<Kind>Code` joins those bodies.
47
+ `makeMediaTypesCode` covers `components.mediaTypes`. `makeSchemaIdentifiers` is the collision
48
+ map (`user` / `User` → `User` / `User2`); `$ref`s resolve through it, so a later collider is
49
+ `User2Schema`.
50
+
51
+ `wrapSchema(expr, slot)` is slot-aware (`response-content`, `request-content`, `header`,
52
+ `parameter`, `media-type`). TypeBox imports from `typebox` and reserves `Compile`. Pass
53
+ `{ ref: true }` to `makeSchemaDeclarations` to register the OpenAPI key — TypeBox writes it
54
+ into the outermost builder options; the other libraries use an outer wrap.
55
+
56
+ ```ts
57
+ import { makeAdapter, makeSchemaDeclarations, makeSchemaIdentifiers } from 'oas-truth'
58
+
59
+ const identifiers = makeSchemaIdentifiers(schemas)
60
+ const declarations = makeSchemaDeclarations(schemas, makeAdapter('arktype'))
61
+ // a cyclic file: import { type, scope } from 'arktype'
62
+ // a non-cyclic file: import { type } from 'arktype'
63
+ const source = `${declarations[0]?.importLine}\n\n${declarations[0]?.code}`
64
+ ```
65
+
31
66
  ## License
32
67
 
33
68
  [MIT](https://github.com/nakita628/oas-truth/blob/main/LICENSE)
package/dist/index.d.ts CHANGED
@@ -502,6 +502,33 @@ 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
+ * Which `schema:` slot a host `wrapSchema` hook is looking at. The second
507
+ * argument is optional so an existing one-argument hook keeps compiling.
508
+ */
509
+ export type SchemaSlot = 'response-content' | 'request-content' | 'header' | 'parameter' | 'media-type';
510
+ /** Optional third argument to `toExpression` — TypeBox puts `ref` in builder options. */
511
+ export type ToExpressionOptions = {
512
+ readonly ref?: string;
513
+ };
514
+ /**
515
+ * Flags `renderImport` uses when the schemas builder needs more than the
516
+ * library's default line — Arktype `scope` for a `$ref` cycle, TypeBox
517
+ * `Static` when type aliases are exported.
518
+ */
519
+ export type RenderImportOptions = {
520
+ readonly cyclic?: boolean;
521
+ readonly exportTypes?: boolean;
522
+ };
523
+ /**
524
+ * How this library's inferred object type differs from a Zod-shaped
525
+ * `prop?: T` literal, so the TS7022 helper matches `cyclicAnnotation` under
526
+ * `exactOptionalPropertyTypes`. Omitted properties keep the Zod form.
527
+ */
528
+ export type CyclicTypeStyle = {
529
+ readonly optionalUndefined?: boolean;
530
+ readonly readonlyArrays?: boolean;
531
+ };
505
532
  /**
506
533
  * The minimal surface the component generators consume from a validator
507
534
  * adapter. Each library's full adapter (carrying `toNamedExport`,
@@ -510,34 +537,45 @@ export type SchemaLib = 'zod' | 'valibot' | 'arktype' | 'effect' | 'typebox';
510
537
  * required without a cast.
511
538
  *
512
539
  * `wrapSchema` is an optional host hook applied to every `schema:` slot
513
- * expression (inline and `$ref` alike). A host that needs to transform the
514
- * expression — e.g. hono-openapi wrapping it in `resolver(...)` — supplies it;
515
- * omitting it leaves the expression untouched (identity), so the shared library
516
- * stays framework-agnostic.
540
+ * expression (inline and `$ref` alike). The second argument is the slot so a
541
+ * host can wrap response content and leave header schemas plain. Omitting the
542
+ * hook leaves the expression untouched (identity), so the shared library stays
543
+ * framework-agnostic.
544
+ *
545
+ * `withRef` is the library-specific outer wrap for a component name
546
+ * (`.meta({ref})`, `v.metadata`, `.configure({ref})`, `.annotate({identifier})`).
547
+ * TypeBox has no post-construction wrap: pass `ref` to `toExpression` instead.
517
548
  *
518
549
  * Cycle handling lives next to each library: `wrapLazy` re-wraps a `$ref`
519
550
  * inside a strongly connected component (Zod, Valibot, Effect);
520
551
  * `cyclicAnnotation` is the TS7022 annotation on that declaration;
552
+ * `cyclicTypeStyle` is the helper type that annotation names;
521
553
  * `renderCyclic` post-processes the `$defs` container TypeBox and Arktype
522
554
  * need (`Type.Cyclic` is already the expression; Arktype extracts `scope`).
523
555
  */
524
556
  export type ComponentAdapter = {
525
- readonly renderImport: () => string;
526
- readonly toExpression: (schema: Schema, paramIn?: ParamIn) => string;
557
+ readonly renderImport: (options?: RenderImportOptions) => string;
558
+ readonly toExpression: (schema: Schema, paramIn?: ParamIn, options?: ToExpressionOptions) => string;
527
559
  readonly renderTypeInfer: (constName: string) => string;
528
- readonly wrapSchema?: (expr: string) => string;
560
+ readonly wrapSchema?: (expr: string, slot?: SchemaSlot) => string;
561
+ readonly withRef?: (expr: string, ref: string) => string;
529
562
  readonly wrapLazy?: (varName: string) => string;
530
563
  readonly cyclicAnnotation?: (typeName: string) => string;
564
+ readonly cyclicTypeStyle?: CyclicTypeStyle;
531
565
  readonly renderCyclic?: (varName: string, containerExpr: string, externals: readonly string[]) => string;
532
566
  readonly reservedTypeNames?: readonly string[];
533
567
  };
534
568
  export declare function makeAdapter(lib: SchemaLib): ComponentAdapter;
535
569
  //#endregion
536
570
  //#region src/helper/ref-resolver.d.ts
537
- export declare function valueToCode(value: unknown, codeReplacements?: ReadonlyMap<unknown, string>): string;
571
+ export declare function valueToCode(value: unknown, codeReplacements?: ReadonlyMap<unknown, string>, identifiers?: ReadonlyMap<string, string>): string;
538
572
  //#endregion
539
573
  //#region src/helper/schema-replacements.d.ts
540
- export declare function makeSchemaReplacements(value: unknown, adapter: ComponentAdapter): ReadonlyMap<unknown, string>;
574
+ type SchemaReplacementsOptions = {
575
+ readonly slot?: SchemaSlot;
576
+ readonly identifiers?: ReadonlyMap<string, string>;
577
+ };
578
+ export declare function makeSchemaReplacements(value: unknown, adapter: ComponentAdapter, options?: SchemaReplacementsOptions): ReadonlyMap<unknown, string>;
541
579
  //#endregion
542
580
  //#region src/utils/index.d.ts
543
581
  export declare function toPascalCase(str: string): string;
@@ -554,6 +592,24 @@ export declare function schemaRefToName(ref: string): string;
554
592
  * injectively so distinct names never collide.
555
593
  */
556
594
  export declare function toIdentifierPascalCase(name: string): string;
595
+ /**
596
+ * `toIdentifierPascalCase` folds `user` and `User` into one identifier; later
597
+ * colliders get a numeric suffix so no declaration is lost. The map is
598
+ * `OpenAPI key → identifier` (`user` → `User`, `User` → `User2`).
599
+ */
600
+ export declare function makeSchemaIdentifiers(schemas: {
601
+ readonly [k: string]: unknown;
602
+ }): Map<string, string>;
603
+ /** Lowercase the first character for a split-file name (`User` → `user`). */
604
+ export declare function declarationFileName(ident: string): string;
605
+ /**
606
+ * Resolve a `#/components/schemas/...` `$ref` to its generated schema variable
607
+ * identifier (`UserSchema`), or `undefined` when the ref does not point at a
608
+ * component schema. Shared by ref-resolver and schema-replacements. Pass the
609
+ * collision map from `makeSchemaIdentifiers` so a later collider resolves to
610
+ * the suffixed name (`User` → `User2Schema`).
611
+ */
612
+ export declare function makeSchemaVarName(ref: string, identifiers?: ReadonlyMap<string, string>): string | undefined;
557
613
  /**
558
614
  * Encode a property key for object-literal output: bare identifiers stay
559
615
  * unquoted, everything else is JSON-encoded so hyphenated/reserved/numeric
@@ -565,28 +621,53 @@ export declare function isRecord(v: unknown): v is {
565
621
  readonly [k: string]: unknown;
566
622
  };
567
623
  //#endregion
624
+ //#region src/generator/components/declaration.d.ts
625
+ type ComponentDeclaration = {
626
+ readonly name: string;
627
+ readonly varName: string;
628
+ readonly fileName: string;
629
+ readonly code: string;
630
+ };
631
+ type ComponentCodeOptions = {
632
+ readonly exportTypes?: boolean;
633
+ readonly readonly?: boolean;
634
+ readonly identifiers?: ReadonlyMap<string, string>;
635
+ };
636
+ //#endregion
568
637
  //#region src/generator/components/callbacks.d.ts
638
+ export declare function makeCallbacksDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
569
639
  export declare function makeCallbacksCode(components: Components, adapter: ComponentAdapter, readonly: boolean): string;
570
640
  //#endregion
571
641
  //#region src/generator/components/examples.d.ts
642
+ export declare function makeExamplesDeclarations(components: Components, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
572
643
  export declare function makeExamplesCode(components: Components, readonly: boolean): string;
573
644
  //#endregion
574
645
  //#region src/generator/components/headers.d.ts
646
+ export declare function makeHeadersDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
575
647
  export declare function makeHeadersCode(components: Components, adapter: ComponentAdapter, exportTypes?: boolean): string;
576
648
  //#endregion
577
649
  //#region src/generator/components/links.d.ts
650
+ export declare function makeLinksDeclarations(components: Components, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
578
651
  export declare function makeLinksCode(components: Components, readonly: boolean): string;
579
652
  //#endregion
653
+ //#region src/generator/components/media-types.d.ts
654
+ export declare function makeMediaTypesDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
655
+ export declare function makeMediaTypesCode(components: Components, adapter: ComponentAdapter, exportTypes?: boolean): string;
656
+ //#endregion
580
657
  //#region src/generator/components/parameters.d.ts
658
+ export declare function makeParametersDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
581
659
  export declare function makeParametersCode(components: Components, adapter: ComponentAdapter, exportTypes?: boolean): string;
582
660
  //#endregion
583
661
  //#region src/generator/components/path-items.d.ts
662
+ export declare function makePathItemsDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
584
663
  export declare function makePathItemsCode(components: Components, adapter: ComponentAdapter, readonly: boolean): string;
585
664
  //#endregion
586
665
  //#region src/generator/components/request-bodies.d.ts
666
+ export declare function makeRequestBodiesDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
587
667
  export declare function makeRequestBodiesCode(components: Components, adapter: ComponentAdapter, readonly: boolean): string;
588
668
  //#endregion
589
669
  //#region src/generator/components/responses.d.ts
670
+ export declare function makeResponsesDeclarations(components: Components, adapter: ComponentAdapter, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
590
671
  export declare function makeResponsesCode(components: Components, adapter: ComponentAdapter, readonly: boolean): string;
591
672
  //#endregion
592
673
  //#region src/generator/components/schemas.d.ts
@@ -598,18 +679,45 @@ type SchemasOptions = {
598
679
  * builders (`UserSchema`); `key` uses the OpenAPI key (`User`).
599
680
  */
600
681
  readonly typeAlias?: 'const' | 'key';
682
+ /**
683
+ * Shape of the TS7022 helper type. `'library'` (default) matches what the
684
+ * validator infers, so `v.GenericSchema<Helper>` / `Schema.Codec<Helper>`
685
+ * type-check under `exactOptionalPropertyTypes`. `'literal'` is the
686
+ * Zod-shaped `prop?: T` form for every library.
687
+ */
688
+ readonly cyclicTypeStyle?: 'library' | 'literal';
601
689
  /**
602
690
  * Host hook around each declaration expression — e.g. hono-openapi ref
603
- * registration. Applied after cycle handling.
691
+ * registration. Applied after cycle handling. Wins over `ref`.
604
692
  */
605
693
  readonly wrapDeclaration?: (expr: string, name: string) => string;
694
+ /**
695
+ * Register the OpenAPI key on each declaration. TypeBox puts it in the
696
+ * outermost builder options via schema-to-library; the other libraries use
697
+ * `adapter.withRef` (an outer wrap). A bare identifier is left unchanged.
698
+ */
699
+ readonly ref?: boolean;
606
700
  };
607
701
  type SchemaDeclaration = {
608
702
  readonly name: string;
609
703
  readonly varName: string;
610
704
  readonly fileName: string;
705
+ /**
706
+ * The library import this declaration needs when written to its own file.
707
+ * An Arktype cycle that is only `scope({...}).export().Member` gets
708
+ * `import { type, scope } from 'arktype'`; a non-cyclic file stays
709
+ * `import { type } from 'arktype'`.
710
+ */
711
+ readonly importLine: string;
611
712
  readonly code: string;
612
713
  };
714
+ /**
715
+ * The import line a schemas file needs. `cyclic` is true when this file (or
716
+ * the bundled document) contains an Arktype `scope` / TypeBox container
717
+ * cycle — split files that are only `scope({...}).export().Member` still
718
+ * have to import `scope`.
719
+ */
720
+ export declare function schemaImportLine(adapter: ComponentAdapter, options?: SchemasOptions, cyclic?: boolean): string;
613
721
  /**
614
722
  * One `export const <X>Schema=...` declaration per `components.schemas` entry,
615
723
  * in dependency-first order. Only references inside a `$ref` cycle are lazy
@@ -622,6 +730,7 @@ export declare function makeSchemaDeclarations(schemas: {
622
730
  name: string;
623
731
  varName: string;
624
732
  fileName: string;
733
+ importLine: string;
625
734
  code: string;
626
735
  }[];
627
736
  /**
@@ -631,6 +740,7 @@ export declare function makeSchemaDeclarations(schemas: {
631
740
  export declare function makeSchemasCode(components: Components, adapter: ComponentAdapter, options?: SchemasOptions): string;
632
741
  //#endregion
633
742
  //#region src/generator/components/security-schemes.d.ts
743
+ export declare function makeSecuritySchemesDeclarations(components: Components, options?: ComponentCodeOptions): readonly ComponentDeclaration[];
634
744
  export declare function makeSecuritySchemesCode(components: Components, readonly: boolean): string;
635
745
  //#endregion
636
- export type { SchemaDeclaration, SchemasOptions };
746
+ export type { ComponentCodeOptions, ComponentDeclaration, SchemaDeclaration, SchemasOptions };
package/dist/index.js CHANGED
@@ -36,6 +36,10 @@ async function parseOpenAPI(input) {
36
36
  }
37
37
  //#endregion
38
38
  //#region src/adapter/index.ts
39
+ /** A generated identifier (`TagSchema`) is already a registered name — do not wrap it. */
40
+ function isBareIdent(expr) {
41
+ return /^[A-Za-z_$][\w$]*$/u.test(expr);
42
+ }
39
43
  /**
40
44
  * Widen the rich `Schema` type to a bare JSON-Schema object for schema-to-library.
41
45
  * `Schema` is not structurally assignable to its `JSONSchema` (e.g. `x-emailPattern`
@@ -105,6 +109,9 @@ function makeZodAdapter() {
105
109
  },
106
110
  cyclicAnnotation(typeName) {
107
111
  return `z.ZodType<${typeName}>`;
112
+ },
113
+ withRef(expr, ref) {
114
+ return isBareIdent(expr) ? expr : `${expr}.meta({ref:${JSON.stringify(ref)}})`;
108
115
  }
109
116
  };
110
117
  }
@@ -129,6 +136,10 @@ function makeValibotAdapter() {
129
136
  },
130
137
  cyclicAnnotation(typeName) {
131
138
  return `v.GenericSchema<${typeName}>`;
139
+ },
140
+ cyclicTypeStyle: { optionalUndefined: true },
141
+ withRef(expr, ref) {
142
+ return isBareIdent(expr) ? expr : `v.pipe(${expr},v.metadata({ref:${JSON.stringify(ref)}}))`;
132
143
  }
133
144
  };
134
145
  }
@@ -142,28 +153,32 @@ function makeArktypeAdapter() {
142
153
  ...paramIn && { paramIn }
143
154
  }));
144
155
  },
145
- renderImport() {
146
- return "import { type } from 'arktype'";
156
+ renderImport(options) {
157
+ return options?.cyclic === true ? "import { type, scope } from 'arktype'" : "import { type } from 'arktype'";
147
158
  },
148
159
  renderTypeInfer(constName) {
149
160
  return `export type ${constName}=typeof ${constName}.infer`;
150
161
  },
151
162
  renderCyclic: renderArktypeCyclic,
152
- reservedTypeNames: ["type", "scope"]
163
+ reservedTypeNames: ["type", "scope"],
164
+ withRef(expr, ref) {
165
+ return isBareIdent(expr) ? expr : `${expr}.configure({ref:${JSON.stringify(ref)}})`;
166
+ }
153
167
  };
154
168
  }
155
169
  function makeTypeboxAdapter() {
156
170
  return {
157
- toExpression(schema, paramIn) {
171
+ toExpression(schema, paramIn, options) {
158
172
  return extractExpr(schemaToTypebox(toJsonSchema(schema), {
159
173
  exportType: false,
160
174
  openapi: true,
161
175
  readonly: false,
162
- ...paramIn && { paramIn }
176
+ ...paramIn && { paramIn },
177
+ ...options?.ref !== void 0 && { ref: options.ref }
163
178
  }));
164
179
  },
165
- renderImport() {
166
- return "import { Type } from '@sinclair/typebox'";
180
+ renderImport(options) {
181
+ return options?.exportTypes === true ? "import { Type, type Static } from 'typebox'" : "import { Type } from 'typebox'";
167
182
  },
168
183
  renderTypeInfer(constName) {
169
184
  return `export type ${constName}=Static<typeof ${constName}>`;
@@ -171,7 +186,8 @@ function makeTypeboxAdapter() {
171
186
  reservedTypeNames: [
172
187
  "Type",
173
188
  "Static",
174
- "Codec"
189
+ "Codec",
190
+ "Compile"
175
191
  ]
176
192
  };
177
193
  }
@@ -194,10 +210,17 @@ function makeEffectAdapter() {
194
210
  wrapLazy(varName) {
195
211
  return `Schema.suspend(() => ${varName})`;
196
212
  },
197
- cyclicAnnotation() {
198
- return "Schema.Codec<any>";
213
+ cyclicAnnotation(typeName) {
214
+ return `Schema.Codec<${typeName}>`;
199
215
  },
200
- reservedTypeNames: ["Schema", "Effect"]
216
+ cyclicTypeStyle: {
217
+ optionalUndefined: true,
218
+ readonlyArrays: true
219
+ },
220
+ reservedTypeNames: ["Schema", "Effect"],
221
+ withRef(expr, ref) {
222
+ return isBareIdent(expr) ? expr : `${expr}.annotate({identifier:${JSON.stringify(ref)}})`;
223
+ }
201
224
  };
202
225
  }
203
226
  //#endregion
@@ -249,14 +272,36 @@ function toIdentifierPascalCase(name) {
249
272
  return result;
250
273
  }
251
274
  /**
275
+ * `name`, or the first of `name2`, `name3`, … not in `used`.
276
+ */
277
+ function claimName(name, used, i = 2) {
278
+ if (!used.has(name)) return name;
279
+ return used.has(`${name}${i}`) ? claimName(name, used, i + 1) : `${name}${i}`;
280
+ }
281
+ /**
282
+ * `toIdentifierPascalCase` folds `user` and `User` into one identifier; later
283
+ * colliders get a numeric suffix so no declaration is lost. The map is
284
+ * `OpenAPI key → identifier` (`user` → `User`, `User` → `User2`).
285
+ */
286
+ function makeSchemaIdentifiers(schemas) {
287
+ return Object.keys(schemas).reduce((acc, key) => acc.set(key, claimName(toIdentifierPascalCase(key), new Set(acc.values()))), /* @__PURE__ */ new Map());
288
+ }
289
+ /** Lowercase the first character for a split-file name (`User` → `user`). */
290
+ function declarationFileName(ident) {
291
+ return `${ident.charAt(0).toLowerCase()}${ident.slice(1)}`;
292
+ }
293
+ /**
252
294
  * Resolve a `#/components/schemas/...` `$ref` to its generated schema variable
253
295
  * identifier (`UserSchema`), or `undefined` when the ref does not point at a
254
- * component schema. Shared by ref-resolver and schema-replacements.
296
+ * component schema. Shared by ref-resolver and schema-replacements. Pass the
297
+ * collision map from `makeSchemaIdentifiers` so a later collider resolves to
298
+ * the suffixed name (`User` → `User2Schema`).
255
299
  */
256
- function makeSchemaVarName(ref) {
300
+ function makeSchemaVarName(ref, identifiers) {
257
301
  const name = ref.match(/^#\/components\/schemas\/(.+)$/u)?.[1];
258
302
  if (name === void 0) return void 0;
259
- return `${toIdentifierPascalCase(safeDecode(name))}Schema`;
303
+ const key = safeDecode(name);
304
+ return `${identifiers?.get(key) ?? toIdentifierPascalCase(key)}Schema`;
260
305
  }
261
306
  /**
262
307
  * Encode a property key for object-literal output: bare identifiers stay
@@ -272,10 +317,10 @@ function isRecord(v) {
272
317
  }
273
318
  //#endregion
274
319
  //#region src/helper/ref-resolver.ts
275
- function valueToCode(value, codeReplacements) {
276
- return encodeValue(value, codeReplacements, /* @__PURE__ */ new Set());
320
+ function valueToCode(value, codeReplacements, identifiers) {
321
+ return encodeValue(value, codeReplacements, identifiers, /* @__PURE__ */ new Set());
277
322
  }
278
- function encodeValue(value, codeReplacements, seen) {
323
+ function encodeValue(value, codeReplacements, identifiers, seen) {
279
324
  const replacement = codeReplacements?.get(value);
280
325
  if (replacement !== void 0) return replacement;
281
326
  if (value === null) return "null";
@@ -287,19 +332,19 @@ function encodeValue(value, codeReplacements, seen) {
287
332
  if (Array.isArray(value)) {
288
333
  if (seen.has(value)) return "null";
289
334
  seen.add(value);
290
- const code = `[${value.map((v) => encodeValue(v, codeReplacements, seen)).join(",")}]`;
335
+ const code = `[${value.map((v) => encodeValue(v, codeReplacements, identifiers, seen)).join(",")}]`;
291
336
  seen.delete(value);
292
337
  return code;
293
338
  }
294
339
  if (isRecord(value)) {
295
340
  if (seen.has(value)) return "null";
296
341
  if ("$ref" in value && typeof value.$ref === "string") {
297
- const varName = makeSchemaVarName(value.$ref);
342
+ const varName = makeSchemaVarName(value.$ref, identifiers);
298
343
  if (varName) return varName;
299
344
  }
300
345
  seen.add(value);
301
346
  const entries = Object.entries(value).map(([k, v]) => {
302
- return `${/^[a-zA-Z_$][a-zA-Z0-9_$]*$/u.test(k) ? k : JSON.stringify(k)}:${encodeValue(v, codeReplacements, seen)}`;
347
+ return `${/^[a-zA-Z_$][a-zA-Z0-9_$]*$/u.test(k) ? k : JSON.stringify(k)}:${encodeValue(v, codeReplacements, identifiers, seen)}`;
303
348
  });
304
349
  seen.delete(value);
305
350
  return `{${entries.join(",")}}`;
@@ -313,135 +358,261 @@ function isInlineSchema(value) {
313
358
  if ("$ref" in value) return false;
314
359
  return "type" in value || "properties" in value || "items" in value || "oneOf" in value || "anyOf" in value || "allOf" in value || "enum" in value || "const" in value || "not" in value;
315
360
  }
316
- function makeSchemaReplacements(value, adapter) {
317
- return new Map(makeEntries(value, adapter, /* @__PURE__ */ new Set()));
361
+ function slotAt(path, fallback) {
362
+ if (path.includes("headers")) return "header";
363
+ if (path.includes("parameters")) return "parameter";
364
+ if (path.includes("content")) return fallback ?? "response-content";
365
+ return fallback ?? "media-type";
318
366
  }
319
- function makeEntries(v, adapter, seen, parentKey) {
367
+ function makeSchemaReplacements(value, adapter, options) {
368
+ return new Map(makeEntries(value, adapter, /* @__PURE__ */ new Set(), [], options));
369
+ }
370
+ function makeEntries(v, adapter, seen, path, options) {
320
371
  if (v === null || v === void 0 || typeof v !== "object") return [];
321
372
  if (seen.has(v)) return [];
322
- const wrap = adapter.wrapSchema ?? ((expr) => expr);
323
- if (parentKey === "schema") {
373
+ const wrap = (expr) => adapter.wrapSchema ? adapter.wrapSchema(expr, slotAt(path, options?.slot)) : expr;
374
+ if (path.at(-1) === "schema") {
324
375
  if (isInlineSchema(v)) return [[v, wrap(adapter.toExpression(v))]];
325
376
  if (isRecord(v) && typeof v.$ref === "string") {
326
- const varName = makeSchemaVarName(v.$ref);
377
+ const varName = makeSchemaVarName(v.$ref, options?.identifiers);
327
378
  if (varName) return [[v, wrap(varName)]];
328
379
  }
329
380
  }
330
381
  seen.add(v);
331
- const entries = Array.isArray(v) ? v.flatMap((item) => makeEntries(item, adapter, seen)) : isRecord(v) ? Object.entries(v).flatMap(([k, child]) => makeEntries(child, adapter, seen, k)) : [];
382
+ const entries = Array.isArray(v) ? v.flatMap((item) => makeEntries(item, adapter, seen, path, options)) : isRecord(v) ? Object.entries(v).flatMap(([k, child]) => makeEntries(child, adapter, seen, [...path, k], options)) : [];
332
383
  seen.delete(v);
333
384
  return entries;
334
385
  }
335
386
  //#endregion
387
+ //#region src/generator/components/declaration.ts
388
+ /**
389
+ * Join declaration bodies the way `make<Kind>Code` already does: `;` between
390
+ * entries, no `import ` line. `trailingNewline` matches examples / links /
391
+ * security-schemes / parameters / headers.
392
+ */
393
+ function joinDeclarations(declarations, options) {
394
+ if (declarations.length === 0) return "";
395
+ const body = declarations.map((d) => d.code).join(";");
396
+ const text = options?.trailingNewline === true ? `${body}\n` : body;
397
+ return options?.importLine === void 0 ? text : `${options.importLine}\n\n${text}`;
398
+ }
399
+ //#endregion
336
400
  //#region src/generator/components/callbacks.ts
337
- function makeCallbacksCode(components, adapter, readonly) {
401
+ function makeCallbacksDeclarations(components, adapter, options) {
338
402
  const { callbacks } = components;
339
- if (!callbacks) return "";
340
- const entries = Object.entries(callbacks);
341
- if (entries.length === 0) return "";
342
- const asConst = readonly ? " as const" : "";
343
- const exports = entries.filter(([, callback]) => !("$ref" in callback && callback.$ref)).map(([name, callback]) => {
344
- return `export const ${`${toIdentifierPascalCase(name)}Callback`}=${valueToCode(callback, makeSchemaReplacements(callback, adapter))}${asConst}`;
345
- }).filter(Boolean);
346
- if (exports.length === 0) return "";
347
- return exports.join(";");
403
+ if (!callbacks) return [];
404
+ const asConst = options?.readonly === true ? " as const" : "";
405
+ return Object.entries(callbacks).flatMap(([name, callback]) => {
406
+ if ("$ref" in callback && callback.$ref) return [];
407
+ const ident = toIdentifierPascalCase(name);
408
+ const varName = `${ident}Callback`;
409
+ const replacements = makeSchemaReplacements(callback, adapter, {
410
+ slot: "response-content",
411
+ ...options?.identifiers && { identifiers: options.identifiers }
412
+ });
413
+ return [{
414
+ name,
415
+ varName,
416
+ fileName: declarationFileName(ident),
417
+ code: `export const ${varName}=${valueToCode(callback, replacements, options?.identifiers)}${asConst}`
418
+ }];
419
+ });
420
+ }
421
+ function makeCallbacksCode(components, adapter, readonly) {
422
+ return joinDeclarations(makeCallbacksDeclarations(components, adapter, { readonly }));
348
423
  }
349
424
  //#endregion
350
425
  //#region src/generator/components/examples.ts
351
- function makeExamplesCode(components, readonly) {
426
+ function makeExamplesDeclarations(components, options) {
352
427
  const { examples } = components;
353
- if (!examples) return "";
354
- const entries = Object.entries(examples);
355
- if (entries.length === 0) return "";
356
- const asConst = readonly ? " as const" : "";
357
- return `${entries.map(([name, example]) => {
358
- return `export const ${`${toIdentifierPascalCase(name)}Example`}=${valueToCode(example)}${asConst}`;
359
- }).join(";")}\n`;
428
+ if (!examples) return [];
429
+ const asConst = options?.readonly === true ? " as const" : "";
430
+ return Object.entries(examples).map(([name, example]) => {
431
+ const ident = toIdentifierPascalCase(name);
432
+ const varName = `${ident}Example`;
433
+ return {
434
+ name,
435
+ varName,
436
+ fileName: declarationFileName(ident),
437
+ code: `export const ${varName}=${valueToCode(example)}${asConst}`
438
+ };
439
+ });
440
+ }
441
+ function makeExamplesCode(components, readonly) {
442
+ return joinDeclarations(makeExamplesDeclarations(components, { readonly }), { trailingNewline: true });
360
443
  }
361
444
  //#endregion
362
445
  //#region src/generator/components/headers.ts
363
- function makeHeadersCode(components, adapter, exportTypes) {
446
+ function makeHeadersDeclarations(components, adapter, options) {
364
447
  const { headers } = components;
365
- if (!headers) return "";
366
- const entries = Object.entries(headers);
367
- if (entries.length === 0) return "";
368
- const imports = adapter.renderImport();
369
- const exports = entries.map(([name, header]) => {
370
- if (!("schema" in header) || !header.schema) return "";
371
- const constName = `${toIdentifierPascalCase(name)}HeaderSchema`;
372
- return `export const ${constName}=${adapter.toExpression(header.schema)}${exportTypes ? `\n\n${adapter.renderTypeInfer(constName)}` : ""}`;
373
- }).filter(Boolean).join(";");
374
- return exports ? `${imports}\n\n${exports}\n` : "";
448
+ if (!headers) return [];
449
+ return Object.entries(headers).flatMap(([name, header]) => {
450
+ if (!("schema" in header) || !header.schema) return [];
451
+ const ident = toIdentifierPascalCase(name);
452
+ const varName = `${ident}HeaderSchema`;
453
+ const raw = adapter.toExpression(header.schema);
454
+ const expr = adapter.wrapSchema ? adapter.wrapSchema(raw, "header") : raw;
455
+ const typeExport = options?.exportTypes === true ? `\n\n${adapter.renderTypeInfer(varName)}` : "";
456
+ return [{
457
+ name,
458
+ varName,
459
+ fileName: declarationFileName(ident),
460
+ code: `export const ${varName}=${expr}${typeExport}`
461
+ }];
462
+ });
463
+ }
464
+ function makeHeadersCode(components, adapter, exportTypes) {
465
+ return joinDeclarations(makeHeadersDeclarations(components, adapter, exportTypes === true ? { exportTypes: true } : void 0), {
466
+ trailingNewline: true,
467
+ importLine: adapter.renderImport()
468
+ });
375
469
  }
376
470
  //#endregion
377
471
  //#region src/generator/components/links.ts
378
- function makeLinksCode(components, readonly) {
472
+ function makeLinksDeclarations(components, options) {
379
473
  const { links } = components;
380
- if (!links) return "";
381
- const entries = Object.entries(links);
382
- if (entries.length === 0) return "";
383
- const asConst = readonly ? " as const" : "";
384
- return `${entries.map(([name, link]) => {
385
- return `export const ${`${toIdentifierPascalCase(name)}Link`}=${valueToCode(link)}${asConst}`;
386
- }).join(";")}\n`;
474
+ if (!links) return [];
475
+ const asConst = options?.readonly === true ? " as const" : "";
476
+ return Object.entries(links).map(([name, link]) => {
477
+ const ident = toIdentifierPascalCase(name);
478
+ const varName = `${ident}Link`;
479
+ return {
480
+ name,
481
+ varName,
482
+ fileName: declarationFileName(ident),
483
+ code: `export const ${varName}=${valueToCode(link)}${asConst}`
484
+ };
485
+ });
486
+ }
487
+ function makeLinksCode(components, readonly) {
488
+ return joinDeclarations(makeLinksDeclarations(components, { readonly }), { trailingNewline: true });
489
+ }
490
+ //#endregion
491
+ //#region src/generator/components/media-types.ts
492
+ function makeMediaTypesDeclarations(components, adapter, options) {
493
+ const { mediaTypes } = components;
494
+ if (!mediaTypes) return [];
495
+ return Object.entries(mediaTypes).flatMap(([name, media]) => {
496
+ if ("$ref" in media && media.$ref) return [];
497
+ if (!("schema" in media) || !media.schema) return [];
498
+ const ident = toIdentifierPascalCase(name);
499
+ const varName = `${ident}MediaTypeSchema`;
500
+ const raw = adapter.toExpression(media.schema);
501
+ const expr = adapter.wrapSchema ? adapter.wrapSchema(raw, "media-type") : raw;
502
+ const typeExport = options?.exportTypes === true ? `\n\n${adapter.renderTypeInfer(varName)}` : "";
503
+ return [{
504
+ name,
505
+ varName,
506
+ fileName: declarationFileName(ident),
507
+ code: `export const ${varName}=${expr}${typeExport}`
508
+ }];
509
+ });
510
+ }
511
+ function makeMediaTypesCode(components, adapter, exportTypes) {
512
+ return joinDeclarations(makeMediaTypesDeclarations(components, adapter, exportTypes === true ? { exportTypes: true } : void 0), {
513
+ trailingNewline: true,
514
+ importLine: adapter.renderImport()
515
+ });
387
516
  }
388
517
  //#endregion
389
518
  //#region src/generator/components/parameters.ts
390
- function makeParametersCode(components, adapter, exportTypes) {
519
+ function makeParametersDeclarations(components, adapter, options) {
391
520
  const { parameters } = components;
392
- if (!parameters) return "";
393
- const entries = Object.entries(parameters);
394
- if (entries.length === 0) return "";
395
- const imports = adapter.renderImport();
396
- const exports = entries.map(([name, param]) => {
397
- if (!param.schema) return "";
521
+ if (!parameters) return [];
522
+ return Object.entries(parameters).flatMap(([name, param]) => {
523
+ if (!param.schema) return [];
398
524
  const paramIn = param.in === "query" || param.in === "path" ? param.in : void 0;
399
- const constName = `${toIdentifierPascalCase(name)}ParamsSchema`;
400
- return `export const ${constName}=${adapter.toExpression(param.schema, paramIn)}${exportTypes ? `\n\n${adapter.renderTypeInfer(constName)}` : ""}`;
401
- }).filter(Boolean).join(";");
402
- return exports ? `${imports}\n\n${exports}\n` : "";
525
+ const ident = toIdentifierPascalCase(name);
526
+ const varName = `${ident}ParamsSchema`;
527
+ const raw = adapter.toExpression(param.schema, paramIn);
528
+ const expr = adapter.wrapSchema ? adapter.wrapSchema(raw, "parameter") : raw;
529
+ const typeExport = options?.exportTypes === true ? `\n\n${adapter.renderTypeInfer(varName)}` : "";
530
+ return [{
531
+ name,
532
+ varName,
533
+ fileName: declarationFileName(ident),
534
+ code: `export const ${varName}=${expr}${typeExport}`
535
+ }];
536
+ });
537
+ }
538
+ function makeParametersCode(components, adapter, exportTypes) {
539
+ return joinDeclarations(makeParametersDeclarations(components, adapter, exportTypes === true ? { exportTypes: true } : void 0), {
540
+ trailingNewline: true,
541
+ importLine: adapter.renderImport()
542
+ });
403
543
  }
404
544
  //#endregion
405
545
  //#region src/generator/components/path-items.ts
406
- function makePathItemsCode(components, adapter, readonly) {
546
+ function makePathItemsDeclarations(components, adapter, options) {
407
547
  const { pathItems } = components;
408
- if (!pathItems) return "";
409
- const entries = Object.entries(pathItems);
410
- if (entries.length === 0) return "";
411
- const asConst = readonly ? " as const" : "";
412
- const exports = entries.map(([name, pathItem]) => {
413
- return `export const ${`${toIdentifierPascalCase(name)}PathItem`}=${valueToCode(pathItem, makeSchemaReplacements(pathItem, adapter))}${asConst}`;
414
- }).filter(Boolean);
415
- if (exports.length === 0) return "";
416
- return exports.join(";");
548
+ if (!pathItems) return [];
549
+ const asConst = options?.readonly === true ? " as const" : "";
550
+ return Object.entries(pathItems).map(([name, pathItem]) => {
551
+ const ident = toIdentifierPascalCase(name);
552
+ const varName = `${ident}PathItem`;
553
+ const replacements = makeSchemaReplacements(pathItem, adapter, {
554
+ slot: "response-content",
555
+ ...options?.identifiers && { identifiers: options.identifiers }
556
+ });
557
+ return {
558
+ name,
559
+ varName,
560
+ fileName: declarationFileName(ident),
561
+ code: `export const ${varName}=${valueToCode(pathItem, replacements, options?.identifiers)}${asConst}`
562
+ };
563
+ });
564
+ }
565
+ function makePathItemsCode(components, adapter, readonly) {
566
+ return joinDeclarations(makePathItemsDeclarations(components, adapter, { readonly }));
417
567
  }
418
568
  //#endregion
419
569
  //#region src/generator/components/request-bodies.ts
420
- function makeRequestBodiesCode(components, adapter, readonly) {
570
+ function makeRequestBodiesDeclarations(components, adapter, options) {
421
571
  const { requestBodies } = components;
422
- if (!requestBodies) return "";
423
- const entries = Object.entries(requestBodies);
424
- if (entries.length === 0) return "";
425
- const asConst = readonly ? " as const" : "";
426
- const exports = entries.map(([name, body]) => {
427
- return `export const ${`${toIdentifierPascalCase(name)}RequestBody`}=${valueToCode(body, makeSchemaReplacements(body, adapter))}${asConst}`;
428
- }).filter(Boolean);
429
- if (exports.length === 0) return "";
430
- return exports.join(";");
572
+ if (!requestBodies) return [];
573
+ const asConst = options?.readonly === true ? " as const" : "";
574
+ return Object.entries(requestBodies).map(([name, body]) => {
575
+ const ident = toIdentifierPascalCase(name);
576
+ const varName = `${ident}RequestBody`;
577
+ const replacements = makeSchemaReplacements(body, adapter, {
578
+ slot: "request-content",
579
+ ...options?.identifiers && { identifiers: options.identifiers }
580
+ });
581
+ return {
582
+ name,
583
+ varName,
584
+ fileName: declarationFileName(ident),
585
+ code: `export const ${varName}=${valueToCode(body, replacements, options?.identifiers)}${asConst}`
586
+ };
587
+ });
588
+ }
589
+ function makeRequestBodiesCode(components, adapter, readonly) {
590
+ return joinDeclarations(makeRequestBodiesDeclarations(components, adapter, { readonly }));
431
591
  }
432
592
  //#endregion
433
593
  //#region src/generator/components/responses.ts
434
- function makeResponsesCode(components, adapter, readonly) {
594
+ function makeResponsesDeclarations(components, adapter, options) {
435
595
  const { responses } = components;
436
- if (!responses) return "";
437
- const entries = Object.entries(responses);
438
- if (entries.length === 0) return "";
439
- const asConst = readonly ? " as const" : "";
440
- const exports = entries.filter(([, response]) => !("$ref" in response && response.$ref)).map(([name, response]) => {
441
- return `export const ${`${toIdentifierPascalCase(name)}Response`}=${valueToCode(response, makeSchemaReplacements(response, adapter))}${asConst}`;
442
- }).filter(Boolean);
443
- if (exports.length === 0) return "";
444
- return exports.join(";");
596
+ if (!responses) return [];
597
+ const asConst = options?.readonly === true ? " as const" : "";
598
+ return Object.entries(responses).flatMap(([name, response]) => {
599
+ if ("$ref" in response && response.$ref) return [];
600
+ const ident = toIdentifierPascalCase(name);
601
+ const varName = `${ident}Response`;
602
+ const replacements = makeSchemaReplacements(response, adapter, {
603
+ slot: "response-content",
604
+ ...options?.identifiers && { identifiers: options.identifiers }
605
+ });
606
+ return [{
607
+ name,
608
+ varName,
609
+ fileName: declarationFileName(ident),
610
+ code: `export const ${varName}=${valueToCode(response, replacements, options?.identifiers)}${asConst}`
611
+ }];
612
+ });
613
+ }
614
+ function makeResponsesCode(components, adapter, readonly) {
615
+ return joinDeclarations(makeResponsesDeclarations(components, adapter, { readonly }));
445
616
  }
446
617
  //#endregion
447
618
  //#region src/helper/graph.ts
@@ -487,8 +658,8 @@ function analyzeSchemas(schemas) {
487
658
  cycles
488
659
  };
489
660
  }
490
- function makeTypeString(schema, self, infer, readonly) {
491
- const recurse = (s) => makeTypeString(s, self, infer, readonly);
661
+ function makeTypeString(schema, self, infer, readonly, style) {
662
+ const recurse = (s) => makeTypeString(s, self, infer, readonly, style);
492
663
  const ro = readonly ? "readonly " : "";
493
664
  if (schema.$ref) {
494
665
  const name = schemaRefToName(schema.$ref);
@@ -501,6 +672,8 @@ function makeTypeString(schema, self, infer, readonly) {
501
672
  if (schema.const !== void 0) return JSON.stringify(schema.const);
502
673
  const types = schema.type === void 0 ? ["object"] : [schema.type].flat();
503
674
  const nullable = schema.nullable === true || types.includes("null");
675
+ const arrayRo = readonly || style.readonlyArrays === true ? "readonly " : "";
676
+ const optionalUndef = style.optionalUndefined === true ? "|undefined" : "";
504
677
  const base = types.filter((type) => type !== "null").map((type) => {
505
678
  if (type === "string") return "string";
506
679
  if (type === "number" || type === "integer") return "number";
@@ -508,10 +681,13 @@ function makeTypeString(schema, self, infer, readonly) {
508
681
  if (type === "array") {
509
682
  const items = schema.items;
510
683
  const item = isRecord(items) ? recurse(items) : "unknown";
511
- return `${ro}(${item})[]`;
684
+ return `${arrayRo}(${item})[]`;
512
685
  }
513
686
  if (type === "object") {
514
- const props = Object.entries(schema.properties ?? {}).map(([key, prop]) => `${ro}${JSON.stringify(key)}${schema.required?.includes(key) ? "" : "?"}:${recurse(prop)}`);
687
+ const props = Object.entries(schema.properties ?? {}).map(([key, prop]) => {
688
+ const required = schema.required?.includes(key) === true;
689
+ return `${ro}${JSON.stringify(key)}${required ? "" : "?"}:${recurse(prop)}${required ? "" : optionalUndef}`;
690
+ });
515
691
  const extra = isRecord(schema.additionalProperties) ? [`${ro}[key:string]:${recurse(schema.additionalProperties)}`] : props.length === 0 ? [`${ro}[key:string]:unknown`] : [];
516
692
  return `{${[...props, ...extra].join(";")}}`;
517
693
  }
@@ -523,13 +699,15 @@ function makeTypeString(schema, self, infer, readonly) {
523
699
  /**
524
700
  * The TypeScript shape of a recursive schema, so its declaration can carry an
525
701
  * explicit `z.ZodType<XType>` / `v.GenericSchema<XType>` annotation (TS7022).
526
- * References to other schemas go through their inferred types.
702
+ * References to other schemas go through their inferred types. `style` is the
703
+ * library's inferred object type (Valibot `| undefined`, Effect `readonly`
704
+ * arrays) so the annotation type-checks under `exactOptionalPropertyTypes`.
527
705
  */
528
- function makeCyclicType(name, typeName, schema, infer, readonly) {
706
+ function makeCyclicType(name, typeName, schema, infer, readonly, style = {}) {
529
707
  return `type ${typeName}=${makeTypeString(schema, {
530
708
  name,
531
709
  typeName
532
- }, infer, readonly)}`;
710
+ }, infer, readonly, style)}`;
533
711
  }
534
712
  //#endregion
535
713
  //#region src/helper/identifiers.ts
@@ -594,19 +772,6 @@ function wrapReferences(expr, names, wrap) {
594
772
  }
595
773
  //#endregion
596
774
  //#region src/generator/components/schemas.ts
597
- /** `name`, or the first of `name2`, `name3`, … not in `used`. */
598
- function claimName(name, used, i = 2) {
599
- if (!used.has(name)) return name;
600
- return used.has(`${name}${i}`) ? claimName(name, used, i + 1) : `${name}${i}`;
601
- }
602
- /**
603
- * `toIdentifierPascalCase` folds `user` and `User` into one identifier; later
604
- * colliders get a numeric suffix so no declaration is lost. A `$ref` to a later
605
- * collider still resolves to the first declaration.
606
- */
607
- function makeSchemaIdentifiers(schemas) {
608
- return Object.keys(schemas).reduce((acc, key) => acc.set(key, claimName(toIdentifierPascalCase(key), new Set(acc.values()))), /* @__PURE__ */ new Map());
609
- }
610
775
  /** Keys whose value is a subschema (or a list of them) and keys whose value maps names to subschemas. */
611
776
  const SUBSCHEMA_KEYS = /* @__PURE__ */ new Set([
612
777
  "items",
@@ -662,33 +827,52 @@ function markReadonly(schema) {
662
827
  * becomes one `Type.Cyclic(...)` / `scope(...)` container and each member selects
663
828
  * its entry. schema-to-library builds the container from a `$defs` document.
664
829
  */
665
- function makeCyclicContainer(varName, group, schemas, identifiers, adapter) {
830
+ function rewriteCollisionRef(node, identifiers) {
831
+ if (typeof node.$ref !== "string" || !node.$ref.startsWith("#/components/schemas/")) return node;
832
+ const key = schemaRefToName(node.$ref);
833
+ const ident = identifiers.get(key);
834
+ if (ident === void 0 || ident === toIdentifierPascalCase(key)) return node;
835
+ return {
836
+ ...node,
837
+ $ref: `#/components/schemas/${ident}`
838
+ };
839
+ }
840
+ function makeCyclicContainer(varName, group, schemas, identifiers, adapter, ref) {
666
841
  const groupIdentifiers = new Map(group.map((name) => [name, identifiers.get(name) ?? name]));
667
842
  const localize = (node) => {
668
- const ident = node.$ref ? groupIdentifiers.get(schemaRefToName(node.$ref)) : void 0;
669
- if (ident === void 0) return node;
670
- const local = Object.fromEntries([...Object.entries(node), ["$ref", `#/$defs/${ident}Schema`]]);
671
- return isSchema(local) ? local : node;
843
+ const key = node.$ref ? schemaRefToName(node.$ref) : void 0;
844
+ if (key === void 0) return node;
845
+ const groupIdent = groupIdentifiers.get(key);
846
+ if (groupIdent !== void 0) {
847
+ const local = Object.fromEntries([...Object.entries(node), ["$ref", `#/$defs/${groupIdent}Schema`]]);
848
+ return isSchema(local) ? local : node;
849
+ }
850
+ return rewriteCollisionRef(node, identifiers);
672
851
  };
673
852
  const $defs = Object.fromEntries(group.map((name) => [`${groupIdentifiers.get(name)}Schema`, mapSchema(schemas[name] ?? {}, localize)]));
674
853
  return adapter.toExpression({
675
854
  title: varName,
676
855
  $defs
677
- });
856
+ }, void 0, ref === void 0 ? void 0 : { ref });
678
857
  }
679
- function schemaImportLine(adapter, options, hasContainerCycle) {
680
- const line = adapter.renderImport();
681
- if (hasContainerCycle && adapter.renderCyclic && line === "import { type } from 'arktype'") return "import { type, scope } from 'arktype'";
682
- if (options?.exportTypes === true && line === "import { Type } from '@sinclair/typebox'") return "import { Type, type Static } from '@sinclair/typebox'";
683
- return line;
858
+ /**
859
+ * The import line a schemas file needs. `cyclic` is true when this file (or
860
+ * the bundled document) contains an Arktype `scope` / TypeBox container
861
+ * cycle — split files that are only `scope({...}).export().Member` still
862
+ * have to import `scope`.
863
+ */
864
+ function schemaImportLine(adapter, options, cyclic = false) {
865
+ const exportTypes = options?.exportTypes === true;
866
+ if (!cyclic && !exportTypes) return adapter.renderImport();
867
+ return adapter.renderImport({
868
+ ...cyclic && { cyclic: true },
869
+ ...exportTypes && { exportTypes: true }
870
+ });
684
871
  }
685
872
  function exportedTypeName(ident, varName, adapter, options) {
686
873
  if (options?.typeAlias !== "key") return varName;
687
874
  return (adapter.reservedTypeNames ?? []).includes(ident) ? `${ident}Type` : ident;
688
875
  }
689
- function fileNameOf(ident) {
690
- return `${ident.charAt(0).toLowerCase()}${ident.slice(1)}`;
691
- }
692
876
  /**
693
877
  * One `export const <X>Schema=...` declaration per `components.schemas` entry,
694
878
  * in dependency-first order. Only references inside a `$ref` cycle are lazy
@@ -705,32 +889,37 @@ function makeSchemaDeclarations(schemas, adapter, options) {
705
889
  ...adapter.reservedTypeNames ?? []
706
890
  ]);
707
891
  const infer = (varName) => adapter.renderTypeInfer(varName).replace(`export type ${varName}=`, "");
892
+ const style = options?.cyclicTypeStyle === "literal" ? {} : adapter.cyclicTypeStyle ?? {};
893
+ const declarationRef = options?.ref === true;
708
894
  return order.map((name) => {
709
- const schema = prepared[name] ?? {};
895
+ const schema = mapSchema(prepared[name] ?? {}, (node) => rewriteCollisionRef(node, identifiers));
710
896
  const ident = identifiers.get(name) ?? toIdentifierPascalCase(name);
711
897
  const varName = `${ident}Schema`;
712
898
  const group = cycles.get(name);
713
899
  const arktypeReadonly = adapter.renderCyclic !== void 0 && options?.readonly === true;
714
- const container = group && adapter.wrapLazy === void 0 ? makeCyclicContainer(varName, group, arktypeReadonly ? schemas : prepared, identifiers, adapter) : void 0;
900
+ const hostRef = declarationRef ? name : void 0;
901
+ const container = group && adapter.wrapLazy === void 0 ? makeCyclicContainer(varName, group, arktypeReadonly ? schemas : prepared, identifiers, adapter, adapter.withRef === void 0 ? hostRef : void 0) : void 0;
715
902
  const peers = group ?? [];
716
903
  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;
717
904
  const expression = (rendered && arktypeReadonly ? `${rendered}.readonly()` : rendered) ?? adapter.toExpression({
718
905
  ...schema,
719
906
  title: varName
720
- });
907
+ }, void 0, adapter.withRef === void 0 && hostRef !== void 0 ? { ref: hostRef } : void 0);
721
908
  const body = adapter.wrapLazy ? wrapReferences(expression, new Set((group ?? []).map((peer) => `${identifiers.get(peer)}Schema`)), adapter.wrapLazy) : expression;
722
- const value = options?.wrapDeclaration ? options.wrapDeclaration(body, name) : body;
909
+ const value = options?.wrapDeclaration ? options.wrapDeclaration(body, name) : hostRef !== void 0 && adapter.withRef ? adapter.withRef(body, name) : body;
723
910
  const helper = group && adapter.cyclicAnnotation ? claimName(`${ident}Type`, taken) : void 0;
724
911
  const annotationText = helper ? adapter.cyclicAnnotation?.(helper) : void 0;
725
912
  const usesHelper = helper !== void 0 && annotationText?.includes(helper) === true;
726
913
  if (helper && usesHelper) taken.add(helper);
727
- const typeDef = helper && usesHelper ? `${makeCyclicType(name, helper, schema, (ref) => infer(`${identifiers.get(ref) ?? toIdentifierPascalCase(ref)}Schema`), options?.readonly === true)}\n\n` : "";
914
+ const typeDef = helper && usesHelper ? `${makeCyclicType(name, helper, schema, (ref) => infer(`${identifiers.get(ref) ?? toIdentifierPascalCase(ref)}Schema`), options?.readonly === true, style)}\n\n` : "";
728
915
  const annotation = annotationText === void 0 ? "" : `:${annotationText}`;
729
916
  const typeExport = options?.exportTypes === true ? `\n\nexport type ${exportedTypeName(ident, varName, adapter, options)}=${infer(varName)}` : "";
917
+ const containerCycle = group !== void 0 && adapter.wrapLazy === void 0;
730
918
  return {
731
919
  name,
732
920
  varName,
733
- fileName: fileNameOf(ident),
921
+ fileName: declarationFileName(ident),
922
+ importLine: schemaImportLine(adapter, options, containerCycle),
734
923
  code: `${typeDef}export const ${varName}${annotation}=${value}${typeExport}`
735
924
  };
736
925
  });
@@ -744,19 +933,27 @@ function makeSchemasCode(components, adapter, options) {
744
933
  if (!schemas) return "";
745
934
  const declarations = makeSchemaDeclarations(schemas, adapter, options);
746
935
  if (declarations.length === 0) return "";
747
- return `${schemaImportLine(adapter, options, adapter.wrapLazy === void 0 && analyzeSchemas(schemas).cycles.size > 0)}\n\n${declarations.map((d) => d.code).join(";")}\n`;
936
+ return `${schemaImportLine(adapter, options, declarations.some((d) => d.importLine !== schemaImportLine(adapter, options)))}\n\n${declarations.map((d) => d.code).join(";")}\n`;
748
937
  }
749
938
  //#endregion
750
939
  //#region src/generator/components/security-schemes.ts
751
- function makeSecuritySchemesCode(components, readonly) {
940
+ function makeSecuritySchemesDeclarations(components, options) {
752
941
  const { securitySchemes } = components;
753
- if (!securitySchemes) return "";
754
- const entries = Object.entries(securitySchemes);
755
- if (entries.length === 0) return "";
756
- const asConst = readonly ? " as const" : "";
757
- return `${entries.map(([name, scheme]) => {
758
- return `export const ${`${toIdentifierPascalCase(name)}SecurityScheme`}=${valueToCode(scheme)}${asConst}`;
759
- }).join(";")}\n`;
942
+ if (!securitySchemes) return [];
943
+ const asConst = options?.readonly === true ? " as const" : "";
944
+ return Object.entries(securitySchemes).map(([name, scheme]) => {
945
+ const ident = toIdentifierPascalCase(name);
946
+ const varName = `${ident}SecurityScheme`;
947
+ return {
948
+ name,
949
+ varName,
950
+ fileName: declarationFileName(ident),
951
+ code: `export const ${varName}=${valueToCode(scheme)}${asConst}`
952
+ };
953
+ });
954
+ }
955
+ function makeSecuritySchemesCode(components, readonly) {
956
+ return joinDeclarations(makeSecuritySchemesDeclarations(components, { readonly }), { trailingNewline: true });
760
957
  }
761
958
  //#endregion
762
- export { isRecord, makeAdapter, makeCallbacksCode, makeExamplesCode, makeHeadersCode, makeLinksCode, makeParametersCode, makePathItemsCode, makeRequestBodiesCode, makeResponsesCode, makeSafeKey, makeSchemaDeclarations, makeSchemaReplacements, makeSchemasCode, makeSecuritySchemesCode, parseOpenAPI, schemaRefToName, toIdentifierPascalCase, toPascalCase, valueToCode };
959
+ export { declarationFileName, isRecord, makeAdapter, makeCallbacksCode, makeCallbacksDeclarations, makeExamplesCode, makeExamplesDeclarations, makeHeadersCode, makeHeadersDeclarations, makeLinksCode, makeLinksDeclarations, makeMediaTypesCode, makeMediaTypesDeclarations, makeParametersCode, makeParametersDeclarations, makePathItemsCode, makePathItemsDeclarations, makeRequestBodiesCode, makeRequestBodiesDeclarations, makeResponsesCode, makeResponsesDeclarations, makeSafeKey, makeSchemaDeclarations, makeSchemaIdentifiers, makeSchemaReplacements, makeSchemaVarName, makeSchemasCode, makeSecuritySchemesCode, makeSecuritySchemesDeclarations, parseOpenAPI, schemaImportLine, schemaRefToName, toIdentifierPascalCase, toPascalCase, valueToCode };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oas-truth",
3
- "version": "0.2.0",
3
+ "version": "0.4.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.1"
31
+ "schema-to-library": "^0.5.0"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@apidevtools/swagger-parser": "^13.0.0",