@amritk/helpers 0.15.3 → 0.16.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.
Files changed (41) hide show
  1. package/dist/assert-id-scopes.js +9 -8
  2. package/dist/assign-key.d.ts +17 -0
  3. package/dist/assign-key.js +10 -0
  4. package/dist/build-anchor-map.js +8 -8
  5. package/dist/build-dynamic-ref-map.js +10 -10
  6. package/dist/build-resource-registry.d.ts +54 -0
  7. package/dist/build-resource-registry.js +35 -12
  8. package/dist/derive-root-type-name.js +9 -5
  9. package/dist/escape-regex-pattern.js +42 -35
  10. package/dist/extract-refs.js +11 -6
  11. package/dist/fold-nullable.js +17 -10
  12. package/dist/generate-index-barrel.js +7 -11
  13. package/dist/generate-type-definition.js +156 -138
  14. package/dist/graft-external-schemas.js +3 -2
  15. package/dist/has-ref.js +1 -1
  16. package/dist/max-schema-depth.d.ts +8 -1
  17. package/dist/max-schema-depth.js +3 -3
  18. package/dist/mjst-extension.js +3 -2
  19. package/dist/normalize-ref-scopes.js +12 -6
  20. package/dist/parse-documentation.js +1 -1
  21. package/dist/prune-external-schemas.js +10 -8
  22. package/dist/quote-js-string.js +3 -1
  23. package/dist/read-key.d.ts +25 -0
  24. package/dist/read-key.js +6 -0
  25. package/dist/ref-to-name.d.ts +41 -0
  26. package/dist/ref-to-name.js +11 -5
  27. package/dist/resolve-dynamic-refs.js +19 -12
  28. package/dist/resolve-ref.js +2 -1
  29. package/dist/safe-accessor.d.ts +1 -1
  30. package/dist/safe-accessor.js +1 -1
  31. package/dist/schema-guards.js +34 -34
  32. package/dist/string-length-check.js +2 -2
  33. package/dist/unknown-key-check.d.ts +14 -3
  34. package/dist/unknown-key-check.js +2 -2
  35. package/dist/upgrade-draft07-schema.js +49 -34
  36. package/dist/validate-record.d.ts +6 -1
  37. package/dist/validate-record.js +1 -1
  38. package/dist/walk-ref-graph.js +75 -33
  39. package/package.json +1 -1
  40. package/src/has-ref.ts +1 -1
  41. package/src/validate-record.ts +7 -2
@@ -1,8 +1,19 @@
1
+ import { assertSchemaDepth, MAX_SCHEMA_DEPTH } from "./max-schema-depth.js";
1
2
  import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive } from "./mjst-extension.js";
3
+ import { readKey } from "./read-key.js";
2
4
  import { refToName } from "./ref-to-name.js";
3
5
  import { resolveRef } from "./resolve-ref.js";
4
6
  import { safeKey } from "./safe-accessor.js";
5
7
  import { isObjectSchema, isSchemaObject } from "./schema-guards.js";
