@amritk/helpers 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Derives the root type name for a generated schema from its `title` keyword.
3
+ *
4
+ * We name the root after the schema itself instead of a generic "Document" so
5
+ * the generated types and parsers read naturally (e.g. an OpenAPI schema yields
6
+ * `OpenApi` / `parseOpenApi`). When the schema has no usable `title`, we fall
7
+ * back to "Document" to keep output deterministic.
8
+ *
9
+ * @param schema - The root JSON Schema. A boolean schema or one without a
10
+ * string `title` falls back to the default.
11
+ * @returns A PascalCase type name derived from the title, or "Document".
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * deriveRootTypeName({ title: 'OpenAPI Document' }) // 'OpenAPIDocument'
16
+ * deriveRootTypeName({ title: 'my-config' }) // 'MyConfig'
17
+ * deriveRootTypeName({ type: 'object' }) // 'Document'
18
+ * ```
19
+ */
20
+ export declare const deriveRootTypeName: (schema: unknown) => string;
@@ -0,0 +1,19 @@
1
+ // src/is-object.ts
2
+ var isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
3
+
4
+ // src/derive-root-type-name.ts
5
+ var titleToPascalCase = (title) => {
6
+ const words = title.split(/[^a-zA-Z0-9]+/).filter(Boolean);
7
+ const pascal = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
8
+ return pascal.replace(/^\d+/, "");
9
+ };
10
+ var deriveRootTypeName = (schema) => {
11
+ if (!isObject(schema) || typeof schema["title"] !== "string") {
12
+ return "Document";
13
+ }
14
+ const name = titleToPascalCase(schema["title"]);
15
+ return name || "Document";
16
+ };
17
+ export {
18
+ deriveRootTypeName
19
+ };
@@ -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) => {
@@ -246,12 +273,25 @@ var buildJsDocBlock = (title, description, commentUrl) => {
246
273
  return block;
247
274
  };
248
275
  var getTypeScriptType = (schema) => {
276
+ const base = getUnbrandedType(schema);
277
+ const brand = getMjstBrand(schema);
278
+ return brand ? `(${base} & { readonly __brand: '${brand}' })` : base;
279
+ };
280
+ var getUnbrandedType = (schema) => {
249
281
  if (typeof schema === "boolean") {
250
282
  return getBooleanSubSchemaType(schema);
251
283
  }
252
284
  if (typeof schema !== "object" || schema === null) {
253
285
  return "unknown";
254
286
  }
287
+ const instanceOf = getMjstInstanceOf(schema);
288
+ if (instanceOf) {
289
+ return instanceOf;
290
+ }
291
+ const primitive = getMjstPrimitive(schema);
292
+ if (primitive) {
293
+ return primitive;
294
+ }
255
295
  if (schema.$ref) {
256
296
  if (!schema.$ref.startsWith("#")) {
257
297
  return "unknown";
@@ -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.2.2",
3
+ "version": "0.4.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/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": "catalog:"
35
+ "json-schema-typed": "^8.0.1"
36
36
  },
37
37
  "exports": {
38
38
  "./package.json": "./package.json",
@@ -41,6 +41,11 @@
41
41
  "default": "./dist/build-dynamic-ref-map.js",
42
42
  "types": "./dist/build-dynamic-ref-map.d.ts"
43
43
  },
44
+ "./derive-root-type-name": {
45
+ "bun": "./src/derive-root-type-name.ts",
46
+ "default": "./dist/derive-root-type-name.js",
47
+ "types": "./dist/derive-root-type-name.d.ts"
48
+ },
44
49
  "./extract-refs": {
45
50
  "bun": "./src/extract-refs.ts",
46
51
  "default": "./dist/extract-refs.js",
@@ -61,6 +66,11 @@
61
66
  "default": "./dist/is-object.js",
62
67
  "types": "./dist/is-object.d.ts"
63
68
  },
69
+ "./mjst-extension": {
70
+ "bun": "./src/mjst-extension.ts",
71
+ "default": "./dist/mjst-extension.js",
72
+ "types": "./dist/mjst-extension.d.ts"
73
+ },
64
74
  "./parse-documentation": {
65
75
  "bun": "./src/parse-documentation.ts",
66
76
  "default": "./dist/parse-documentation.js",
@@ -0,0 +1,42 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { deriveRootTypeName } from './derive-root-type-name'
4
+
5
+ describe('derive-root-type-name', () => {
6
+ it('derives a PascalCase name from a single-word title', () => {
7
+ expect(deriveRootTypeName({ title: 'Document' })).toBe('Document')
8
+ })
9
+
10
+ it('joins multi-word titles into PascalCase', () => {
11
+ expect(deriveRootTypeName({ title: 'OpenAPI Document' })).toBe('OpenAPIDocument')
12
+ })
13
+
14
+ it('preserves acronyms intact', () => {
15
+ expect(deriveRootTypeName({ title: 'JSON Schema' })).toBe('JSONSchema')
16
+ })
17
+
18
+ it('splits on non-alphanumeric separators', () => {
19
+ expect(deriveRootTypeName({ title: 'my-config_file.spec' })).toBe('MyConfigFileSpec')
20
+ })
21
+
22
+ it('drops leading digits so the name is a valid identifier', () => {
23
+ expect(deriveRootTypeName({ title: '3 amigos' })).toBe('Amigos')
24
+ })
25
+
26
+ it('falls back to Document when the title is missing', () => {
27
+ expect(deriveRootTypeName({ type: 'object' })).toBe('Document')
28
+ })
29
+
30
+ it('falls back to Document when the title is not a string', () => {
31
+ expect(deriveRootTypeName({ title: 42 })).toBe('Document')
32
+ })
33
+
34
+ it('falls back to Document for a title with no usable characters', () => {
35
+ expect(deriveRootTypeName({ title: ' --- ' })).toBe('Document')
36
+ })
37
+
38
+ it('falls back to Document for boolean schemas', () => {
39
+ expect(deriveRootTypeName(true)).toBe('Document')
40
+ expect(deriveRootTypeName(false)).toBe('Document')
41
+ })
42
+ })
@@ -0,0 +1,42 @@
1
+ import { isObject } from './is-object'
2
+
3
+ /**
4
+ * Converts an arbitrary title string into a PascalCase TypeScript identifier.
5
+ * Splits on any run of non-alphanumeric characters, capitalizes the first
6
+ * letter of each word while preserving the rest (so acronyms like "API" or
7
+ * "JSON" survive intact), and drops leading digits since an identifier may not
8
+ * start with a number.
9
+ */
10
+ const titleToPascalCase = (title: string): string => {
11
+ const words = title.split(/[^a-zA-Z0-9]+/).filter(Boolean)
12
+ const pascal = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join('')
13
+ return pascal.replace(/^\d+/, '')
14
+ }
15
+
16
+ /**
17
+ * Derives the root type name for a generated schema from its `title` keyword.
18
+ *
19
+ * We name the root after the schema itself instead of a generic "Document" so
20
+ * the generated types and parsers read naturally (e.g. an OpenAPI schema yields
21
+ * `OpenApi` / `parseOpenApi`). When the schema has no usable `title`, we fall
22
+ * back to "Document" to keep output deterministic.
23
+ *
24
+ * @param schema - The root JSON Schema. A boolean schema or one without a
25
+ * string `title` falls back to the default.
26
+ * @returns A PascalCase type name derived from the title, or "Document".
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * deriveRootTypeName({ title: 'OpenAPI Document' }) // 'OpenAPIDocument'
31
+ * deriveRootTypeName({ title: 'my-config' }) // 'MyConfig'
32
+ * deriveRootTypeName({ type: 'object' }) // 'Document'
33
+ * ```
34
+ */
35
+ export const deriveRootTypeName = (schema: unknown): string => {
36
+ if (!isObject(schema) || typeof schema['title'] !== 'string') {
37
+ return 'Document'
38
+ }
39
+
40
+ const name = titleToPascalCase(schema['title'])
41
+ return name || 'Document'
42
+ }
@@ -1207,4 +1207,67 @@ 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
+ })
1210
1273
  })
