@amritk/helpers 0.3.0 → 0.5.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 +6 -1
- package/dist/generate-type-definition.js +74 -31
- package/dist/mjst-extension.d.ts +43 -0
- package/dist/mjst-extension.js +123 -0
- package/package.json +8 -3
- package/src/generate-type-definition.test.ts +107 -0
- package/src/generate-type-definition.ts +73 -32
- package/src/mjst-extension.test.ts +59 -0
- package/src/mjst-extension.ts +81 -0
|
@@ -1,7 +1,12 @@
|
|
|
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
|
+
};
|
|
2
7
|
/**
|
|
3
8
|
* Generates a TypeScript type definition from a JSON Schema.
|
|
4
9
|
* Handles required vs optional properties based on the schema's required array.
|
|
5
10
|
* Uses $comment as inline JSDoc description when present.
|
|
6
11
|
*/
|
|
7
|
-
export declare const generateTypeDefinition: (schema: JSONSchema, typeName: string) => string;
|
|
12
|
+
export declare const generateTypeDefinition: (schema: JSONSchema, typeName: string, options?: TypeOptions) => string;
|
|
@@ -89,6 +89,33 @@ var hasMaxProperties = (schema) => {
|
|
|
89
89
|
return isSchemaObject(schema) && "maxProperties" in schema && typeof schema.maxProperties === "number";
|
|
90
90
|
};
|
|
91
91
|
|
|
92
|
+
// src/mjst-extension.ts
|
|
93
|
+
var MJST_EXTENSION_KEY = "x-mjst";
|
|
94
|
+
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
95
|
+
var SUPPORTED_PRIMITIVES = new Set(["bigint"]);
|
|
96
|
+
var SAFE_BRAND = /^[\w$ -]+$/;
|
|
97
|
+
var readExtensionString = (schema, field) => {
|
|
98
|
+
if (!isSchemaObject(schema))
|
|
99
|
+
return;
|
|
100
|
+
const extension = schema[MJST_EXTENSION_KEY];
|
|
101
|
+
if (typeof extension !== "object" || extension === null)
|
|
102
|
+
return;
|
|
103
|
+
const value = extension[field];
|
|
104
|
+
return typeof value === "string" ? value : undefined;
|
|
105
|
+
};
|
|
106
|
+
var getMjstInstanceOf = (schema) => {
|
|
107
|
+
const instanceOf = readExtensionString(schema, "instanceOf");
|
|
108
|
+
return instanceOf !== undefined && IDENTIFIER.test(instanceOf) ? instanceOf : undefined;
|
|
109
|
+
};
|
|
110
|
+
var getMjstPrimitive = (schema) => {
|
|
111
|
+
const primitive = readExtensionString(schema, "primitive");
|
|
112
|
+
return primitive !== undefined && SUPPORTED_PRIMITIVES.has(primitive) ? primitive : undefined;
|
|
113
|
+
};
|
|
114
|
+
var getMjstBrand = (schema) => {
|
|
115
|
+
const brand = readExtensionString(schema, "brand");
|
|
116
|
+
return brand !== undefined && SAFE_BRAND.test(brand) ? brand : undefined;
|
|
117
|
+
};
|
|
118
|
+
|
|
92
119
|
// src/ref-to-filename.ts
|
|
93
120
|
var toKebabCase = (value) => value.replace(/OAuth/g, "Oauth").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z\d])([A-Z])/g, "$1-$2").toLowerCase();
|
|
94
121
|
var uriRefToFilename = (uri) => {
|
|
@@ -245,13 +272,27 @@ var buildJsDocBlock = (title, description, commentUrl) => {
|
|
|
245
272
|
`;
|
|
246
273
|
return block;
|
|
247
274
|
};
|
|
248
|
-
var getTypeScriptType = (schema) => {
|
|
275
|
+
var getTypeScriptType = (schema, options = {}) => {
|
|
276
|
+
const base = getUnbrandedType(schema, options);
|
|
277
|
+
const brand = getMjstBrand(schema);
|
|
278
|
+
return brand ? `(${base} & { readonly __brand: '${brand}' })` : base;
|
|
279
|
+
};
|
|
280
|
+
var recordType = (keyType, valueType, options) => options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`;
|
|
281
|
+
var getUnbrandedType = (schema, options = {}) => {
|
|
249
282
|
if (typeof schema === "boolean") {
|
|
250
283
|
return getBooleanSubSchemaType(schema);
|
|
251
284
|
}
|
|
252
285
|
if (typeof schema !== "object" || schema === null) {
|
|
253
286
|
return "unknown";
|
|
254
287
|
}
|
|
288
|
+
const instanceOf = getMjstInstanceOf(schema);
|
|
289
|
+
if (instanceOf) {
|
|
290
|
+
return instanceOf;
|
|
291
|
+
}
|
|
292
|
+
const primitive = getMjstPrimitive(schema);
|
|
293
|
+
if (primitive) {
|
|
294
|
+
return primitive;
|
|
295
|
+
}
|
|
255
296
|
if (schema.$ref) {
|
|
256
297
|
if (!schema.$ref.startsWith("#")) {
|
|
257
298
|
return "unknown";
|
|
@@ -285,29 +326,29 @@ var getTypeScriptType = (schema) => {
|
|
|
285
326
|
return multiEnumUnion;
|
|
286
327
|
}
|
|
287
328
|
if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
288
|
-
let oneOfUnion = getTypeScriptType(schema.oneOf[0]);
|
|
329
|
+
let oneOfUnion = getTypeScriptType(schema.oneOf[0], options);
|
|
289
330
|
for (let i = 1;i < schema.oneOf.length; i++) {
|
|
290
|
-
oneOfUnion += " | " + getTypeScriptType(schema.oneOf[i]);
|
|
331
|
+
oneOfUnion += " | " + getTypeScriptType(schema.oneOf[i], options);
|
|
291
332
|
}
|
|
292
333
|
return oneOfUnion;
|
|
293
334
|
}
|
|
294
335
|
if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
295
|
-
let anyOfUnion = getTypeScriptType(schema.anyOf[0]);
|
|
336
|
+
let anyOfUnion = getTypeScriptType(schema.anyOf[0], options);
|
|
296
337
|
for (let i = 1;i < schema.anyOf.length; i++) {
|
|
297
|
-
anyOfUnion += " | " + getTypeScriptType(schema.anyOf[i]);
|
|
338
|
+
anyOfUnion += " | " + getTypeScriptType(schema.anyOf[i], options);
|
|
298
339
|
}
|
|
299
340
|
return anyOfUnion;
|
|
300
341
|
}
|
|
301
342
|
if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
302
|
-
let intersectionTypes = getTypeScriptType(schema.allOf[0]);
|
|
343
|
+
let intersectionTypes = getTypeScriptType(schema.allOf[0], options);
|
|
303
344
|
for (let i = 1;i < schema.allOf.length; i++) {
|
|
304
|
-
intersectionTypes += " & " + getTypeScriptType(schema.allOf[i]);
|
|
345
|
+
intersectionTypes += " & " + getTypeScriptType(schema.allOf[i], options);
|
|
305
346
|
}
|
|
306
347
|
return intersectionTypes;
|
|
307
348
|
}
|
|
308
349
|
const conditionalResult = getConditionalObjectSchema(schema);
|
|
309
350
|
if (conditionalResult) {
|
|
310
|
-
const baseType = getTypeScriptType(conditionalResult.schema);
|
|
351
|
+
const baseType = getTypeScriptType(conditionalResult.schema, options);
|
|
311
352
|
if (conditionalResult.thenRef) {
|
|
312
353
|
return `(${baseType}) & ${refToName(conditionalResult.thenRef)}`;
|
|
313
354
|
}
|
|
@@ -316,20 +357,20 @@ var getTypeScriptType = (schema) => {
|
|
|
316
357
|
if (!schema.type) {
|
|
317
358
|
if (schema.additionalProperties !== undefined) {
|
|
318
359
|
if (typeof schema.additionalProperties === "boolean") {
|
|
319
|
-
return
|
|
360
|
+
return recordType("string", getBooleanSubSchemaType(schema.additionalProperties), options);
|
|
320
361
|
}
|
|
321
|
-
return
|
|
362
|
+
return recordType("string", getTypeScriptType(schema.additionalProperties, options), options);
|
|
322
363
|
}
|
|
323
364
|
if (schema.patternProperties && typeof schema.patternProperties === "object") {
|
|
324
365
|
const firstEntry = Object.entries(schema.patternProperties)[0];
|
|
325
366
|
if (firstEntry) {
|
|
326
367
|
const [pattern, value] = firstEntry;
|
|
327
368
|
if (value !== undefined) {
|
|
328
|
-
const valueType = typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value);
|
|
369
|
+
const valueType = typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options);
|
|
329
370
|
if (pattern === "^x-") {
|
|
330
|
-
return `
|
|
371
|
+
return recordType("`x-${string}`", valueType, options);
|
|
331
372
|
}
|
|
332
|
-
return
|
|
373
|
+
return recordType("string", valueType, options);
|
|
333
374
|
}
|
|
334
375
|
}
|
|
335
376
|
}
|
|
@@ -382,41 +423,42 @@ var getTypeScriptType = (schema) => {
|
|
|
382
423
|
return "boolean";
|
|
383
424
|
case "array":
|
|
384
425
|
if (schema.items) {
|
|
385
|
-
const itemType = getTypeScriptType(schema.items);
|
|
426
|
+
const itemType = getTypeScriptType(schema.items, options);
|
|
386
427
|
const wrappedItemType = itemType.includes(" | ") ? `(${itemType})` : itemType;
|
|
387
|
-
return `${wrappedItemType}[]`;
|
|
428
|
+
return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`;
|
|
388
429
|
}
|
|
389
|
-
return "unknown[]";
|
|
430
|
+
return options.readonly ? "readonly unknown[]" : "unknown[]";
|
|
390
431
|
case "object":
|
|
391
432
|
if (schema.properties) {
|
|
433
|
+
const readonlyPrefix = options.readonly ? "readonly " : "";
|
|
392
434
|
let properties = "";
|
|
393
435
|
let first = true;
|
|
394
436
|
for (const key in schema.properties) {
|
|
395
437
|
const propSchema = schema.properties[key];
|
|
396
438
|
const isRequired = schema.required?.includes(key) ?? false;
|
|
397
439
|
const optional = isRequired ? "" : "?";
|
|
398
|
-
const propType = getTypeScriptType(propSchema);
|
|
440
|
+
const propType = getTypeScriptType(propSchema, options);
|
|
399
441
|
if (!first)
|
|
400
442
|
properties += "; ";
|
|
401
|
-
properties += safeKey(key) + optional + ": " + propType;
|
|
443
|
+
properties += readonlyPrefix + safeKey(key) + optional + ": " + propType;
|
|
402
444
|
first = false;
|
|
403
445
|
}
|
|
404
446
|
return "{ " + properties + " }";
|
|
405
447
|
}
|
|
406
448
|
if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
|
|
407
|
-
const additionalPropType = getTypeScriptType(schema.additionalProperties);
|
|
408
|
-
return
|
|
449
|
+
const additionalPropType = getTypeScriptType(schema.additionalProperties, options);
|
|
450
|
+
return recordType("string", additionalPropType, options);
|
|
409
451
|
}
|
|
410
452
|
if (schema.patternProperties && typeof schema.patternProperties === "object") {
|
|
411
453
|
const firstEntry = Object.entries(schema.patternProperties)[0];
|
|
412
454
|
if (firstEntry) {
|
|
413
455
|
const [pattern, patternVal] = firstEntry;
|
|
414
456
|
if (patternVal) {
|
|
415
|
-
const valueType = getTypeScriptType(patternVal);
|
|
457
|
+
const valueType = getTypeScriptType(patternVal, options);
|
|
416
458
|
if (pattern === "^x-") {
|
|
417
|
-
return `
|
|
459
|
+
return recordType("`x-${string}`", valueType, options);
|
|
418
460
|
}
|
|
419
|
-
return
|
|
461
|
+
return recordType("string", valueType, options);
|
|
420
462
|
}
|
|
421
463
|
}
|
|
422
464
|
}
|
|
@@ -425,9 +467,10 @@ var getTypeScriptType = (schema) => {
|
|
|
425
467
|
return "unknown";
|
|
426
468
|
}
|
|
427
469
|
};
|
|
428
|
-
var generateTypeDefinition = (schema, typeName) => {
|
|
470
|
+
var generateTypeDefinition = (schema, typeName, options = {}) => {
|
|
471
|
+
const readonlyPrefix = options.readonly ? "readonly " : "";
|
|
429
472
|
if (!isObjectLikeSchema(schema)) {
|
|
430
|
-
const tsType = getTypeScriptType(schema);
|
|
473
|
+
const tsType = getTypeScriptType(schema, options);
|
|
431
474
|
let result = "";
|
|
432
475
|
if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === "string") {
|
|
433
476
|
result += buildJsDocBlock(typeName, schema.$comment);
|
|
@@ -455,23 +498,23 @@ var generateTypeDefinition = (schema, typeName) => {
|
|
|
455
498
|
if (firstPatternProperty === undefined) {
|
|
456
499
|
return `export type ${typeName} = Record<string, unknown>;`;
|
|
457
500
|
}
|
|
458
|
-
const patternPropType = typeof firstPatternProperty === "boolean" ? getBooleanSubSchemaType(firstPatternProperty) : getTypeScriptType(firstPatternProperty);
|
|
501
|
+
const patternPropType = typeof firstPatternProperty === "boolean" ? getBooleanSubSchemaType(firstPatternProperty) : getTypeScriptType(firstPatternProperty, options);
|
|
459
502
|
const keyType = firstPattern === "^x-" ? "`x-${string}`" : "string";
|
|
460
503
|
let result2 = "";
|
|
461
504
|
if (jsDocTitle && jsDocDescription) {
|
|
462
505
|
result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
|
|
463
506
|
}
|
|
464
|
-
result2 += `export type ${typeName} =
|
|
507
|
+
result2 += `export type ${typeName} = ${recordType(keyType, patternPropType, options)};`;
|
|
465
508
|
return result2;
|
|
466
509
|
}
|
|
467
510
|
if (!hasProperties2 && hasAdditionalProperties2 && normalizedSchema.additionalProperties) {
|
|
468
|
-
const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties);
|
|
511
|
+
const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties, options);
|
|
469
512
|
let result2 = "";
|
|
470
513
|
if (jsDocTitle && jsDocDescription) {
|
|
471
514
|
result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
|
|
472
515
|
}
|
|
473
516
|
result2 += `export type ${typeName} = {
|
|
474
|
-
[key: string]: ${additionalPropType};
|
|
517
|
+
${readonlyPrefix}[key: string]: ${additionalPropType};
|
|
475
518
|
};`;
|
|
476
519
|
return result2;
|
|
477
520
|
}
|
|
@@ -482,8 +525,8 @@ var generateTypeDefinition = (schema, typeName) => {
|
|
|
482
525
|
const propSchema = schemaProps[key];
|
|
483
526
|
const isRequired = normalizedSchema.required?.includes(key) ?? false;
|
|
484
527
|
const optional = isRequired ? "" : "?";
|
|
485
|
-
const propType = getTypeScriptType(propSchema);
|
|
486
|
-
const quotedKey = safeKey(key);
|
|
528
|
+
const propType = getTypeScriptType(propSchema, options);
|
|
529
|
+
const quotedKey = readonlyPrefix + safeKey(key);
|
|
487
530
|
if (!isFirstProp)
|
|
488
531
|
properties += `
|
|
489
532
|
`;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
2
|
+
/**
|
|
3
|
+
* Vendor extension keyword carrying mjst-specific runtime hints that plain JSON
|
|
4
|
+
* Schema cannot express on its own. Adapters (TypeBox, Zod, ...) emit it when a
|
|
5
|
+
* source construct has no native JSON Schema equivalent, and the generators read
|
|
6
|
+
* it to produce the right TypeScript type and runtime checks.
|
|
7
|
+
*/
|
|
8
|
+
export declare const MJST_EXTENSION_KEY = "x-mjst";
|
|
9
|
+
/**
|
|
10
|
+
* The shape of the `x-mjst` extension object.
|
|
11
|
+
*
|
|
12
|
+
* - `instanceOf` names a JavaScript class the value must be an instance of at
|
|
13
|
+
* runtime (e.g. `'Date'`). It round-trips constructs like TypeBox's
|
|
14
|
+
* `Type.Date()` that JSON Schema's core vocabulary has no keyword for.
|
|
15
|
+
* - `primitive` names a non-JSON primitive type (e.g. `'bigint'`) that has no
|
|
16
|
+
* JSON Schema representation. Unlike `instanceOf`, the value is checked with
|
|
17
|
+
* `typeof`, not `instanceof`.
|
|
18
|
+
* - `brand` carries a nominal-typing brand name. It is purely type-level: the
|
|
19
|
+
* runtime value still validates as its underlying JSON Schema type, but the
|
|
20
|
+
* generated TypeScript type is intersected with a unique brand so values are
|
|
21
|
+
* not interchangeable with the unbranded base type.
|
|
22
|
+
*/
|
|
23
|
+
export type MjstExtension = {
|
|
24
|
+
readonly instanceOf?: string;
|
|
25
|
+
readonly primitive?: string;
|
|
26
|
+
readonly brand?: string;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Reads the `instanceOf` class name from a schema's `x-mjst` extension, when it
|
|
30
|
+
* is present and a safe identifier. Returns undefined otherwise so callers fall
|
|
31
|
+
* back to ordinary type handling.
|
|
32
|
+
*/
|
|
33
|
+
export declare const getMjstInstanceOf: (schema: JSONSchema) => string | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* Reads the `primitive` type name from a schema's `x-mjst` extension, when it is
|
|
36
|
+
* one we support (e.g. `'bigint'`). Returns undefined otherwise.
|
|
37
|
+
*/
|
|
38
|
+
export declare const getMjstPrimitive: (schema: JSONSchema) => string | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* Reads the nominal `brand` name from a schema's `x-mjst` extension, when it is
|
|
41
|
+
* present and safe to embed in generated output. Returns undefined otherwise.
|
|
42
|
+
*/
|
|
43
|
+
export declare const getMjstBrand: (schema: JSONSchema) => string | undefined;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// src/has-ref.ts
|
|
2
|
+
var hasRef = (value) => {
|
|
3
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && "$ref" in value && typeof value.$ref === "string";
|
|
4
|
+
};
|
|
5
|
+
|
|
6
|
+
// src/schema-guards.ts
|
|
7
|
+
var isSchemaObject = (schema) => {
|
|
8
|
+
return typeof schema === "object" && schema !== null && typeof schema !== "boolean";
|
|
9
|
+
};
|
|
10
|
+
var hasType = (schema) => {
|
|
11
|
+
return isSchemaObject(schema) && "type" in schema && typeof schema.type === "string";
|
|
12
|
+
};
|
|
13
|
+
var isObjectSchema = (schema) => {
|
|
14
|
+
return isSchemaObject(schema) && (("type" in schema) && schema.type === "object" || ("properties" in schema));
|
|
15
|
+
};
|
|
16
|
+
var hasProperties = (schema) => {
|
|
17
|
+
return isSchemaObject(schema) && "properties" in schema && typeof schema.properties === "object" && schema.properties !== null;
|
|
18
|
+
};
|
|
19
|
+
var hasEnum = (schema) => {
|
|
20
|
+
return isSchemaObject(schema) && "enum" in schema && Array.isArray(schema.enum);
|
|
21
|
+
};
|
|
22
|
+
var hasConst = (schema) => {
|
|
23
|
+
return isSchemaObject(schema) && "const" in schema;
|
|
24
|
+
};
|
|
25
|
+
var hasPattern = (schema) => {
|
|
26
|
+
return isSchemaObject(schema) && "pattern" in schema && typeof schema.pattern === "string";
|
|
27
|
+
};
|
|
28
|
+
var hasFormat = (schema) => {
|
|
29
|
+
return isSchemaObject(schema) && "format" in schema && typeof schema.format === "string";
|
|
30
|
+
};
|
|
31
|
+
var hasDefault = (schema) => {
|
|
32
|
+
return isSchemaObject(schema) && "default" in schema;
|
|
33
|
+
};
|
|
34
|
+
var hasExamples = (schema) => {
|
|
35
|
+
return isSchemaObject(schema) && "examples" in schema && Array.isArray(schema.examples);
|
|
36
|
+
};
|
|
37
|
+
var hasOneOf = (schema) => {
|
|
38
|
+
return isSchemaObject(schema) && "oneOf" in schema && Array.isArray(schema.oneOf);
|
|
39
|
+
};
|
|
40
|
+
var hasAnyOf = (schema) => {
|
|
41
|
+
return isSchemaObject(schema) && "anyOf" in schema && Array.isArray(schema.anyOf);
|
|
42
|
+
};
|
|
43
|
+
var hasAllOf = (schema) => {
|
|
44
|
+
return isSchemaObject(schema) && "allOf" in schema && Array.isArray(schema.allOf);
|
|
45
|
+
};
|
|
46
|
+
var hasRequired = (schema) => {
|
|
47
|
+
return isSchemaObject(schema) && "required" in schema && Array.isArray(schema.required);
|
|
48
|
+
};
|
|
49
|
+
var hasItems = (schema) => {
|
|
50
|
+
return isSchemaObject(schema) && "items" in schema && typeof schema.items === "object" && schema.items !== null && typeof schema.items !== "boolean";
|
|
51
|
+
};
|
|
52
|
+
var hasAdditionalProperties = (schema) => {
|
|
53
|
+
return isSchemaObject(schema) && "additionalProperties" in schema;
|
|
54
|
+
};
|
|
55
|
+
var hasMinLength = (schema) => {
|
|
56
|
+
return isSchemaObject(schema) && "minLength" in schema && typeof schema.minLength === "number";
|
|
57
|
+
};
|
|
58
|
+
var hasMaxLength = (schema) => {
|
|
59
|
+
return isSchemaObject(schema) && "maxLength" in schema && typeof schema.maxLength === "number";
|
|
60
|
+
};
|
|
61
|
+
var hasMinimum = (schema) => {
|
|
62
|
+
return isSchemaObject(schema) && "minimum" in schema && typeof schema.minimum === "number";
|
|
63
|
+
};
|
|
64
|
+
var hasMaximum = (schema) => {
|
|
65
|
+
return isSchemaObject(schema) && "maximum" in schema && typeof schema.maximum === "number";
|
|
66
|
+
};
|
|
67
|
+
var hasExclusiveMinimum = (schema) => {
|
|
68
|
+
return isSchemaObject(schema) && "exclusiveMinimum" in schema && typeof schema.exclusiveMinimum === "number";
|
|
69
|
+
};
|
|
70
|
+
var hasExclusiveMaximum = (schema) => {
|
|
71
|
+
return isSchemaObject(schema) && "exclusiveMaximum" in schema && typeof schema.exclusiveMaximum === "number";
|
|
72
|
+
};
|
|
73
|
+
var hasMultipleOf = (schema) => {
|
|
74
|
+
return isSchemaObject(schema) && "multipleOf" in schema && typeof schema.multipleOf === "number";
|
|
75
|
+
};
|
|
76
|
+
var hasMinItems = (schema) => {
|
|
77
|
+
return isSchemaObject(schema) && "minItems" in schema && typeof schema.minItems === "number";
|
|
78
|
+
};
|
|
79
|
+
var hasMaxItems = (schema) => {
|
|
80
|
+
return isSchemaObject(schema) && "maxItems" in schema && typeof schema.maxItems === "number";
|
|
81
|
+
};
|
|
82
|
+
var hasUniqueItems = (schema) => {
|
|
83
|
+
return isSchemaObject(schema) && "uniqueItems" in schema && typeof schema.uniqueItems === "boolean";
|
|
84
|
+
};
|
|
85
|
+
var hasMinProperties = (schema) => {
|
|
86
|
+
return isSchemaObject(schema) && "minProperties" in schema && typeof schema.minProperties === "number";
|
|
87
|
+
};
|
|
88
|
+
var hasMaxProperties = (schema) => {
|
|
89
|
+
return isSchemaObject(schema) && "maxProperties" in schema && typeof schema.maxProperties === "number";
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// src/mjst-extension.ts
|
|
93
|
+
var MJST_EXTENSION_KEY = "x-mjst";
|
|
94
|
+
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
95
|
+
var SUPPORTED_PRIMITIVES = new Set(["bigint"]);
|
|
96
|
+
var SAFE_BRAND = /^[\w$ -]+$/;
|
|
97
|
+
var readExtensionString = (schema, field) => {
|
|
98
|
+
if (!isSchemaObject(schema))
|
|
99
|
+
return;
|
|
100
|
+
const extension = schema[MJST_EXTENSION_KEY];
|
|
101
|
+
if (typeof extension !== "object" || extension === null)
|
|
102
|
+
return;
|
|
103
|
+
const value = extension[field];
|
|
104
|
+
return typeof value === "string" ? value : undefined;
|
|
105
|
+
};
|
|
106
|
+
var getMjstInstanceOf = (schema) => {
|
|
107
|
+
const instanceOf = readExtensionString(schema, "instanceOf");
|
|
108
|
+
return instanceOf !== undefined && IDENTIFIER.test(instanceOf) ? instanceOf : undefined;
|
|
109
|
+
};
|
|
110
|
+
var getMjstPrimitive = (schema) => {
|
|
111
|
+
const primitive = readExtensionString(schema, "primitive");
|
|
112
|
+
return primitive !== undefined && SUPPORTED_PRIMITIVES.has(primitive) ? primitive : undefined;
|
|
113
|
+
};
|
|
114
|
+
var getMjstBrand = (schema) => {
|
|
115
|
+
const brand = readExtensionString(schema, "brand");
|
|
116
|
+
return brand !== undefined && SAFE_BRAND.test(brand) ? brand : undefined;
|
|
117
|
+
};
|
|
118
|
+
export {
|
|
119
|
+
getMjstPrimitive,
|
|
120
|
+
getMjstInstanceOf,
|
|
121
|
+
getMjstBrand,
|
|
122
|
+
MJST_EXTENSION_KEY
|
|
123
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/helpers",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Shared utilities for the mjst code generation ecosystem.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -28,11 +28,11 @@
|
|
|
28
28
|
},
|
|
29
29
|
"scripts": {
|
|
30
30
|
"build": "bun run build:code && bun run build:types",
|
|
31
|
-
"build:code": "bun build ./src/build-dynamic-ref-map.ts ./src/derive-root-type-name.ts ./src/extract-refs.ts ./src/generate-type-definition.ts ./src/has-ref.ts ./src/is-object.ts ./src/parse-documentation.ts ./src/ref-to-filename.ts ./src/ref-to-name.ts ./src/resolve-dynamic-refs.ts ./src/resolve-ref.ts ./src/safe-accessor.ts ./src/schema-guards.ts ./src/upgrade-draft07-schema.ts ./src/validate-array.ts ./src/validate-record.ts --outdir=dist --root=src --target=node",
|
|
31
|
+
"build:code": "bun build ./src/build-dynamic-ref-map.ts ./src/derive-root-type-name.ts ./src/extract-refs.ts ./src/generate-type-definition.ts ./src/has-ref.ts ./src/is-object.ts ./src/mjst-extension.ts ./src/parse-documentation.ts ./src/ref-to-filename.ts ./src/ref-to-name.ts ./src/resolve-dynamic-refs.ts ./src/resolve-ref.ts ./src/safe-accessor.ts ./src/schema-guards.ts ./src/upgrade-draft07-schema.ts ./src/validate-array.ts ./src/validate-record.ts --outdir=dist --root=src --target=node",
|
|
32
32
|
"build:types": "tsc -p ."
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"json-schema-typed": "
|
|
35
|
+
"json-schema-typed": "^8.0.1"
|
|
36
36
|
},
|
|
37
37
|
"exports": {
|
|
38
38
|
"./package.json": "./package.json",
|
|
@@ -66,6 +66,11 @@
|
|
|
66
66
|
"default": "./dist/is-object.js",
|
|
67
67
|
"types": "./dist/is-object.d.ts"
|
|
68
68
|
},
|
|
69
|
+
"./mjst-extension": {
|
|
70
|
+
"bun": "./src/mjst-extension.ts",
|
|
71
|
+
"default": "./dist/mjst-extension.js",
|
|
72
|
+
"types": "./dist/mjst-extension.d.ts"
|
|
73
|
+
},
|
|
69
74
|
"./parse-documentation": {
|
|
70
75
|
"bun": "./src/parse-documentation.ts",
|
|
71
76
|
"default": "./dist/parse-documentation.js",
|
|
@@ -1207,4 +1207,111 @@ describe('generateTypeDefinition', () => {
|
|
|
1207
1207
|
expect(result).toMatch(/\* A plain-text description with no URL\.\n\*\//)
|
|
1208
1208
|
expect(result).not.toContain('* \n*/')
|
|
1209
1209
|
})
|
|
1210
|
+
|
|
1211
|
+
it('emits the class name for an x-mjst instanceOf property', () => {
|
|
1212
|
+
const schema: JSONSchema = {
|
|
1213
|
+
type: 'object',
|
|
1214
|
+
properties: { createdAt: { 'x-mjst': { instanceOf: 'Date' } } },
|
|
1215
|
+
required: ['createdAt'],
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
expect(generateTypeDefinition(schema, 'Event')).toContain('createdAt: Date;')
|
|
1219
|
+
})
|
|
1220
|
+
|
|
1221
|
+
it('emits the class name for a top-level x-mjst instanceOf schema', () => {
|
|
1222
|
+
const schema: JSONSchema = { 'x-mjst': { instanceOf: 'Date' } }
|
|
1223
|
+
|
|
1224
|
+
expect(generateTypeDefinition(schema, 'When')).toBe('export type When = Date;')
|
|
1225
|
+
})
|
|
1226
|
+
|
|
1227
|
+
it('ignores an x-mjst instanceOf that is not a safe identifier', () => {
|
|
1228
|
+
const schema: JSONSchema = { 'x-mjst': { instanceOf: 'Date; doEvil()' } }
|
|
1229
|
+
|
|
1230
|
+
expect(generateTypeDefinition(schema, 'When')).not.toContain('doEvil')
|
|
1231
|
+
})
|
|
1232
|
+
|
|
1233
|
+
it('emits a primitive type for an x-mjst bigint property', () => {
|
|
1234
|
+
const schema: JSONSchema = {
|
|
1235
|
+
type: 'object',
|
|
1236
|
+
properties: { balance: { 'x-mjst': { primitive: 'bigint' } } },
|
|
1237
|
+
required: ['balance'],
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
expect(generateTypeDefinition(schema, 'Account')).toContain('balance: bigint;')
|
|
1241
|
+
})
|
|
1242
|
+
|
|
1243
|
+
it('emits a primitive type for a top-level x-mjst bigint schema', () => {
|
|
1244
|
+
expect(generateTypeDefinition({ 'x-mjst': { primitive: 'bigint' } }, 'Big')).toBe('export type Big = bigint;')
|
|
1245
|
+
})
|
|
1246
|
+
|
|
1247
|
+
it('wraps a branded property in a nominal intersection', () => {
|
|
1248
|
+
const schema: JSONSchema = {
|
|
1249
|
+
type: 'object',
|
|
1250
|
+
properties: { id: { type: 'string', 'x-mjst': { brand: 'UserId' } } },
|
|
1251
|
+
required: ['id'],
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
expect(generateTypeDefinition(schema, 'User')).toContain("id: (string & { readonly __brand: 'UserId' });")
|
|
1255
|
+
})
|
|
1256
|
+
|
|
1257
|
+
it('brands a top-level schema and combines with instanceOf', () => {
|
|
1258
|
+
expect(generateTypeDefinition({ type: 'string', 'x-mjst': { brand: 'Email' } }, 'Email')).toBe(
|
|
1259
|
+
"export type Email = (string & { readonly __brand: 'Email' });",
|
|
1260
|
+
)
|
|
1261
|
+
expect(generateTypeDefinition({ 'x-mjst': { instanceOf: 'Date', brand: 'Timestamp' } }, 'Ts')).toBe(
|
|
1262
|
+
"export type Ts = (Date & { readonly __brand: 'Timestamp' });",
|
|
1263
|
+
)
|
|
1264
|
+
})
|
|
1265
|
+
|
|
1266
|
+
it('ignores an x-mjst brand that is not safe to embed', () => {
|
|
1267
|
+
const schema: JSONSchema = { type: 'string', 'x-mjst': { brand: "x'; doEvil()" } }
|
|
1268
|
+
|
|
1269
|
+
const result = generateTypeDefinition(schema, 'Bad')
|
|
1270
|
+
expect(result).not.toContain('doEvil')
|
|
1271
|
+
expect(result).toBe('export type Bad = string;')
|
|
1272
|
+
})
|
|
1273
|
+
|
|
1274
|
+
describe('readonly option', () => {
|
|
1275
|
+
it('marks every property as readonly, deeply', () => {
|
|
1276
|
+
const schema: JSONSchema = {
|
|
1277
|
+
type: 'object',
|
|
1278
|
+
properties: {
|
|
1279
|
+
id: { type: 'string' },
|
|
1280
|
+
tags: { type: 'array', items: { type: 'string' } },
|
|
1281
|
+
nested: {
|
|
1282
|
+
type: 'object',
|
|
1283
|
+
properties: { value: { type: 'number' } },
|
|
1284
|
+
},
|
|
1285
|
+
},
|
|
1286
|
+
required: ['id'],
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
const result = generateTypeDefinition(schema, 'Doc', { readonly: true })
|
|
1290
|
+
|
|
1291
|
+
expect(result).toContain('readonly id: string;')
|
|
1292
|
+
expect(result).toContain('readonly tags?: readonly string[];')
|
|
1293
|
+
expect(result).toContain('readonly nested?: { readonly value?: number }')
|
|
1294
|
+
})
|
|
1295
|
+
|
|
1296
|
+
it('wraps record types in Readonly', () => {
|
|
1297
|
+
const schema: JSONSchema = {
|
|
1298
|
+
type: 'object',
|
|
1299
|
+
additionalProperties: { type: 'number' },
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
expect(generateTypeDefinition(schema, 'Map', { readonly: true })).toContain('readonly [key: string]: number;')
|
|
1303
|
+
})
|
|
1304
|
+
|
|
1305
|
+
it('leaves output unchanged when readonly is not set', () => {
|
|
1306
|
+
const schema: JSONSchema = {
|
|
1307
|
+
type: 'object',
|
|
1308
|
+
properties: { id: { type: 'string' } },
|
|
1309
|
+
required: ['id'],
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
const result = generateTypeDefinition(schema, 'Doc')
|
|
1313
|
+
expect(result).not.toContain('readonly')
|
|
1314
|
+
expect(result).toContain('id: string;')
|
|
1315
|
+
})
|
|
1316
|
+
})
|
|
1210
1317
|
})
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
2
|
|
|
3
|
+
import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive } from './mjst-extension'
|
|
3
4
|
import { refToName } from './ref-to-name'
|
|
4
5
|
import { safeKey } from './safe-accessor'
|
|
5
6
|
import { isObjectSchema, isSchemaObject } from './schema-guards'
|
|
@@ -9,6 +10,12 @@ type ConditionalObjectResult = {
|
|
|
9
10
|
thenRef: string | null
|
|
10
11
|
}
|
|
11
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
|
+
|
|
12
19
|
const getConditionalObjectSchema = (schema: JSONSchema): ConditionalObjectResult | null => {
|
|
13
20
|
if (!isSchemaObject(schema)) {
|
|
14
21
|
return null
|
|
@@ -107,10 +114,26 @@ const buildJsDocBlock = (title: string, description: string, commentUrl?: string
|
|
|
107
114
|
}
|
|
108
115
|
|
|
109
116
|
/**
|
|
110
|
-
* Converts a JSON Schema type to its TypeScript equivalent
|
|
117
|
+
* Converts a JSON Schema type to its TypeScript equivalent, applying any
|
|
118
|
+
* `x-mjst` brand. Branding is type-level only, so we compute the underlying
|
|
119
|
+
* type and intersect it with a unique brand marker. This is the recursion entry
|
|
120
|
+
* point, so branded nested fields are wrapped too.
|
|
121
|
+
*/
|
|
122
|
+
const getTypeScriptType = (schema: JSONSchema, options: TypeOptions = {}): string => {
|
|
123
|
+
const base = getUnbrandedType(schema, options)
|
|
124
|
+
const brand = getMjstBrand(schema)
|
|
125
|
+
return brand ? `(${base} & { readonly __brand: '${brand}' })` : base
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Wraps a `Record<...>` in `Readonly<...>` when readonly output is requested. */
|
|
129
|
+
const recordType = (keyType: string, valueType: string, options: TypeOptions): string =>
|
|
130
|
+
options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Converts a JSON Schema type to its TypeScript equivalent, ignoring any brand.
|
|
111
134
|
* Recursively handles nested objects and arrays.
|
|
112
135
|
*/
|
|
113
|
-
const
|
|
136
|
+
const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string => {
|
|
114
137
|
// Boolean schema: `true` means any value is valid (unknown), `false` means no value is valid (never)
|
|
115
138
|
if (typeof schema === 'boolean') {
|
|
116
139
|
return getBooleanSubSchemaType(schema)
|
|
@@ -121,6 +144,20 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
121
144
|
return 'unknown'
|
|
122
145
|
}
|
|
123
146
|
|
|
147
|
+
// An x-mjst instanceOf hint means the value is a runtime class (e.g. Date)
|
|
148
|
+
// that JSON Schema cannot describe — emit the class name as the type directly.
|
|
149
|
+
const instanceOf = getMjstInstanceOf(schema)
|
|
150
|
+
if (instanceOf) {
|
|
151
|
+
return instanceOf
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// An x-mjst primitive hint (e.g. bigint) names a non-JSON primitive — emit it
|
|
155
|
+
// directly as the TypeScript type.
|
|
156
|
+
const primitive = getMjstPrimitive(schema)
|
|
157
|
+
if (primitive) {
|
|
158
|
+
return primitive
|
|
159
|
+
}
|
|
160
|
+
|
|
124
161
|
// Handle $ref
|
|
125
162
|
if (schema.$ref) {
|
|
126
163
|
// External refs (e.g. http://json-schema.org/...) cannot be resolved locally — treat as unknown
|
|
@@ -168,17 +205,17 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
168
205
|
// Handle union types (oneOf, anyOf) - check this before returning unknown
|
|
169
206
|
if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
170
207
|
// schema.oneOf[0] is safe: we guard with .length > 0 above
|
|
171
|
-
let oneOfUnion = getTypeScriptType(schema.oneOf[0]
|
|
208
|
+
let oneOfUnion = getTypeScriptType(schema.oneOf[0]!, options)
|
|
172
209
|
for (let i = 1; i < schema.oneOf.length; i++) {
|
|
173
|
-
oneOfUnion += ' | ' + getTypeScriptType(schema.oneOf[i]
|
|
210
|
+
oneOfUnion += ' | ' + getTypeScriptType(schema.oneOf[i]!, options)
|
|
174
211
|
}
|
|
175
212
|
return oneOfUnion
|
|
176
213
|
}
|
|
177
214
|
if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
178
215
|
// schema.anyOf[0] is safe: we guard with .length > 0 above
|
|
179
|
-
let anyOfUnion = getTypeScriptType(schema.anyOf[0]
|
|
216
|
+
let anyOfUnion = getTypeScriptType(schema.anyOf[0]!, options)
|
|
180
217
|
for (let i = 1; i < schema.anyOf.length; i++) {
|
|
181
|
-
anyOfUnion += ' | ' + getTypeScriptType(schema.anyOf[i]
|
|
218
|
+
anyOfUnion += ' | ' + getTypeScriptType(schema.anyOf[i]!, options)
|
|
182
219
|
}
|
|
183
220
|
return anyOfUnion
|
|
184
221
|
}
|
|
@@ -186,9 +223,9 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
186
223
|
// Handle allOf (intersection types)
|
|
187
224
|
if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
188
225
|
// schema.allOf[0] is safe: we guard with .length > 0 above
|
|
189
|
-
let intersectionTypes = getTypeScriptType(schema.allOf[0]
|
|
226
|
+
let intersectionTypes = getTypeScriptType(schema.allOf[0]!, options)
|
|
190
227
|
for (let i = 1; i < schema.allOf.length; i++) {
|
|
191
|
-
intersectionTypes += ' & ' + getTypeScriptType(schema.allOf[i]
|
|
228
|
+
intersectionTypes += ' & ' + getTypeScriptType(schema.allOf[i]!, options)
|
|
192
229
|
}
|
|
193
230
|
return intersectionTypes
|
|
194
231
|
}
|
|
@@ -196,7 +233,7 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
196
233
|
// Handle object-like conditional schemas that use if/then without declaring type
|
|
197
234
|
const conditionalResult = getConditionalObjectSchema(schema)
|
|
198
235
|
if (conditionalResult) {
|
|
199
|
-
const baseType = getTypeScriptType(conditionalResult.schema)
|
|
236
|
+
const baseType = getTypeScriptType(conditionalResult.schema, options)
|
|
200
237
|
if (conditionalResult.thenRef) {
|
|
201
238
|
return `(${baseType}) & ${refToName(conditionalResult.thenRef)}`
|
|
202
239
|
}
|
|
@@ -207,9 +244,9 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
207
244
|
if (!schema.type) {
|
|
208
245
|
if (schema.additionalProperties !== undefined) {
|
|
209
246
|
if (typeof schema.additionalProperties === 'boolean') {
|
|
210
|
-
return
|
|
247
|
+
return recordType('string', getBooleanSubSchemaType(schema.additionalProperties), options)
|
|
211
248
|
}
|
|
212
|
-
return
|
|
249
|
+
return recordType('string', getTypeScriptType(schema.additionalProperties, options), options)
|
|
213
250
|
}
|
|
214
251
|
|
|
215
252
|
if (schema.patternProperties && typeof schema.patternProperties === 'object') {
|
|
@@ -217,13 +254,14 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
217
254
|
if (firstEntry) {
|
|
218
255
|
const [pattern, value] = firstEntry
|
|
219
256
|
if (value !== undefined) {
|
|
220
|
-
const valueType =
|
|
257
|
+
const valueType =
|
|
258
|
+
typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options)
|
|
221
259
|
// The ^x- pattern is a common JSON Schema convention for vendor extensions
|
|
222
260
|
// that maps naturally to the TypeScript template literal `x-${string}`
|
|
223
261
|
if (pattern === '^x-') {
|
|
224
|
-
return `
|
|
262
|
+
return recordType('`x-${string}`', valueType, options)
|
|
225
263
|
}
|
|
226
|
-
return
|
|
264
|
+
return recordType('string', valueType, options)
|
|
227
265
|
}
|
|
228
266
|
}
|
|
229
267
|
}
|
|
@@ -288,16 +326,17 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
288
326
|
// Array
|
|
289
327
|
case 'array':
|
|
290
328
|
if (schema.items) {
|
|
291
|
-
const itemType = getTypeScriptType(schema.items)
|
|
329
|
+
const itemType = getTypeScriptType(schema.items, options)
|
|
292
330
|
// Wrap union types in parentheses so `(A | B)[]` is not misread as `A | B[]`
|
|
293
331
|
const wrappedItemType = itemType.includes(' | ') ? `(${itemType})` : itemType
|
|
294
|
-
return `${wrappedItemType}[]`
|
|
332
|
+
return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`
|
|
295
333
|
}
|
|
296
|
-
return 'unknown[]'
|
|
334
|
+
return options.readonly ? 'readonly unknown[]' : 'unknown[]'
|
|
297
335
|
|
|
298
336
|
// Object
|
|
299
337
|
case 'object':
|
|
300
338
|
if (schema.properties) {
|
|
339
|
+
const readonlyPrefix = options.readonly ? 'readonly ' : ''
|
|
301
340
|
let properties = ''
|
|
302
341
|
let first = true
|
|
303
342
|
for (const key in schema.properties) {
|
|
@@ -305,17 +344,17 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
305
344
|
const propSchema = schema.properties[key]!
|
|
306
345
|
const isRequired = schema.required?.includes(key) ?? false
|
|
307
346
|
const optional = isRequired ? '' : '?'
|
|
308
|
-
const propType = getTypeScriptType(propSchema)
|
|
347
|
+
const propType = getTypeScriptType(propSchema, options)
|
|
309
348
|
if (!first) properties += '; '
|
|
310
|
-
properties += safeKey(key) + optional + ': ' + propType
|
|
349
|
+
properties += readonlyPrefix + safeKey(key) + optional + ': ' + propType
|
|
311
350
|
first = false
|
|
312
351
|
}
|
|
313
352
|
return '{ ' + properties + ' }'
|
|
314
353
|
}
|
|
315
354
|
// Handle additionalProperties with $ref or $dynamicRef
|
|
316
355
|
if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
|
|
317
|
-
const additionalPropType = getTypeScriptType(schema.additionalProperties)
|
|
318
|
-
return
|
|
356
|
+
const additionalPropType = getTypeScriptType(schema.additionalProperties, options)
|
|
357
|
+
return recordType('string', additionalPropType, options)
|
|
319
358
|
}
|
|
320
359
|
// Handle patternProperties as a Record type
|
|
321
360
|
if (schema.patternProperties && typeof schema.patternProperties === 'object') {
|
|
@@ -323,11 +362,11 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
323
362
|
if (firstEntry) {
|
|
324
363
|
const [pattern, patternVal] = firstEntry
|
|
325
364
|
if (patternVal) {
|
|
326
|
-
const valueType = getTypeScriptType(patternVal)
|
|
365
|
+
const valueType = getTypeScriptType(patternVal, options)
|
|
327
366
|
if (pattern === '^x-') {
|
|
328
|
-
return `
|
|
367
|
+
return recordType('`x-${string}`', valueType, options)
|
|
329
368
|
}
|
|
330
|
-
return
|
|
369
|
+
return recordType('string', valueType, options)
|
|
331
370
|
}
|
|
332
371
|
}
|
|
333
372
|
}
|
|
@@ -344,10 +383,12 @@ const getTypeScriptType = (schema: JSONSchema): string => {
|
|
|
344
383
|
* Handles required vs optional properties based on the schema's required array.
|
|
345
384
|
* Uses $comment as inline JSDoc description when present.
|
|
346
385
|
*/
|
|
347
|
-
export const generateTypeDefinition = (schema: JSONSchema, typeName: string): string => {
|
|
386
|
+
export const generateTypeDefinition = (schema: JSONSchema, typeName: string, options: TypeOptions = {}): string => {
|
|
387
|
+
const readonlyPrefix = options.readonly ? 'readonly ' : ''
|
|
388
|
+
|
|
348
389
|
// Handle non-object schemas first
|
|
349
390
|
if (!isObjectLikeSchema(schema)) {
|
|
350
|
-
const tsType = getTypeScriptType(schema)
|
|
391
|
+
const tsType = getTypeScriptType(schema, options)
|
|
351
392
|
let result = ''
|
|
352
393
|
|
|
353
394
|
if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === 'string') {
|
|
@@ -391,7 +432,7 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string): st
|
|
|
391
432
|
const patternPropType =
|
|
392
433
|
typeof firstPatternProperty === 'boolean'
|
|
393
434
|
? getBooleanSubSchemaType(firstPatternProperty)
|
|
394
|
-
: getTypeScriptType(firstPatternProperty)
|
|
435
|
+
: getTypeScriptType(firstPatternProperty, options)
|
|
395
436
|
|
|
396
437
|
// The ^x- pattern is a common JSON Schema convention for vendor extensions
|
|
397
438
|
// that maps naturally to the TypeScript template literal `x-${string}`
|
|
@@ -401,20 +442,20 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string): st
|
|
|
401
442
|
if (jsDocTitle && jsDocDescription) {
|
|
402
443
|
result += buildJsDocBlock(jsDocTitle, jsDocDescription)
|
|
403
444
|
}
|
|
404
|
-
result += `export type ${typeName} =
|
|
445
|
+
result += `export type ${typeName} = ${recordType(keyType, patternPropType, options)};`
|
|
405
446
|
|
|
406
447
|
return result
|
|
407
448
|
}
|
|
408
449
|
|
|
409
450
|
// Handle objects with only additionalProperties (no fixed properties)
|
|
410
451
|
if (!hasProperties && hasAdditionalProperties && normalizedSchema.additionalProperties) {
|
|
411
|
-
const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties)
|
|
452
|
+
const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties, options)
|
|
412
453
|
|
|
413
454
|
let result = ''
|
|
414
455
|
if (jsDocTitle && jsDocDescription) {
|
|
415
456
|
result += buildJsDocBlock(jsDocTitle, jsDocDescription)
|
|
416
457
|
}
|
|
417
|
-
result += `export type ${typeName} = {\n [key: string]: ${additionalPropType};\n};`
|
|
458
|
+
result += `export type ${typeName} = {\n ${readonlyPrefix}[key: string]: ${additionalPropType};\n};`
|
|
418
459
|
|
|
419
460
|
return result
|
|
420
461
|
}
|
|
@@ -427,8 +468,8 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string): st
|
|
|
427
468
|
const propSchema = schemaProps[key]!
|
|
428
469
|
const isRequired = normalizedSchema.required?.includes(key) ?? false
|
|
429
470
|
const optional = isRequired ? '' : '?'
|
|
430
|
-
const propType = getTypeScriptType(propSchema)
|
|
431
|
-
const quotedKey = safeKey(key)
|
|
471
|
+
const propType = getTypeScriptType(propSchema, options)
|
|
472
|
+
const quotedKey = readonlyPrefix + safeKey(key)
|
|
432
473
|
|
|
433
474
|
if (!isFirstProp) properties += '\n'
|
|
434
475
|
isFirstProp = false
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
|
+
import { describe, expect, it } from 'vitest'
|
|
3
|
+
|
|
4
|
+
import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive, MJST_EXTENSION_KEY } from './mjst-extension'
|
|
5
|
+
|
|
6
|
+
describe('getMjstInstanceOf', () => {
|
|
7
|
+
it('reads a valid instanceOf class name', () => {
|
|
8
|
+
expect(getMjstInstanceOf({ 'x-mjst': { instanceOf: 'Date' } })).toBe('Date')
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('returns undefined when the extension is absent', () => {
|
|
12
|
+
expect(getMjstInstanceOf({ type: 'string' })).toBeUndefined()
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
it('returns undefined for a boolean schema', () => {
|
|
16
|
+
expect(getMjstInstanceOf(true as unknown as JSONSchema)).toBeUndefined()
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
it('rejects instanceOf values that are not safe identifiers', () => {
|
|
20
|
+
expect(getMjstInstanceOf({ 'x-mjst': { instanceOf: 'Date; doEvil()' } })).toBeUndefined()
|
|
21
|
+
expect(getMjstInstanceOf({ 'x-mjst': { instanceOf: '' } })).toBeUndefined()
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('exposes the extension key', () => {
|
|
25
|
+
expect(MJST_EXTENSION_KEY).toBe('x-mjst')
|
|
26
|
+
})
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
describe('getMjstPrimitive', () => {
|
|
30
|
+
it('reads a supported primitive', () => {
|
|
31
|
+
expect(getMjstPrimitive({ 'x-mjst': { primitive: 'bigint' } })).toBe('bigint')
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('ignores unsupported primitives', () => {
|
|
35
|
+
expect(getMjstPrimitive({ 'x-mjst': { primitive: 'symbol' } })).toBeUndefined()
|
|
36
|
+
expect(getMjstPrimitive({ 'x-mjst': { primitive: 'evil()' } })).toBeUndefined()
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('returns undefined when the extension is absent', () => {
|
|
40
|
+
expect(getMjstPrimitive({ type: 'string' })).toBeUndefined()
|
|
41
|
+
})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
describe('getMjstBrand', () => {
|
|
45
|
+
it('reads a safe brand name', () => {
|
|
46
|
+
expect(getMjstBrand({ 'x-mjst': { brand: 'UserId' } })).toBe('UserId')
|
|
47
|
+
expect(getMjstBrand({ 'x-mjst': { brand: 'order-id 2' } })).toBe('order-id 2')
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('rejects brand names that could break out of a string literal', () => {
|
|
51
|
+
expect(getMjstBrand({ 'x-mjst': { brand: "x'; doEvil()" } })).toBeUndefined()
|
|
52
|
+
expect(getMjstBrand({ 'x-mjst': { brand: 'a\\b' } })).toBeUndefined()
|
|
53
|
+
expect(getMjstBrand({ 'x-mjst': { brand: '' } })).toBeUndefined()
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('returns undefined when the extension is absent', () => {
|
|
57
|
+
expect(getMjstBrand({ type: 'string' })).toBeUndefined()
|
|
58
|
+
})
|
|
59
|
+
})
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
|
+
|
|
3
|
+
import { isSchemaObject } from './schema-guards'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Vendor extension keyword carrying mjst-specific runtime hints that plain JSON
|
|
7
|
+
* Schema cannot express on its own. Adapters (TypeBox, Zod, ...) emit it when a
|
|
8
|
+
* source construct has no native JSON Schema equivalent, and the generators read
|
|
9
|
+
* it to produce the right TypeScript type and runtime checks.
|
|
10
|
+
*/
|
|
11
|
+
export const MJST_EXTENSION_KEY = 'x-mjst'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The shape of the `x-mjst` extension object.
|
|
15
|
+
*
|
|
16
|
+
* - `instanceOf` names a JavaScript class the value must be an instance of at
|
|
17
|
+
* runtime (e.g. `'Date'`). It round-trips constructs like TypeBox's
|
|
18
|
+
* `Type.Date()` that JSON Schema's core vocabulary has no keyword for.
|
|
19
|
+
* - `primitive` names a non-JSON primitive type (e.g. `'bigint'`) that has no
|
|
20
|
+
* JSON Schema representation. Unlike `instanceOf`, the value is checked with
|
|
21
|
+
* `typeof`, not `instanceof`.
|
|
22
|
+
* - `brand` carries a nominal-typing brand name. It is purely type-level: the
|
|
23
|
+
* runtime value still validates as its underlying JSON Schema type, but the
|
|
24
|
+
* generated TypeScript type is intersected with a unique brand so values are
|
|
25
|
+
* not interchangeable with the unbranded base type.
|
|
26
|
+
*/
|
|
27
|
+
export type MjstExtension = {
|
|
28
|
+
readonly instanceOf?: string
|
|
29
|
+
readonly primitive?: string
|
|
30
|
+
readonly brand?: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Only identifier-safe class names are honoured, so a malicious or malformed
|
|
34
|
+
// schema cannot inject arbitrary code into the generated output.
|
|
35
|
+
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
|
|
36
|
+
|
|
37
|
+
// The non-JSON primitives we know how to generate type/runtime handling for.
|
|
38
|
+
// Anything outside this set is ignored so unknown hints degrade gracefully.
|
|
39
|
+
const SUPPORTED_PRIMITIVES = new Set(['bigint'])
|
|
40
|
+
|
|
41
|
+
// Brand names are embedded inside a single-quoted string literal in generated
|
|
42
|
+
// output, so we only allow characters that cannot break out of the literal.
|
|
43
|
+
const SAFE_BRAND = /^[\w$ -]+$/
|
|
44
|
+
|
|
45
|
+
const readExtensionString = (schema: JSONSchema, field: keyof MjstExtension): string | undefined => {
|
|
46
|
+
if (!isSchemaObject(schema)) return undefined
|
|
47
|
+
|
|
48
|
+
const extension = (schema as Record<string, unknown>)[MJST_EXTENSION_KEY]
|
|
49
|
+
if (typeof extension !== 'object' || extension === null) return undefined
|
|
50
|
+
|
|
51
|
+
const value = (extension as Record<string, unknown>)[field]
|
|
52
|
+
return typeof value === 'string' ? value : undefined
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Reads the `instanceOf` class name from a schema's `x-mjst` extension, when it
|
|
57
|
+
* is present and a safe identifier. Returns undefined otherwise so callers fall
|
|
58
|
+
* back to ordinary type handling.
|
|
59
|
+
*/
|
|
60
|
+
export const getMjstInstanceOf = (schema: JSONSchema): string | undefined => {
|
|
61
|
+
const instanceOf = readExtensionString(schema, 'instanceOf')
|
|
62
|
+
return instanceOf !== undefined && IDENTIFIER.test(instanceOf) ? instanceOf : undefined
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Reads the `primitive` type name from a schema's `x-mjst` extension, when it is
|
|
67
|
+
* one we support (e.g. `'bigint'`). Returns undefined otherwise.
|
|
68
|
+
*/
|
|
69
|
+
export const getMjstPrimitive = (schema: JSONSchema): string | undefined => {
|
|
70
|
+
const primitive = readExtensionString(schema, 'primitive')
|
|
71
|
+
return primitive !== undefined && SUPPORTED_PRIMITIVES.has(primitive) ? primitive : undefined
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Reads the nominal `brand` name from a schema's `x-mjst` extension, when it is
|
|
76
|
+
* present and safe to embed in generated output. Returns undefined otherwise.
|
|
77
|
+
*/
|
|
78
|
+
export const getMjstBrand = (schema: JSONSchema): string | undefined => {
|
|
79
|
+
const brand = readExtensionString(schema, 'brand')
|
|
80
|
+
return brand !== undefined && SAFE_BRAND.test(brand) ? brand : undefined
|
|
81
|
+
}
|