8
+ const keywordOf = (schema, name) => readKey(schema, name);
9
+ const keywordMap = (schema, name) => {
10
+ const value = keywordOf(schema, name);
11
+ if (typeof value !== "object" || value === null || Array.isArray(value))
12
+ return void 0;
13
+ return value;
14
+ };
15
+ const MAX_TYPE_DEPTH = Math.floor(MAX_SCHEMA_DEPTH / 5);
16
+ const declares = (schema, name) => Object.hasOwn(schema, name);
6
17
  const refTypeName = (ref, options) => {
7
18
  if (ref.startsWith("#"))
8
19
  return refToName(ref, options.typeSuffix);
@@ -16,17 +27,17 @@ const getConditionalObjectSchema = (schema) => {
16
27
  if (!isSchemaObject(schema)) {
17
28
  return null;
18
29
  }
19
- if (!("if" in schema) || !("then" in schema)) {
30
+ if (!declares(schema, "if") || !declares(schema, "then")) {
20
31
  return null;
21
32
  }
22
- const ifSchema = schema.if;
23
- const thenSchema = schema.then;
33
+ const ifSchema = keywordOf(schema, "if");
34
+ const thenSchema = keywordOf(schema, "then");
24
35
  if (!isSchemaObject(ifSchema) || !isSchemaObject(thenSchema)) {
25
36
  return null;
26
37
  }
27
- const ownProperties = schema.properties;
28
- const ifProperties = ifSchema.properties;
29
- const thenProperties = thenSchema.properties;
38
+ const ownProperties = keywordOf(schema, "properties");
39
+ const ifProperties = keywordOf(ifSchema, "properties");
40
+ const thenProperties = keywordOf(thenSchema, "properties");
30
41
  const hasOwnProperties = ownProperties && typeof ownProperties === "object";
31
42
  const hasIfProperties = ifProperties && typeof ifProperties === "object";
32
43
  const hasThenProperties = thenProperties && typeof thenProperties === "object";
@@ -39,32 +50,25 @@ const getConditionalObjectSchema = (schema) => {
39
50
  ...hasThenProperties ? thenProperties : {}
40
51
  };
41
52
  const required = /* @__PURE__ */ new Set();
42
- if (Array.isArray(schema.required)) {
43
- for (const key of schema.required) {
44
- required.add(key);
45
- }
46
- }
47
- if (Array.isArray(ifSchema.required)) {
48
- for (const key of ifSchema.required) {
49
- required.add(key);
53
+ for (const node of [schema, ifSchema, thenSchema]) {
54
+ const declared = keywordOf(node, "required");
55
+ if (Array.isArray(declared)) {
56
+ for (const key of declared)
57
+ required.add(key);
50
58
  }
51
59
  }
52
60
  if (hasIfProperties) {
53
- for (const key in ifProperties) {
54
- required.add(key);
55
- }
56
- }
57
- if (Array.isArray(thenSchema.required)) {
58
- for (const key of thenSchema.required) {
61
+ for (const key of Object.keys(ifProperties)) {
59
62
  required.add(key);
60
63
  }
61
64
  }
62
65
  if (hasThenProperties) {
63
- for (const key in thenProperties) {
66
+ for (const key of Object.keys(thenProperties)) {
64
67
  required.add(key);
65
68
  }
66
69
  }
67
- const thenRef = typeof thenSchema.$ref === "string" ? thenSchema.$ref : null;
70
+ const thenRefValue = keywordOf(thenSchema, "$ref");
71
+ const thenRef = typeof thenRefValue === "string" ? thenRefValue : null;
68
72
  return {
69
73
  schema: {
70
74
  type: "object",
@@ -81,7 +85,7 @@ const isObjectLikeSchema = (schema) => {
81
85
  if (isObjectSchema(schema)) {
82
86
  return true;
83
87
  }
84
- return "patternProperties" in schema || "additionalProperties" in schema || "if" in schema && "then" in schema;
88
+ return declares(schema, "patternProperties") || declares(schema, "additionalProperties") || declares(schema, "if") && declares(schema, "then");
85
89
  };
86
90
  const getBooleanSubSchemaType = (schema) => {
87
91
  return schema ? "unknown" : "never";
@@ -90,24 +94,11 @@ const escapeCommentText = (text) => text.replace(/\*\//g, "*\\/");
90
94
  const renderJsDocBody = (description, indent) => escapeCommentText(description).split("\n").map((line) => line.length > 0 ? `${indent}* ${line}
91
95
  ` : `${indent}*
92
96
  `).join("");
93
- const buildJsDocBlock = (title, description, commentUrl) => {
94
- let block = `/**
97
+ const buildJsDocBlock = (title, description) => `/**
98
+ * ${title}
99
+ *
100
+ ${renderJsDocBody(description, "")}*/
95
101
  `;
96
- block += `* ${title}
97
- `;
98
- block += `*
99
- `;
100
- block += renderJsDocBody(description, "");
101
- if (commentUrl?.startsWith("http")) {
102
- block += `*
103
- `;
104
- block += `* @see {@link ${commentUrl}}
105
- `;
106
- }
107
- block += `*/
108
- `;
109
- return block;
110
- };
111
102
  const buildInlinePropertyComment = (description) => {
112
103
  if (!description.includes("\n")) {
113
104
  return ` /** ${escapeCommentText(description)} */
@@ -117,13 +108,14 @@ const buildInlinePropertyComment = (description) => {
117
108
  ${renderJsDocBody(description, " ")} */
118
109
  `;
119
110
  };
120
- const getTypeScriptType = (schema, options = {}) => {
121
- const base = getUnbrandedType(schema, options);
111
+ const getTypeScriptType = (schema, options, depth) => {
112
+ assertSchemaDepth(depth, "generateTypeDefinition", MAX_TYPE_DEPTH);
113
+ const base = getUnbrandedType(schema, options, depth);
122
114
  const brand = getMjstBrand(schema);
123
115
  const branded = brand ? `(${base} & { readonly __brand: '${brand}' })` : base;
124
116
  return isNullableSchema(schema) ? withNull(branded) : branded;
125
117
  };
126
- const isNullableSchema = (schema) => isSchemaObject(schema) && schema["nullable"] === true;
118
+ const isNullableSchema = (schema) => isSchemaObject(schema) && keywordOf(schema, "nullable") === true;
127
119
  const wrapUnion = (type) => type.includes(" | ") ? `(${type})` : type;
128
120
  const withNull = (type) => type.split(" | ").includes("null") ? type : `${type} | null`;
129
121
  const unionOf = (members) => [...new Set(members)].join(" | ");
@@ -137,14 +129,14 @@ const intersectionOf = (members) => {
137
129
  return meaningful.join(" & ");
138
130
  };
139
131
  const recordType = (keyType, valueType, options) => options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`;
140
- const patternPropertiesRecordType = (patternProperties, options) => {
132
+ const patternPropertiesRecordType = (patternProperties, options, depth) => {
141
133
  const entries = Object.entries(patternProperties);
142
134
  if (entries.length === 0)
143
135
  return void 0;
144
136
  const seen = /* @__PURE__ */ new Set();
145
137
  const valueTypes = [];
146
138
  for (const [, value] of entries) {
147
- const valueType2 = typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options);
139
+ const valueType2 = typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options, depth + 1);
148
140
  if (!seen.has(valueType2)) {
149
141
  seen.add(valueType2);
150
142
  valueTypes.push(valueType2);
@@ -157,52 +149,54 @@ const patternPropertiesRecordType = (patternProperties, options) => {
157
149
  return recordType(keyType, valueType, options);
158
150
  };
159
151
  const getTuplePositions = (schema) => {
160
- const record = schema;
161
- const prefixItems = record["prefixItems"];
152
+ const prefixItems = keywordOf(schema, "prefixItems");
162
153
  if (Array.isArray(prefixItems))
163
154
  return prefixItems.length > 0 ? prefixItems : void 0;
164
- if (Array.isArray(schema.items) && schema.items.length > 0)
165
- return schema.items;
155
+ const items = keywordOf(schema, "items");
156
+ if (Array.isArray(items) && items.length > 0)
157
+ return items;
166
158
  return void 0;
167
159
  };
168
- const tupleTypeToTs = (schema, positions, options) => {
169
- const record = schema;
170
- const rest = Array.isArray(schema.items) ? record["additionalItems"] : record["items"];
171
- const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
160
+ const tupleTypeToTs = (schema, positions, options, depth) => {
161
+ const items = keywordOf(schema, "items");
162
+ const rest = Array.isArray(items) ? keywordOf(schema, "additionalItems") : items;
163
+ const declaredMin = keywordOf(schema, "minItems");
164
+ const minItems = typeof declaredMin === "number" ? declaredMin : 0;
172
165
  const parts = [];
173
166
  for (let i = 0; i < positions.length; i++) {
174
- const positionType = wrapUnion(getTypeScriptType(positions[i], options));
167
+ const positionType = wrapUnion(getTypeScriptType(positions[i], options, depth + 1));
175
168
  parts.push(i < minItems ? positionType : `${positionType}?`);
176
169
  }
177
170
  if (rest !== false) {
178
- const restType = rest === void 0 || rest === true ? "unknown" : wrapUnion(getTypeScriptType(rest, options));
171
+ const restType = rest === void 0 || rest === true ? "unknown" : wrapUnion(getTypeScriptType(rest, options, depth + 1));
179
172
  parts.push(`...${restType}[]`);
180
173
  }
181
174
  const tuple = `[${parts.join(", ")}]`;
182
175
  return options.readonly ? `readonly ${tuple}` : tuple;
183
176
  };
184
- const arrayTypeToTs = (schema, options) => {
177
+ const arrayTypeToTs = (schema, options, depth) => {
185
178
  const positions = getTuplePositions(schema);
186
179
  if (positions)
187
- return tupleTypeToTs(schema, positions, options);
188
- if (schema.items !== void 0 && !Array.isArray(schema.items)) {
189
- const itemType = getTypeScriptType(schema.items, options);
180
+ return tupleTypeToTs(schema, positions, options, depth);
181
+ const items = keywordOf(schema, "items");
182
+ if (items !== void 0 && !Array.isArray(items)) {
183
+ const itemType = getTypeScriptType(items, options, depth + 1);
190
184
  const wrappedItemType = wrapUnion(itemType);
191
185
  return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`;
192
186
  }
193
187
  return options.readonly ? "readonly unknown[]" : "unknown[]";
194
188
  };
195
- const getIndexSignature = (schema, options) => {
196
- const additionalProperties = schema.additionalProperties;
189
+ const getIndexSignature = (schema, options, depth) => {
190
+ const additionalProperties = keywordOf(schema, "additionalProperties");
197
191
  if (additionalProperties !== void 0 && typeof additionalProperties !== "boolean") {
198
- return { key: "string", value: getTypeScriptType(additionalProperties, options) };
192
+ return { key: "string", value: getTypeScriptType(additionalProperties, options, depth + 1) };
199
193
  }
200
- const patternProperties = schema.patternProperties;
194
+ const patternProperties = keywordOf(schema, "patternProperties");
201
195
  if (patternProperties && typeof patternProperties === "object") {
202
196
  const entries = Object.entries(patternProperties);
203
197
  if (entries.length === 0)
204
198
  return void 0;
205
- const valueTypes = entries.map(([, value]) => typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options));
199
+ const valueTypes = entries.map(([, value]) => typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options, depth + 1));
206
200
  const key = entries.length === 1 && entries[0]?.[0] === "^x-" ? "`x-${string}`" : "string";
207
201
  return { key, value: unionOf(valueTypes) };
208
202
  }
@@ -222,28 +216,32 @@ const buildIndexSignatureLine = (index, declaredTypes, hasOptionalProperty, opti
222
216
  const propertyDescription = (propSchema) => {
223
217
  if (!isSchemaObject(propSchema))
224
218
  return void 0;
225
- if (typeof propSchema.description === "string")
226
- return propSchema.description;
227
- if (typeof propSchema.$comment === "string")
228
- return propSchema.$comment;
219
+ const description = keywordOf(propSchema, "description");
220
+ if (typeof description === "string")
221
+ return description;
222
+ const comment = keywordOf(propSchema, "$comment");
223
+ if (typeof comment === "string")
224
+ return comment;
229
225
  return void 0;
230
226
  };
231
- const objectTypeToTs = (schema, options) => {
232
- const index = getIndexSignature(schema, options);
233
- if (schema.properties && Object.keys(schema.properties).length > 0) {
227
+ const objectTypeToTs = (schema, options, depth) => {
228
+ const index = getIndexSignature(schema, options, depth);
229
+ const properties = keywordOf(schema, "properties");
230
+ if (properties && Object.keys(properties).length > 0) {
234
231
  const readonlyPrefix = options.readonly ? "readonly " : "";
235
- const requiredSet = new Set(Array.isArray(schema.required) ? schema.required : []);
236
- const hasDescriptions = Object.values(schema.properties).some((p) => propertyDescription(p) !== void 0);
232
+ const declaredRequired = keywordOf(schema, "required");
233
+ const requiredSet = new Set(Array.isArray(declaredRequired) ? declaredRequired : []);
234
+ const hasDescriptions = Object.values(properties).some((p) => propertyDescription(p) !== void 0);
237
235
  const declaredTypes = [];
238
236
  let hasOptionalProperty = false;
239
237
  const entries = [];
240
- for (const key in schema.properties) {
241
- const propSchema = schema.properties[key];
238
+ for (const key of Object.keys(properties)) {
239
+ const propSchema = properties[key];
242
240
  const isRequired = requiredSet.has(key);
243
241
  const optional = isRequired ? "" : "?";
244
242
  if (!isRequired)
245
243
  hasOptionalProperty = true;
246
- const propType = getTypeScriptType(propSchema, options);
244
+ const propType = getTypeScriptType(propSchema, options, depth + 1);
247
245
  declaredTypes.push(propType);
248
246
  const declaration = readonlyPrefix + safeKey(key) + optional + ": " + propType;
249
247
  if (!hasDescriptions) {
@@ -266,37 +264,41 @@ const objectTypeToTs = (schema, options) => {
266
264
  }
267
265
  return "object";
268
266
  };
269
- const getLocalShapeType = (schema, options) => {
267
+ const getLocalShapeType = (schema, options, depth) => {
270
268
  const conditionalResult = getConditionalObjectSchema(schema);
271
269
  if (conditionalResult) {
272
- const baseType = objectTypeToTs(conditionalResult.schema, options);
270
+ const baseType = objectTypeToTs(conditionalResult.schema, options, depth);
273
271
  return conditionalResult.thenRef ? `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}` : baseType;
274
272
  }
275
- if (!schema.type) {
276
- const index = getIndexSignature(schema, options);
273
+ const type = keywordOf(schema, "type");
274
+ if (!type) {
275
+ const index = getIndexSignature(schema, options, depth);
277
276
  if (index)
278
- return objectTypeToTs(schema, options);
279
- if (schema.additionalProperties !== void 0 && typeof schema.additionalProperties === "boolean") {
280
- return recordType("string", getBooleanSubSchemaType(schema.additionalProperties), options);
277
+ return objectTypeToTs(schema, options, depth);
278
+ const additionalProperties = keywordOf(schema, "additionalProperties");
279
+ if (typeof additionalProperties === "boolean") {
280
+ return recordType("string", getBooleanSubSchemaType(additionalProperties), options);
281
281
  }
282
- if (schema.properties && Object.keys(schema.properties).length > 0)
283
- return objectTypeToTs(schema, options);
284
- if (schema.default !== void 0) {
285
- if (typeof schema.default === "string")
282
+ const properties = keywordOf(schema, "properties");
283
+ if (properties && Object.keys(properties).length > 0)
284
+ return objectTypeToTs(schema, options, depth);
285
+ const defaultValue = keywordOf(schema, "default");
286
+ if (defaultValue !== void 0) {
287
+ if (typeof defaultValue === "string")
286
288
  return "string";
287
- if (typeof schema.default === "number")
289
+ if (typeof defaultValue === "number")
288
290
  return "number";
289
- if (typeof schema.default === "boolean")
291
+ if (typeof defaultValue === "boolean")
290
292
  return "boolean";
291
293
  }
292
294
  return void 0;
293
295
  }
294
- if (Array.isArray(schema.type)) {
295
- return unionOf(schema.type.map((type) => singleTypeToTs(schema, type, options)));
296
+ if (Array.isArray(type)) {
297
+ return unionOf(type.map((member) => singleTypeToTs(schema, member, options, depth)));
296
298
  }
297
- return singleTypeToTs(schema, schema.type, options);
299
+ return singleTypeToTs(schema, type, options, depth);
298
300
  };
299
- const singleTypeToTs = (schema, type, options) => {
301
+ const singleTypeToTs = (schema, type, options, depth) => {
300
302
  switch (type) {
301
303
  case "string":
302
304
  return "string";
@@ -308,16 +310,16 @@ const singleTypeToTs = (schema, type, options) => {
308
310
  case "null":
309
311
  return "null";
310
312
  case "array":
311
- return arrayTypeToTs(schema, options);
313
+ return arrayTypeToTs(schema, options, depth);
312
314
  case "object": {
313
- const rendered = objectTypeToTs(schema, options);
314
- return rendered === "object" && Array.isArray(schema.type) ? recordType("string", "unknown", options) : rendered;
315
+ const rendered = objectTypeToTs(schema, options, depth);
316
+ return rendered === "object" && Array.isArray(keywordOf(schema, "type")) ? recordType("string", "unknown", options) : rendered;
315
317
  }
316
318
  default:
317
319
  return "unknown";
318
320
  }
319
321
  };
320
- const getUnbrandedType = (schema, options = {}) => {
322
+ const getUnbrandedType = (schema, options, depth) => {
321
323
  if (typeof schema === "boolean") {
322
324
  return getBooleanSubSchemaType(schema);
323
325
  }
@@ -332,32 +334,33 @@ const getUnbrandedType = (schema, options = {}) => {
332
334
  if (primitive) {
333
335
  return primitive;
334
336
  }
335
- if (schema.$ref) {
336
- return refTypeName(schema.$ref, options);
337
+ const ref = keywordOf(schema, "$ref");
338
+ if (typeof ref === "string" && ref !== "") {
339
+ return refTypeName(ref, options);
337
340
  }
338
- if (schema.$dynamicRef) {
341
+ if (keywordOf(schema, "$dynamicRef")) {
339
342
  return "unknown";
340
343
  }
341
- if (schema.const !== void 0) {
342
- return JSON.stringify(schema.const);
344
+ if (declares(schema, "const")) {
345
+ return JSON.stringify(keywordOf(schema, "const"));
343
346
  }
344
- if (schema.enum && schema.enum.length > 0) {
345
- return unionOf(schema.enum.map((value) => JSON.stringify(value)));
347
+ const enumValues = keywordOf(schema, "enum");
348
+ if (Array.isArray(enumValues) && enumValues.length > 0) {
349
+ return unionOf(enumValues.map((value) => JSON.stringify(value)));
346
350
  }
347
351
  const members = [];
348
- const localType = getLocalShapeType(schema, options);
352
+ const localType = getLocalShapeType(schema, options, depth);
349
353
  if (localType !== void 0)
350
354
  members.push(localType);
351
- if (Array.isArray(schema.allOf)) {
352
- for (const entry of schema.allOf)
353
- members.push(wrapUnion(getTypeScriptType(entry, options)));
355
+ const allOf = keywordOf(schema, "allOf");
356
+ if (Array.isArray(allOf)) {
357
+ for (const entry of allOf)
358
+ members.push(wrapUnion(getTypeScriptType(entry, options, depth + 1)));
354
359
  }
355
- const branches = Array.isArray(schema.oneOf) && schema.oneOf.length > 0 ? schema.oneOf : void 0;
356
- const anyBranches = Array.isArray(schema.anyOf) && schema.anyOf.length > 0 ? schema.anyOf : void 0;
357
- const unionBranches = branches ?? anyBranches;
360
+ const unionBranches = unionBranchesOf(schema);
358
361
  if (unionBranches) {
359
- const union = unionOf(unionBranches.map((branch) => getTypeScriptType(branch, options)));
360
- if (members.length === 0 && !Array.isArray(schema.allOf))
362
+ const union = unionOf(unionBranches.map((branch) => getTypeScriptType(branch, options, depth + 1)));
363
+ if (members.length === 0 && !Array.isArray(allOf))
361
364
  return union;
362
365
  members.push(wrapUnion(union));
363
366
  }
@@ -365,29 +368,40 @@ const getUnbrandedType = (schema, options = {}) => {
365
368
  return "unknown";
366
369
  return intersectionOf(members);
367
370
  };
368
- const getCompositionMembers = (schema, options) => {
371
+ const unionBranchesOf = (schema) => {
372
+ const oneOf = keywordOf(schema, "oneOf");
373
+ if (Array.isArray(oneOf) && oneOf.length > 0)
374
+ return oneOf;
375
+ const anyOf = keywordOf(schema, "anyOf");
376
+ if (Array.isArray(anyOf) && anyOf.length > 0)
377
+ return anyOf;
378
+ return void 0;
379
+ };
380
+ const getCompositionMembers = (schema, options, depth) => {
369
381
  if (!isSchemaObject(schema))
370
382
  return [];
371
383
  const members = [];
372
- if (Array.isArray(schema.allOf)) {
373
- for (const entry of schema.allOf)
374
- members.push(wrapUnion(getTypeScriptType(entry, options)));
384
+ const allOf = keywordOf(schema, "allOf");
385
+ if (Array.isArray(allOf)) {
386
+ for (const entry of allOf)
387
+ members.push(wrapUnion(getTypeScriptType(entry, options, depth + 1)));
375
388
  }
376
- if (typeof schema.$ref === "string") {
377
- members.push(refTypeName(schema.$ref, options));
389
+ const ref = keywordOf(schema, "$ref");
390
+ if (typeof ref === "string") {
391
+ members.push(refTypeName(ref, options));
378
392
  }
379
- const unionBranches = Array.isArray(schema.oneOf) && schema.oneOf.length > 0 ? schema.oneOf : Array.isArray(schema.anyOf) && schema.anyOf.length > 0 ? schema.anyOf : void 0;
393
+ const unionBranches = unionBranchesOf(schema);
380
394
  if (unionBranches) {
381
- members.push(wrapUnion(unionOf(unionBranches.map((branch) => getTypeScriptType(branch, options)))));
395
+ members.push(wrapUnion(unionOf(unionBranches.map((branch) => getTypeScriptType(branch, options, depth + 1)))));
382
396
  }
383
397
  return [...new Set(members)].filter((member) => member !== "unknown");
384
398
  };
385
399
  const generateTypeDefinition = (schema, typeName, options = {}) => {
386
400
  const readonlyPrefix = options.readonly ? "readonly " : "";
387
- if (!isObjectLikeSchema(schema) || isSchemaObject(schema) && Array.isArray(schema.type)) {
388
- const tsType = getTypeScriptType(schema, options);
401
+ if (!isObjectLikeSchema(schema) || isSchemaObject(schema) && Array.isArray(keywordOf(schema, "type"))) {
402
+ const tsType = getTypeScriptType(schema, options, 0);
389
403
  let result = "";
390
- const topLevelComment = isSchemaObject(schema) && typeof schema.description === "string" && schema.description || isSchemaObject(schema) && typeof schema.$comment === "string" && schema.$comment || void 0;
404
+ const topLevelComment = isSchemaObject(schema) ? propertyDescription(schema) : void 0;
391
405
  if (topLevelComment) {
392
406
  result += buildJsDocBlock(typeName, topLevelComment);
393
407
  }
@@ -400,16 +414,19 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
400
414
  const conditionalThenRef = conditionalResult?.thenRef ?? null;
401
415
  let jsDocTitle;
402
416
  let jsDocDescription;
403
- const topLevelComment = isSchemaObject(schema) && typeof schema.description === "string" && schema.description || isSchemaObject(schema) && typeof schema.$comment === "string" && schema.$comment || void 0;
417
+ const topLevelComment = isSchemaObject(schema) ? propertyDescription(schema) : void 0;
404
418
  if (topLevelComment) {
405
419
  jsDocTitle = typeName;
406
420
  jsDocDescription = topLevelComment;
407
421
  }
408
- const hasProperties = normalizedSchema.properties && Object.keys(normalizedSchema.properties).length > 0;
409
- const hasAdditionalProperties = normalizedSchema.additionalProperties && typeof normalizedSchema.additionalProperties === "object";
410
- const hasPatternProperties = normalizedSchema.patternProperties && typeof normalizedSchema.patternProperties === "object" && Object.keys(normalizedSchema.patternProperties).length > 0;
411
- if (!hasProperties && hasPatternProperties && normalizedSchema.patternProperties) {
412
- const record = patternPropertiesRecordType(normalizedSchema.patternProperties, options) ?? "Record<string, unknown>";
422
+ const declaredProperties = keywordMap(normalizedSchema, "properties");
423
+ const additionalProperties = keywordOf(normalizedSchema, "additionalProperties");
424
+ const patternProperties = keywordMap(normalizedSchema, "patternProperties");
425
+ const hasProperties = declaredProperties !== void 0 && Object.keys(declaredProperties).length > 0;
426
+ const hasAdditionalProperties = typeof additionalProperties === "object" && additionalProperties !== null;
427
+ const hasPatternProperties = patternProperties !== void 0 && Object.keys(patternProperties).length > 0;
428
+ if (!hasProperties && hasPatternProperties) {
429
+ const record = patternPropertiesRecordType(patternProperties, options, 0) ?? "Record<string, unknown>";
413
430
  let result2 = "";
414
431
  if (jsDocTitle && jsDocDescription) {
415
432
  result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
@@ -417,8 +434,8 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
417
434
  result2 += `export type ${typeName} = ${record};`;
418
435
  return result2;
419
436
  }
420
- if (!hasProperties && hasAdditionalProperties && normalizedSchema.additionalProperties) {
421
- const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties, options);
437
+ if (!hasProperties && hasAdditionalProperties) {
438
+ const additionalPropType = getTypeScriptType(additionalProperties, options, 0);
422
439
  let result2 = "";
423
440
  if (jsDocTitle && jsDocDescription) {
424
441
  result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
@@ -428,8 +445,9 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
428
445
  };`;
429
446
  return result2;
430
447
  }
431
- const schemaProps = normalizedSchema.properties ?? {};
432
- const requiredSet = new Set(Array.isArray(normalizedSchema.required) ? normalizedSchema.required : []);
448
+ const schemaProps = declaredProperties ?? {};
449
+ const declaredRequired = keywordOf(normalizedSchema, "required");
450
+ const requiredSet = new Set(Array.isArray(declaredRequired) ? declaredRequired : []);
433
451
  const declaredTypes = [];
434
452
  let hasOptionalProperty = false;
435
453
  let properties = "";
@@ -440,19 +458,19 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
440
458
  isFirstProp = false;
441
459
  properties += line;
442
460
  };
443
- for (const key in schemaProps) {
461
+ for (const key of Object.keys(schemaProps)) {
444
462
  const propSchema = schemaProps[key];
445
463
  const isRequired = requiredSet.has(key);
446
464
  const optional = isRequired ? "" : "?";
447
465
  if (!isRequired)
448
466
  hasOptionalProperty = true;
449
- const propType = getTypeScriptType(propSchema, options);
467
+ const propType = getTypeScriptType(propSchema, options, 0);
450
468
  declaredTypes.push(propType);
451
469
  const quotedKey = readonlyPrefix + safeKey(key);
452
470
  const inlineDescription = propertyDescription(propSchema);
453
471
  appendLine(inlineDescription ? buildInlinePropertyComment(inlineDescription) + " " + quotedKey + optional + ": " + propType + ";" : " " + quotedKey + optional + ": " + propType + ";");
454
472
  }
455
- const index = getIndexSignature(normalizedSchema, options);
473
+ const index = getIndexSignature(normalizedSchema, options, 0);
456
474
  if (index) {
457
475
  appendLine(" " + buildIndexSignatureLine(index, declaredTypes, hasOptionalProperty, options) + ";");
458
476
  }
@@ -464,7 +482,7 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
464
482
  if (conditionalThenRef) {
465
483
  typeBody += " & " + refToName(conditionalThenRef, options.typeSuffix);
466
484
  }
467
- for (const intersectionType of getCompositionMembers(schema, options)) {
485
+ for (const intersectionType of getCompositionMembers(schema, options, 0)) {
468
486
  typeBody += " & " + intersectionType;
469
487
  }
470
488
  if (isNullableSchema(schema))
@@ -1,3 +1,4 @@
1
+ import { assignKey } from "./assign-key.js";
1
2
  import { resolveUri, SYNTHETIC_BASE } from "./build-resource-registry.js";
2
3
  import { refToFilename } from "./ref-to-filename.js";
3
4
  const normalizeUri = (uri) => {
@@ -57,9 +58,9 @@ const graftExternalSchemas = (root, schemas) => {
57
58
  const uri = normalizeUri(key);
58
59
  const plan = planFor(resource, uri);
59
60
  const name = claim(refToFilename(uri), uri);
60
- defs[name] = plan.kind === "adopt-uri" ? { $id: uri, ...resource } : resource;
61
+ assignKey(defs, name, plan.kind === "adopt-uri" ? { $id: uri, ...resource } : resource);
61
62
  if (plan.kind === "aliased") {
62
- defs[claim(`${name}-retrieved`, uri)] = { $id: uri, $ref: plan.id };
63
+ assignKey(defs, claim(`${name}-retrieved`, uri), { $id: uri, $ref: plan.id });
63
64
  }
64
65
  }
65
66
  return names.size === 0 ? { document: root, names: EMPTY_NAMES } : { document: { ...root, $defs: defs }, names };
package/dist/has-ref.js CHANGED
@@ -1,5 +1,5 @@
1
1
  const hasRef = (value) => {
2
- return typeof value === "object" && value !== null && !Array.isArray(value) && "$ref" in value && typeof value.$ref === "string";
2
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.hasOwn(value, "$ref") && typeof value.$ref === "string";
3
3
  };
4
4
  export {
5
5
  hasRef
@@ -18,5 +18,12 @@ export declare const MAX_SCHEMA_DEPTH = 2000;
18
18
  * Call this at the top of each recursive step with the *current* depth. The
19
19
  * `walker` label is the traversal that hit the limit, so a report points at the
20
20
  * pass that failed rather than at whichever helper happened to be deepest.
21
+ *
22
+ * `limit` defaults to {@link MAX_SCHEMA_DEPTH}, which assumes the walker spends
23
+ * roughly one stack frame per schema level — true of every document walk here.
24
+ * A pass that spends several frames per level runs the stack out before the
25
+ * shared cap is reached, so the cap never fires and the bare `RangeError` comes
26
+ * back; such a pass passes its own lower limit instead, and the message names
27
+ * the limit that actually applied.
21
28
  */
22
- export declare const assertSchemaDepth: (depth: number, walker: string) => void;
29
+ export declare const assertSchemaDepth: (depth: number, walker: string, limit?: number) => void;
@@ -1,7 +1,7 @@
1
1
  const MAX_SCHEMA_DEPTH = 2e3;
2
- const assertSchemaDepth = (depth, walker) => {
3
- if (depth > MAX_SCHEMA_DEPTH) {
4
- throw new Error(`Schema nesting exceeds ${MAX_SCHEMA_DEPTH} levels while running ${walker}. Flatten the document (or split the deepest subschema into a $defs entry and $ref it) and try again.`);
2
+ const assertSchemaDepth = (depth, walker, limit = MAX_SCHEMA_DEPTH) => {
3
+ if (depth > limit) {
4
+ throw new Error(`Schema nesting exceeds ${limit} levels while running ${walker}. Flatten the document (or split the deepest subschema into a $defs entry and $ref it) and try again.`);
5
5
  }
6
6
  };
7
7
  export {
@@ -1,3 +1,4 @@
1
+ import { readKey } from "./read-key.js";
1
2
  import { isSchemaObject } from "./schema-guards.js";
2
3
  const MJST_EXTENSION_KEY = "x-mjst";
3
4
  const SUPPORTED_INSTANCE_CLASSES = /* @__PURE__ */ new Set(["Date"]);
@@ -7,10 +8,10 @@ const SAFE_BRAND = /^[\w$ -]+$/;
7
8
  const readExtensionString = (schema, field) => {
8
9
  if (!isSchemaObject(schema))
9
10
  return void 0;
10
- const extension = schema[MJST_EXTENSION_KEY];
11
+ const extension = readKey(schema, MJST_EXTENSION_KEY);
11
12
  if (typeof extension !== "object" || extension === null)
12
13
  return void 0;
13
- const value = extension[field];
14
+ const value = readKey(extension, field);
14
15
  return typeof value === "string" ? value : void 0;
15
16
  };
16
17
  const getMjstInstanceOf = (schema) => {