genoc 0.4.0 → 0.4.1
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 +2 -2
- package/dist/analyzer/analyze.js +32 -73
- package/dist/analyzer/discriminator-registry.d.ts +108 -0
- package/dist/analyzer/discriminator-registry.js +209 -0
- package/dist/analyzer/schema-mapper.d.ts +66 -5
- package/dist/analyzer/schema-mapper.js +291 -36
- package/dist/analyzer/types.d.ts +8 -1
- package/dist/cli/impl.js +4 -1
- package/dist/pipeline.d.ts +2 -0
- package/dist/pipeline.js +1 -0
- package/dist/utils/proxy.d.ts +2 -0
- package/dist/utils/proxy.js +16 -0
- package/dist/utils/string.d.ts +7 -0
- package/dist/utils/string.js +9 -0
- package/package.json +16 -8
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Generate TypeScript HTTP clients from OpenAPI 3.0 or 3.1 specifications.
|
|
|
4
4
|
Generated code depends only on the tiny `genoc/runtime` module. Full type safety. Bring your own HTTP client.
|
|
5
5
|
|
|
6
6
|
[](https://www.npmjs.com/package/genoc)
|
|
7
|
-
[](https://nodejs.org/)
|
|
8
8
|
[](https://www.typescriptlang.org/)
|
|
9
9
|
[](./LICENSE)
|
|
10
10
|
|
|
@@ -122,7 +122,7 @@ For the full example of catching and narrowing errors, see [Error handling](./do
|
|
|
122
122
|
|
|
123
123
|
## Requirements
|
|
124
124
|
|
|
125
|
-
- Node.js 18 or later
|
|
125
|
+
- Node.js 20.18.1 or later
|
|
126
126
|
- OpenAPI 3.0.x or 3.1.x specification (JSON or YAML, file path or URL)
|
|
127
127
|
|
|
128
128
|
## License
|
package/dist/analyzer/analyze.js
CHANGED
|
@@ -1,42 +1,21 @@
|
|
|
1
1
|
import { RefResolver } from '../parser/ref-resolver.js';
|
|
2
2
|
import { buildSchemaRenameMap, buildTypeJsDoc, sanitizeJsDocText, sanitizeTypeName, toPascalCase, } from '../utils/generator-helpers.js';
|
|
3
3
|
import { operationEmissions, RESERVED_TYPE_NAMES } from '../utils/operation-naming.js';
|
|
4
|
+
import { buildDiscriminatorRegistry, renameAwareTypeName } from './discriminator-registry.js';
|
|
4
5
|
import { analyzePathsDetailed } from './path-analyzer.js';
|
|
5
6
|
import { SchemaMapper } from './schema-mapper.js';
|
|
6
|
-
/**
|
|
7
|
-
* If the schema is a $ref to a discriminated base type (or an array whose items
|
|
8
|
-
* are), replace the type name with the {Base}Variant union type.
|
|
9
|
-
*/
|
|
10
|
-
function substituteDiscriminatedType(tsType, schema, discriminatorInfo, renameMap) {
|
|
11
|
-
const refSchema = schema;
|
|
12
|
-
if (!refSchema || typeof refSchema !== 'object')
|
|
13
|
-
return tsType;
|
|
14
|
-
if (typeof refSchema.$ref === 'string') {
|
|
15
|
-
const rawName = refSchema.$ref.split('/').pop();
|
|
16
|
-
const schemaName = sanitizeTypeName(rawName);
|
|
17
|
-
if (schemaName && discriminatorInfo.has(schemaName)) {
|
|
18
|
-
const renamed = renameMap.get(rawName) ?? schemaName;
|
|
19
|
-
return tsType.replace(new RegExp(`\\b${renamed}\\b`, 'g'), `${renamed}Variant`);
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
if (refSchema.items && typeof refSchema.items === 'object') {
|
|
23
|
-
const items = refSchema.items;
|
|
24
|
-
if (typeof items.$ref === 'string') {
|
|
25
|
-
const rawName = items.$ref.split('/').pop();
|
|
26
|
-
const schemaName = sanitizeTypeName(rawName);
|
|
27
|
-
if (schemaName && discriminatorInfo.has(schemaName)) {
|
|
28
|
-
const renamed = renameMap.get(rawName) ?? schemaName;
|
|
29
|
-
return tsType.replace(new RegExp(`\\b${renamed}\\b`, 'g'), `${renamed}Variant`);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
return tsType;
|
|
34
|
-
}
|
|
35
7
|
/**
|
|
36
8
|
* Indent unit matching `INDENT_UNIT` in schema-mapper.ts (2 spaces, pinned by
|
|
37
9
|
* the mapper's golden tests). Kept local to avoid modifying the mapper module.
|
|
38
10
|
*/
|
|
39
11
|
const INDENT_UNIT = ' ';
|
|
12
|
+
/**
|
|
13
|
+
* Shared warning channel for analyze() and the discriminator registry —
|
|
14
|
+
* the same sink the mapper defaults to.
|
|
15
|
+
*/
|
|
16
|
+
function writeWarning(message) {
|
|
17
|
+
process.stderr.write(message);
|
|
18
|
+
}
|
|
40
19
|
/**
|
|
41
20
|
* Build a description-only type-level JSDoc comment for operation-derived
|
|
42
21
|
* types (body / response). Returns '' when the description is absent or
|
|
@@ -301,45 +280,25 @@ export function analyze(doc, opts = {}) {
|
|
|
301
280
|
const renamingTypeGenerator = (refString) => {
|
|
302
281
|
const segments = refString.split('/');
|
|
303
282
|
const rawSegment = segments[segments.length - 1] || 'unknown';
|
|
304
|
-
return renameMap
|
|
283
|
+
return renameAwareTypeName(renameMap, rawSegment);
|
|
305
284
|
};
|
|
306
|
-
const discriminatorInfo = new Map();
|
|
307
|
-
if (doc.components?.schemas) {
|
|
308
|
-
for (const [name, schema] of Object.entries(doc.components.schemas)) {
|
|
309
|
-
const resolved = resolver.resolve(schema);
|
|
310
|
-
if (resolved.discriminator) {
|
|
311
|
-
const mapping = new Map();
|
|
312
|
-
if (resolved.discriminator.mapping) {
|
|
313
|
-
for (const [key, ref] of Object.entries(resolved.discriminator.mapping)) {
|
|
314
|
-
const rawTarget = ref.split('/').pop() || key;
|
|
315
|
-
const renamedTarget = renameMap.get(rawTarget) ?? sanitizeTypeName(rawTarget);
|
|
316
|
-
mapping.set(key, renamedTarget);
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
discriminatorInfo.set(sanitizeTypeName(name), {
|
|
320
|
-
rawName: name,
|
|
321
|
-
propertyName: resolved.discriminator.propertyName,
|
|
322
|
-
mapping,
|
|
323
|
-
});
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
const discriminatorTargets = new Map();
|
|
328
|
-
for (const [, info] of discriminatorInfo) {
|
|
329
|
-
for (const [mappingKey, schemaName] of info.mapping) {
|
|
330
|
-
discriminatorTargets.set(schemaName, {
|
|
331
|
-
propertyName: info.propertyName,
|
|
332
|
-
literalValue: mappingKey,
|
|
333
|
-
});
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
285
|
const allSchemaNames = new Set();
|
|
337
286
|
if (doc.components?.schemas) {
|
|
338
287
|
for (const name of Object.keys(doc.components.schemas)) {
|
|
339
288
|
allSchemaNames.add(renameMap.get(name) ?? sanitizeTypeName(name));
|
|
340
289
|
}
|
|
341
290
|
}
|
|
342
|
-
|
|
291
|
+
// Family-aware discriminator registry (plan D5) — the single knowledge
|
|
292
|
+
// source for discriminator translation: the mapper's ref-translation seam
|
|
293
|
+
// consumes it, and the always-emitted `{Base}Variant` unions below are
|
|
294
|
+
// emitted from it.
|
|
295
|
+
const discriminatorRegistry = buildDiscriminatorRegistry(doc.components?.schemas, resolver, renameMap, allSchemaNames, writeWarning);
|
|
296
|
+
const mapper = new SchemaMapper(resolver, {
|
|
297
|
+
typeNameGenerator: renamingTypeGenerator,
|
|
298
|
+
emittedNames: allSchemaNames,
|
|
299
|
+
discriminatorRegistry,
|
|
300
|
+
effectiveVersion: opts?.effectiveVersion,
|
|
301
|
+
});
|
|
343
302
|
// Section 1: Schema types
|
|
344
303
|
const schemaEntries = [];
|
|
345
304
|
if (doc.components?.schemas) {
|
|
@@ -362,17 +321,18 @@ export function analyze(doc, opts = {}) {
|
|
|
362
321
|
definition: entry.definition,
|
|
363
322
|
jsDoc: entry.jsDoc,
|
|
364
323
|
}));
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
324
|
+
// Variant unions are emitted from the registry (D6): ALWAYS (mapping
|
|
325
|
+
// values ∪ implicit oneOf/anyOf refs, deduped by rename-aware name) and
|
|
326
|
+
// under collision-safe names so a user schema named `{Base}Variant`
|
|
327
|
+
// cannot collide with the generated union.
|
|
328
|
+
for (const family of discriminatorRegistry.families.values()) {
|
|
329
|
+
if (family.variantUnionMembers.length === 0)
|
|
368
330
|
continue;
|
|
369
|
-
const unionType = subtypeNames.join(' | ');
|
|
370
|
-
const renamedBase = renameMap.get(info.rawName) ?? sanitizeTypeName(info.rawName);
|
|
371
331
|
schemaTypes.push({
|
|
372
|
-
name:
|
|
373
|
-
definition: `export type ${
|
|
332
|
+
name: family.variantUnionName,
|
|
333
|
+
definition: `export type ${family.variantUnionName} = ${family.variantUnionMembers.join(' | ')};`,
|
|
374
334
|
});
|
|
375
|
-
allSchemaNames.add(
|
|
335
|
+
allSchemaNames.add(family.variantUnionName);
|
|
376
336
|
}
|
|
377
337
|
const { operations: analyzedOperations, requestBodySchemas } = analyzePathsDetailed(doc, resolver, strategy);
|
|
378
338
|
const operations = [];
|
|
@@ -461,10 +421,9 @@ export function analyze(doc, opts = {}) {
|
|
|
461
421
|
return 'StreamResponse';
|
|
462
422
|
}
|
|
463
423
|
if (r.schema) {
|
|
464
|
-
const
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
return substituted;
|
|
424
|
+
const tsType = mapper.mapSchema(r.schema, undefined, 'response').tsType;
|
|
425
|
+
r.finishedType = tsType;
|
|
426
|
+
return tsType;
|
|
468
427
|
}
|
|
469
428
|
r.finishedType = r.isVoid ? 'void' : 'unknown';
|
|
470
429
|
return r.finishedType;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { RefResolver } from '../parser/ref-resolver.js';
|
|
2
|
+
import type { SchemaObject } from '../types/openapi.js';
|
|
3
|
+
/**
|
|
4
|
+
* Family-aware discriminator registry (plan D5) — the single knowledge source
|
|
5
|
+
* for discriminator families the mapper seam will translate through:
|
|
6
|
+
*
|
|
7
|
+
* - One record per discriminator family (a component schema declaring
|
|
8
|
+
* `discriminator`), keyed by `familyId` (the base's raw component name).
|
|
9
|
+
* - Variant entries keyed by the FULL `$ref` string (mapping values are exact
|
|
10
|
+
* ref strings) plus a derived rename-aware name index.
|
|
11
|
+
* - Literals are stored PRE-ESCAPED (D8: `'` and `\` only) so the mapper never
|
|
12
|
+
* interpolates raw values into string literals.
|
|
13
|
+
* - Implicit variants (oneOf/anyOf `$ref` members absent from `mapping`) carry
|
|
14
|
+
* the RAW last ref segment as their literal (D3 precedence: mapping key >
|
|
15
|
+
* own `const` > single-value `enum` > raw segment).
|
|
16
|
+
*
|
|
17
|
+
* Field budget (D5): audited — every remaining field has a live consumer in
|
|
18
|
+
* production (seam / Variant-union emission) or in the registry unit tests.
|
|
19
|
+
* Rename-aware keying is mandatory: the name index goes through the same
|
|
20
|
+
* `buildSchemaRenameMap` machinery `analyze()` uses (see the past-bug note at
|
|
21
|
+
* schema-mapper.ts:75–78 — raw-name keying silently drops literal injection
|
|
22
|
+
* for renamed subtypes).
|
|
23
|
+
*/
|
|
24
|
+
/** Rename-aware type-name derivation — the exact expression `analyze()` wires
|
|
25
|
+
* into the mapper's `typeNameGenerator` (`renameMap.get(raw) ?? sanitized`).
|
|
26
|
+
* Single source of truth so registry name keys can never diverge from the
|
|
27
|
+
* names the mapper emits for the same `$ref`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function renameAwareTypeName(renameMap: Map<string, string>, rawName: string): string;
|
|
30
|
+
/**
|
|
31
|
+
* One discriminator variant target inside a family. Consumers: `propertyName`
|
|
32
|
+
* → literal append + `Omit<M, quoteKey(P)>` key + union wrapper;
|
|
33
|
+
* `literalValue` → the appended literal (pre-escaped — render as
|
|
34
|
+
* `'${literalValue}'`); `isNamed` → bare-name vs inline-expansion decision;
|
|
35
|
+
* `isUnion`/`isNullable` → spine `Omit` fallback decision (D2); `familyId` →
|
|
36
|
+
* same-family spine detection (D1/D2); `refStr` → identity match at the
|
|
37
|
+
* ref-translation seam; `typeName` → bare-name emission and the name index.
|
|
38
|
+
*/
|
|
39
|
+
export interface DiscriminatorVariantEntry {
|
|
40
|
+
/** Discriminator property name declared by the family base (e.g. `'$type'`). */
|
|
41
|
+
propertyName: string;
|
|
42
|
+
/** Pre-escaped literal (D8) — the mapping key, own const/enum value, or raw ref segment. No surrounding quotes. */
|
|
43
|
+
literalValue: string;
|
|
44
|
+
/** The rename-aware derived name is an emitted component schema (`∈ allSchemaNames`). */
|
|
45
|
+
isNamed: boolean;
|
|
46
|
+
/** The target's own resolved schema declares `oneOf`/`anyOf` (spine `Omit` would drop variant props — D2 fallback). */
|
|
47
|
+
isUnion: boolean;
|
|
48
|
+
/** The target's own resolved schema is nullable (3.0 `nullable: true` or a 3.1 type array containing `'null'`). */
|
|
49
|
+
isNullable: boolean;
|
|
50
|
+
/** Owning family id — the discriminator base's raw component name. */
|
|
51
|
+
familyId: string;
|
|
52
|
+
/** The exact `$ref` string that produced this entry (mapping value or oneOf/anyOf member ref). */
|
|
53
|
+
refStr: string;
|
|
54
|
+
/** Rename-aware type name for the ref (same derivation as the mapper's `typeNameGenerator`). */
|
|
55
|
+
typeName: string;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* One discriminator family: a component schema declaring `discriminator`
|
|
59
|
+
* (`familyId` = its raw component name). Consumers: `baseRefStr` → base-ref
|
|
60
|
+
* detection at the seam (D1: `$ref` to the base emits `variantUnionName`
|
|
61
|
+
* outside same-family spines); `variantUnionName` / `variantUnionMembers` →
|
|
62
|
+
* the always-emit `{Base}Variant` union (D6); `entriesByRef` → family
|
|
63
|
+
* construction substrate and per-family lookups.
|
|
64
|
+
*/
|
|
65
|
+
export interface DiscriminatorFamily {
|
|
66
|
+
/** Raw component name of the discriminator base — the family id. */
|
|
67
|
+
familyId: string;
|
|
68
|
+
/** Rename-aware emitted type name of the base. */
|
|
69
|
+
baseTypeName: string;
|
|
70
|
+
/** Canonical ref of the base component (`#/components/schemas/<encoded key>`). */
|
|
71
|
+
baseRefStr: string;
|
|
72
|
+
/** Discriminator property name (`discriminator.propertyName`). */
|
|
73
|
+
propertyName: string;
|
|
74
|
+
/** Collision-safe `{Base}Variant` union name (D6 — via the reserved-name machinery). */
|
|
75
|
+
variantUnionName: string;
|
|
76
|
+
/** Union member type names (rename-aware, deduped; mapping order, then unmapped oneOf/anyOf refs). */
|
|
77
|
+
variantUnionMembers: string[];
|
|
78
|
+
/** Family entries keyed by the FULL `$ref` string (mapping value or oneOf/anyOf member ref). */
|
|
79
|
+
entriesByRef: Map<string, DiscriminatorVariantEntry>;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The discriminator registry built once per `analyze()` run. Consumers:
|
|
83
|
+
* `byRef`/`byName` for variant-target lookup at the ref-translation seam;
|
|
84
|
+
* `baseRefs` for D1 base-ref translation; `families` for same-family spine
|
|
85
|
+
* scoping (entry `familyId` → family) and the `{Base}Variant` union emission.
|
|
86
|
+
* Flat lookups are first-wins across families (spec order) — ambiguous
|
|
87
|
+
* cross-family targets stay reachable through their per-family maps.
|
|
88
|
+
*/
|
|
89
|
+
export interface DiscriminatorRegistry {
|
|
90
|
+
/** Families keyed by familyId (raw base component name), in spec order. */
|
|
91
|
+
families: Map<string, DiscriminatorFamily>;
|
|
92
|
+
/** Flat lookup: full refStr → entry (first-wins across families). */
|
|
93
|
+
byRef: Map<string, DiscriminatorVariantEntry>;
|
|
94
|
+
/** Flat lookup: rename-aware type name → entry (first-wins across families). */
|
|
95
|
+
byName: Map<string, DiscriminatorVariantEntry>;
|
|
96
|
+
/** Canonical base refStr → family, for D1 base-ref translation. */
|
|
97
|
+
baseRefs: Map<string, DiscriminatorFamily>;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Build the family-aware discriminator registry from the component schemas.
|
|
101
|
+
*
|
|
102
|
+
* Inputs must be the SAME `renameMap` / `allSchemaNames` `analyze()` derives
|
|
103
|
+
* (the rename-aware keying discipline) — pass `buildSchemaRenameMap`'s output
|
|
104
|
+
* and the emitted-name set, never a parallel sanitization. Pure with respect
|
|
105
|
+
* to the document: no mutation of the schemas; warnings (D3 mapping-key
|
|
106
|
+
* conflicts) go to `warnSink`.
|
|
107
|
+
*/
|
|
108
|
+
export declare function buildDiscriminatorRegistry(schemas: Record<string, SchemaObject> | undefined, resolver: RefResolver, renameMap: Map<string, string>, allSchemaNames: ReadonlySet<string>, warnSink?: (message: string) => void): DiscriminatorRegistry;
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { buildSchemaRenameMap, sanitizeTypeName } from '../utils/generator-helpers.js';
|
|
2
|
+
import { RESERVED_TYPE_NAMES } from '../utils/operation-naming.js';
|
|
3
|
+
import { escapeStringLiteral } from '../utils/string.js';
|
|
4
|
+
import { parseJsonPointer } from '../utils/url.js';
|
|
5
|
+
/**
|
|
6
|
+
* Family-aware discriminator registry (plan D5) — the single knowledge source
|
|
7
|
+
* for discriminator families the mapper seam will translate through:
|
|
8
|
+
*
|
|
9
|
+
* - One record per discriminator family (a component schema declaring
|
|
10
|
+
* `discriminator`), keyed by `familyId` (the base's raw component name).
|
|
11
|
+
* - Variant entries keyed by the FULL `$ref` string (mapping values are exact
|
|
12
|
+
* ref strings) plus a derived rename-aware name index.
|
|
13
|
+
* - Literals are stored PRE-ESCAPED (D8: `'` and `\` only) so the mapper never
|
|
14
|
+
* interpolates raw values into string literals.
|
|
15
|
+
* - Implicit variants (oneOf/anyOf `$ref` members absent from `mapping`) carry
|
|
16
|
+
* the RAW last ref segment as their literal (D3 precedence: mapping key >
|
|
17
|
+
* own `const` > single-value `enum` > raw segment).
|
|
18
|
+
*
|
|
19
|
+
* Field budget (D5): audited — every remaining field has a live consumer in
|
|
20
|
+
* production (seam / Variant-union emission) or in the registry unit tests.
|
|
21
|
+
* Rename-aware keying is mandatory: the name index goes through the same
|
|
22
|
+
* `buildSchemaRenameMap` machinery `analyze()` uses (see the past-bug note at
|
|
23
|
+
* schema-mapper.ts:75–78 — raw-name keying silently drops literal injection
|
|
24
|
+
* for renamed subtypes).
|
|
25
|
+
*/
|
|
26
|
+
/** Rename-aware type-name derivation — the exact expression `analyze()` wires
|
|
27
|
+
* into the mapper's `typeNameGenerator` (`renameMap.get(raw) ?? sanitized`).
|
|
28
|
+
* Single source of truth so registry name keys can never diverge from the
|
|
29
|
+
* names the mapper emits for the same `$ref`.
|
|
30
|
+
*/
|
|
31
|
+
export function renameAwareTypeName(renameMap, rawName) {
|
|
32
|
+
return renameMap.get(rawName) ?? sanitizeTypeName(rawName);
|
|
33
|
+
}
|
|
34
|
+
function isRefObject(obj) {
|
|
35
|
+
return (obj !== null &&
|
|
36
|
+
typeof obj === 'object' &&
|
|
37
|
+
!Array.isArray(obj) &&
|
|
38
|
+
'$ref' in obj);
|
|
39
|
+
}
|
|
40
|
+
/** Decode the last segment of a `$ref` string into its raw component key (`~1`/`~0` unescaped). */
|
|
41
|
+
function rawRefSegment(refStr) {
|
|
42
|
+
const segments = refStr.startsWith('#') ? parseJsonPointer(refStr.slice(1)) : refStr.split('/');
|
|
43
|
+
return segments[segments.length - 1] ?? refStr;
|
|
44
|
+
}
|
|
45
|
+
/** Encode a component key for embedding in a `#/components/schemas/…` ref string. */
|
|
46
|
+
function encodePointerSegment(segment) {
|
|
47
|
+
return segment.replace(/~/g, '~0').replace(/\//g, '~1');
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A discriminator variant's own declared literal on the discriminator
|
|
51
|
+
* property: `const` first, then a single-value `enum` (D3 steps 2–3).
|
|
52
|
+
* Returns the string form; multi-value enums and absent props yield nothing.
|
|
53
|
+
*/
|
|
54
|
+
function resolveOwnDiscriminatorLiteral(resolved, propertyName, resolver) {
|
|
55
|
+
if (!resolved)
|
|
56
|
+
return undefined;
|
|
57
|
+
let prop = resolved.properties?.[propertyName];
|
|
58
|
+
if (prop === undefined)
|
|
59
|
+
return undefined;
|
|
60
|
+
if (isRefObject(prop)) {
|
|
61
|
+
try {
|
|
62
|
+
prop = resolver.resolveSchema(prop);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (prop.const !== undefined)
|
|
69
|
+
return { value: String(prop.const), source: 'const' };
|
|
70
|
+
if (prop.enum !== undefined && prop.enum.length === 1) {
|
|
71
|
+
return { value: String(prop.enum[0]), source: 'enum' };
|
|
72
|
+
}
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
/** Resolve a mapping/oneOf ref target for flag facts; unresolvable refs degrade to undefined (mapper-style try/catch). */
|
|
76
|
+
function resolveTargetSchema(resolver, refStr) {
|
|
77
|
+
try {
|
|
78
|
+
return resolver.resolveSchema({ $ref: refStr });
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Build the family-aware discriminator registry from the component schemas.
|
|
86
|
+
*
|
|
87
|
+
* Inputs must be the SAME `renameMap` / `allSchemaNames` `analyze()` derives
|
|
88
|
+
* (the rename-aware keying discipline) — pass `buildSchemaRenameMap`'s output
|
|
89
|
+
* and the emitted-name set, never a parallel sanitization. Pure with respect
|
|
90
|
+
* to the document: no mutation of the schemas; warnings (D3 mapping-key
|
|
91
|
+
* conflicts) go to `warnSink`.
|
|
92
|
+
*/
|
|
93
|
+
export function buildDiscriminatorRegistry(schemas, resolver, renameMap, allSchemaNames, warnSink) {
|
|
94
|
+
const warn = warnSink ??
|
|
95
|
+
((message) => {
|
|
96
|
+
process.stderr.write(message);
|
|
97
|
+
});
|
|
98
|
+
const registry = {
|
|
99
|
+
families: new Map(),
|
|
100
|
+
byRef: new Map(),
|
|
101
|
+
byName: new Map(),
|
|
102
|
+
baseRefs: new Map(),
|
|
103
|
+
};
|
|
104
|
+
if (!schemas)
|
|
105
|
+
return registry;
|
|
106
|
+
// Pass 1 — discover families; per family, register mapping entries first
|
|
107
|
+
// (D3: mapping key wins), then implicit oneOf/anyOf variants absent from
|
|
108
|
+
// the mapping (literal = own const > single-value enum > RAW ref segment).
|
|
109
|
+
for (const [name, schema] of Object.entries(schemas)) {
|
|
110
|
+
const resolved = resolver.resolve(schema);
|
|
111
|
+
const disc = resolved.discriminator;
|
|
112
|
+
if (!disc)
|
|
113
|
+
continue;
|
|
114
|
+
const familyId = name;
|
|
115
|
+
const family = {
|
|
116
|
+
familyId,
|
|
117
|
+
baseTypeName: renameAwareTypeName(renameMap, name),
|
|
118
|
+
baseRefStr: `#/components/schemas/${encodePointerSegment(name)}`,
|
|
119
|
+
propertyName: disc.propertyName,
|
|
120
|
+
variantUnionName: '',
|
|
121
|
+
variantUnionMembers: [],
|
|
122
|
+
entriesByRef: new Map(),
|
|
123
|
+
};
|
|
124
|
+
const mappedRefStrs = new Set();
|
|
125
|
+
if (disc.mapping) {
|
|
126
|
+
for (const [mappingKey, refStr] of Object.entries(disc.mapping)) {
|
|
127
|
+
if (mappedRefStrs.has(refStr))
|
|
128
|
+
continue; // two keys → same target: first key wins
|
|
129
|
+
mappedRefStrs.add(refStr);
|
|
130
|
+
const target = resolveTargetSchema(resolver, refStr);
|
|
131
|
+
const own = resolveOwnDiscriminatorLiteral(target, disc.propertyName, resolver);
|
|
132
|
+
if (own !== undefined && own.value !== mappingKey) {
|
|
133
|
+
warn(`Warning: Discriminator mapping key "${mappingKey}" for "${refStr}" conflicts with its own declared ${own.source} literal "${own.value}"; the mapping key wins.\n`);
|
|
134
|
+
}
|
|
135
|
+
const rawSegment = rawRefSegment(refStr);
|
|
136
|
+
const entry = {
|
|
137
|
+
propertyName: disc.propertyName,
|
|
138
|
+
literalValue: escapeStringLiteral(mappingKey),
|
|
139
|
+
isNamed: allSchemaNames.has(renameAwareTypeName(renameMap, rawSegment)),
|
|
140
|
+
isUnion: (target?.oneOf?.length ?? 0) > 0 || (target?.anyOf?.length ?? 0) > 0,
|
|
141
|
+
isNullable: target?.nullable === true ||
|
|
142
|
+
(Array.isArray(target?.type) ? target.type.includes('null') : false),
|
|
143
|
+
familyId,
|
|
144
|
+
refStr,
|
|
145
|
+
typeName: renameAwareTypeName(renameMap, rawSegment),
|
|
146
|
+
};
|
|
147
|
+
family.entriesByRef.set(refStr, entry);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const implicitRefs = [];
|
|
151
|
+
for (const member of [...(resolved.oneOf ?? []), ...(resolved.anyOf ?? [])]) {
|
|
152
|
+
if (isRefObject(member))
|
|
153
|
+
implicitRefs.push(member.$ref);
|
|
154
|
+
}
|
|
155
|
+
for (const refStr of implicitRefs) {
|
|
156
|
+
if (mappedRefStrs.has(refStr))
|
|
157
|
+
continue; // already registered via mapping
|
|
158
|
+
const target = resolveTargetSchema(resolver, refStr);
|
|
159
|
+
const own = resolveOwnDiscriminatorLiteral(target, disc.propertyName, resolver);
|
|
160
|
+
const rawSegment = rawRefSegment(refStr);
|
|
161
|
+
const entry = {
|
|
162
|
+
propertyName: disc.propertyName,
|
|
163
|
+
// D3 fallback chain for unmapped variants: own const > single-value
|
|
164
|
+
// enum > RAW last ref segment (the runtime value, NOT the sanitized
|
|
165
|
+
// type name).
|
|
166
|
+
literalValue: escapeStringLiteral(own?.value ?? rawSegment),
|
|
167
|
+
isNamed: allSchemaNames.has(renameAwareTypeName(renameMap, rawSegment)),
|
|
168
|
+
isUnion: (target?.oneOf?.length ?? 0) > 0 || (target?.anyOf?.length ?? 0) > 0,
|
|
169
|
+
isNullable: target?.nullable === true ||
|
|
170
|
+
(Array.isArray(target?.type) ? target.type.includes('null') : false),
|
|
171
|
+
familyId,
|
|
172
|
+
refStr,
|
|
173
|
+
typeName: renameAwareTypeName(renameMap, rawSegment),
|
|
174
|
+
};
|
|
175
|
+
family.entriesByRef.set(refStr, entry);
|
|
176
|
+
}
|
|
177
|
+
registry.families.set(familyId, family);
|
|
178
|
+
}
|
|
179
|
+
// Pass 2 — flat lookups + per-family name index + union members
|
|
180
|
+
// (mapping order, then unmapped oneOf/anyOf refs; deduped by refStr and
|
|
181
|
+
// by typeName — alias refs to one emitted name collapse).
|
|
182
|
+
for (const family of registry.families.values()) {
|
|
183
|
+
const memberNames = [];
|
|
184
|
+
const seenNames = new Set();
|
|
185
|
+
for (const [refStr, entry] of family.entriesByRef) {
|
|
186
|
+
if (!registry.byRef.has(refStr))
|
|
187
|
+
registry.byRef.set(refStr, entry);
|
|
188
|
+
if (!registry.byName.has(entry.typeName))
|
|
189
|
+
registry.byName.set(entry.typeName, entry);
|
|
190
|
+
if (!seenNames.has(entry.typeName)) {
|
|
191
|
+
seenNames.add(entry.typeName);
|
|
192
|
+
memberNames.push(entry.typeName);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
family.variantUnionMembers = memberNames;
|
|
196
|
+
registry.baseRefs.set(family.baseRefStr, family);
|
|
197
|
+
}
|
|
198
|
+
// Pass 3 — collision-safe `{Base}Variant` union names (D6): candidates go
|
|
199
|
+
// through the SAME reserved-name machinery as schemas, seeded with every
|
|
200
|
+
// emitted schema name, so a user schema literally named `ThingVariant`
|
|
201
|
+
// forces the generated union to `ThingVariantModel` (no duplicate export).
|
|
202
|
+
const unionCandidates = [...registry.families.values()].map((f) => `${f.baseTypeName}Variant`);
|
|
203
|
+
const unionRenames = buildSchemaRenameMap(unionCandidates, new Set([...RESERVED_TYPE_NAMES, ...allSchemaNames]));
|
|
204
|
+
for (const family of registry.families.values()) {
|
|
205
|
+
const candidate = `${family.baseTypeName}Variant`;
|
|
206
|
+
family.variantUnionName = unionRenames.get(candidate) ?? candidate;
|
|
207
|
+
}
|
|
208
|
+
return registry;
|
|
209
|
+
}
|
|
@@ -1,10 +1,32 @@
|
|
|
1
1
|
import { RefResolver } from '../parser/ref-resolver.js';
|
|
2
2
|
import type { TypeMappingResult } from '../types/contracts.js';
|
|
3
3
|
import type { SchemaObject, ReferenceObject } from '../types/openapi.js';
|
|
4
|
+
import type { DiscriminatorRegistry } from './discriminator-registry.js';
|
|
4
5
|
/**
|
|
5
6
|
* Callback to customize how $ref strings are converted to TypeScript type names.
|
|
6
7
|
*/
|
|
7
8
|
export type TypeNameGenerator = (refString: string) => string;
|
|
9
|
+
/**
|
|
10
|
+
* Optional construction dependencies for {@link SchemaMapper}. Every field is
|
|
11
|
+
* optional and defaults exactly as the previous positional constructor
|
|
12
|
+
* parameters did.
|
|
13
|
+
*/
|
|
14
|
+
export interface SchemaMapperOptions {
|
|
15
|
+
typeNameGenerator?: TypeNameGenerator;
|
|
16
|
+
discriminatorTargets?: Map<string, {
|
|
17
|
+
propertyName: string;
|
|
18
|
+
literalValue: string;
|
|
19
|
+
}>;
|
|
20
|
+
emittedNames?: Set<string>;
|
|
21
|
+
warnSink?: (message: string) => void;
|
|
22
|
+
discriminatorRegistry?: DiscriminatorRegistry;
|
|
23
|
+
/**
|
|
24
|
+
* Effective OpenAPI dialect. Omitted is treated as '3.1' (the nullable
|
|
25
|
+
* deprecation warning fires). Pass '3.0' to silence it — 'nullable' is the
|
|
26
|
+
* correct mechanism in 3.0.
|
|
27
|
+
*/
|
|
28
|
+
effectiveVersion?: '3.0' | '3.1';
|
|
29
|
+
}
|
|
8
30
|
/**
|
|
9
31
|
* SchemaMapper converts OpenAPI 3.1 Schema Objects to TypeScript type strings.
|
|
10
32
|
*
|
|
@@ -15,14 +37,13 @@ export declare class SchemaMapper {
|
|
|
15
37
|
private readonly resolver;
|
|
16
38
|
private readonly typeNameGenerator;
|
|
17
39
|
private readonly discriminatorTargets;
|
|
18
|
-
private readonly
|
|
40
|
+
private readonly emittedNames;
|
|
41
|
+
private readonly discriminatorRegistry;
|
|
19
42
|
private readonly brandedTypes;
|
|
20
43
|
private nullableWarned;
|
|
21
44
|
private readonly warnSink;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
literalValue: string;
|
|
25
|
-
}>, reservedNames?: Set<string>, warnSink?: (message: string) => void);
|
|
45
|
+
private readonly effectiveVersion;
|
|
46
|
+
constructor(resolver: RefResolver, opts?: SchemaMapperOptions);
|
|
26
47
|
getBrandedTypes(): Map<string, {
|
|
27
48
|
name: string;
|
|
28
49
|
format: string;
|
|
@@ -37,12 +58,52 @@ export declare class SchemaMapper {
|
|
|
37
58
|
* @returns TypeMappingResult with tsType string and imports array
|
|
38
59
|
*/
|
|
39
60
|
mapSchema(schema: SchemaObject | ReferenceObject, name?: string, context?: 'request' | 'response'): TypeMappingResult;
|
|
61
|
+
/**
|
|
62
|
+
* Append the discriminator literal intersection exactly ONCE (site 2),
|
|
63
|
+
* parenthesizing a top-level union so `X | null & {...}` cannot bind the
|
|
64
|
+
* literal to the last union member only (D9).
|
|
65
|
+
*/
|
|
66
|
+
private appendDiscriminatorLiteral;
|
|
40
67
|
private getBrandTypeName;
|
|
41
68
|
private mapInternal;
|
|
69
|
+
/**
|
|
70
|
+
* The single ref-translation seam (site 1). When the mapper carries a
|
|
71
|
+
* discriminator registry, EVERY `$ref` resolves through here:
|
|
72
|
+
*
|
|
73
|
+
* - a discriminator BASE becomes `{Base}Variant` at all sites except
|
|
74
|
+
* inside a same-family member's own definition spine, where it stays
|
|
75
|
+
* the bare base name (structural inheritance, no circularity — D1);
|
|
76
|
+
* - a same-family mapping target inside a spine becomes `Omit<M, 'P'>`,
|
|
77
|
+
* falling back to inline expansion WITHOUT the literal when M is a
|
|
78
|
+
* union, nullable, unnamed or non-object (D2/D4);
|
|
79
|
+
* - a mapping target at any other site is its bare name — the literal is
|
|
80
|
+
* injected exactly once, at the target's own named definition.
|
|
81
|
+
*/
|
|
82
|
+
private translateRefThroughSeam;
|
|
83
|
+
/**
|
|
84
|
+
* D2/D4 spine rule for a same-family `$ref`. `Omit<M, 'P'>` strips the
|
|
85
|
+
* sibling's own literal so the appender can re-add ours; the inline-strip
|
|
86
|
+
* fallback covers the cases where `Omit` would silently drop data
|
|
87
|
+
* (union target: `Omit<A|B,K>` drops variant props; nullable target:
|
|
88
|
+
* `Omit<M|null,K>` collapses to `{}`; unnamed/non-object target).
|
|
89
|
+
*/
|
|
90
|
+
private mapSameFamilySpineRef;
|
|
91
|
+
/** Normalize a `#/components/schemas/…` ref to its canonically-encoded form (`a/b` ↔ `a~1b`). */
|
|
92
|
+
private canonicalSchemasRef;
|
|
93
|
+
private tryResolveRef;
|
|
94
|
+
private isObjectIshSchema;
|
|
42
95
|
private resolveDiscriminatorInfo;
|
|
43
96
|
private mapEnumValues;
|
|
44
97
|
private mapCombinator;
|
|
45
98
|
private mapDiscriminatedUnion;
|
|
99
|
+
/**
|
|
100
|
+
* D3 literal precedence for registry-mode wrapper literals (inline variant
|
|
101
|
+
* schemas and foreign refs): mapping key > own `const` on the discriminant
|
|
102
|
+
* property > single-value `enum` > RAW last ref segment (the runtime
|
|
103
|
+
* value, NOT the sanitized type name). Values are escaped for a
|
|
104
|
+
* single-quoted TS string.
|
|
105
|
+
*/
|
|
106
|
+
private resolveRegistryDiscriminantValue;
|
|
46
107
|
private resolveDiscriminantValue;
|
|
47
108
|
private mapArray;
|
|
48
109
|
/**
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { RefResolver } from '../parser/ref-resolver.js';
|
|
2
2
|
import { formatToBrandTypeName } from '../utils/case.js';
|
|
3
3
|
import { buildTypeJsDoc, sanitizeTypeName } from '../utils/generator-helpers.js';
|
|
4
|
-
import { quoteKey } from '../utils/string.js';
|
|
4
|
+
import { escapeStringLiteral, quoteKey } from '../utils/string.js';
|
|
5
|
+
import { parseJsonPointer } from '../utils/url.js';
|
|
5
6
|
/** Indentation contract for multi-line types — 2-space unit pinned from the generated ServerParams interface; binding for downstream generators. */
|
|
6
7
|
const INDENT_UNIT = ' ';
|
|
7
8
|
function indentBy(level) {
|
|
@@ -28,6 +29,70 @@ function isComplexType(tsType) {
|
|
|
28
29
|
function needsParens(tsType) {
|
|
29
30
|
return tsType.includes(' | ') || tsType.includes(' & ');
|
|
30
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Whether the rendered type has a top-level `|` (depth 0, outside any
|
|
34
|
+
* brackets/braces and outside string literals). Unlike the substring check
|
|
35
|
+
* in `needsParens`, nested unions inside `{...}`, `<...>` or `'...'` do not
|
|
36
|
+
* trigger it — this is the guard for appending `& {...}` onto a type whose
|
|
37
|
+
* tail could otherwise capture the append (`X | null & {...}` loses the
|
|
38
|
+
* literal to `null`).
|
|
39
|
+
*/
|
|
40
|
+
function hasTopLevelUnion(tsType) {
|
|
41
|
+
let depth = 0;
|
|
42
|
+
let inString = false;
|
|
43
|
+
for (let i = 0; i < tsType.length; i++) {
|
|
44
|
+
const ch = tsType[i];
|
|
45
|
+
if (ch === '\\') {
|
|
46
|
+
i++;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (ch === "'") {
|
|
50
|
+
inString = !inString;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (inString)
|
|
54
|
+
continue;
|
|
55
|
+
if (ch === '(' || ch === '{' || ch === '[' || ch === '<')
|
|
56
|
+
depth++;
|
|
57
|
+
else if (ch === ')' || ch === '}' || ch === ']' || ch === '>')
|
|
58
|
+
depth--;
|
|
59
|
+
else if (depth === 0 && ch === '|' && tsType[i - 1] === ' ' && tsType[i + 1] === ' ') {
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
/** Decode the last segment of a `$ref` string into its raw component key (`~1`/`~0` unescaped). */
|
|
66
|
+
function decodedLastRefSegment(refStr) {
|
|
67
|
+
const segments = refStr.startsWith('#') ? parseJsonPointer(refStr.slice(1)) : refStr.split('/');
|
|
68
|
+
return segments[segments.length - 1] ?? refStr;
|
|
69
|
+
}
|
|
70
|
+
/** Encode a component key for embedding in a `#/components/schemas/…` ref string. */
|
|
71
|
+
function encodePointerSegment(segment) {
|
|
72
|
+
return segment.replace(/~/g, '~0').replace(/\//g, '~1');
|
|
73
|
+
}
|
|
74
|
+
function spineForEntry(entry) {
|
|
75
|
+
return {
|
|
76
|
+
familyId: entry.familyId,
|
|
77
|
+
propertyName: entry.propertyName,
|
|
78
|
+
literalValue: entry.literalValue,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A variant's own declared discriminant on the discriminator property:
|
|
83
|
+
* `const` first, then a single-value `enum` (D3). Multi-value enums and
|
|
84
|
+
* absent props yield nothing.
|
|
85
|
+
*/
|
|
86
|
+
function ownDeclaredDiscriminant(propSchema) {
|
|
87
|
+
if (!propSchema)
|
|
88
|
+
return undefined;
|
|
89
|
+
if (propSchema.const !== undefined)
|
|
90
|
+
return String(propSchema.const);
|
|
91
|
+
if (propSchema.enum !== undefined && propSchema.enum.length === 1) {
|
|
92
|
+
return String(propSchema.enum[0]);
|
|
93
|
+
}
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
31
96
|
/**
|
|
32
97
|
* SchemaMapper converts OpenAPI 3.1 Schema Objects to TypeScript type strings.
|
|
33
98
|
*
|
|
@@ -38,24 +103,33 @@ export class SchemaMapper {
|
|
|
38
103
|
resolver;
|
|
39
104
|
typeNameGenerator;
|
|
40
105
|
discriminatorTargets;
|
|
41
|
-
|
|
106
|
+
emittedNames;
|
|
107
|
+
discriminatorRegistry;
|
|
42
108
|
brandedTypes = new Map();
|
|
43
109
|
nullableWarned = false;
|
|
44
110
|
warnSink;
|
|
45
|
-
|
|
111
|
+
effectiveVersion;
|
|
112
|
+
constructor(resolver, opts) {
|
|
46
113
|
// NOTE: discriminatorTargets must be keyed by names produced by the SAME
|
|
47
114
|
// (rename-aware) typeNameGenerator that resolves $refs. Passing targets
|
|
48
115
|
// keyed by raw schema names means renamed subtypes silently lose their
|
|
49
116
|
// `& { prop: 'literal' }` intersection in the generated output.
|
|
117
|
+
// analyze() no longer builds or passes a targets map — the discriminator
|
|
118
|
+
// registry (when provided) is the SINGLE discriminator knowledge source
|
|
119
|
+
// (D1–D10 seam). The optional legacy targets param is kept for
|
|
120
|
+
// registry-less constructions; it only drives the legacy ref fallback in
|
|
121
|
+
// `resolveDiscriminatorInfo` below.
|
|
50
122
|
this.resolver = resolver;
|
|
51
|
-
this.typeNameGenerator = typeNameGenerator ?? defaultTypeNameGenerator;
|
|
52
|
-
this.discriminatorTargets = discriminatorTargets ?? new Map();
|
|
53
|
-
this.
|
|
123
|
+
this.typeNameGenerator = opts?.typeNameGenerator ?? defaultTypeNameGenerator;
|
|
124
|
+
this.discriminatorTargets = opts?.discriminatorTargets ?? new Map();
|
|
125
|
+
this.emittedNames = opts?.emittedNames ?? new Set();
|
|
126
|
+
this.discriminatorRegistry = opts?.discriminatorRegistry;
|
|
54
127
|
this.warnSink =
|
|
55
|
-
warnSink ??
|
|
128
|
+
opts?.warnSink ??
|
|
56
129
|
((message) => {
|
|
57
130
|
process.stderr.write(message);
|
|
58
131
|
});
|
|
132
|
+
this.effectiveVersion = opts?.effectiveVersion;
|
|
59
133
|
}
|
|
60
134
|
getBrandedTypes() {
|
|
61
135
|
return this.brandedTypes;
|
|
@@ -73,12 +147,28 @@ export class SchemaMapper {
|
|
|
73
147
|
return { tsType: schema ? 'unknown' : 'never', imports: [] };
|
|
74
148
|
}
|
|
75
149
|
const visited = new Set();
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const
|
|
79
|
-
result.
|
|
150
|
+
if (this.discriminatorRegistry && name !== undefined) {
|
|
151
|
+
const entry = this.discriminatorRegistry.byName.get(name);
|
|
152
|
+
const spine = entry ? spineForEntry(entry) : undefined;
|
|
153
|
+
const result = this.mapInternal(schema, name, context, visited, 0, spine);
|
|
154
|
+
if (entry) {
|
|
155
|
+
return this.appendDiscriminatorLiteral(result, entry.propertyName, entry.literalValue);
|
|
156
|
+
}
|
|
157
|
+
return result;
|
|
80
158
|
}
|
|
81
|
-
return
|
|
159
|
+
return this.mapInternal(schema, name, context, visited, 0, undefined);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Append the discriminator literal intersection exactly ONCE (site 2),
|
|
163
|
+
* parenthesizing a top-level union so `X | null & {...}` cannot bind the
|
|
164
|
+
* literal to the last union member only (D9).
|
|
165
|
+
*/
|
|
166
|
+
appendDiscriminatorLiteral(result, propertyName, literalValue) {
|
|
167
|
+
const appendage = ` & { ${quoteKey(propertyName)}: '${literalValue}' }`;
|
|
168
|
+
const tsType = hasTopLevelUnion(result.tsType)
|
|
169
|
+
? `(${result.tsType})${appendage}`
|
|
170
|
+
: `${result.tsType}${appendage}`;
|
|
171
|
+
return { tsType, imports: result.imports };
|
|
82
172
|
}
|
|
83
173
|
getBrandTypeName(format, openApiType) {
|
|
84
174
|
if (!format || format.trim() === '')
|
|
@@ -86,14 +176,17 @@ export class SchemaMapper {
|
|
|
86
176
|
if (format === 'binary' || format === 'byte')
|
|
87
177
|
return null;
|
|
88
178
|
const brandName = formatToBrandTypeName(format, openApiType);
|
|
89
|
-
if (this.
|
|
179
|
+
if (this.emittedNames.has(brandName))
|
|
90
180
|
return null;
|
|
91
181
|
return brandName;
|
|
92
182
|
}
|
|
93
|
-
mapInternal(schema, name, context, visited, indent) {
|
|
183
|
+
mapInternal(schema, name, context, visited, indent, spine) {
|
|
94
184
|
if (isRefObject(schema)) {
|
|
95
185
|
const refStr = schema.$ref;
|
|
96
186
|
const refName = this.typeNameGenerator(refStr);
|
|
187
|
+
if (this.discriminatorRegistry) {
|
|
188
|
+
return this.translateRefThroughSeam(refStr, refName, context, visited, indent, spine);
|
|
189
|
+
}
|
|
97
190
|
let resolved;
|
|
98
191
|
try {
|
|
99
192
|
resolved = this.resolver.resolveSchema(schema);
|
|
@@ -104,9 +197,8 @@ export class SchemaMapper {
|
|
|
104
197
|
if (resolved) {
|
|
105
198
|
const discInfo = this.resolveDiscriminatorInfo(resolved, refStr);
|
|
106
199
|
if (discInfo) {
|
|
107
|
-
const expanded = this.mapInternal(resolved, undefined, context, visited, indent);
|
|
108
|
-
expanded
|
|
109
|
-
return expanded;
|
|
200
|
+
const expanded = this.mapInternal(resolved, undefined, context, visited, indent, undefined);
|
|
201
|
+
return this.appendDiscriminatorLiteral(expanded, discInfo.propertyName, escapeStringLiteral(discInfo.literalValue));
|
|
110
202
|
}
|
|
111
203
|
}
|
|
112
204
|
return { tsType: refName, imports: [refName] };
|
|
@@ -122,7 +214,7 @@ export class SchemaMapper {
|
|
|
122
214
|
// TODO: Remove deprecated nullable warning and handling when OpenAPI 3.1 support is complete
|
|
123
215
|
// The 'nullable' property is deprecated in OpenAPI 3.1 in favor of type arrays like ["string", "null"]
|
|
124
216
|
// This warning should be removed once full type array support is implemented
|
|
125
|
-
if (s.nullable === true && !this.nullableWarned) {
|
|
217
|
+
if (s.nullable === true && this.effectiveVersion !== '3.0' && !this.nullableWarned) {
|
|
126
218
|
this.warnSink('Warning: \'nullable\' is deprecated in OpenAPI 3.1. Use \'type: ["string", "null"]\' instead.');
|
|
127
219
|
this.nullableWarned = true;
|
|
128
220
|
}
|
|
@@ -134,7 +226,7 @@ export class SchemaMapper {
|
|
|
134
226
|
return { tsType, imports: [] };
|
|
135
227
|
}
|
|
136
228
|
if (s.allOf !== undefined && s.allOf.length > 0) {
|
|
137
|
-
const result = this.mapCombinator(s.allOf, '&', context, visited, indent);
|
|
229
|
+
const result = this.mapCombinator(s.allOf, '&', context, visited, indent, spine);
|
|
138
230
|
if (s.nullable === true) {
|
|
139
231
|
return {
|
|
140
232
|
tsType: needsParens(result.tsType)
|
|
@@ -147,8 +239,8 @@ export class SchemaMapper {
|
|
|
147
239
|
}
|
|
148
240
|
if (s.oneOf !== undefined && s.oneOf.length > 0) {
|
|
149
241
|
const result = s.discriminator
|
|
150
|
-
? this.mapDiscriminatedUnion(s.oneOf, s.discriminator, context, visited, indent)
|
|
151
|
-
: this.mapCombinator(s.oneOf, '|', context, visited, indent);
|
|
242
|
+
? this.mapDiscriminatedUnion(s.oneOf, s.discriminator, context, visited, indent, spine)
|
|
243
|
+
: this.mapCombinator(s.oneOf, '|', context, visited, indent, spine);
|
|
152
244
|
if (s.nullable === true) {
|
|
153
245
|
return {
|
|
154
246
|
tsType: needsParens(result.tsType)
|
|
@@ -161,8 +253,8 @@ export class SchemaMapper {
|
|
|
161
253
|
}
|
|
162
254
|
if (s.anyOf !== undefined && s.anyOf.length > 0) {
|
|
163
255
|
const result = s.discriminator
|
|
164
|
-
? this.mapDiscriminatedUnion(s.anyOf, s.discriminator, context, visited, indent)
|
|
165
|
-
: this.mapCombinator(s.anyOf, '|', context, visited, indent);
|
|
256
|
+
? this.mapDiscriminatedUnion(s.anyOf, s.discriminator, context, visited, indent, spine)
|
|
257
|
+
: this.mapCombinator(s.anyOf, '|', context, visited, indent, spine);
|
|
166
258
|
if (s.nullable === true) {
|
|
167
259
|
return {
|
|
168
260
|
tsType: needsParens(result.tsType)
|
|
@@ -182,7 +274,7 @@ export class SchemaMapper {
|
|
|
182
274
|
if (nonNull.length === 0) {
|
|
183
275
|
return { tsType: 'null', imports: [] };
|
|
184
276
|
}
|
|
185
|
-
const baseResult = this.mapInternal({ ...s, type: nonNull[0] }, name, context, new Set(visited), indent);
|
|
277
|
+
const baseResult = this.mapInternal({ ...s, type: nonNull[0] }, name, context, new Set(visited), indent, spine);
|
|
186
278
|
if (hasNull) {
|
|
187
279
|
return {
|
|
188
280
|
tsType: `${baseResult.tsType} | null`,
|
|
@@ -239,11 +331,96 @@ export class SchemaMapper {
|
|
|
239
331
|
case 'array':
|
|
240
332
|
return this.mapArray(s, context, visited, indent);
|
|
241
333
|
case 'object':
|
|
242
|
-
return this.mapObject(s, name, context, visited, indent);
|
|
334
|
+
return this.mapObject(s, name, context, visited, indent, spine);
|
|
243
335
|
default:
|
|
244
336
|
return { tsType: 'unknown', imports: [] };
|
|
245
337
|
}
|
|
246
338
|
}
|
|
339
|
+
/**
|
|
340
|
+
* The single ref-translation seam (site 1). When the mapper carries a
|
|
341
|
+
* discriminator registry, EVERY `$ref` resolves through here:
|
|
342
|
+
*
|
|
343
|
+
* - a discriminator BASE becomes `{Base}Variant` at all sites except
|
|
344
|
+
* inside a same-family member's own definition spine, where it stays
|
|
345
|
+
* the bare base name (structural inheritance, no circularity — D1);
|
|
346
|
+
* - a same-family mapping target inside a spine becomes `Omit<M, 'P'>`,
|
|
347
|
+
* falling back to inline expansion WITHOUT the literal when M is a
|
|
348
|
+
* union, nullable, unnamed or non-object (D2/D4);
|
|
349
|
+
* - a mapping target at any other site is its bare name — the literal is
|
|
350
|
+
* injected exactly once, at the target's own named definition.
|
|
351
|
+
*/
|
|
352
|
+
translateRefThroughSeam(refStr, refName, context, visited, indent, spine) {
|
|
353
|
+
const registry = this.discriminatorRegistry;
|
|
354
|
+
const canonical = this.canonicalSchemasRef(refStr);
|
|
355
|
+
const baseFamily = registry.baseRefs.get(refStr) ?? registry.baseRefs.get(canonical);
|
|
356
|
+
if (baseFamily) {
|
|
357
|
+
if (spine && spine.familyId === baseFamily.familyId) {
|
|
358
|
+
return { tsType: baseFamily.baseTypeName, imports: [baseFamily.baseTypeName] };
|
|
359
|
+
}
|
|
360
|
+
return { tsType: baseFamily.variantUnionName, imports: [baseFamily.variantUnionName] };
|
|
361
|
+
}
|
|
362
|
+
const entry = registry.byRef.get(refStr) ?? registry.byRef.get(canonical);
|
|
363
|
+
if (entry) {
|
|
364
|
+
if (spine && spine.familyId === entry.familyId) {
|
|
365
|
+
return this.mapSameFamilySpineRef(entry, context, visited, indent);
|
|
366
|
+
}
|
|
367
|
+
if (entry.isNamed) {
|
|
368
|
+
return { tsType: entry.typeName, imports: [entry.typeName] };
|
|
369
|
+
}
|
|
370
|
+
// Unnamed target at a leaf site: expand inline and append the literal
|
|
371
|
+
// here — the target has no named definition to carry it.
|
|
372
|
+
const resolved = this.tryResolveRef(entry.refStr);
|
|
373
|
+
if (resolved) {
|
|
374
|
+
const expanded = this.mapInternal(resolved, undefined, context, visited, indent, spineForEntry(entry));
|
|
375
|
+
return this.appendDiscriminatorLiteral(expanded, entry.propertyName, entry.literalValue);
|
|
376
|
+
}
|
|
377
|
+
return { tsType: entry.typeName, imports: [entry.typeName] };
|
|
378
|
+
}
|
|
379
|
+
return { tsType: refName, imports: [refName] };
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* D2/D4 spine rule for a same-family `$ref`. `Omit<M, 'P'>` strips the
|
|
383
|
+
* sibling's own literal so the appender can re-add ours; the inline-strip
|
|
384
|
+
* fallback covers the cases where `Omit` would silently drop data
|
|
385
|
+
* (union target: `Omit<A|B,K>` drops variant props; nullable target:
|
|
386
|
+
* `Omit<M|null,K>` collapses to `{}`; unnamed/non-object target).
|
|
387
|
+
*/
|
|
388
|
+
mapSameFamilySpineRef(entry, context, visited, indent) {
|
|
389
|
+
const resolved = this.tryResolveRef(entry.refStr);
|
|
390
|
+
if (entry.isNamed && !entry.isUnion && !entry.isNullable && this.isObjectIshSchema(resolved)) {
|
|
391
|
+
const key = `'${escapeStringLiteral(entry.propertyName)}'`;
|
|
392
|
+
return { tsType: `Omit<${entry.typeName}, ${key}>`, imports: [entry.typeName] };
|
|
393
|
+
}
|
|
394
|
+
if (resolved) {
|
|
395
|
+
return this.mapInternal(resolved, undefined, context, visited, indent, spineForEntry(entry));
|
|
396
|
+
}
|
|
397
|
+
return { tsType: entry.typeName, imports: [entry.typeName] };
|
|
398
|
+
}
|
|
399
|
+
/** Normalize a `#/components/schemas/…` ref to its canonically-encoded form (`a/b` ↔ `a~1b`). */
|
|
400
|
+
canonicalSchemasRef(refStr) {
|
|
401
|
+
if (!refStr.startsWith('#/components/schemas/'))
|
|
402
|
+
return refStr;
|
|
403
|
+
return `#/components/schemas/${encodePointerSegment(decodedLastRefSegment(refStr))}`;
|
|
404
|
+
}
|
|
405
|
+
tryResolveRef(refStr) {
|
|
406
|
+
try {
|
|
407
|
+
return this.resolver.resolveSchema({ $ref: refStr });
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
return undefined;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
isObjectIshSchema(s) {
|
|
414
|
+
if (!s)
|
|
415
|
+
return false;
|
|
416
|
+
if (s.type === 'object')
|
|
417
|
+
return true;
|
|
418
|
+
if (Array.isArray(s.type))
|
|
419
|
+
return s.type.includes('object');
|
|
420
|
+
if (s.allOf !== undefined && s.allOf.length > 0)
|
|
421
|
+
return true;
|
|
422
|
+
return s.type === undefined && s.properties !== undefined;
|
|
423
|
+
}
|
|
247
424
|
resolveDiscriminatorInfo(schema, refStr) {
|
|
248
425
|
const schemaName = this.typeNameGenerator(refStr);
|
|
249
426
|
const target = this.discriminatorTargets.get(schemaName);
|
|
@@ -272,7 +449,7 @@ export class SchemaMapper {
|
|
|
272
449
|
return values
|
|
273
450
|
.map((v) => {
|
|
274
451
|
if (typeof v === 'string')
|
|
275
|
-
return `'${v}'`;
|
|
452
|
+
return `'${escapeStringLiteral(v)}'`;
|
|
276
453
|
if (typeof v === 'number')
|
|
277
454
|
return String(v);
|
|
278
455
|
if (typeof v === 'boolean')
|
|
@@ -283,8 +460,8 @@ export class SchemaMapper {
|
|
|
283
460
|
})
|
|
284
461
|
.join(' | ');
|
|
285
462
|
}
|
|
286
|
-
mapCombinator(schemas, kind, context, visited, indent) {
|
|
287
|
-
const results = schemas.map((s) => this.mapInternal(s, undefined, context, visited, indent));
|
|
463
|
+
mapCombinator(schemas, kind, context, visited, indent, spine) {
|
|
464
|
+
const results = schemas.map((s) => this.mapInternal(s, undefined, context, visited, indent, spine));
|
|
288
465
|
const allImports = [];
|
|
289
466
|
for (const r of results) {
|
|
290
467
|
allImports.push(...r.imports);
|
|
@@ -298,20 +475,83 @@ export class SchemaMapper {
|
|
|
298
475
|
});
|
|
299
476
|
return { tsType: parts.join(separator), imports: allImports };
|
|
300
477
|
}
|
|
301
|
-
mapDiscriminatedUnion(schemas, discriminator, context, visited, indent) {
|
|
478
|
+
mapDiscriminatedUnion(schemas, discriminator, context, visited, indent, spine) {
|
|
302
479
|
const propertyName = discriminator.propertyName;
|
|
303
480
|
const mapping = discriminator.mapping;
|
|
304
481
|
const allImports = [];
|
|
305
482
|
const parts = [];
|
|
306
483
|
for (const schema of schemas) {
|
|
307
|
-
|
|
308
|
-
|
|
484
|
+
if (this.discriminatorRegistry && isRefObject(schema)) {
|
|
485
|
+
const refStr = schema.$ref;
|
|
486
|
+
const canonical = this.canonicalSchemasRef(refStr);
|
|
487
|
+
const entry = this.discriminatorRegistry.byRef.get(refStr) ??
|
|
488
|
+
this.discriminatorRegistry.byRef.get(canonical);
|
|
489
|
+
// D7: registered family variants are bare names — their named
|
|
490
|
+
// definitions already carry the literal exactly once. An explicit
|
|
491
|
+
// mapping defines the family's membership: when one exists, a
|
|
492
|
+
// oneOf member absent from it is foreign (wrapper + warn below);
|
|
493
|
+
// without a mapping every oneOf ref is an implicit member (D3).
|
|
494
|
+
const mappedRef = mapping !== undefined &&
|
|
495
|
+
(Object.values(mapping).includes(refStr) || Object.values(mapping).includes(canonical));
|
|
496
|
+
if (entry && entry.propertyName === propertyName && (mapping === undefined || mappedRef)) {
|
|
497
|
+
if (entry.isNamed) {
|
|
498
|
+
allImports.push(entry.typeName);
|
|
499
|
+
parts.push(entry.typeName);
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
const resolved = this.tryResolveRef(entry.refStr);
|
|
503
|
+
if (resolved) {
|
|
504
|
+
const expanded = this.mapInternal(resolved, undefined, context, visited, indent, spineForEntry(entry));
|
|
505
|
+
allImports.push(...expanded.imports);
|
|
506
|
+
parts.push(this.appendDiscriminatorLiteral(expanded, propertyName, entry.literalValue).tsType);
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
// Foreign (non-family) ref: keep the literal wrapper and warn —
|
|
511
|
+
// nothing guarantees the target declares its own discriminant.
|
|
512
|
+
this.warnSink(`Warning: discriminated union member "${refStr}" is not registered in a discriminator family; keeping the inline '{ ${propertyName}: <literal> } &' wrapper.\n`);
|
|
513
|
+
}
|
|
514
|
+
const discriminantValue = this.discriminatorRegistry
|
|
515
|
+
? this.resolveRegistryDiscriminantValue(schema, propertyName, mapping)
|
|
516
|
+
: this.resolveDiscriminantValue(schema, propertyName, mapping);
|
|
517
|
+
const variantResult = this.mapInternal(schema, undefined, context, visited, indent, this.discriminatorRegistry ? undefined : spine);
|
|
309
518
|
allImports.push(...variantResult.imports);
|
|
310
519
|
const quotedProp = quoteKey(propertyName);
|
|
311
520
|
parts.push(`({ ${quotedProp}: '${discriminantValue}' } & ${variantResult.tsType})`);
|
|
312
521
|
}
|
|
313
522
|
return { tsType: parts.join(' | '), imports: allImports };
|
|
314
523
|
}
|
|
524
|
+
/**
|
|
525
|
+
* D3 literal precedence for registry-mode wrapper literals (inline variant
|
|
526
|
+
* schemas and foreign refs): mapping key > own `const` on the discriminant
|
|
527
|
+
* property > single-value `enum` > RAW last ref segment (the runtime
|
|
528
|
+
* value, NOT the sanitized type name). Values are escaped for a
|
|
529
|
+
* single-quoted TS string.
|
|
530
|
+
*/
|
|
531
|
+
resolveRegistryDiscriminantValue(schema, propertyName, mapping) {
|
|
532
|
+
if (mapping && isRefObject(schema)) {
|
|
533
|
+
const refStr = schema.$ref;
|
|
534
|
+
for (const [value, ref] of Object.entries(mapping)) {
|
|
535
|
+
if (ref === refStr)
|
|
536
|
+
return escapeStringLiteral(value);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
const resolved = isRefObject(schema)
|
|
540
|
+
? this.tryResolveRef(schema.$ref)
|
|
541
|
+
: schema;
|
|
542
|
+
const propSchema = resolved?.properties?.[propertyName];
|
|
543
|
+
if (propSchema && propSchema.const !== undefined) {
|
|
544
|
+
return escapeStringLiteral(String(propSchema.const));
|
|
545
|
+
}
|
|
546
|
+
if (propSchema && propSchema.enum !== undefined && propSchema.enum.length === 1) {
|
|
547
|
+
return escapeStringLiteral(String(propSchema.enum[0]));
|
|
548
|
+
}
|
|
549
|
+
if (isRefObject(schema)) {
|
|
550
|
+
const refStr = schema.$ref;
|
|
551
|
+
return escapeStringLiteral(decodedLastRefSegment(refStr));
|
|
552
|
+
}
|
|
553
|
+
return 'unknown';
|
|
554
|
+
}
|
|
315
555
|
resolveDiscriminantValue(schema, propertyName, mapping) {
|
|
316
556
|
// Try explicit mapping first
|
|
317
557
|
if (mapping && isRefObject(schema)) {
|
|
@@ -343,7 +583,7 @@ export class SchemaMapper {
|
|
|
343
583
|
imports: [],
|
|
344
584
|
};
|
|
345
585
|
}
|
|
346
|
-
const itemResult = this.mapInternal(schema.items, undefined, context, visited, indent);
|
|
586
|
+
const itemResult = this.mapInternal(schema.items, undefined, context, visited, indent, undefined);
|
|
347
587
|
const tsType = isComplexType(itemResult.tsType)
|
|
348
588
|
? `Array<${itemResult.tsType}>`
|
|
349
589
|
: `${itemResult.tsType}[]`;
|
|
@@ -378,7 +618,7 @@ export class SchemaMapper {
|
|
|
378
618
|
const ind = indentBy(indentLevel);
|
|
379
619
|
return block.split('\n').map((line) => `${ind}${line}`);
|
|
380
620
|
}
|
|
381
|
-
mapObject(schema, name, context, visited, indent) {
|
|
621
|
+
mapObject(schema, name, context, visited, indent, spine) {
|
|
382
622
|
const properties = schema.properties ?? {};
|
|
383
623
|
const requiredSet = new Set(schema.required ?? []);
|
|
384
624
|
const propNames = Object.keys(properties);
|
|
@@ -393,6 +633,19 @@ export class SchemaMapper {
|
|
|
393
633
|
return false;
|
|
394
634
|
return true;
|
|
395
635
|
});
|
|
636
|
+
// Inside a mapping target's own definition the discriminator property is
|
|
637
|
+
// supplied by the single literal append — an own redeclaration (const or
|
|
638
|
+
// enum) would intersect a conflicting literal and collapse to `never`.
|
|
639
|
+
if (spine) {
|
|
640
|
+
const ownDiscIndex = filteredPropNames.indexOf(spine.propertyName);
|
|
641
|
+
if (ownDiscIndex !== -1) {
|
|
642
|
+
const ownValue = ownDeclaredDiscriminant(properties[spine.propertyName]);
|
|
643
|
+
if (ownValue !== undefined && escapeStringLiteral(ownValue) !== spine.literalValue) {
|
|
644
|
+
this.warnSink(`Warning: Discriminator mapping key "${spine.literalValue}" for property "${spine.propertyName}" conflicts with the variant's own declared value "${ownValue}"; the mapping key wins.\n`);
|
|
645
|
+
}
|
|
646
|
+
filteredPropNames.splice(ownDiscIndex, 1);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
396
649
|
const ownIndent = indentBy(indent);
|
|
397
650
|
const memberIndent = indentBy(indent + 1);
|
|
398
651
|
const memberLines = [];
|
|
@@ -407,7 +660,7 @@ export class SchemaMapper {
|
|
|
407
660
|
}
|
|
408
661
|
for (const propName of filteredPropNames) {
|
|
409
662
|
const propSchema = properties[propName];
|
|
410
|
-
const propResult = this.mapInternal(propSchema, undefined, context, visited, indent + 1);
|
|
663
|
+
const propResult = this.mapInternal(propSchema, undefined, context, visited, indent + 1, undefined);
|
|
411
664
|
allImports.push(...propResult.imports);
|
|
412
665
|
memberLines.push(...this.renderPropertyJsDoc(propSchema, indent + 1));
|
|
413
666
|
const optional = requiredSet.has(propName) ? '' : '?';
|
|
@@ -423,7 +676,7 @@ export class SchemaMapper {
|
|
|
423
676
|
indexSignature = '[key: string]: unknown';
|
|
424
677
|
}
|
|
425
678
|
else if (additionalProps !== undefined && typeof additionalProps === 'object') {
|
|
426
|
-
const addPropResult = this.mapInternal(additionalProps, undefined, context, visited, indent + 1);
|
|
679
|
+
const addPropResult = this.mapInternal(additionalProps, undefined, context, visited, indent + 1, undefined);
|
|
427
680
|
allImports.push(...addPropResult.imports);
|
|
428
681
|
indexSignature = `[key: string]: ${addPropResult.tsType}`;
|
|
429
682
|
}
|
|
@@ -471,7 +724,9 @@ export class SchemaMapper {
|
|
|
471
724
|
}
|
|
472
725
|
if (schema.nullable === true) {
|
|
473
726
|
return {
|
|
474
|
-
tsType:
|
|
727
|
+
tsType: hasTopLevelUnion(result.tsType)
|
|
728
|
+
? `(${result.tsType}) | null`
|
|
729
|
+
: `${result.tsType} | null`,
|
|
475
730
|
imports: result.imports,
|
|
476
731
|
};
|
|
477
732
|
}
|
package/dist/analyzer/types.d.ts
CHANGED
|
@@ -95,7 +95,9 @@ export interface AnalyzedSpec {
|
|
|
95
95
|
/**
|
|
96
96
|
* Section-1 component schema declarations as finished entries, in the
|
|
97
97
|
* pre-refactor emission order: topologically sorted schemas first, then
|
|
98
|
-
*
|
|
98
|
+
* one always-emitted `{Base}Variant` union per discriminator family
|
|
99
|
+
* (members = mapping values ∪ implicit oneOf/anyOf refs, sourced from the
|
|
100
|
+
* discriminator registry; collision-safe names) in family discovery order.
|
|
99
101
|
*/
|
|
100
102
|
schemaTypes: TypeDeclaration[];
|
|
101
103
|
/** Branded format types discovered during mapping, in discovery order. */
|
|
@@ -116,4 +118,9 @@ export interface AnalyzeOptions {
|
|
|
116
118
|
resolver?: RefResolver;
|
|
117
119
|
/** Method naming strategy; defaults to `'path-based'`. */
|
|
118
120
|
strategy?: MethodNameStrategy;
|
|
121
|
+
/**
|
|
122
|
+
* Effective OpenAPI dialect, sourced from `VersionProfile.effective`.
|
|
123
|
+
* Omitted is treated as `'3.1'`.
|
|
124
|
+
*/
|
|
125
|
+
effectiveVersion?: '3.0' | '3.1';
|
|
119
126
|
}
|
package/dist/cli/impl.js
CHANGED
|
@@ -165,7 +165,10 @@ async function runOneTarget(target, context) {
|
|
|
165
165
|
};
|
|
166
166
|
const { preserveRefSiblings } = profile;
|
|
167
167
|
context.process.stdout.write('Generating client...\n');
|
|
168
|
-
await generateFullOutput(doc, config, {
|
|
168
|
+
await generateFullOutput(doc, config, {
|
|
169
|
+
preserveRefSiblings,
|
|
170
|
+
effectiveVersion: profile.effective,
|
|
171
|
+
});
|
|
169
172
|
context.process.stdout.write(`✅ Success! Generated client files:\n`);
|
|
170
173
|
context.process.stdout.write(` - ${target.outputDir}/contracts.ts\n`);
|
|
171
174
|
context.process.stdout.write(` - ${target.outputDir}/client.ts\n`);
|
package/dist/pipeline.d.ts
CHANGED
|
@@ -4,6 +4,8 @@ import type { OpenAPIDocument } from './types/openapi.js';
|
|
|
4
4
|
export interface GenerationOptions {
|
|
5
5
|
/** When true, sibling properties alongside $ref are preserved (OpenAPI 3.1 behavior). */
|
|
6
6
|
preserveRefSiblings?: boolean;
|
|
7
|
+
/** Effective OpenAPI dialect, sourced from `VersionProfile.effective`. */
|
|
8
|
+
effectiveVersion?: '3.0' | '3.1';
|
|
7
9
|
}
|
|
8
10
|
/**
|
|
9
11
|
* Generate and write all output files to disk: builds the resolver, runs the
|
package/dist/pipeline.js
CHANGED
|
@@ -15,6 +15,7 @@ export async function generateFullOutput(doc, config, options) {
|
|
|
15
15
|
const analyzed = analyze(doc, {
|
|
16
16
|
resolver,
|
|
17
17
|
strategy: config.methodNameStrategy ?? 'path-based',
|
|
18
|
+
effectiveVersion: options?.effectiveVersion,
|
|
18
19
|
});
|
|
19
20
|
const { contracts, client, index } = generateOutput(analyzed, config);
|
|
20
21
|
await mkdir(config.outputDir, { recursive: true });
|
package/dist/utils/proxy.d.ts
CHANGED
|
@@ -3,4 +3,6 @@ export type LoadOptions = {
|
|
|
3
3
|
};
|
|
4
4
|
export declare function assertValidProxyUrl(url: string): void;
|
|
5
5
|
export declare function hasProxyEnv(): boolean;
|
|
6
|
+
/** True when the dynamic `import('undici')` failed because undici is not installed (Node: ERR_MODULE_NOT_FOUND; Bun: "Cannot find package" message). */
|
|
7
|
+
export declare function isMissingUndiciError(err: unknown): boolean;
|
|
6
8
|
export declare function fetchSpec(url: string, opts?: LoadOptions): Promise<Response>;
|
package/dist/utils/proxy.js
CHANGED
|
@@ -48,6 +48,16 @@ export function hasProxyEnv() {
|
|
|
48
48
|
process.env.HTTPS_PROXY ||
|
|
49
49
|
process.env.https_proxy);
|
|
50
50
|
}
|
|
51
|
+
/** True when the dynamic `import('undici')` failed because undici is not installed (Node: ERR_MODULE_NOT_FOUND; Bun: "Cannot find package" message). */
|
|
52
|
+
export function isMissingUndiciError(err) {
|
|
53
|
+
if (!(err instanceof Error))
|
|
54
|
+
return false;
|
|
55
|
+
const code = err.code;
|
|
56
|
+
if (code === 'ERR_MODULE_NOT_FOUND')
|
|
57
|
+
return true;
|
|
58
|
+
return /Cannot find (?:module|package) ['"]?undici/.test(err.message);
|
|
59
|
+
}
|
|
60
|
+
const MISSING_UNDICI_MESSAGE = "Proxy support requires the 'undici' package. Install it: npm install undici";
|
|
51
61
|
export async function fetchSpec(url, opts) {
|
|
52
62
|
if (opts?.proxy) {
|
|
53
63
|
assertValidProxyUrl(opts.proxy);
|
|
@@ -59,6 +69,9 @@ export async function fetchSpec(url, opts) {
|
|
|
59
69
|
}));
|
|
60
70
|
}
|
|
61
71
|
catch (err) {
|
|
72
|
+
if (isMissingUndiciError(err)) {
|
|
73
|
+
throw new Error(MISSING_UNDICI_MESSAGE);
|
|
74
|
+
}
|
|
62
75
|
throw new Error(`Failed to fetch spec from URL via proxy ${redacted}: ${describeFetchError(err)}`, {
|
|
63
76
|
cause: err,
|
|
64
77
|
});
|
|
@@ -72,6 +85,9 @@ export async function fetchSpec(url, opts) {
|
|
|
72
85
|
}));
|
|
73
86
|
}
|
|
74
87
|
catch (err) {
|
|
88
|
+
if (isMissingUndiciError(err)) {
|
|
89
|
+
throw new Error(MISSING_UNDICI_MESSAGE);
|
|
90
|
+
}
|
|
75
91
|
throw new Error(`Failed to fetch spec from URL via proxy env: ${describeFetchError(err)}`, {
|
|
76
92
|
cause: err,
|
|
77
93
|
});
|
package/dist/utils/string.d.ts
CHANGED
|
@@ -26,6 +26,13 @@ export declare function isReservedWord(str: string): boolean;
|
|
|
26
26
|
* @returns Safe TypeScript identifier
|
|
27
27
|
*/
|
|
28
28
|
export declare function sanitizeIdentifier(str: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* Escape a value for interpolation inside a TypeScript single-quoted string
|
|
31
|
+
* literal (backslash first, then the quote itself)
|
|
32
|
+
* @param value The raw string value
|
|
33
|
+
* @returns The value with `\` and `'` escaped
|
|
34
|
+
*/
|
|
35
|
+
export declare function escapeStringLiteral(value: string): string;
|
|
29
36
|
/**
|
|
30
37
|
* Quote a key if needed for TypeScript object literals
|
|
31
38
|
* @param key The key to potentially quote
|
package/dist/utils/string.js
CHANGED
|
@@ -163,6 +163,15 @@ export function sanitizeIdentifier(str) {
|
|
|
163
163
|
}
|
|
164
164
|
return final;
|
|
165
165
|
}
|
|
166
|
+
/**
|
|
167
|
+
* Escape a value for interpolation inside a TypeScript single-quoted string
|
|
168
|
+
* literal (backslash first, then the quote itself)
|
|
169
|
+
* @param value The raw string value
|
|
170
|
+
* @returns The value with `\` and `'` escaped
|
|
171
|
+
*/
|
|
172
|
+
export function escapeStringLiteral(value) {
|
|
173
|
+
return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
174
|
+
}
|
|
166
175
|
/**
|
|
167
176
|
* Quote a key if needed for TypeScript object literals
|
|
168
177
|
* @param key The key to potentially quote
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "genoc",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Generate typed HTTP clients from OpenAPI 3.0 / 3.1 specifications",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"client",
|
|
@@ -43,19 +43,27 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@stricli/core": "^1.2.6",
|
|
45
45
|
"lilconfig": "^3.1.3",
|
|
46
|
-
"undici": "^6.13.0",
|
|
47
46
|
"yaml": "^2.2.2",
|
|
48
47
|
"zod": "^4.0.0"
|
|
49
48
|
},
|
|
50
49
|
"devDependencies": {
|
|
51
|
-
"@changesets/cli": "^
|
|
52
|
-
"@types/node": "^
|
|
53
|
-
"oxfmt": "^0.
|
|
54
|
-
"oxlint": "^1.
|
|
50
|
+
"@changesets/cli": "^3.0.3",
|
|
51
|
+
"@types/node": "^26.6.2",
|
|
52
|
+
"oxfmt": "^0.70.0",
|
|
53
|
+
"oxlint": "^1.85.0",
|
|
55
54
|
"typescript": "^6.0.3",
|
|
56
|
-
"
|
|
55
|
+
"undici": "^8",
|
|
56
|
+
"vitest": "^5.0.1"
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"undici": "^6.13.0 || ^7 || ^8"
|
|
60
|
+
},
|
|
61
|
+
"peerDependenciesMeta": {
|
|
62
|
+
"undici": {
|
|
63
|
+
"optional": true
|
|
64
|
+
}
|
|
57
65
|
},
|
|
58
66
|
"engines": {
|
|
59
|
-
"node": ">=18"
|
|
67
|
+
"node": ">=20.18.1"
|
|
60
68
|
}
|
|
61
69
|
}
|