@amritk/helpers 0.13.2 → 0.13.3

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.
@@ -1,501 +1,415 @@
1
- import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive } from './mjst-extension.js';
2
- import { refToName } from './ref-to-name.js';
3
- import { safeKey } from './safe-accessor.js';
4
- import { isObjectSchema, isSchemaObject } from './schema-guards.js';
1
+ import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive } from "./mjst-extension.js";
2
+ import { refToName } from "./ref-to-name.js";
3
+ import { safeKey } from "./safe-accessor.js";
4
+ import { isObjectSchema, isSchemaObject } from "./schema-guards.js";
5
5
  const getConditionalObjectSchema = (schema) => {
6
- if (!isSchemaObject(schema)) {
7
- return null;
6
+ if (!isSchemaObject(schema)) {
7
+ return null;
8
+ }
9
+ if (!("if" in schema) || !("then" in schema)) {
10
+ return null;
11
+ }
12
+ const ifSchema = schema.if;
13
+ const thenSchema = schema.then;
14
+ if (!isSchemaObject(ifSchema) || !isSchemaObject(thenSchema)) {
15
+ return null;
16
+ }
17
+ const ifProperties = ifSchema.properties;
18
+ const thenProperties = thenSchema.properties;
19
+ const hasIfProperties = ifProperties && typeof ifProperties === "object";
20
+ const hasThenProperties = thenProperties && typeof thenProperties === "object";
21
+ if (!hasIfProperties && !hasThenProperties) {
22
+ return null;
23
+ }
24
+ const properties = {
25
+ ...hasIfProperties ? ifProperties : {},
26
+ ...hasThenProperties ? thenProperties : {}
27
+ };
28
+ const required = /* @__PURE__ */ new Set();
29
+ if (Array.isArray(ifSchema.required)) {
30
+ for (const key of ifSchema.required) {
31
+ required.add(key);
8
32
  }
9
- if (!('if' in schema) || !('then' in schema)) {
10
- return null;
33
+ }
34
+ if (hasIfProperties) {
35
+ for (const key in ifProperties) {
36
+ required.add(key);
11
37
  }
12
- const ifSchema = schema.if;
13
- const thenSchema = schema.then;
14
- if (!isSchemaObject(ifSchema) || !isSchemaObject(thenSchema)) {
15
- return null;
38
+ }
39
+ if (Array.isArray(thenSchema.required)) {
40
+ for (const key of thenSchema.required) {
41
+ required.add(key);
16
42
  }
17
- const ifProperties = ifSchema.properties;
18
- const thenProperties = thenSchema.properties;
19
- const hasIfProperties = ifProperties && typeof ifProperties === 'object';
20
- const hasThenProperties = thenProperties && typeof thenProperties === 'object';
21
- if (!hasIfProperties && !hasThenProperties) {
22
- return null;
43
+ }
44
+ if (hasThenProperties) {
45
+ for (const key in thenProperties) {
46
+ required.add(key);
23
47
  }
24
- const properties = {
25
- ...(hasIfProperties ? ifProperties : {}),
26
- ...(hasThenProperties ? thenProperties : {}),
27
- };
28
- const required = new Set();
29
- if (Array.isArray(ifSchema.required)) {
30
- for (const key of ifSchema.required) {
31
- required.add(key);
32
- }
33
- }
34
- if (hasIfProperties) {
35
- for (const key in ifProperties) {
36
- required.add(key);
37
- }
38
- }
39
- if (Array.isArray(thenSchema.required)) {
40
- for (const key of thenSchema.required) {
41
- required.add(key);
42
- }
43
- }
44
- if (hasThenProperties) {
45
- for (const key in thenProperties) {
46
- required.add(key);
47
- }
48
- }
49
- const thenRef = typeof thenSchema.$ref === 'string' ? thenSchema.$ref : null;
50
- return {
51
- schema: {
52
- type: 'object',
53
- properties,
54
- ...(required.size > 0 ? { required: Array.from(required) } : {}),
55
- },
56
- thenRef,
57
- };
48
+ }
49
+ const thenRef = typeof thenSchema.$ref === "string" ? thenSchema.$ref : null;
50
+ return {
51
+ schema: {
52
+ type: "object",
53
+ properties,
54
+ ...required.size > 0 ? { required: Array.from(required) } : {}
55
+ },
56
+ thenRef
57
+ };
58
58
  };
59
59
  const isObjectLikeSchema = (schema) => {
60
- if (!isSchemaObject(schema)) {
61
- return false;
62
- }
63
- if (isObjectSchema(schema)) {
64
- return true;
65
- }
66
- return 'patternProperties' in schema || 'additionalProperties' in schema || ('if' in schema && 'then' in schema);
60
+ if (!isSchemaObject(schema)) {
61
+ return false;
62
+ }
63
+ if (isObjectSchema(schema)) {
64
+ return true;
65
+ }
66
+ return "patternProperties" in schema || "additionalProperties" in schema || "if" in schema && "then" in schema;
67
67
  };
68
68
  const getBooleanSubSchemaType = (schema) => {
69
- return schema ? 'unknown' : 'never';
69
+ return schema ? "unknown" : "never";
70
70
  };
71
- /**
72
- * Renders a possibly multi-line description as JSDoc body lines, prefixing each
73
- * line with `${indent}* `. Blank lines become a bare `${indent}*` so we never
74
- * emit trailing whitespace. Without this, embedded newlines would leave
75
- * continuation lines unprefixed and break the comment block.
76
- */
77
- const renderJsDocBody = (description, indent) => description
78
- .split('\n')
79
- .map((line) => (line.length > 0 ? `${indent}* ${line}\n` : `${indent}*\n`))
80
- .join('');
71
+ const renderJsDocBody = (description, indent) => description.split("\n").map((line) => line.length > 0 ? `${indent}* ${line}
72
+ ` : `${indent}*
73
+ `).join("");
81
74
  const buildJsDocBlock = (title, description, commentUrl) => {
82
- let block = `/**\n`;
83
- block += `* ${title}\n`;
84
- block += `*\n`;
85
- block += renderJsDocBody(description, '');
86
- if (commentUrl?.startsWith('http')) {
87
- block += `* \n`;
88
- block += `* @see {@link ${commentUrl}}\n`;
89
- }
90
- block += `*/\n`;
91
- return block;
75
+ let block = `/**
76
+ `;
77
+ block += `* ${title}
78
+ `;
79
+ block += `*
80
+ `;
81
+ block += renderJsDocBody(description, "");
82
+ if (commentUrl?.startsWith("http")) {
83
+ block += `*
84
+ `;
85
+ block += `* @see {@link ${commentUrl}}
86
+ `;
87
+ }
88
+ block += `*/
89
+ `;
90
+ return block;
92
91
  };
93
- /**
94
- * Builds the inline JSDoc comment that precedes a generated property. A
95
- * single-line description stays compact (` /** text *\/`); a multi-line
96
- * description expands into an asterisk-prefixed block so every line is
97
- * commented. The returned string always ends with a newline, ready for the
98
- * property declaration to follow.
99
- */
100
92
  const buildInlinePropertyComment = (description) => {
101
- if (!description.includes('\n')) {
102
- return ` /** ${description} */\n`;
103
- }
104
- return ` /**\n${renderJsDocBody(description, ' ')} */\n`;
93
+ if (!description.includes("\n")) {
94
+ return ` /** ${description} */
95
+ `;
96
+ }
97
+ return ` /**
98
+ ${renderJsDocBody(description, " ")} */
99
+ `;
105
100
  };
106
- /**
107
- * Converts a JSON Schema type to its TypeScript equivalent, applying any
108
- * `x-mjst` brand. Branding is type-level only, so we compute the underlying
109
- * type and intersect it with a unique brand marker. This is the recursion entry
110
- * point, so branded nested fields are wrapped too.
111
- */
112
101
  const getTypeScriptType = (schema, options = {}) => {
113
- const base = getUnbrandedType(schema, options);
114
- const brand = getMjstBrand(schema);
115
- return brand ? `(${base} & { readonly __brand: '${brand}' })` : base;
102
+ const base = getUnbrandedType(schema, options);
103
+ const brand = getMjstBrand(schema);
104
+ return brand ? `(${base} & { readonly __brand: '${brand}' })` : base;
116
105
  };
117
- /** Wraps a `Record<...>` in `Readonly<...>` when readonly output is requested. */
118
106
  const recordType = (keyType, valueType, options) => options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`;
119
- /**
120
- * Builds the `Record<…>` type for a schema's `patternProperties`. Every pattern's
121
- * value type is unioned (deduplicated) rather than only the first being used, so
122
- * `{ '^a': string-schema, '^b': number-schema }` becomes `Record<string, string |
123
- * number>` instead of silently dropping the second pattern. The template-literal
124
- * `` `x-${string}` `` key is kept only when the sole pattern is the `^x-` vendor
125
- * convention. Returns `undefined` when there are no usable patterns.
126
- */
127
107
  const patternPropertiesRecordType = (patternProperties, options) => {
128
- const entries = Object.entries(patternProperties);
129
- if (entries.length === 0)
130
- return undefined;
131
- const seen = new Set();
132
- const valueTypes = [];
133
- for (const [, value] of entries) {
134
- const valueType = typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options);
135
- if (!seen.has(valueType)) {
136
- seen.add(valueType);
137
- valueTypes.push(valueType);
138
- }
108
+ const entries = Object.entries(patternProperties);
109
+ if (entries.length === 0)
110
+ return void 0;
111
+ const seen = /* @__PURE__ */ new Set();
112
+ const valueTypes = [];
113
+ for (const [, value] of entries) {
114
+ const valueType2 = typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options);
115
+ if (!seen.has(valueType2)) {
116
+ seen.add(valueType2);
117
+ valueTypes.push(valueType2);
139
118
  }
140
- if (valueTypes.length === 0)
141
- return undefined;
142
- const valueType = valueTypes.join(' | ');
143
- // The `^x-` vendor-extension convention maps to a template-literal key, but only
144
- // when it is the single pattern (a union of key patterns can't be expressed).
145
- const keyType = entries.length === 1 && entries[0]?.[0] === '^x-' ? '`x-${string}`' : 'string';
146
- return recordType(keyType, valueType, options);
119
+ }
120
+ if (valueTypes.length === 0)
121
+ return void 0;
122
+ const valueType = valueTypes.join(" | ");
123
+ const keyType = entries.length === 1 && entries[0]?.[0] === "^x-" ? "`x-${string}`" : "string";
124
+ return recordType(keyType, valueType, options);
147
125
  };
148
- /**
149
- * Converts a JSON Schema type to its TypeScript equivalent, ignoring any brand.
150
- * Recursively handles nested objects and arrays.
151
- */
152
126
  const getUnbrandedType = (schema, options = {}) => {
153
- // Boolean schema: `true` means any value is valid (unknown), `false` means no value is valid (never)
154
- if (typeof schema === 'boolean') {
155
- return getBooleanSubSchemaType(schema);
127
+ if (typeof schema === "boolean") {
128
+ return getBooleanSubSchemaType(schema);
129
+ }
130
+ if (typeof schema !== "object" || schema === null) {
131
+ return "unknown";
132
+ }
133
+ const instanceOf = getMjstInstanceOf(schema);
134
+ if (instanceOf) {
135
+ return instanceOf;
136
+ }
137
+ const primitive = getMjstPrimitive(schema);
138
+ if (primitive) {
139
+ return primitive;
140
+ }
141
+ if (schema.$ref) {
142
+ if (!schema.$ref.startsWith("#")) {
143
+ return "unknown";
156
144
  }
157
- // Check if schema is an object (not a boolean schema)
158
- if (typeof schema !== 'object' || schema === null) {
159
- return 'unknown';
145
+ return refToName(schema.$ref, options.typeSuffix);
146
+ }
147
+ if (schema.$dynamicRef) {
148
+ if (schema.$dynamicRef === "#meta") {
149
+ return `Schema${options.typeSuffix ?? ""}`;
160
150
  }
161
- // An x-mjst instanceOf hint means the value is a runtime class (e.g. Date)
162
- // that JSON Schema cannot describe — emit the class name as the type directly.
163
- const instanceOf = getMjstInstanceOf(schema);
164
- if (instanceOf) {
165
- return instanceOf;
151
+ return refToName(schema.$dynamicRef, options.typeSuffix);
152
+ }
153
+ if (schema.const !== void 0) {
154
+ return JSON.stringify(schema.const);
155
+ }
156
+ if (schema.enum && schema.enum.length > 0) {
157
+ if (schema.enum.length === 1) {
158
+ return JSON.stringify(schema.enum[0]);
166
159
  }
167
- // An x-mjst primitive hint (e.g. bigint) names a non-JSON primitive — emit it
168
- // directly as the TypeScript type.
169
- const primitive = getMjstPrimitive(schema);
170
- if (primitive) {
171
- return primitive;
160
+ let enumUnion = JSON.stringify(schema.enum[0]);
161
+ for (let i = 1; i < schema.enum.length; i++) {
162
+ enumUnion += " | " + JSON.stringify(schema.enum[i]);
172
163
  }
173
- // Handle $ref
174
- if (schema.$ref) {
175
- // External refs (e.g. http://json-schema.org/...) cannot be resolved locally — treat as unknown
176
- if (!schema.$ref.startsWith('#')) {
177
- return 'unknown';
178
- }
179
- return refToName(schema.$ref, options.typeSuffix);
164
+ return enumUnion;
165
+ }
166
+ if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
167
+ let oneOfUnion = getTypeScriptType(schema.oneOf[0], options);
168
+ for (let i = 1; i < schema.oneOf.length; i++) {
169
+ oneOfUnion += " | " + getTypeScriptType(schema.oneOf[i], options);
180
170
  }
181
- // Handle $dynamicRef (used for recursive schemas)
182
- if (schema.$dynamicRef) {
183
- // For #meta, this refers to the Schema type itself (JSON Schema 2020-12 $dynamicAnchor pattern)
184
- if (schema.$dynamicRef === '#meta') {
185
- return `Schema${options.typeSuffix ?? ''}`;
186
- }
187
- return refToName(schema.$dynamicRef, options.typeSuffix);
171
+ return oneOfUnion;
172
+ }
173
+ if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
174
+ let anyOfUnion = getTypeScriptType(schema.anyOf[0], options);
175
+ for (let i = 1; i < schema.anyOf.length; i++) {
176
+ anyOfUnion += " | " + getTypeScriptType(schema.anyOf[i], options);
188
177
  }
189
- // Handle const - literal type
190
- if (schema.const !== undefined) {
191
- return JSON.stringify(schema.const);
178
+ return anyOfUnion;
179
+ }
180
+ if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length > 0) {
181
+ let intersectionTypes = getTypeScriptType(schema.allOf[0], options);
182
+ for (let i = 1; i < schema.allOf.length; i++) {
183
+ intersectionTypes += " & " + getTypeScriptType(schema.allOf[i], options);
192
184
  }
193
- // Handle enum - union of literal types
194
- if (schema.enum && schema.enum.length > 0) {
195
- if (schema.enum.length === 1) {
196
- return JSON.stringify(schema.enum[0]);
197
- }
198
- let enumUnion = JSON.stringify(schema.enum[0]);
199
- for (let i = 1; i < schema.enum.length; i++) {
200
- enumUnion += ' | ' + JSON.stringify(schema.enum[i]);
201
- }
202
- return enumUnion;
203
- }
204
- // Handle union types (oneOf, anyOf) - check this before returning unknown
205
- if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
206
- // schema.oneOf[0] is safe: we guard with .length > 0 above
207
- let oneOfUnion = getTypeScriptType(schema.oneOf[0], options);
208
- for (let i = 1; i < schema.oneOf.length; i++) {
209
- oneOfUnion += ' | ' + getTypeScriptType(schema.oneOf[i], options);
210
- }
211
- return oneOfUnion;
212
- }
213
- if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
214
- // schema.anyOf[0] is safe: we guard with .length > 0 above
215
- let anyOfUnion = getTypeScriptType(schema.anyOf[0], options);
216
- for (let i = 1; i < schema.anyOf.length; i++) {
217
- anyOfUnion += ' | ' + getTypeScriptType(schema.anyOf[i], options);
218
- }
219
- return anyOfUnion;
220
- }
221
- // Handle allOf (intersection types)
222
- if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length > 0) {
223
- // schema.allOf[0] is safe: we guard with .length > 0 above
224
- let intersectionTypes = getTypeScriptType(schema.allOf[0], options);
225
- for (let i = 1; i < schema.allOf.length; i++) {
226
- intersectionTypes += ' & ' + getTypeScriptType(schema.allOf[i], options);
227
- }
228
- return intersectionTypes;
185
+ return intersectionTypes;
186
+ }
187
+ const conditionalResult = getConditionalObjectSchema(schema);
188
+ if (conditionalResult) {
189
+ const baseType = getTypeScriptType(conditionalResult.schema, options);
190
+ if (conditionalResult.thenRef) {
191
+ return `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}`;
229
192
  }
230
- // Handle object-like conditional schemas that use if/then without declaring type
231
- const conditionalResult = getConditionalObjectSchema(schema);
232
- if (conditionalResult) {
233
- const baseType = getTypeScriptType(conditionalResult.schema, options);
234
- if (conditionalResult.thenRef) {
235
- return `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}`;
236
- }
237
- return baseType;
193
+ return baseType;
194
+ }
195
+ if (!schema.type) {
196
+ if (schema.additionalProperties !== void 0) {
197
+ if (typeof schema.additionalProperties === "boolean") {
198
+ return recordType("string", getBooleanSubSchemaType(schema.additionalProperties), options);
199
+ }
200
+ return recordType("string", getTypeScriptType(schema.additionalProperties, options), options);
238
201
  }
239
- // No type so we return unknown
240
- if (!schema.type) {
241
- if (schema.additionalProperties !== undefined) {
242
- if (typeof schema.additionalProperties === 'boolean') {
243
- return recordType('string', getBooleanSubSchemaType(schema.additionalProperties), options);
244
- }
245
- return recordType('string', getTypeScriptType(schema.additionalProperties, options), options);
246
- }
247
- if (schema.patternProperties && typeof schema.patternProperties === 'object') {
248
- const record = patternPropertiesRecordType(schema.patternProperties, options);
249
- if (record !== undefined)
250
- return record;
251
- }
252
- if (schema.default !== undefined) {
253
- if (typeof schema.default === 'string') {
254
- return 'string';
255
- }
256
- if (typeof schema.default === 'number') {
257
- return 'number';
258
- }
259
- if (typeof schema.default === 'boolean') {
260
- return 'boolean';
261
- }
262
- }
263
- return 'unknown';
202
+ if (schema.patternProperties && typeof schema.patternProperties === "object") {
203
+ const record = patternPropertiesRecordType(schema.patternProperties, options);
204
+ if (record !== void 0)
205
+ return record;
264
206
  }
265
- // Handle type as an array (union of types)
266
- if (Array.isArray(schema.type)) {
267
- const mapType = (t) => {
268
- switch (t) {
269
- case 'string':
270
- return 'string';
271
- case 'number':
272
- case 'integer':
273
- return 'number';
274
- case 'boolean':
275
- return 'boolean';
276
- case 'null':
277
- return 'null';
278
- case 'array':
279
- return 'unknown[]';
280
- case 'object':
281
- return 'Record<string, unknown>';
282
- default:
283
- return 'unknown';
284
- }
285
- };
286
- let typeUnion = mapType(schema.type[0]);
287
- for (let i = 1; i < schema.type.length; i++) {
288
- typeUnion += ' | ' + mapType(schema.type[i]);
289
- }
290
- return typeUnion;
207
+ if (schema.default !== void 0) {
208
+ if (typeof schema.default === "string") {
209
+ return "string";
210
+ }
211
+ if (typeof schema.default === "number") {
212
+ return "number";
213
+ }
214
+ if (typeof schema.default === "boolean") {
215
+ return "boolean";
216
+ }
291
217
  }
292
- switch (schema.type) {
293
- // String
294
- case 'string':
295
- return 'string';
296
- // Number
297
- case 'number':
298
- case 'integer':
299
- return 'number';
300
- // Boolean
301
- case 'boolean':
302
- return 'boolean';
303
- // Array
304
- case 'array':
305
- if (schema.items) {
306
- const itemType = getTypeScriptType(schema.items, options);
307
- // Wrap union types in parentheses so `(A | B)[]` is not misread as `A | B[]`
308
- const wrappedItemType = itemType.includes(' | ') ? `(${itemType})` : itemType;
309
- return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`;
310
- }
311
- return options.readonly ? 'readonly unknown[]' : 'unknown[]';
312
- // Object
313
- case 'object':
314
- if (schema.properties) {
315
- const readonlyPrefix = options.readonly ? 'readonly ' : '';
316
- // Build the required-key set once instead of an O(required) `includes`
317
- // per property (O(properties × required) for a wide object).
318
- const requiredSet = new Set(Array.isArray(schema.required) ? schema.required : []);
319
- const hasDescriptions = Object.values(schema.properties).some((p) => isSchemaObject(p) && (typeof p.description === 'string' || typeof p.$comment === 'string'));
320
- if (hasDescriptions) {
321
- let properties = '';
322
- let first = true;
323
- for (const key in schema.properties) {
324
- // schema.properties[key] is safe: key comes from iterating schema.properties
325
- const propSchema = schema.properties[key];
326
- const isRequired = requiredSet.has(key);
327
- const optional = isRequired ? '' : '?';
328
- const propType = getTypeScriptType(propSchema, options);
329
- const inlineDescription = isSchemaObject(propSchema) && typeof propSchema.description === 'string'
330
- ? propSchema.description
331
- : isSchemaObject(propSchema) && typeof propSchema.$comment === 'string'
332
- ? propSchema.$comment
333
- : undefined;
334
- if (!first)
335
- properties += '\n';
336
- first = false;
337
- if (inlineDescription) {
338
- properties +=
339
- buildInlinePropertyComment(inlineDescription) +
340
- ' ' +
341
- readonlyPrefix +
342
- safeKey(key) +
343
- optional +
344
- ': ' +
345
- propType +
346
- ';';
347
- }
348
- else {
349
- properties += ' ' + readonlyPrefix + safeKey(key) + optional + ': ' + propType + ';';
350
- }
351
- }
352
- return '{\n' + properties + '\n}';
353
- }
354
- let properties = '';
355
- let first = true;
356
- for (const key in schema.properties) {
357
- // schema.properties[key] is safe: key comes from iterating schema.properties
358
- const propSchema = schema.properties[key];
359
- const isRequired = requiredSet.has(key);
360
- const optional = isRequired ? '' : '?';
361
- const propType = getTypeScriptType(propSchema, options);
362
- if (!first)
363
- properties += '; ';
364
- properties += readonlyPrefix + safeKey(key) + optional + ': ' + propType;
365
- first = false;
366
- }
367
- return '{ ' + properties + ' }';
368
- }
369
- // Handle additionalProperties with $ref or $dynamicRef
370
- if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
371
- const additionalPropType = getTypeScriptType(schema.additionalProperties, options);
372
- return recordType('string', additionalPropType, options);
373
- }
374
- // Handle patternProperties as a Record type
375
- if (schema.patternProperties && typeof schema.patternProperties === 'object') {
376
- const record = patternPropertiesRecordType(schema.patternProperties, options);
377
- if (record !== undefined)
378
- return record;
379
- }
380
- return 'object';
381
- // Default to unknown
218
+ return "unknown";
219
+ }
220
+ if (Array.isArray(schema.type)) {
221
+ const mapType = (t) => {
222
+ switch (t) {
223
+ case "string":
224
+ return "string";
225
+ case "number":
226
+ case "integer":
227
+ return "number";
228
+ case "boolean":
229
+ return "boolean";
230
+ case "null":
231
+ return "null";
232
+ case "array":
233
+ return "unknown[]";
234
+ case "object":
235
+ return "Record<string, unknown>";
382
236
  default:
383
- return 'unknown';
384
- }
385
- };
386
- /**
387
- * Generates a TypeScript type definition from a JSON Schema.
388
- * Handles required vs optional properties based on the schema's required array.
389
- * Uses $comment as inline JSDoc description when present.
390
- */
391
- export const generateTypeDefinition = (schema, typeName, options = {}) => {
392
- const readonlyPrefix = options.readonly ? 'readonly ' : '';
393
- // Handle non-object schemas first
394
- if (!isObjectLikeSchema(schema)) {
395
- const tsType = getTypeScriptType(schema, options);
396
- let result = '';
397
- const topLevelComment = (isSchemaObject(schema) && typeof schema.description === 'string' && schema.description) ||
398
- (isSchemaObject(schema) && typeof schema.$comment === 'string' && schema.$comment) ||
399
- undefined;
400
- if (topLevelComment) {
401
- result += buildJsDocBlock(typeName, topLevelComment);
402
- }
403
- result += `export type ${typeName} = ${tsType};`;
404
- return result;
237
+ return "unknown";
238
+ }
239
+ };
240
+ let typeUnion = mapType(schema.type[0]);
241
+ for (let i = 1; i < schema.type.length; i++) {
242
+ typeUnion += " | " + mapType(schema.type[i]);
405
243
  }
406
- if (isObjectLikeSchema(schema)) {
407
- const conditionalResult = getConditionalObjectSchema(schema);
408
- const normalizedSchema = conditionalResult?.schema ?? schema;
409
- const conditionalThenRef = conditionalResult?.thenRef ?? null;
410
- let jsDocTitle;
411
- let jsDocDescription;
412
- const topLevelComment = (isSchemaObject(schema) && typeof schema.description === 'string' && schema.description) ||
413
- (isSchemaObject(schema) && typeof schema.$comment === 'string' && schema.$comment) ||
414
- undefined;
415
- if (topLevelComment) {
416
- jsDocTitle = typeName;
417
- jsDocDescription = topLevelComment;
418
- }
419
- const hasProperties = normalizedSchema.properties && Object.keys(normalizedSchema.properties).length > 0;
420
- const hasAdditionalProperties = normalizedSchema.additionalProperties && typeof normalizedSchema.additionalProperties === 'object';
421
- const hasPatternProperties = normalizedSchema.patternProperties &&
422
- typeof normalizedSchema.patternProperties === 'object' &&
423
- Object.keys(normalizedSchema.patternProperties).length > 0;
424
- // Handle objects with only patternProperties (no fixed properties)
425
- if (!hasProperties && hasPatternProperties && normalizedSchema.patternProperties) {
426
- const record = patternPropertiesRecordType(normalizedSchema.patternProperties, options) ?? 'Record<string, unknown>';
427
- let result = '';
428
- if (jsDocTitle && jsDocDescription) {
429
- result += buildJsDocBlock(jsDocTitle, jsDocDescription);
430
- }
431
- result += `export type ${typeName} = ${record};`;
432
- return result;
433
- }
434
- // Handle objects with only additionalProperties (no fixed properties)
435
- if (!hasProperties && hasAdditionalProperties && normalizedSchema.additionalProperties) {
436
- const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties, options);
437
- let result = '';
438
- if (jsDocTitle && jsDocDescription) {
439
- result += buildJsDocBlock(jsDocTitle, jsDocDescription);
440
- }
441
- result += `export type ${typeName} = {\n ${readonlyPrefix}[key: string]: ${additionalPropType};\n};`;
442
- return result;
443
- }
444
- const schemaProps = normalizedSchema.properties ?? {};
445
- const requiredSet = new Set(Array.isArray(normalizedSchema.required) ? normalizedSchema.required : []);
446
- let properties = '';
447
- let isFirstProp = true;
448
- for (const key in schemaProps) {
449
- // schemaProps[key] is safe: key comes from iterating schemaProps
450
- const propSchema = schemaProps[key];
244
+ return typeUnion;
245
+ }
246
+ switch (schema.type) {
247
+ // String
248
+ case "string":
249
+ return "string";
250
+ // Number
251
+ case "number":
252
+ case "integer":
253
+ return "number";
254
+ // Boolean
255
+ case "boolean":
256
+ return "boolean";
257
+ // Array
258
+ case "array":
259
+ if (schema.items) {
260
+ const itemType = getTypeScriptType(schema.items, options);
261
+ const wrappedItemType = itemType.includes(" | ") ? `(${itemType})` : itemType;
262
+ return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`;
263
+ }
264
+ return options.readonly ? "readonly unknown[]" : "unknown[]";
265
+ // Object
266
+ case "object":
267
+ if (schema.properties) {
268
+ const readonlyPrefix = options.readonly ? "readonly " : "";
269
+ const requiredSet = new Set(Array.isArray(schema.required) ? schema.required : []);
270
+ const hasDescriptions = Object.values(schema.properties).some((p) => isSchemaObject(p) && (typeof p.description === "string" || typeof p.$comment === "string"));
271
+ if (hasDescriptions) {
272
+ let properties2 = "";
273
+ let first2 = true;
274
+ for (const key in schema.properties) {
275
+ const propSchema = schema.properties[key];
451
276
  const isRequired = requiredSet.has(key);
452
- const optional = isRequired ? '' : '?';
277
+ const optional = isRequired ? "" : "?";
453
278
  const propType = getTypeScriptType(propSchema, options);
454
- const quotedKey = readonlyPrefix + safeKey(key);
455
- if (!isFirstProp)
456
- properties += '\n';
457
- isFirstProp = false;
458
- // Add JSDoc comment from $comment or description if available
459
- const inlineDescription = isSchemaObject(propSchema) && typeof propSchema.description === 'string'
460
- ? propSchema.description
461
- : isSchemaObject(propSchema) && typeof propSchema.$comment === 'string'
462
- ? propSchema.$comment
463
- : undefined;
279
+ const inlineDescription = isSchemaObject(propSchema) && typeof propSchema.description === "string" ? propSchema.description : isSchemaObject(propSchema) && typeof propSchema.$comment === "string" ? propSchema.$comment : void 0;
280
+ if (!first2)
281
+ properties2 += "\n";
282
+ first2 = false;
464
283
  if (inlineDescription) {
465
- properties +=
466
- buildInlinePropertyComment(inlineDescription) + ' ' + quotedKey + optional + ': ' + propType + ';';
467
- }
468
- else {
469
- properties += ' ' + quotedKey + optional + ': ' + propType + ';';
284
+ properties2 += buildInlinePropertyComment(inlineDescription) + " " + readonlyPrefix + safeKey(key) + optional + ": " + propType + ";";
285
+ } else {
286
+ properties2 += " " + readonlyPrefix + safeKey(key) + optional + ": " + propType + ";";
470
287
  }
288
+ }
289
+ return "{\n" + properties2 + "\n}";
471
290
  }
472
- // Collect allOf $ref intersections
473
- const allOfIntersections = [];
474
- if (isSchemaObject(schema) && Array.isArray(schema.allOf)) {
475
- for (const entry of schema.allOf) {
476
- if (isSchemaObject(entry) && entry.$ref) {
477
- allOfIntersections.push(refToName(entry.$ref, options.typeSuffix));
478
- }
479
- }
480
- }
481
- // JSON Schema 2019-09+ allows $ref as a sibling to other keywords.
482
- // Treat it as an additional intersection type (e.g. for specification-extensions).
483
- if (isSchemaObject(schema) && typeof schema.$ref === 'string' && schema.$ref.startsWith('#')) {
484
- allOfIntersections.push(refToName(schema.$ref, options.typeSuffix));
485
- }
486
- let result = '';
487
- if (jsDocTitle && jsDocDescription) {
488
- result += buildJsDocBlock(jsDocTitle, jsDocDescription);
489
- }
490
- let typeBody = '{\n' + properties + '\n}';
491
- if (conditionalThenRef) {
492
- typeBody += ' & ' + refToName(conditionalThenRef, options.typeSuffix);
291
+ let properties = "";
292
+ let first = true;
293
+ for (const key in schema.properties) {
294
+ const propSchema = schema.properties[key];
295
+ const isRequired = requiredSet.has(key);
296
+ const optional = isRequired ? "" : "?";
297
+ const propType = getTypeScriptType(propSchema, options);
298
+ if (!first)
299
+ properties += "; ";
300
+ properties += readonlyPrefix + safeKey(key) + optional + ": " + propType;
301
+ first = false;
493
302
  }
494
- for (const intersectionType of allOfIntersections) {
495
- typeBody += ' & ' + intersectionType;
303
+ return "{ " + properties + " }";
304
+ }
305
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
306
+ const additionalPropType = getTypeScriptType(schema.additionalProperties, options);
307
+ return recordType("string", additionalPropType, options);
308
+ }
309
+ if (schema.patternProperties && typeof schema.patternProperties === "object") {
310
+ const record = patternPropertiesRecordType(schema.patternProperties, options);
311
+ if (record !== void 0)
312
+ return record;
313
+ }
314
+ return "object";
315
+ // Default to unknown
316
+ default:
317
+ return "unknown";
318
+ }
319
+ };
320
+ const generateTypeDefinition = (schema, typeName, options = {}) => {
321
+ const readonlyPrefix = options.readonly ? "readonly " : "";
322
+ if (!isObjectLikeSchema(schema)) {
323
+ const tsType = getTypeScriptType(schema, options);
324
+ let result = "";
325
+ const topLevelComment = isSchemaObject(schema) && typeof schema.description === "string" && schema.description || isSchemaObject(schema) && typeof schema.$comment === "string" && schema.$comment || void 0;
326
+ if (topLevelComment) {
327
+ result += buildJsDocBlock(typeName, topLevelComment);
328
+ }
329
+ result += `export type ${typeName} = ${tsType};`;
330
+ return result;
331
+ }
332
+ if (isObjectLikeSchema(schema)) {
333
+ const conditionalResult = getConditionalObjectSchema(schema);
334
+ const normalizedSchema = conditionalResult?.schema ?? schema;
335
+ const conditionalThenRef = conditionalResult?.thenRef ?? null;
336
+ let jsDocTitle;
337
+ let jsDocDescription;
338
+ const topLevelComment = isSchemaObject(schema) && typeof schema.description === "string" && schema.description || isSchemaObject(schema) && typeof schema.$comment === "string" && schema.$comment || void 0;
339
+ if (topLevelComment) {
340
+ jsDocTitle = typeName;
341
+ jsDocDescription = topLevelComment;
342
+ }
343
+ const hasProperties = normalizedSchema.properties && Object.keys(normalizedSchema.properties).length > 0;
344
+ const hasAdditionalProperties = normalizedSchema.additionalProperties && typeof normalizedSchema.additionalProperties === "object";
345
+ const hasPatternProperties = normalizedSchema.patternProperties && typeof normalizedSchema.patternProperties === "object" && Object.keys(normalizedSchema.patternProperties).length > 0;
346
+ if (!hasProperties && hasPatternProperties && normalizedSchema.patternProperties) {
347
+ const record = patternPropertiesRecordType(normalizedSchema.patternProperties, options) ?? "Record<string, unknown>";
348
+ let result2 = "";
349
+ if (jsDocTitle && jsDocDescription) {
350
+ result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
351
+ }
352
+ result2 += `export type ${typeName} = ${record};`;
353
+ return result2;
354
+ }
355
+ if (!hasProperties && hasAdditionalProperties && normalizedSchema.additionalProperties) {
356
+ const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties, options);
357
+ let result2 = "";
358
+ if (jsDocTitle && jsDocDescription) {
359
+ result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
360
+ }
361
+ result2 += `export type ${typeName} = {
362
+ ${readonlyPrefix}[key: string]: ${additionalPropType};
363
+ };`;
364
+ return result2;
365
+ }
366
+ const schemaProps = normalizedSchema.properties ?? {};
367
+ const requiredSet = new Set(Array.isArray(normalizedSchema.required) ? normalizedSchema.required : []);
368
+ let properties = "";
369
+ let isFirstProp = true;
370
+ for (const key in schemaProps) {
371
+ const propSchema = schemaProps[key];
372
+ const isRequired = requiredSet.has(key);
373
+ const optional = isRequired ? "" : "?";
374
+ const propType = getTypeScriptType(propSchema, options);
375
+ const quotedKey = readonlyPrefix + safeKey(key);
376
+ if (!isFirstProp)
377
+ properties += "\n";
378
+ isFirstProp = false;
379
+ const inlineDescription = isSchemaObject(propSchema) && typeof propSchema.description === "string" ? propSchema.description : isSchemaObject(propSchema) && typeof propSchema.$comment === "string" ? propSchema.$comment : void 0;
380
+ if (inlineDescription) {
381
+ properties += buildInlinePropertyComment(inlineDescription) + " " + quotedKey + optional + ": " + propType + ";";
382
+ } else {
383
+ properties += " " + quotedKey + optional + ": " + propType + ";";
384
+ }
385
+ }
386
+ const allOfIntersections = [];
387
+ if (isSchemaObject(schema) && Array.isArray(schema.allOf)) {
388
+ for (const entry of schema.allOf) {
389
+ if (isSchemaObject(entry) && entry.$ref) {
390
+ allOfIntersections.push(refToName(entry.$ref, options.typeSuffix));
496
391
  }
497
- result += 'export type ' + typeName + ' = ' + typeBody + ';';
498
- return result;
392
+ }
393
+ }
394
+ if (isSchemaObject(schema) && typeof schema.$ref === "string" && schema.$ref.startsWith("#")) {
395
+ allOfIntersections.push(refToName(schema.$ref, options.typeSuffix));
499
396
  }
500
- return 'export type ' + typeName + ' = unknown;';
397
+ let result = "";
398
+ if (jsDocTitle && jsDocDescription) {
399
+ result += buildJsDocBlock(jsDocTitle, jsDocDescription);
400
+ }
401
+ let typeBody = "{\n" + properties + "\n}";
402
+ if (conditionalThenRef) {
403
+ typeBody += " & " + refToName(conditionalThenRef, options.typeSuffix);
404
+ }
405
+ for (const intersectionType of allOfIntersections) {
406
+ typeBody += " & " + intersectionType;
407
+ }
408
+ result += "export type " + typeName + " = " + typeBody + ";";
409
+ return result;
410
+ }
411
+ return "export type " + typeName + " = unknown;";
412
+ };
413
+ export {
414
+ generateTypeDefinition
501
415
  };