@@ -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'
@@ -107,10 +108,22 @@ const buildJsDocBlock = (title: string, description: string, commentUrl?: string
107
108
  }
108
109
 
109
110
  /**
110
- * Converts a JSON Schema type to its TypeScript equivalent.
111
- * Recursively handles nested objects and arrays.
111
+ * Converts a JSON Schema type to its TypeScript equivalent, applying any
112
+ * `x-mjst` brand. Branding is type-level only, so we compute the underlying
113
+ * type and intersect it with a unique brand marker. This is the recursion entry
114
+ * point, so branded nested fields are wrapped too.
112
115
  */
113
116
  const getTypeScriptType = (schema: JSONSchema): string => {
117
+ const base = getUnbrandedType(schema)
118
+ const brand = getMjstBrand(schema)
119
+ return brand ? `(${base} & { readonly __brand: '${brand}' })` : base
120
+ }
121
+
122
+ /**
123
+ * Converts a JSON Schema type to its TypeScript equivalent, ignoring any brand.
124
+ * Recursively handles nested objects and arrays.
125
+ */
126
+ const getUnbrandedType = (schema: JSONSchema): string => {
114
127
  // Boolean schema: `true` means any value is valid (unknown), `false` means no value is valid (never)
115
128
  if (typeof schema === 'boolean') {
116
129
  return getBooleanSubSchemaType(schema)
@@ -121,6 +134,20 @@ const getTypeScriptType = (schema: JSONSchema): string => {
121
134
  return 'unknown'
122
135
  }
123
136
 
137
+ // An x-mjst instanceOf hint means the value is a runtime class (e.g. Date)
138
+ // that JSON Schema cannot describe — emit the class name as the type directly.
139
+ const instanceOf = getMjstInstanceOf(schema)
140
+ if (instanceOf) {
141
+ return instanceOf
142
+ }
143
+
144
+ // An x-mjst primitive hint (e.g. bigint) names a non-JSON primitive — emit it
145
+ // directly as the TypeScript type.
146
+ const primitive = getMjstPrimitive(schema)
147
+ if (primitive) {
148
+ return primitive
149
+ }
150
+
124
151
  // Handle $ref
125
152
  if (schema.$ref) {
126
153
  // External refs (e.g. http://json-schema.org/...) cannot be resolved locally — treat as unknown
@@ -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
+ }