@amritk/helpers 0.4.0 → 0.6.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/dist/generate-type-definition.d.ts +11 -1
- package/dist/generate-type-definition.js +46 -43
- package/dist/ref-to-name.d.ts +10 -7
- package/dist/ref-to-name.js +3 -3
- package/package.json +1 -1
- package/src/generate-type-definition.test.ts +116 -53
- package/src/generate-type-definition.ts +59 -40
- package/src/ref-to-name.test.ts +20 -11
- package/src/ref-to-name.ts +16 -12
|
@@ -1,7 +1,17 @@
|
|
|
1
1
|
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
2
|
+
/** Options controlling generated type output. */
|
|
3
|
+
export type TypeOptions = {
|
|
4
|
+
/** When true, every property, array, and record in the generated types is emitted as readonly. */
|
|
5
|
+
readonly readonly?: boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Suffix appended to every generated type name derived from a `$ref`.
|
|
8
|
+
* Defaults to `''` (no suffix). Set to e.g. `'Object'` to emit `ContactObject`.
|
|
9
|
+
*/
|
|
10
|
+
readonly typeSuffix?: string;
|
|
11
|
+
};
|
|
2
12
|
/**
|
|
3
13
|
* Generates a TypeScript type definition from a JSON Schema.
|
|
4
14
|
* Handles required vs optional properties based on the schema's required array.
|
|
5
15
|
* Uses $comment as inline JSDoc description when present.
|
|
6
16
|
*/
|
|
7
|
-
export declare const generateTypeDefinition: (schema: JSONSchema, typeName: string) => string;
|
|
17
|
+
export declare const generateTypeDefinition: (schema: JSONSchema, typeName: string, options?: TypeOptions) => string;
|
|
@@ -158,15 +158,15 @@ var refToFilename = (ref) => {
|
|
|
158
158
|
};
|
|
159
159
|
|
|
160
160
|
// src/ref-to-name.ts
|
|
161
|
-
var kebabToPascal = (kebab) => {
|
|
161
|
+
var kebabToPascal = (kebab, suffix) => {
|
|
162
162
|
const words = kebab.split("-");
|
|
163
163
|
let pascalCase = "";
|
|
164
164
|
for (const word of words) {
|
|
165
165
|
pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
|
|
166
166
|
}
|
|
167
|
-
return pascalCase +
|
|
167
|
+
return pascalCase + suffix;
|
|
168
168
|
};
|
|
169
|
-
var refToName = (ref) => kebabToPascal(refToFilename(ref));
|
|
169
|
+
var refToName = (ref, suffix = "") => kebabToPascal(refToFilename(ref), suffix);
|
|
170
170
|
|
|
171
171
|
// src/safe-accessor.ts
|
|
172
172
|
var JS_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
@@ -272,12 +272,13 @@ var buildJsDocBlock = (title, description, commentUrl) => {
|
|
|
272
272
|
`;
|
|
273
273
|
return block;
|
|
274
274
|
};
|
|
275
|
-
var getTypeScriptType = (schema) => {
|
|
276
|
-
const base = getUnbrandedType(schema);
|
|
275
|
+
var getTypeScriptType = (schema, options = {}) => {
|
|
276
|
+
const base = getUnbrandedType(schema, options);
|
|
277
277
|
const brand = getMjstBrand(schema);
|
|
278
278
|
return brand ? `(${base} & { readonly __brand: '${brand}' })` : base;
|
|
279
279
|
};
|
|
280
|
-
var
|
|
280
|
+
var recordType = (keyType, valueType, options) => options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`;
|
|
281
|
+
var getUnbrandedType = (schema, options = {}) => {
|
|
281
282
|
if (typeof schema === "boolean") {
|
|
282
283
|
return getBooleanSubSchemaType(schema);
|
|
283
284
|
}
|
|
@@ -296,13 +297,13 @@ var getUnbrandedType = (schema) => {
|
|
|
296
297
|
if (!schema.$ref.startsWith("#")) {
|
|
297
298
|
return "unknown";
|
|
298
299
|
}
|
|
299
|
-
return refToName(schema.$ref);
|
|
300
|
+
return refToName(schema.$ref, options.typeSuffix);
|
|
300
301
|
}
|
|
301
302
|
if (schema.$dynamicRef) {
|
|
302
303
|
if (schema.$dynamicRef === "#meta") {
|
|
303
|
-
return
|
|
304
|
+
return `Schema${options.typeSuffix ?? ""}`;
|
|
304
305
|
}
|
|
305
|
-
return refToName(schema.$dynamicRef);
|
|
306
|
+
return refToName(schema.$dynamicRef, options.typeSuffix);
|
|
306
307
|
}
|
|
307
308
|
if (schema.const !== undefined) {
|
|
308
309
|
return JSON.stringify(schema.const);
|
|
@@ -325,51 +326,51 @@ var getUnbrandedType = (schema) => {
|
|
|
325
326
|
return multiEnumUnion;
|
|
326
327
|
}
|
|
327
328
|
if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
328
|
-
let oneOfUnion = getTypeScriptType(schema.oneOf[0]);
|
|
329
|
+
let oneOfUnion = getTypeScriptType(schema.oneOf[0], options);
|
|
329
330
|
for (let i = 1;i < schema.oneOf.length; i++) {
|
|
330
|
-
oneOfUnion += " | " + getTypeScriptType(schema.oneOf[i]);
|
|
331
|
+
oneOfUnion += " | " + getTypeScriptType(schema.oneOf[i], options);
|
|
331
332
|
}
|
|
332
333
|
return oneOfUnion;
|
|
333
334
|
}
|
|
334
335
|
if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
335
|
-
let anyOfUnion = getTypeScriptType(schema.anyOf[0]);
|
|
336
|
+
let anyOfUnion = getTypeScriptType(schema.anyOf[0], options);
|
|
336
337
|
for (let i = 1;i < schema.anyOf.length; i++) {
|
|
337
|
-
anyOfUnion += " | " + getTypeScriptType(schema.anyOf[i]);
|
|
338
|
+
anyOfUnion += " | " + getTypeScriptType(schema.anyOf[i], options);
|
|
338
339
|
}
|
|
339
340
|
return anyOfUnion;
|
|
340
341
|
}
|
|
341
342
|
if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
342
|
-
let intersectionTypes = getTypeScriptType(schema.allOf[0]);
|
|
343
|
+
let intersectionTypes = getTypeScriptType(schema.allOf[0], options);
|
|
343
344
|
for (let i = 1;i < schema.allOf.length; i++) {
|
|
344
|
-
intersectionTypes += " & " + getTypeScriptType(schema.allOf[i]);
|
|
345
|
+
intersectionTypes += " & " + getTypeScriptType(schema.allOf[i], options);
|
|
345
346
|
}
|
|
346
347
|
return intersectionTypes;
|
|
347
348
|
}
|
|
348
349
|
const conditionalResult = getConditionalObjectSchema(schema);
|
|
349
350
|
if (conditionalResult) {
|
|
350
|
-
const baseType = getTypeScriptType(conditionalResult.schema);
|
|
351
|
+
const baseType = getTypeScriptType(conditionalResult.schema, options);
|
|
351
352
|
if (conditionalResult.thenRef) {
|
|
352
|
-
return `(${baseType}) & ${refToName(conditionalResult.thenRef)}`;
|
|
353
|
+
return `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}`;
|
|
353
354
|
}
|
|
354
355
|
return baseType;
|
|
355
356
|
}
|
|
356
357
|
if (!schema.type) {
|
|
357
358
|
if (schema.additionalProperties !== undefined) {
|
|
358
359
|
if (typeof schema.additionalProperties === "boolean") {
|
|
359
|
-
return
|
|
360
|
+
return recordType("string", getBooleanSubSchemaType(schema.additionalProperties), options);
|
|
360
361
|
}
|
|
361
|
-
return
|
|
362
|
+
return recordType("string", getTypeScriptType(schema.additionalProperties, options), options);
|
|
362
363
|
}
|
|
363
364
|
if (schema.patternProperties && typeof schema.patternProperties === "object") {
|
|
364
365
|
const firstEntry = Object.entries(schema.patternProperties)[0];
|
|
365
366
|
if (firstEntry) {
|
|
366
367
|
const [pattern, value] = firstEntry;
|
|
367
368
|
if (value !== undefined) {
|
|
368
|
-
const valueType = typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value);
|
|
369
|
+
const valueType = typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options);
|
|
369
370
|
if (pattern === "^x-") {
|
|
370
|
-
return `
|
|
371
|
+
return recordType("`x-${string}`", valueType, options);
|
|
371
372
|
}
|
|
372
|
-
return
|
|
373
|
+
return recordType("string", valueType, options);
|
|
373
374
|
}
|
|
374
375
|
}
|
|
375
376
|
}
|
|
@@ -422,41 +423,42 @@ var getUnbrandedType = (schema) => {
|
|
|
422
423
|
return "boolean";
|
|
423
424
|
case "array":
|
|
424
425
|
if (schema.items) {
|
|
425
|
-
const itemType = getTypeScriptType(schema.items);
|
|
426
|
+
const itemType = getTypeScriptType(schema.items, options);
|
|
426
427
|
const wrappedItemType = itemType.includes(" | ") ? `(${itemType})` : itemType;
|
|
427
|
-
return `${wrappedItemType}[]`;
|
|
428
|
+
return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`;
|
|
428
429
|
}
|
|
429
|
-
return "unknown[]";
|
|
430
|
+
return options.readonly ? "readonly unknown[]" : "unknown[]";
|
|
430
431
|
case "object":
|
|
431
432
|
if (schema.properties) {
|
|
433
|
+
const readonlyPrefix = options.readonly ? "readonly " : "";
|
|
432
434
|
let properties = "";
|
|
433
435
|
let first = true;
|
|
434
436
|
for (const key in schema.properties) {
|
|
435
437
|
const propSchema = schema.properties[key];
|
|
436
438
|
const isRequired = schema.required?.includes(key) ?? false;
|
|
437
439
|
const optional = isRequired ? "" : "?";
|
|
438
|
-
const propType = getTypeScriptType(propSchema);
|
|
440
|
+
const propType = getTypeScriptType(propSchema, options);
|
|
439
441
|
if (!first)
|
|
440
442
|
properties += "; ";
|
|
441
|
-
properties += safeKey(key) + optional + ": " + propType;
|
|
443
|
+
properties += readonlyPrefix + safeKey(key) + optional + ": " + propType;
|
|
442
444
|
first = false;
|
|
443
445
|
}
|
|
444
446
|
return "{ " + properties + " }";
|
|
445
447
|
}
|
|
446
448
|
if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
|
|
447
|
-
const additionalPropType = getTypeScriptType(schema.additionalProperties);
|
|
448
|
-
return
|
|
449
|
+
const additionalPropType = getTypeScriptType(schema.additionalProperties, options);
|
|
450
|
+
return recordType("string", additionalPropType, options);
|
|
449
451
|
}
|
|
450
452
|
if (schema.patternProperties && typeof schema.patternProperties === "object") {
|
|
451
453
|
const firstEntry = Object.entries(schema.patternProperties)[0];
|
|
452
454
|
if (firstEntry) {
|
|
453
455
|
const [pattern, patternVal] = firstEntry;
|
|
454
456
|
if (patternVal) {
|
|
455
|
-
const valueType = getTypeScriptType(patternVal);
|
|
457
|
+
const valueType = getTypeScriptType(patternVal, options);
|
|
456
458
|
if (pattern === "^x-") {
|
|
457
|
-
return `
|
|
459
|
+
return recordType("`x-${string}`", valueType, options);
|
|
458
460
|
}
|
|
459
|
-
return
|
|
461
|
+
return recordType("string", valueType, options);
|
|
460
462
|
}
|
|
461
463
|
}
|
|
462
464
|
}
|
|
@@ -465,9 +467,10 @@ var getUnbrandedType = (schema) => {
|
|
|
465
467
|
return "unknown";
|
|
466
468
|
}
|
|
467
469
|
};
|
|
468
|
-
var generateTypeDefinition = (schema, typeName) => {
|
|
470
|
+
var generateTypeDefinition = (schema, typeName, options = {}) => {
|
|
471
|
+
const readonlyPrefix = options.readonly ? "readonly " : "";
|
|
469
472
|
if (!isObjectLikeSchema(schema)) {
|
|
470
|
-
const tsType = getTypeScriptType(schema);
|
|
473
|
+
const tsType = getTypeScriptType(schema, options);
|
|
471
474
|
let result = "";
|
|
472
475
|
if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === "string") {
|
|
473
476
|
result += buildJsDocBlock(typeName, schema.$comment);
|
|
@@ -495,23 +498,23 @@ var generateTypeDefinition = (schema, typeName) => {
|
|
|
495
498
|
if (firstPatternProperty === undefined) {
|
|
496
499
|
return `export type ${typeName} = Record<string, unknown>;`;
|
|
497
500
|
}
|
|
498
|
-
const patternPropType = typeof firstPatternProperty === "boolean" ? getBooleanSubSchemaType(firstPatternProperty) : getTypeScriptType(firstPatternProperty);
|
|
501
|
+
const patternPropType = typeof firstPatternProperty === "boolean" ? getBooleanSubSchemaType(firstPatternProperty) : getTypeScriptType(firstPatternProperty, options);
|
|
499
502
|
const keyType = firstPattern === "^x-" ? "`x-${string}`" : "string";
|
|
500
503
|
let result2 = "";
|
|
501
504
|
if (jsDocTitle && jsDocDescription) {
|
|
502
505
|
result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
|
|
503
506
|
}
|
|
504
|
-
result2 += `export type ${typeName} =
|
|
507
|
+
result2 += `export type ${typeName} = ${recordType(keyType, patternPropType, options)};`;
|
|
505
508
|
return result2;
|
|
506
509
|
}
|
|
507
510
|
if (!hasProperties2 && hasAdditionalProperties2 && normalizedSchema.additionalProperties) {
|
|
508
|
-
const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties);
|
|
511
|
+
const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties, options);
|
|
509
512
|
let result2 = "";
|
|
510
513
|
if (jsDocTitle && jsDocDescription) {
|
|
511
514
|
result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
|
|
512
515
|
}
|
|
513
516
|
result2 += `export type ${typeName} = {
|
|
514
|
-
[key: string]: ${additionalPropType};
|
|
517
|
+
${readonlyPrefix}[key: string]: ${additionalPropType};
|
|
515
518
|
};`;
|
|
516
519
|
return result2;
|
|
517
520
|
}
|
|
@@ -522,8 +525,8 @@ var generateTypeDefinition = (schema, typeName) => {
|
|
|
522
525
|
const propSchema = schemaProps[key];
|
|
523
526
|
const isRequired = normalizedSchema.required?.includes(key) ?? false;
|
|
524
527
|
const optional = isRequired ? "" : "?";
|
|
525
|
-
const propType = getTypeScriptType(propSchema);
|
|
526
|
-
const quotedKey = safeKey(key);
|
|
528
|
+
const propType = getTypeScriptType(propSchema, options);
|
|
529
|
+
const quotedKey = readonlyPrefix + safeKey(key);
|
|
527
530
|
if (!isFirstProp)
|
|
528
531
|
properties += `
|
|
529
532
|
`;
|
|
@@ -540,12 +543,12 @@ var generateTypeDefinition = (schema, typeName) => {
|
|
|
540
543
|
if (isSchemaObject(schema) && Array.isArray(schema.allOf)) {
|
|
541
544
|
for (const entry of schema.allOf) {
|
|
542
545
|
if (isSchemaObject(entry) && entry.$ref) {
|
|
543
|
-
allOfIntersections.push(refToName(entry.$ref));
|
|
546
|
+
allOfIntersections.push(refToName(entry.$ref, options.typeSuffix));
|
|
544
547
|
}
|
|
545
548
|
}
|
|
546
549
|
}
|
|
547
550
|
if (isSchemaObject(schema) && typeof schema.$ref === "string" && schema.$ref.startsWith("#")) {
|
|
548
|
-
allOfIntersections.push(refToName(schema.$ref));
|
|
551
|
+
allOfIntersections.push(refToName(schema.$ref, options.typeSuffix));
|
|
549
552
|
}
|
|
550
553
|
let result = "";
|
|
551
554
|
if (jsDocTitle && jsDocDescription) {
|
|
@@ -555,7 +558,7 @@ var generateTypeDefinition = (schema, typeName) => {
|
|
|
555
558
|
` + properties + `
|
|
556
559
|
}`;
|
|
557
560
|
if (conditionalThenRef) {
|
|
558
|
-
typeBody += " & " + refToName(conditionalThenRef);
|
|
561
|
+
typeBody += " & " + refToName(conditionalThenRef, options.typeSuffix);
|
|
559
562
|
}
|
|
560
563
|
for (const intersectionType of allOfIntersections) {
|
|
561
564
|
typeBody += " & " + intersectionType;
|
package/dist/ref-to-name.d.ts
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Converts a JSON Schema $ref to a type name.
|
|
3
|
-
* Derives the filename via `refToFilename` then converts to PascalCase
|
|
4
|
-
* an
|
|
3
|
+
* Derives the filename via `refToFilename` then converts to PascalCase,
|
|
4
|
+
* appending an optional suffix.
|
|
5
5
|
*
|
|
6
6
|
* Handles all ref forms: internal `#/$defs/...`, `#/definitions/...`, and URI refs.
|
|
7
7
|
*
|
|
8
8
|
* @param ref - The $ref string
|
|
9
|
-
* @
|
|
9
|
+
* @param suffix - Optional suffix appended to the PascalCase name. Defaults to
|
|
10
|
+
* `''` (no suffix). Pass e.g. `'Object'` to get `ContactObject`.
|
|
11
|
+
* @returns The type name in PascalCase with the suffix applied
|
|
10
12
|
*
|
|
11
13
|
* @example
|
|
12
14
|
* ```ts
|
|
13
|
-
* refToName('#/$defs/contact') // '
|
|
14
|
-
* refToName('#/$defs/server-variable') // '
|
|
15
|
-
* refToName('
|
|
15
|
+
* refToName('#/$defs/contact') // 'Contact'
|
|
16
|
+
* refToName('#/$defs/server-variable') // 'ServerVariable'
|
|
17
|
+
* refToName('#/$defs/contact', 'Object') // 'ContactObject'
|
|
18
|
+
* refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'Channel'
|
|
16
19
|
* ```
|
|
17
20
|
*/
|
|
18
|
-
export declare const refToName: (ref: string) => string;
|
|
21
|
+
export declare const refToName: (ref: string, suffix?: string) => string;
|
package/dist/ref-to-name.js
CHANGED
|
@@ -40,15 +40,15 @@ var refToFilename = (ref) => {
|
|
|
40
40
|
};
|
|
41
41
|
|
|
42
42
|
// src/ref-to-name.ts
|
|
43
|
-
var kebabToPascal = (kebab) => {
|
|
43
|
+
var kebabToPascal = (kebab, suffix) => {
|
|
44
44
|
const words = kebab.split("-");
|
|
45
45
|
let pascalCase = "";
|
|
46
46
|
for (const word of words) {
|
|
47
47
|
pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
|
|
48
48
|
}
|
|
49
|
-
return pascalCase +
|
|
49
|
+
return pascalCase + suffix;
|
|
50
50
|
};
|
|
51
|
-
var refToName = (ref) => kebabToPascal(refToFilename(ref));
|
|
51
|
+
var refToName = (ref, suffix = "") => kebabToPascal(refToFilename(ref), suffix);
|
|
52
52
|
export {
|
|
53
53
|
refToName
|
|
54
54
|
};
|
package/package.json
CHANGED
|
@@ -164,9 +164,9 @@ describe('generateTypeDefinition', () => {
|
|
|
164
164
|
},
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
-
const result = generateTypeDefinition(schema, '
|
|
167
|
+
const result = generateTypeDefinition(schema, 'Generic')
|
|
168
168
|
|
|
169
|
-
expect(result).toStrictEqual('export type
|
|
169
|
+
expect(result).toStrictEqual('export type Generic = {\n' + ' metadata?: object;\n' + '};')
|
|
170
170
|
})
|
|
171
171
|
|
|
172
172
|
it('generates type for complex nested structure with arrays and objects', () => {
|
|
@@ -220,9 +220,9 @@ describe('generateTypeDefinition', () => {
|
|
|
220
220
|
properties: {},
|
|
221
221
|
}
|
|
222
222
|
|
|
223
|
-
const result = generateTypeDefinition(schema, '
|
|
223
|
+
const result = generateTypeDefinition(schema, 'Empty')
|
|
224
224
|
|
|
225
|
-
expect(result).toStrictEqual('export type
|
|
225
|
+
expect(result).toStrictEqual('export type Empty = {\n' + '\n' + '};')
|
|
226
226
|
})
|
|
227
227
|
|
|
228
228
|
it('generates type for object with no type specified', () => {
|
|
@@ -575,18 +575,18 @@ describe('generateTypeDefinition', () => {
|
|
|
575
575
|
required: ['title', 'version'],
|
|
576
576
|
}
|
|
577
577
|
|
|
578
|
-
const result = generateTypeDefinition(info, '
|
|
578
|
+
const result = generateTypeDefinition(info, 'Info')
|
|
579
579
|
|
|
580
580
|
expect(result).toStrictEqual(
|
|
581
581
|
'/**\n' +
|
|
582
|
-
'*
|
|
582
|
+
'* Info\n' +
|
|
583
583
|
'*\n' +
|
|
584
584
|
'* https://spec.openapis.org/oas/v3.1#info-object\n' +
|
|
585
585
|
'*/\n' +
|
|
586
|
-
'export type
|
|
586
|
+
'export type Info = {\n' +
|
|
587
587
|
' title: string;\n' +
|
|
588
588
|
' summary?: string;\n' +
|
|
589
|
-
' contact?:
|
|
589
|
+
' contact?: Contact;\n' +
|
|
590
590
|
' version: string;\n' +
|
|
591
591
|
'};',
|
|
592
592
|
)
|
|
@@ -611,18 +611,18 @@ describe('generateTypeDefinition', () => {
|
|
|
611
611
|
},
|
|
612
612
|
}
|
|
613
613
|
|
|
614
|
-
const result = generateTypeDefinition(components, '
|
|
614
|
+
const result = generateTypeDefinition(components, 'Components')
|
|
615
615
|
|
|
616
616
|
expect(result).toStrictEqual(
|
|
617
|
-
'export type
|
|
618
|
-
' responses?: Record<string,
|
|
619
|
-
' parameters?: Record<string,
|
|
620
|
-
' pathItems?: Record<string,
|
|
617
|
+
'export type Components = {\n' +
|
|
618
|
+
' responses?: Record<string, Response>;\n' +
|
|
619
|
+
' parameters?: Record<string, Parameter>;\n' +
|
|
620
|
+
' pathItems?: Record<string, PathItem>;\n' +
|
|
621
621
|
'};',
|
|
622
622
|
)
|
|
623
623
|
})
|
|
624
624
|
|
|
625
|
-
it('generates type for object with paths property as Record<string,
|
|
625
|
+
it('generates type for object with paths property as Record<string, PathItem>', () => {
|
|
626
626
|
const document: JSONSchema.Object = {
|
|
627
627
|
$comment: 'https://spec.openapis.org/oas/v3.1#openapi-object',
|
|
628
628
|
type: 'object',
|
|
@@ -647,8 +647,8 @@ describe('generateTypeDefinition', () => {
|
|
|
647
647
|
'*/\n' +
|
|
648
648
|
'export type Document = {\n' +
|
|
649
649
|
' openapi: string;\n' +
|
|
650
|
-
' info:
|
|
651
|
-
' paths?: Record<string,
|
|
650
|
+
' info: Info;\n' +
|
|
651
|
+
' paths?: Record<string, PathItem>;\n' +
|
|
652
652
|
'};',
|
|
653
653
|
)
|
|
654
654
|
})
|
|
@@ -702,12 +702,12 @@ describe('generateTypeDefinition', () => {
|
|
|
702
702
|
'*/\n' +
|
|
703
703
|
'export type Document = {\n' +
|
|
704
704
|
' openapi: string;\n' +
|
|
705
|
-
' info:
|
|
705
|
+
' info: Info;\n' +
|
|
706
706
|
' jsonSchemaDialect?: string;\n' +
|
|
707
|
-
' servers?:
|
|
708
|
-
' paths?: Record<string,
|
|
709
|
-
' webhooks?: Record<string,
|
|
710
|
-
' components?:
|
|
707
|
+
' servers?: Server[];\n' +
|
|
708
|
+
' paths?: Record<string, PathItem>;\n' +
|
|
709
|
+
' webhooks?: Record<string, PathItem>;\n' +
|
|
710
|
+
' components?: Components;\n' +
|
|
711
711
|
'};',
|
|
712
712
|
)
|
|
713
713
|
})
|
|
@@ -723,15 +723,15 @@ describe('generateTypeDefinition', () => {
|
|
|
723
723
|
},
|
|
724
724
|
}
|
|
725
725
|
|
|
726
|
-
const result = generateTypeDefinition(paths, '
|
|
726
|
+
const result = generateTypeDefinition(paths, 'Paths')
|
|
727
727
|
|
|
728
728
|
expect(result).toStrictEqual(
|
|
729
729
|
'/**\n' +
|
|
730
|
-
'*
|
|
730
|
+
'* Paths\n' +
|
|
731
731
|
'*\n' +
|
|
732
732
|
'* https://spec.openapis.org/oas/v3.1#paths-object\n' +
|
|
733
733
|
'*/\n' +
|
|
734
|
-
'export type
|
|
734
|
+
'export type Paths = Record<string, PathItem>;',
|
|
735
735
|
)
|
|
736
736
|
})
|
|
737
737
|
|
|
@@ -743,7 +743,7 @@ describe('generateTypeDefinition', () => {
|
|
|
743
743
|
name: { type: 'string' as const },
|
|
744
744
|
},
|
|
745
745
|
}
|
|
746
|
-
const result = generateTypeDefinition(schema, '
|
|
746
|
+
const result = generateTypeDefinition(schema, 'InfoExtensions')
|
|
747
747
|
expect(result).toContain("'x-linkedin'?: string;")
|
|
748
748
|
expect(result).toContain('name?: string;')
|
|
749
749
|
})
|
|
@@ -767,11 +767,9 @@ describe('generateTypeDefinition', () => {
|
|
|
767
767
|
},
|
|
768
768
|
}
|
|
769
769
|
|
|
770
|
-
const result = generateTypeDefinition(schema, '
|
|
770
|
+
const result = generateTypeDefinition(schema, 'TypeHttp')
|
|
771
771
|
|
|
772
|
-
expect(result).toStrictEqual(
|
|
773
|
-
'export type TypeHttpObject = {\n' + ' type: "http";\n' + ' scheme: string;\n' + '};',
|
|
774
|
-
)
|
|
772
|
+
expect(result).toStrictEqual('export type TypeHttp = {\n' + ' type: "http";\n' + ' scheme: string;\n' + '};')
|
|
775
773
|
})
|
|
776
774
|
|
|
777
775
|
it('generates required property from then properties without explicit required', () => {
|
|
@@ -792,10 +790,10 @@ describe('generateTypeDefinition', () => {
|
|
|
792
790
|
},
|
|
793
791
|
}
|
|
794
792
|
|
|
795
|
-
const result = generateTypeDefinition(schema, '
|
|
793
|
+
const result = generateTypeDefinition(schema, 'TypeHttp')
|
|
796
794
|
|
|
797
795
|
expect(result).toStrictEqual(
|
|
798
|
-
'export type
|
|
796
|
+
'export type TypeHttp = {\n' + ' type: "http";\n' + ' bearerFormat: string;\n' + '};',
|
|
799
797
|
)
|
|
800
798
|
})
|
|
801
799
|
|
|
@@ -823,9 +821,9 @@ describe('generateTypeDefinition', () => {
|
|
|
823
821
|
},
|
|
824
822
|
}
|
|
825
823
|
|
|
826
|
-
const result = generateTypeDefinition(schema, '
|
|
824
|
+
const result = generateTypeDefinition(schema, 'TypeHttp')
|
|
827
825
|
|
|
828
|
-
expect(result).toContain('*
|
|
826
|
+
expect(result).toContain('* TypeHttp')
|
|
829
827
|
expect(result).toContain('* https://spec.openapis.org/oas/v3.1#security-scheme-object')
|
|
830
828
|
expect(result).toContain('type: "http";')
|
|
831
829
|
expect(result).toContain('scheme: string;')
|
|
@@ -847,13 +845,13 @@ describe('generateTypeDefinition', () => {
|
|
|
847
845
|
allOf: [{ $ref: '#/$defs/type-apikey' }, { $ref: '#/$defs/type-http' }, { $ref: '#/$defs/type-oauth2' }],
|
|
848
846
|
}
|
|
849
847
|
|
|
850
|
-
const result = generateTypeDefinition(securityScheme, '
|
|
848
|
+
const result = generateTypeDefinition(securityScheme, 'SecurityScheme')
|
|
851
849
|
|
|
852
850
|
expect(result).toStrictEqual(
|
|
853
|
-
'export type
|
|
851
|
+
'export type SecurityScheme = {\n' +
|
|
854
852
|
' type: "apiKey" | "http" | "oauth2";\n' +
|
|
855
853
|
' description?: string;\n' +
|
|
856
|
-
'} &
|
|
854
|
+
'} & TypeApikey & TypeHttp & TypeOauth2;',
|
|
857
855
|
)
|
|
858
856
|
})
|
|
859
857
|
|
|
@@ -870,12 +868,12 @@ describe('generateTypeDefinition', () => {
|
|
|
870
868
|
allOf: [{ $ref: '#/$defs/type-apikey' }, { $ref: '#/$defs/type-http' }],
|
|
871
869
|
}
|
|
872
870
|
|
|
873
|
-
const result = generateTypeDefinition(securityScheme, '
|
|
871
|
+
const result = generateTypeDefinition(securityScheme, 'SecurityScheme')
|
|
874
872
|
|
|
875
|
-
expect(result).toContain('*
|
|
873
|
+
expect(result).toContain('* SecurityScheme')
|
|
876
874
|
expect(result).toContain('* https://spec.openapis.org/oas/v3.1#security-scheme-object')
|
|
877
875
|
expect(result).toContain('type: "apiKey" | "http" | "oauth2";')
|
|
878
|
-
expect(result).toContain('} &
|
|
876
|
+
expect(result).toContain('} & TypeApikey & TypeHttp;')
|
|
879
877
|
})
|
|
880
878
|
|
|
881
879
|
it('generates record type for patternProperties-only schema without explicit type', () => {
|
|
@@ -885,9 +883,9 @@ describe('generateTypeDefinition', () => {
|
|
|
885
883
|
},
|
|
886
884
|
}
|
|
887
885
|
|
|
888
|
-
const result = generateTypeDefinition(schema, '
|
|
886
|
+
const result = generateTypeDefinition(schema, 'SpecificationExtensions')
|
|
889
887
|
|
|
890
|
-
expect(result).toStrictEqual('export type
|
|
888
|
+
expect(result).toStrictEqual('export type SpecificationExtensions = Record<`x-${string}`, unknown>;')
|
|
891
889
|
})
|
|
892
890
|
|
|
893
891
|
it('generates Record<string, never> for patternProperties-only schema with false boolean value', () => {
|
|
@@ -899,9 +897,9 @@ describe('generateTypeDefinition', () => {
|
|
|
899
897
|
},
|
|
900
898
|
}
|
|
901
899
|
|
|
902
|
-
const result = generateTypeDefinition(schema, '
|
|
900
|
+
const result = generateTypeDefinition(schema, 'Restricted')
|
|
903
901
|
|
|
904
|
-
expect(result).toStrictEqual('export type
|
|
902
|
+
expect(result).toStrictEqual('export type Restricted = Record<`x-${string}`, never>;')
|
|
905
903
|
})
|
|
906
904
|
|
|
907
905
|
it('generates Schema type for property with $dynamicRef pointing to #meta', () => {
|
|
@@ -930,7 +928,7 @@ describe('generateTypeDefinition', () => {
|
|
|
930
928
|
|
|
931
929
|
const result = generateTypeDefinition(schema, 'ContentContainer')
|
|
932
930
|
|
|
933
|
-
expect(result).toContain('content?:
|
|
931
|
+
expect(result).toContain('content?: Schema')
|
|
934
932
|
})
|
|
935
933
|
|
|
936
934
|
it('generates union type for schema with array of types', () => {
|
|
@@ -1058,12 +1056,12 @@ describe('generateTypeDefinition', () => {
|
|
|
1058
1056
|
},
|
|
1059
1057
|
}
|
|
1060
1058
|
|
|
1061
|
-
const result = generateTypeDefinition(schema, '
|
|
1059
|
+
const result = generateTypeDefinition(schema, 'Callback')
|
|
1062
1060
|
|
|
1063
1061
|
expect(result).toContain('/**')
|
|
1064
|
-
expect(result).toContain('*
|
|
1062
|
+
expect(result).toContain('* Callback')
|
|
1065
1063
|
expect(result).toContain('* https://spec.openapis.org/oas/v3.1#callback-object')
|
|
1066
|
-
expect(result).toContain('[key: string]:
|
|
1064
|
+
expect(result).toContain('[key: string]: PathItem')
|
|
1067
1065
|
})
|
|
1068
1066
|
|
|
1069
1067
|
it('generates type for product schema with required, optional, and array fields', () => {
|
|
@@ -1151,7 +1149,7 @@ describe('generateTypeDefinition', () => {
|
|
|
1151
1149
|
|
|
1152
1150
|
const result = generateTypeDefinition(schema, 'Parameters')
|
|
1153
1151
|
|
|
1154
|
-
expect(result).toBe('export type Parameters = (
|
|
1152
|
+
expect(result).toBe('export type Parameters = (Parameter | Reference)[];')
|
|
1155
1153
|
})
|
|
1156
1154
|
|
|
1157
1155
|
it('emits JSDoc for non-object schemas with a $comment URL', () => {
|
|
@@ -1165,7 +1163,7 @@ describe('generateTypeDefinition', () => {
|
|
|
1165
1163
|
|
|
1166
1164
|
expect(result).toContain('/**')
|
|
1167
1165
|
expect(result).toContain('* https://spec.openapis.org/oas/v3.1#contact-object')
|
|
1168
|
-
expect(result).toContain('export type Contacts =
|
|
1166
|
+
expect(result).toContain('export type Contacts = Server[];')
|
|
1169
1167
|
})
|
|
1170
1168
|
|
|
1171
1169
|
it('emits JSDoc for non-object schemas with a plain-text $comment', () => {
|
|
@@ -1179,7 +1177,7 @@ describe('generateTypeDefinition', () => {
|
|
|
1179
1177
|
|
|
1180
1178
|
expect(result).toContain('/**')
|
|
1181
1179
|
expect(result).toContain('A list of parameters applicable to the operation.')
|
|
1182
|
-
expect(result).toContain('export type Parameters =
|
|
1180
|
+
expect(result).toContain('export type Parameters = Parameter[];')
|
|
1183
1181
|
})
|
|
1184
1182
|
|
|
1185
1183
|
it('generates unknown for external $ref', () => {
|
|
@@ -1188,9 +1186,9 @@ describe('generateTypeDefinition', () => {
|
|
|
1188
1186
|
$ref: 'http://json-schema.org/draft-04/schema#/properties/maximum',
|
|
1189
1187
|
}
|
|
1190
1188
|
|
|
1191
|
-
const result = generateTypeDefinition(schema, '
|
|
1189
|
+
const result = generateTypeDefinition(schema, 'Maximum')
|
|
1192
1190
|
|
|
1193
|
-
expect(result).toBe('export type
|
|
1191
|
+
expect(result).toBe('export type Maximum = unknown;')
|
|
1194
1192
|
})
|
|
1195
1193
|
|
|
1196
1194
|
it('does not emit a trailing blank line in JSDoc when there is no @see link', () => {
|
|
@@ -1202,7 +1200,7 @@ describe('generateTypeDefinition', () => {
|
|
|
1202
1200
|
},
|
|
1203
1201
|
}
|
|
1204
1202
|
|
|
1205
|
-
const result = generateTypeDefinition(schema, '
|
|
1203
|
+
const result = generateTypeDefinition(schema, 'PlainComment')
|
|
1206
1204
|
|
|
1207
1205
|
expect(result).toMatch(/\* A plain-text description with no URL\.\n\*\//)
|
|
1208
1206
|
expect(result).not.toContain('* \n*/')
|
|
@@ -1270,4 +1268,69 @@ describe('generateTypeDefinition', () => {
|
|
|
1270
1268
|
expect(result).not.toContain('doEvil')
|
|
1271
1269
|
expect(result).toBe('export type Bad = string;')
|
|
1272
1270
|
})
|
|
1271
|
+
|
|
1272
|
+
describe('readonly option', () => {
|
|
1273
|
+
it('marks every property as readonly, deeply', () => {
|
|
1274
|
+
const schema: JSONSchema = {
|
|
1275
|
+
type: 'object',
|
|
1276
|
+
properties: {
|
|
1277
|
+
id: { type: 'string' },
|
|
1278
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
1279
|
+
nested: {
|
|
1280
|
+
type: 'object',
|
|
1281
|
+
properties: { value: { type: 'number' } },
|
|
1282
|
+
},
|
|
1283
|
+
},
|
|
1284
|
+
required: ['id'],
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
const result = generateTypeDefinition(schema, 'Doc', { readonly: true })
|
|
1288
|
+
|
|
1289
|
+
expect(result).toContain('readonly id: string;')
|
|
1290
|
+
expect(result).toContain('readonly tags?: readonly string[];')
|
|
1291
|
+
expect(result).toContain('readonly nested?: { readonly value?: number }')
|
|
1292
|
+
})
|
|
1293
|
+
|
|
1294
|
+
it('wraps record types in Readonly', () => {
|
|
1295
|
+
const schema: JSONSchema = {
|
|
1296
|
+
type: 'object',
|
|
1297
|
+
additionalProperties: { type: 'number' },
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
expect(generateTypeDefinition(schema, 'Map', { readonly: true })).toContain('readonly [key: string]: number;')
|
|
1301
|
+
})
|
|
1302
|
+
|
|
1303
|
+
it('leaves output unchanged when readonly is not set', () => {
|
|
1304
|
+
const schema: JSONSchema = {
|
|
1305
|
+
type: 'object',
|
|
1306
|
+
properties: { id: { type: 'string' } },
|
|
1307
|
+
required: ['id'],
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
const result = generateTypeDefinition(schema, 'Doc')
|
|
1311
|
+
expect(result).not.toContain('readonly')
|
|
1312
|
+
expect(result).toContain('id: string;')
|
|
1313
|
+
})
|
|
1314
|
+
})
|
|
1315
|
+
|
|
1316
|
+
describe('typeSuffix', () => {
|
|
1317
|
+
const schema: JSONSchema = {
|
|
1318
|
+
type: 'object',
|
|
1319
|
+
properties: {
|
|
1320
|
+
contact: { $ref: '#/$defs/contact' },
|
|
1321
|
+
},
|
|
1322
|
+
required: ['contact'],
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
it('appends the suffix to ref-derived type names', () => {
|
|
1326
|
+
const result = generateTypeDefinition(schema, 'Document', { typeSuffix: 'Object' })
|
|
1327
|
+
expect(result).toContain('contact: ContactObject;')
|
|
1328
|
+
})
|
|
1329
|
+
|
|
1330
|
+
it('emits no suffix by default', () => {
|
|
1331
|
+
const result = generateTypeDefinition(schema, 'Document')
|
|
1332
|
+
expect(result).toContain('contact: Contact;')
|
|
1333
|
+
expect(result).not.toContain('ContactObject')
|
|
1334
|
+
})
|
|
1335
|
+
})
|
|
1273
1336
|
})
|
|
@@ -10,6 +10,17 @@ type ConditionalObjectResult = {
|
|
|
10
10
|
thenRef: string | null
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
/** Options controlling generated type output. */
|
|
14
|
+
export type TypeOptions = {
|
|
15
|
+
/** When true, every property, array, and record in the generated types is emitted as readonly. */
|
|
16
|
+
readonly readonly?: boolean
|
|
17
|
+
/**
|
|
18
|
+
* Suffix appended to every generated type name derived from a `$ref`.
|
|
19
|
+
* Defaults to `''` (no suffix). Set to e.g. `'Object'` to emit `ContactObject`.
|
|
20
|
+
*/
|
|
21
|
+
readonly typeSuffix?: string
|
|
22
|
+
}
|
|
23
|
+
|
|
13
24
|
const getConditionalObjectSchema = (schema: JSONSchema): ConditionalObjectResult | null => {
|
|
14
25
|
if (!isSchemaObject(schema)) {
|
|
15
26
|
return null
|
|
@@ -113,17 +124,21 @@ const buildJsDocBlock = (title: string, description: string, commentUrl?: string
|
|
|
113
124
|
* type and intersect it with a unique brand marker. This is the recursion entry
|
|
114
125
|
* point, so branded nested fields are wrapped too.
|
|
115
126
|
*/
|
|
116
|
-
const getTypeScriptType = (schema: JSONSchema): string => {
|
|
117
|
-
const base = getUnbrandedType(schema)
|
|
127
|
+
const getTypeScriptType = (schema: JSONSchema, options: TypeOptions = {}): string => {
|
|
128
|
+
const base = getUnbrandedType(schema, options)
|
|
118
129
|
const brand = getMjstBrand(schema)
|
|
119
130
|
return brand ? `(${base} & { readonly __brand: '${brand}' })` : base
|
|
120
131
|
}
|
|
121
132
|
|
|
133
|
+
/** Wraps a `Record<...>` in `Readonly<...>` when readonly output is requested. */
|
|
134
|
+
const recordType = (keyType: string, valueType: string, options: TypeOptions): string =>
|
|
135
|
+
options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`
|
|
136
|
+
|
|
122
137
|
/**
|
|
123
138
|
* Converts a JSON Schema type to its TypeScript equivalent, ignoring any brand.
|
|
124
139
|
* Recursively handles nested objects and arrays.
|
|
125
140
|
*/
|
|
126
|
-
const getUnbrandedType = (schema: JSONSchema): string => {
|
|
141
|
+
const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string => {
|
|
127
142
|
// Boolean schema: `true` means any value is valid (unknown), `false` means no value is valid (never)
|
|
128
143
|
if (typeof schema === 'boolean') {
|
|
129
144
|
return getBooleanSubSchemaType(schema)
|
|
@@ -154,16 +169,16 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
154
169
|
if (!schema.$ref.startsWith('#')) {
|
|
155
170
|
return 'unknown'
|
|
156
171
|
}
|
|
157
|
-
return refToName(schema.$ref)
|
|
172
|
+
return refToName(schema.$ref, options.typeSuffix)
|
|
158
173
|
}
|
|
159
174
|
|
|
160
175
|
// Handle $dynamicRef (used for recursive schemas)
|
|
161
176
|
if (schema.$dynamicRef) {
|
|
162
177
|
// For #meta, this refers to the Schema type itself (JSON Schema 2020-12 $dynamicAnchor pattern)
|
|
163
178
|
if (schema.$dynamicRef === '#meta') {
|
|
164
|
-
return
|
|
179
|
+
return `Schema${options.typeSuffix ?? ''}`
|
|
165
180
|
}
|
|
166
|
-
return refToName(schema.$dynamicRef)
|
|
181
|
+
return refToName(schema.$dynamicRef, options.typeSuffix)
|
|
167
182
|
}
|
|
168
183
|
|
|
169
184
|
// Handle const - literal type
|
|
@@ -195,17 +210,17 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
195
210
|
// Handle union types (oneOf, anyOf) - check this before returning unknown
|
|
196
211
|
if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
197
212
|
// schema.oneOf[0] is safe: we guard with .length > 0 above
|
|
198
|
-
let oneOfUnion = getTypeScriptType(schema.oneOf[0]
|
|
213
|
+
let oneOfUnion = getTypeScriptType(schema.oneOf[0]!, options)
|
|
199
214
|
for (let i = 1; i < schema.oneOf.length; i++) {
|
|
200
|
-
oneOfUnion += ' | ' + getTypeScriptType(schema.oneOf[i]
|
|
215
|
+
oneOfUnion += ' | ' + getTypeScriptType(schema.oneOf[i]!, options)
|
|
201
216
|
}
|
|
202
217
|
return oneOfUnion
|
|
203
218
|
}
|
|
204
219
|
if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
205
220
|
// schema.anyOf[0] is safe: we guard with .length > 0 above
|
|
206
|
-
let anyOfUnion = getTypeScriptType(schema.anyOf[0]
|
|
221
|
+
let anyOfUnion = getTypeScriptType(schema.anyOf[0]!, options)
|
|
207
222
|
for (let i = 1; i < schema.anyOf.length; i++) {
|
|
208
|
-
anyOfUnion += ' | ' + getTypeScriptType(schema.anyOf[i]
|
|
223
|
+
anyOfUnion += ' | ' + getTypeScriptType(schema.anyOf[i]!, options)
|
|
209
224
|
}
|
|
210
225
|
return anyOfUnion
|
|
211
226
|
}
|
|
@@ -213,9 +228,9 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
213
228
|
// Handle allOf (intersection types)
|
|
214
229
|
if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
215
230
|
// schema.allOf[0] is safe: we guard with .length > 0 above
|
|
216
|
-
let intersectionTypes = getTypeScriptType(schema.allOf[0]
|
|
231
|
+
let intersectionTypes = getTypeScriptType(schema.allOf[0]!, options)
|
|
217
232
|
for (let i = 1; i < schema.allOf.length; i++) {
|
|
218
|
-
intersectionTypes += ' & ' + getTypeScriptType(schema.allOf[i]
|
|
233
|
+
intersectionTypes += ' & ' + getTypeScriptType(schema.allOf[i]!, options)
|
|
219
234
|
}
|
|
220
235
|
return intersectionTypes
|
|
221
236
|
}
|
|
@@ -223,9 +238,9 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
223
238
|
// Handle object-like conditional schemas that use if/then without declaring type
|
|
224
239
|
const conditionalResult = getConditionalObjectSchema(schema)
|
|
225
240
|
if (conditionalResult) {
|
|
226
|
-
const baseType = getTypeScriptType(conditionalResult.schema)
|
|
241
|
+
const baseType = getTypeScriptType(conditionalResult.schema, options)
|
|
227
242
|
if (conditionalResult.thenRef) {
|
|
228
|
-
return `(${baseType}) & ${refToName(conditionalResult.thenRef)}`
|
|
243
|
+
return `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}`
|
|
229
244
|
}
|
|
230
245
|
return baseType
|
|
231
246
|
}
|
|
@@ -234,9 +249,9 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
234
249
|
if (!schema.type) {
|
|
235
250
|
if (schema.additionalProperties !== undefined) {
|
|
236
251
|
if (typeof schema.additionalProperties === 'boolean') {
|
|
237
|
-
return
|
|
252
|
+
return recordType('string', getBooleanSubSchemaType(schema.additionalProperties), options)
|
|
238
253
|
}
|
|
239
|
-
return
|
|
254
|
+
return recordType('string', getTypeScriptType(schema.additionalProperties, options), options)
|
|
240
255
|
}
|
|
241
256
|
|
|
242
257
|
if (schema.patternProperties && typeof schema.patternProperties === 'object') {
|
|
@@ -244,13 +259,14 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
244
259
|
if (firstEntry) {
|
|
245
260
|
const [pattern, value] = firstEntry
|
|
246
261
|
if (value !== undefined) {
|
|
247
|
-
const valueType =
|
|
262
|
+
const valueType =
|
|
263
|
+
typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options)
|
|
248
264
|
// The ^x- pattern is a common JSON Schema convention for vendor extensions
|
|
249
265
|
// that maps naturally to the TypeScript template literal `x-${string}`
|
|
250
266
|
if (pattern === '^x-') {
|
|
251
|
-
return `
|
|
267
|
+
return recordType('`x-${string}`', valueType, options)
|
|
252
268
|
}
|
|
253
|
-
return
|
|
269
|
+
return recordType('string', valueType, options)
|
|
254
270
|
}
|
|
255
271
|
}
|
|
256
272
|
}
|
|
@@ -315,16 +331,17 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
315
331
|
// Array
|
|
316
332
|
case 'array':
|
|
317
333
|
if (schema.items) {
|
|
318
|
-
const itemType = getTypeScriptType(schema.items)
|
|
334
|
+
const itemType = getTypeScriptType(schema.items, options)
|
|
319
335
|
// Wrap union types in parentheses so `(A | B)[]` is not misread as `A | B[]`
|
|
320
336
|
const wrappedItemType = itemType.includes(' | ') ? `(${itemType})` : itemType
|
|
321
|
-
return `${wrappedItemType}[]`
|
|
337
|
+
return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`
|
|
322
338
|
}
|
|
323
|
-
return 'unknown[]'
|
|
339
|
+
return options.readonly ? 'readonly unknown[]' : 'unknown[]'
|
|
324
340
|
|
|
325
341
|
// Object
|
|
326
342
|
case 'object':
|
|
327
343
|
if (schema.properties) {
|
|
344
|
+
const readonlyPrefix = options.readonly ? 'readonly ' : ''
|
|
328
345
|
let properties = ''
|
|
329
346
|
let first = true
|
|
330
347
|
for (const key in schema.properties) {
|
|
@@ -332,17 +349,17 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
332
349
|
const propSchema = schema.properties[key]!
|
|
333
350
|
const isRequired = schema.required?.includes(key) ?? false
|
|
334
351
|
const optional = isRequired ? '' : '?'
|
|
335
|
-
const propType = getTypeScriptType(propSchema)
|
|
352
|
+
const propType = getTypeScriptType(propSchema, options)
|
|
336
353
|
if (!first) properties += '; '
|
|
337
|
-
properties += safeKey(key) + optional + ': ' + propType
|
|
354
|
+
properties += readonlyPrefix + safeKey(key) + optional + ': ' + propType
|
|
338
355
|
first = false
|
|
339
356
|
}
|
|
340
357
|
return '{ ' + properties + ' }'
|
|
341
358
|
}
|
|
342
359
|
// Handle additionalProperties with $ref or $dynamicRef
|
|
343
360
|
if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
|
|
344
|
-
const additionalPropType = getTypeScriptType(schema.additionalProperties)
|
|
345
|
-
return
|
|
361
|
+
const additionalPropType = getTypeScriptType(schema.additionalProperties, options)
|
|
362
|
+
return recordType('string', additionalPropType, options)
|
|
346
363
|
}
|
|
347
364
|
// Handle patternProperties as a Record type
|
|
348
365
|
if (schema.patternProperties && typeof schema.patternProperties === 'object') {
|
|
@@ -350,11 +367,11 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
350
367
|
if (firstEntry) {
|
|
351
368
|
const [pattern, patternVal] = firstEntry
|
|
352
369
|
if (patternVal) {
|
|
353
|
-
const valueType = getTypeScriptType(patternVal)
|
|
370
|
+
const valueType = getTypeScriptType(patternVal, options)
|
|
354
371
|
if (pattern === '^x-') {
|
|
355
|
-
return `
|
|
372
|
+
return recordType('`x-${string}`', valueType, options)
|
|
356
373
|
}
|
|
357
|
-
return
|
|
374
|
+
return recordType('string', valueType, options)
|
|
358
375
|
}
|
|
359
376
|
}
|
|
360
377
|
}
|
|
@@ -371,10 +388,12 @@ const getUnbrandedType = (schema: JSONSchema): string => {
|
|
|
371
388
|
* Handles required vs optional properties based on the schema's required array.
|
|
372
389
|
* Uses $comment as inline JSDoc description when present.
|
|
373
390
|
*/
|
|
374
|
-
export const generateTypeDefinition = (schema: JSONSchema, typeName: string): string => {
|
|
391
|
+
export const generateTypeDefinition = (schema: JSONSchema, typeName: string, options: TypeOptions = {}): string => {
|
|
392
|
+
const readonlyPrefix = options.readonly ? 'readonly ' : ''
|
|
393
|
+
|
|
375
394
|
// Handle non-object schemas first
|
|
376
395
|
if (!isObjectLikeSchema(schema)) {
|
|
377
|
-
const tsType = getTypeScriptType(schema)
|
|
396
|
+
const tsType = getTypeScriptType(schema, options)
|
|
378
397
|
let result = ''
|
|
379
398
|
|
|
380
399
|
if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === 'string') {
|
|
@@ -418,7 +437,7 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string): st
|
|
|
418
437
|
const patternPropType =
|
|
419
438
|
typeof firstPatternProperty === 'boolean'
|
|
420
439
|
? getBooleanSubSchemaType(firstPatternProperty)
|
|
421
|
-
: getTypeScriptType(firstPatternProperty)
|
|
440
|
+
: getTypeScriptType(firstPatternProperty, options)
|
|
422
441
|
|
|
423
442
|
// The ^x- pattern is a common JSON Schema convention for vendor extensions
|
|
424
443
|
// that maps naturally to the TypeScript template literal `x-${string}`
|
|
@@ -428,20 +447,20 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string): st
|
|
|
428
447
|
if (jsDocTitle && jsDocDescription) {
|
|
429
448
|
result += buildJsDocBlock(jsDocTitle, jsDocDescription)
|
|
430
449
|
}
|
|
431
|
-
result += `export type ${typeName} =
|
|
450
|
+
result += `export type ${typeName} = ${recordType(keyType, patternPropType, options)};`
|
|
432
451
|
|
|
433
452
|
return result
|
|
434
453
|
}
|
|
435
454
|
|
|
436
455
|
// Handle objects with only additionalProperties (no fixed properties)
|
|
437
456
|
if (!hasProperties && hasAdditionalProperties && normalizedSchema.additionalProperties) {
|
|
438
|
-
const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties)
|
|
457
|
+
const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties, options)
|
|
439
458
|
|
|
440
459
|
let result = ''
|
|
441
460
|
if (jsDocTitle && jsDocDescription) {
|
|
442
461
|
result += buildJsDocBlock(jsDocTitle, jsDocDescription)
|
|
443
462
|
}
|
|
444
|
-
result += `export type ${typeName} = {\n [key: string]: ${additionalPropType};\n};`
|
|
463
|
+
result += `export type ${typeName} = {\n ${readonlyPrefix}[key: string]: ${additionalPropType};\n};`
|
|
445
464
|
|
|
446
465
|
return result
|
|
447
466
|
}
|
|
@@ -454,8 +473,8 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string): st
|
|
|
454
473
|
const propSchema = schemaProps[key]!
|
|
455
474
|
const isRequired = normalizedSchema.required?.includes(key) ?? false
|
|
456
475
|
const optional = isRequired ? '' : '?'
|
|
457
|
-
const propType = getTypeScriptType(propSchema)
|
|
458
|
-
const quotedKey = safeKey(key)
|
|
476
|
+
const propType = getTypeScriptType(propSchema, options)
|
|
477
|
+
const quotedKey = readonlyPrefix + safeKey(key)
|
|
459
478
|
|
|
460
479
|
if (!isFirstProp) properties += '\n'
|
|
461
480
|
isFirstProp = false
|
|
@@ -479,7 +498,7 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string): st
|
|
|
479
498
|
if (isSchemaObject(schema) && Array.isArray(schema.allOf)) {
|
|
480
499
|
for (const entry of schema.allOf) {
|
|
481
500
|
if (isSchemaObject(entry) && entry.$ref) {
|
|
482
|
-
allOfIntersections.push(refToName(entry.$ref))
|
|
501
|
+
allOfIntersections.push(refToName(entry.$ref, options.typeSuffix))
|
|
483
502
|
}
|
|
484
503
|
}
|
|
485
504
|
}
|
|
@@ -487,7 +506,7 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string): st
|
|
|
487
506
|
// JSON Schema 2019-09+ allows $ref as a sibling to other keywords.
|
|
488
507
|
// Treat it as an additional intersection type (e.g. for specification-extensions).
|
|
489
508
|
if (isSchemaObject(schema) && typeof schema.$ref === 'string' && schema.$ref.startsWith('#')) {
|
|
490
|
-
allOfIntersections.push(refToName(schema.$ref))
|
|
509
|
+
allOfIntersections.push(refToName(schema.$ref, options.typeSuffix))
|
|
491
510
|
}
|
|
492
511
|
|
|
493
512
|
let result = ''
|
|
@@ -498,7 +517,7 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string): st
|
|
|
498
517
|
let typeBody = '{\n' + properties + '\n}'
|
|
499
518
|
|
|
500
519
|
if (conditionalThenRef) {
|
|
501
|
-
typeBody += ' & ' + refToName(conditionalThenRef)
|
|
520
|
+
typeBody += ' & ' + refToName(conditionalThenRef, options.typeSuffix)
|
|
502
521
|
}
|
|
503
522
|
|
|
504
523
|
for (const intersectionType of allOfIntersections) {
|
package/src/ref-to-name.test.ts
CHANGED
|
@@ -4,45 +4,54 @@ import { refToName } from './ref-to-name'
|
|
|
4
4
|
|
|
5
5
|
describe('ref-to-name', () => {
|
|
6
6
|
it('converts simple ref to PascalCase', () => {
|
|
7
|
-
expect(refToName('#/$defs/contact')).toBe('
|
|
7
|
+
expect(refToName('#/$defs/contact')).toBe('Contact')
|
|
8
8
|
})
|
|
9
9
|
|
|
10
10
|
it('converts kebab-case ref to PascalCase', () => {
|
|
11
|
-
expect(refToName('#/$defs/server-variable')).toBe('
|
|
11
|
+
expect(refToName('#/$defs/server-variable')).toBe('ServerVariable')
|
|
12
12
|
})
|
|
13
13
|
|
|
14
14
|
it('converts multi-word kebab-case ref to PascalCase', () => {
|
|
15
|
-
expect(refToName('#/$defs/external-documentation')).toBe('
|
|
15
|
+
expect(refToName('#/$defs/external-documentation')).toBe('ExternalDocumentation')
|
|
16
16
|
})
|
|
17
17
|
|
|
18
18
|
it('handles refs with multiple path segments', () => {
|
|
19
|
-
expect(refToName('#/components/schemas/user-profile')).toBe('
|
|
19
|
+
expect(refToName('#/components/schemas/user-profile')).toBe('UserProfile')
|
|
20
20
|
})
|
|
21
21
|
|
|
22
22
|
it('handles single word refs', () => {
|
|
23
|
-
expect(refToName('#/$defs/info')).toBe('
|
|
23
|
+
expect(refToName('#/$defs/info')).toBe('Info')
|
|
24
24
|
})
|
|
25
25
|
|
|
26
26
|
it('handles refs with numbers', () => {
|
|
27
|
-
expect(refToName('#/$defs/oauth2-flow')).toBe('
|
|
27
|
+
expect(refToName('#/$defs/oauth2-flow')).toBe('Oauth2Flow')
|
|
28
28
|
})
|
|
29
29
|
|
|
30
30
|
it('converts uppercase acronym keys to PascalCase via kebab normalization', () => {
|
|
31
|
-
expect(refToName('#/$defs/APIKey')).toBe('
|
|
31
|
+
expect(refToName('#/$defs/APIKey')).toBe('ApiKey')
|
|
32
32
|
})
|
|
33
33
|
|
|
34
34
|
it('derives type name from a URI ref', () => {
|
|
35
|
-
expect(refToName('http://asyncapi.com/definitions/3.1.0/channel.json')).toBe('
|
|
36
|
-
expect(refToName('http://asyncapi.com/definitions/3.1.0/info.json')).toBe('
|
|
35
|
+
expect(refToName('http://asyncapi.com/definitions/3.1.0/channel.json')).toBe('Channel')
|
|
36
|
+
expect(refToName('http://asyncapi.com/definitions/3.1.0/info.json')).toBe('Info')
|
|
37
37
|
})
|
|
38
38
|
|
|
39
39
|
it('derives type name from a URI ref with a fragment', () => {
|
|
40
40
|
expect(refToName('http://asyncapi.com/bindings/sns/0.1.0/channel.json#/definitions/queue')).toBe(
|
|
41
|
-
'
|
|
41
|
+
'BindingsSns010ChannelQueue',
|
|
42
42
|
)
|
|
43
43
|
})
|
|
44
44
|
|
|
45
45
|
it('handles draft-07 schema URI', () => {
|
|
46
|
-
expect(refToName('http://json-schema.org/draft-07/schema')).toBe('
|
|
46
|
+
expect(refToName('http://json-schema.org/draft-07/schema')).toBe('Draft07Schema')
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('appends the suffix when one is provided', () => {
|
|
50
|
+
expect(refToName('#/$defs/contact', 'Object')).toBe('ContactObject')
|
|
51
|
+
expect(refToName('#/$defs/server-variable', 'Object')).toBe('ServerVariableObject')
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('treats an empty suffix the same as omitting it', () => {
|
|
55
|
+
expect(refToName('#/$defs/contact', '')).toBe('Contact')
|
|
47
56
|
})
|
|
48
57
|
})
|
package/src/ref-to-name.ts
CHANGED
|
@@ -1,38 +1,42 @@
|
|
|
1
1
|
import { refToFilename } from './ref-to-filename'
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* Converts a kebab-case filename to PascalCase
|
|
4
|
+
* Converts a kebab-case filename to PascalCase, appending an optional suffix.
|
|
5
5
|
*
|
|
6
6
|
* @example
|
|
7
7
|
* ```ts
|
|
8
|
-
* kebabToPascal('server-variable') // '
|
|
9
|
-
* kebabToPascal('channel') // '
|
|
8
|
+
* kebabToPascal('server-variable') // 'ServerVariable'
|
|
9
|
+
* kebabToPascal('channel') // 'Channel'
|
|
10
|
+
* kebabToPascal('channel', 'Object') // 'ChannelObject'
|
|
10
11
|
* ```
|
|
11
12
|
*/
|
|
12
|
-
const kebabToPascal = (kebab: string): string => {
|
|
13
|
+
const kebabToPascal = (kebab: string, suffix: string): string => {
|
|
13
14
|
const words = kebab.split('-')
|
|
14
15
|
let pascalCase = ''
|
|
15
16
|
for (const word of words) {
|
|
16
17
|
pascalCase += word.charAt(0).toUpperCase() + word.slice(1)
|
|
17
18
|
}
|
|
18
|
-
return pascalCase +
|
|
19
|
+
return pascalCase + suffix
|
|
19
20
|
}
|
|
20
21
|
|
|
21
22
|
/**
|
|
22
23
|
* Converts a JSON Schema $ref to a type name.
|
|
23
|
-
* Derives the filename via `refToFilename` then converts to PascalCase
|
|
24
|
-
* an
|
|
24
|
+
* Derives the filename via `refToFilename` then converts to PascalCase,
|
|
25
|
+
* appending an optional suffix.
|
|
25
26
|
*
|
|
26
27
|
* Handles all ref forms: internal `#/$defs/...`, `#/definitions/...`, and URI refs.
|
|
27
28
|
*
|
|
28
29
|
* @param ref - The $ref string
|
|
29
|
-
* @
|
|
30
|
+
* @param suffix - Optional suffix appended to the PascalCase name. Defaults to
|
|
31
|
+
* `''` (no suffix). Pass e.g. `'Object'` to get `ContactObject`.
|
|
32
|
+
* @returns The type name in PascalCase with the suffix applied
|
|
30
33
|
*
|
|
31
34
|
* @example
|
|
32
35
|
* ```ts
|
|
33
|
-
* refToName('#/$defs/contact') // '
|
|
34
|
-
* refToName('#/$defs/server-variable') // '
|
|
35
|
-
* refToName('
|
|
36
|
+
* refToName('#/$defs/contact') // 'Contact'
|
|
37
|
+
* refToName('#/$defs/server-variable') // 'ServerVariable'
|
|
38
|
+
* refToName('#/$defs/contact', 'Object') // 'ContactObject'
|
|
39
|
+
* refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'Channel'
|
|
36
40
|
* ```
|
|
37
41
|
*/
|
|
38
|
-
export const refToName = (ref: string): string => kebabToPascal(refToFilename(ref))
|
|
42
|
+
export const refToName = (ref: string, suffix = ''): string => kebabToPascal(refToFilename(ref), suffix)
|