@amritk/helpers 0.7.1 → 0.9.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 (83) hide show
  1. package/dist/build-dynamic-ref-map.d.ts +0 -1
  2. package/dist/derive-root-type-name.d.ts +0 -1
  3. package/dist/escape-regex-pattern.d.ts +16 -0
  4. package/dist/escape-regex-pattern.js +20 -0
  5. package/dist/extract-dynamic-anchor-defs.d.ts +0 -1
  6. package/dist/extract-refs.d.ts +0 -1
  7. package/dist/generate-index-barrel.d.ts +0 -1
  8. package/dist/generate-type-definition.d.ts +0 -1
  9. package/dist/has-ref.d.ts +0 -1
  10. package/dist/is-object.d.ts +0 -1
  11. package/dist/mjst-extension.d.ts +0 -1
  12. package/dist/parse-documentation.d.ts +0 -1
  13. package/dist/ref-to-filename.d.ts +0 -1
  14. package/dist/ref-to-name.d.ts +0 -1
  15. package/dist/resolve-dynamic-refs.d.ts +4 -4
  16. package/dist/resolve-dynamic-refs.js +10 -4
  17. package/dist/resolve-ref.d.ts +0 -1
  18. package/dist/safe-accessor.d.ts +0 -1
  19. package/dist/schema-guards.d.ts +16 -1
  20. package/dist/schema-guards.js +29 -0
  21. package/dist/upgrade-draft07-schema.d.ts +0 -1
  22. package/dist/validate-array.d.ts +0 -1
  23. package/dist/validate-record.d.ts +0 -1
  24. package/dist/walk-ref-graph.d.ts +0 -1
  25. package/package.json +2 -4
  26. package/dist/build-dynamic-ref-map.d.ts.map +0 -1
  27. package/dist/derive-root-type-name.d.ts.map +0 -1
  28. package/dist/extract-dynamic-anchor-defs.d.ts.map +0 -1
  29. package/dist/extract-refs.d.ts.map +0 -1
  30. package/dist/generate-index-barrel.d.ts.map +0 -1
  31. package/dist/generate-type-definition.d.ts.map +0 -1
  32. package/dist/has-ref.d.ts.map +0 -1
  33. package/dist/is-object.d.ts.map +0 -1
  34. package/dist/mjst-extension.d.ts.map +0 -1
  35. package/dist/parse-documentation.d.ts.map +0 -1
  36. package/dist/ref-to-filename.d.ts.map +0 -1
  37. package/dist/ref-to-name.d.ts.map +0 -1
  38. package/dist/resolve-dynamic-refs.d.ts.map +0 -1
  39. package/dist/resolve-ref.d.ts.map +0 -1
  40. package/dist/safe-accessor.d.ts.map +0 -1
  41. package/dist/schema-guards.d.ts.map +0 -1
  42. package/dist/upgrade-draft07-schema.d.ts.map +0 -1
  43. package/dist/validate-array.d.ts.map +0 -1
  44. package/dist/validate-record.d.ts.map +0 -1
  45. package/dist/walk-ref-graph.d.ts.map +0 -1
  46. package/src/build-dynamic-ref-map.test.ts +0 -65
  47. package/src/build-dynamic-ref-map.ts +0 -42
  48. package/src/derive-root-type-name.test.ts +0 -42
  49. package/src/derive-root-type-name.ts +0 -42
  50. package/src/extract-dynamic-anchor-defs.test.ts +0 -29
  51. package/src/extract-dynamic-anchor-defs.ts +0 -33
  52. package/src/extract-refs.test.ts +0 -183
  53. package/src/extract-refs.ts +0 -73
  54. package/src/generate-index-barrel.test.ts +0 -41
  55. package/src/generate-index-barrel.ts +0 -62
  56. package/src/generate-type-definition.test.ts +0 -1386
  57. package/src/generate-type-definition.ts +0 -580
  58. package/src/has-ref.ts +0 -10
  59. package/src/is-object.test.ts +0 -65
  60. package/src/is-object.ts +0 -15
  61. package/src/mjst-extension.test.ts +0 -59
  62. package/src/mjst-extension.ts +0 -81
  63. package/src/parse-documentation.test.ts +0 -313
  64. package/src/parse-documentation.ts +0 -173
  65. package/src/ref-to-filename.test.ts +0 -64
  66. package/src/ref-to-filename.ts +0 -116
  67. package/src/ref-to-name.test.ts +0 -57
  68. package/src/ref-to-name.ts +0 -42
  69. package/src/resolve-dynamic-refs.test.ts +0 -94
  70. package/src/resolve-dynamic-refs.ts +0 -48
  71. package/src/resolve-ref.test.ts +0 -186
  72. package/src/resolve-ref.ts +0 -82
  73. package/src/safe-accessor.test.ts +0 -41
  74. package/src/safe-accessor.ts +0 -48
  75. package/src/schema-guards.test.ts +0 -406
  76. package/src/schema-guards.ts +0 -160
  77. package/src/upgrade-draft07-schema.ts +0 -179
  78. package/src/validate-array.test.ts +0 -52
  79. package/src/validate-array.ts +0 -15
  80. package/src/validate-record.test.ts +0 -56
  81. package/src/validate-record.ts +0 -19
  82. package/src/walk-ref-graph.test.ts +0 -118
  83. package/src/walk-ref-graph.ts +0 -184
@@ -1,580 +0,0 @@
1
- import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
-
3
- import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive } from './mjst-extension'
4
- import { refToName } from './ref-to-name'
5
- import { safeKey } from './safe-accessor'
6
- import { isObjectSchema, isSchemaObject } from './schema-guards'
7
-
8
- type ConditionalObjectResult = {
9
- schema: JSONSchema.Object
10
- thenRef: string | null
11
- }
12
-
13
- /** Options controlling generated type output. */
14
- export type TypeOptions = {
15
- /** When true, every property, array, and record in the generated types is emitted as readonly. */
16
- readonly readonly?: boolean
17
- /**
18
- * Suffix appended to every generated type name derived from a `$ref`.
19
- * Defaults to `''` (no suffix). Set to e.g. `'Object'` to emit `ContactObject`.
20
- */
21
- readonly typeSuffix?: string
22
- }
23
-
24
- const getConditionalObjectSchema = (schema: JSONSchema): ConditionalObjectResult | null => {
25
- if (!isSchemaObject(schema)) {
26
- return null
27
- }
28
-
29
- if (!('if' in schema) || !('then' in schema)) {
30
- return null
31
- }
32
-
33
- const ifSchema = schema.if
34
- const thenSchema = schema.then
35
-
36
- if (!isSchemaObject(ifSchema) || !isSchemaObject(thenSchema)) {
37
- return null
38
- }
39
-
40
- const ifProperties = ifSchema.properties
41
- const thenProperties = thenSchema.properties
42
- const hasIfProperties = ifProperties && typeof ifProperties === 'object'
43
- const hasThenProperties = thenProperties && typeof thenProperties === 'object'
44
-
45
- if (!hasIfProperties && !hasThenProperties) {
46
- return null
47
- }
48
-
49
- const properties = {
50
- ...(hasIfProperties ? ifProperties : {}),
51
- ...(hasThenProperties ? thenProperties : {}),
52
- }
53
-
54
- const required = new Set<string>()
55
-
56
- if (Array.isArray(ifSchema.required)) {
57
- for (const key of ifSchema.required) {
58
- required.add(key)
59
- }
60
- }
61
-
62
- if (hasIfProperties) {
63
- for (const key in ifProperties) {
64
- required.add(key)
65
- }
66
- }
67
-
68
- if (Array.isArray(thenSchema.required)) {
69
- for (const key of thenSchema.required) {
70
- required.add(key)
71
- }
72
- }
73
-
74
- if (hasThenProperties) {
75
- for (const key in thenProperties) {
76
- required.add(key)
77
- }
78
- }
79
-
80
- const thenRef = typeof thenSchema.$ref === 'string' ? thenSchema.$ref : null
81
-
82
- return {
83
- schema: {
84
- type: 'object',
85
- properties,
86
- ...(required.size > 0 ? { required: Array.from(required) } : {}),
87
- },
88
- thenRef,
89
- }
90
- }
91
-
92
- const isObjectLikeSchema = (schema: JSONSchema): schema is JSONSchema.Object => {
93
- if (!isSchemaObject(schema)) {
94
- return false
95
- }
96
-
97
- if (isObjectSchema(schema)) {
98
- return true
99
- }
100
-
101
- return 'patternProperties' in schema || 'additionalProperties' in schema || ('if' in schema && 'then' in schema)
102
- }
103
-
104
- const getBooleanSubSchemaType = (schema: boolean): string => {
105
- return schema ? 'unknown' : 'never'
106
- }
107
-
108
- const buildJsDocBlock = (title: string, description: string, commentUrl?: string): string => {
109
- let block = `/**\n`
110
- block += `* ${title}\n`
111
- block += `*\n`
112
- block += `* ${description}\n`
113
- if (commentUrl?.startsWith('http')) {
114
- block += `* \n`
115
- block += `* @see {@link ${commentUrl}}\n`
116
- }
117
- block += `*/\n`
118
- return block
119
- }
120
-
121
- /**
122
- * Converts a JSON Schema type to its TypeScript equivalent, applying any
123
- * `x-mjst` brand. Branding is type-level only, so we compute the underlying
124
- * type and intersect it with a unique brand marker. This is the recursion entry
125
- * point, so branded nested fields are wrapped too.
126
- */
127
- const getTypeScriptType = (schema: JSONSchema, options: TypeOptions = {}): string => {
128
- const base = getUnbrandedType(schema, options)
129
- const brand = getMjstBrand(schema)
130
- return brand ? `(${base} & { readonly __brand: '${brand}' })` : base
131
- }
132
-
133
- /** Wraps a `Record<...>` in `Readonly<...>` when readonly output is requested. */
134
- const recordType = (keyType: string, valueType: string, options: TypeOptions): string =>
135
- options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`
136
-
137
- /**
138
- * Converts a JSON Schema type to its TypeScript equivalent, ignoring any brand.
139
- * Recursively handles nested objects and arrays.
140
- */
141
- const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string => {
142
- // Boolean schema: `true` means any value is valid (unknown), `false` means no value is valid (never)
143
- if (typeof schema === 'boolean') {
144
- return getBooleanSubSchemaType(schema)
145
- }
146
-
147
- // Check if schema is an object (not a boolean schema)
148
- if (typeof schema !== 'object' || schema === null) {
149
- return 'unknown'
150
- }
151
-
152
- // An x-mjst instanceOf hint means the value is a runtime class (e.g. Date)
153
- // that JSON Schema cannot describe — emit the class name as the type directly.
154
- const instanceOf = getMjstInstanceOf(schema)
155
- if (instanceOf) {
156
- return instanceOf
157
- }
158
-
159
- // An x-mjst primitive hint (e.g. bigint) names a non-JSON primitive — emit it
160
- // directly as the TypeScript type.
161
- const primitive = getMjstPrimitive(schema)
162
- if (primitive) {
163
- return primitive
164
- }
165
-
166
- // Handle $ref
167
- if (schema.$ref) {
168
- // External refs (e.g. http://json-schema.org/...) cannot be resolved locally — treat as unknown
169
- if (!schema.$ref.startsWith('#')) {
170
- return 'unknown'
171
- }
172
- return refToName(schema.$ref, options.typeSuffix)
173
- }
174
-
175
- // Handle $dynamicRef (used for recursive schemas)
176
- if (schema.$dynamicRef) {
177
- // For #meta, this refers to the Schema type itself (JSON Schema 2020-12 $dynamicAnchor pattern)
178
- if (schema.$dynamicRef === '#meta') {
179
- return `Schema${options.typeSuffix ?? ''}`
180
- }
181
- return refToName(schema.$dynamicRef, options.typeSuffix)
182
- }
183
-
184
- // Handle const - literal type
185
- if (schema.const !== undefined) {
186
- return JSON.stringify(schema.const)
187
- }
188
-
189
- // Handle enum - union of literal types
190
- if (schema.enum && schema.enum.length > 0) {
191
- if (schema.enum.length === 1) {
192
- return JSON.stringify(schema.enum[0])
193
- }
194
- let enumUnion = JSON.stringify(schema.enum[0])
195
- for (let i = 1; i < schema.enum.length; i++) {
196
- enumUnion += ' | ' + JSON.stringify(schema.enum[i])
197
- }
198
- return enumUnion
199
- }
200
-
201
- // Handle multi-value enum - union of literal types
202
- if (schema.enum && schema.enum.length > 1) {
203
- let multiEnumUnion = JSON.stringify(schema.enum[0])
204
- for (let i = 1; i < schema.enum.length; i++) {
205
- multiEnumUnion += ' | ' + JSON.stringify(schema.enum[i])
206
- }
207
- return multiEnumUnion
208
- }
209
-
210
- // Handle union types (oneOf, anyOf) - check this before returning unknown
211
- if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
212
- // schema.oneOf[0] is safe: we guard with .length > 0 above
213
- let oneOfUnion = getTypeScriptType(schema.oneOf[0]!, options)
214
- for (let i = 1; i < schema.oneOf.length; i++) {
215
- oneOfUnion += ' | ' + getTypeScriptType(schema.oneOf[i]!, options)
216
- }
217
- return oneOfUnion
218
- }
219
- if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
220
- // schema.anyOf[0] is safe: we guard with .length > 0 above
221
- let anyOfUnion = getTypeScriptType(schema.anyOf[0]!, options)
222
- for (let i = 1; i < schema.anyOf.length; i++) {
223
- anyOfUnion += ' | ' + getTypeScriptType(schema.anyOf[i]!, options)
224
- }
225
- return anyOfUnion
226
- }
227
-
228
- // Handle allOf (intersection types)
229
- if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length > 0) {
230
- // schema.allOf[0] is safe: we guard with .length > 0 above
231
- let intersectionTypes = getTypeScriptType(schema.allOf[0]!, options)
232
- for (let i = 1; i < schema.allOf.length; i++) {
233
- intersectionTypes += ' & ' + getTypeScriptType(schema.allOf[i]!, options)
234
- }
235
- return intersectionTypes
236
- }
237
-
238
- // Handle object-like conditional schemas that use if/then without declaring type
239
- const conditionalResult = getConditionalObjectSchema(schema)
240
- if (conditionalResult) {
241
- const baseType = getTypeScriptType(conditionalResult.schema, options)
242
- if (conditionalResult.thenRef) {
243
- return `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}`
244
- }
245
- return baseType
246
- }
247
-
248
- // No type so we return unknown
249
- if (!schema.type) {
250
- if (schema.additionalProperties !== undefined) {
251
- if (typeof schema.additionalProperties === 'boolean') {
252
- return recordType('string', getBooleanSubSchemaType(schema.additionalProperties), options)
253
- }
254
- return recordType('string', getTypeScriptType(schema.additionalProperties, options), options)
255
- }
256
-
257
- if (schema.patternProperties && typeof schema.patternProperties === 'object') {
258
- const firstEntry = Object.entries(schema.patternProperties)[0]
259
- if (firstEntry) {
260
- const [pattern, value] = firstEntry
261
- if (value !== undefined) {
262
- const valueType =
263
- typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options)
264
- // The ^x- pattern is a common JSON Schema convention for vendor extensions
265
- // that maps naturally to the TypeScript template literal `x-${string}`
266
- if (pattern === '^x-') {
267
- return recordType('`x-${string}`', valueType, options)
268
- }
269
- return recordType('string', valueType, options)
270
- }
271
- }
272
- }
273
-
274
- if (schema.default !== undefined) {
275
- if (typeof schema.default === 'string') {
276
- return 'string'
277
- }
278
- if (typeof schema.default === 'number') {
279
- return 'number'
280
- }
281
- if (typeof schema.default === 'boolean') {
282
- return 'boolean'
283
- }
284
- }
285
-
286
- return 'unknown'
287
- }
288
-
289
- // Handle type as an array (union of types)
290
- if (Array.isArray(schema.type)) {
291
- const mapType = (t: string): string => {
292
- switch (t) {
293
- case 'string':
294
- return 'string'
295
- case 'number':
296
- case 'integer':
297
- return 'number'
298
- case 'boolean':
299
- return 'boolean'
300
- case 'null':
301
- return 'null'
302
- case 'array':
303
- return 'unknown[]'
304
- case 'object':
305
- return 'Record<string, unknown>'
306
- default:
307
- return 'unknown'
308
- }
309
- }
310
- let typeUnion = mapType(schema.type[0])
311
- for (let i = 1; i < schema.type.length; i++) {
312
- typeUnion += ' | ' + mapType(schema.type[i])
313
- }
314
- return typeUnion
315
- }
316
-
317
- switch (schema.type) {
318
- // String
319
- case 'string':
320
- return 'string'
321
-
322
- // Number
323
- case 'number':
324
- case 'integer':
325
- return 'number'
326
-
327
- // Boolean
328
- case 'boolean':
329
- return 'boolean'
330
-
331
- // Array
332
- case 'array':
333
- if (schema.items) {
334
- const itemType = getTypeScriptType(schema.items, options)
335
- // Wrap union types in parentheses so `(A | B)[]` is not misread as `A | B[]`
336
- const wrappedItemType = itemType.includes(' | ') ? `(${itemType})` : itemType
337
- return options.readonly ? `readonly ${wrappedItemType}[]` : `${wrappedItemType}[]`
338
- }
339
- return options.readonly ? 'readonly unknown[]' : 'unknown[]'
340
-
341
- // Object
342
- case 'object':
343
- if (schema.properties) {
344
- const readonlyPrefix = options.readonly ? 'readonly ' : ''
345
- const hasDescriptions = Object.values(schema.properties).some(
346
- (p) => isSchemaObject(p) && (typeof p.description === 'string' || typeof p.$comment === 'string'),
347
- )
348
-
349
- if (hasDescriptions) {
350
- let properties = ''
351
- let first = true
352
- for (const key in schema.properties) {
353
- // schema.properties[key] is safe: key comes from iterating schema.properties
354
- const propSchema = schema.properties[key]!
355
- const isRequired = schema.required?.includes(key) ?? false
356
- const optional = isRequired ? '' : '?'
357
- const propType = getTypeScriptType(propSchema, options)
358
- const inlineDescription =
359
- isSchemaObject(propSchema) && typeof propSchema.description === 'string'
360
- ? propSchema.description
361
- : isSchemaObject(propSchema) && typeof propSchema.$comment === 'string'
362
- ? propSchema.$comment
363
- : undefined
364
- if (!first) properties += '\n'
365
- first = false
366
- if (inlineDescription) {
367
- properties +=
368
- ' /** ' +
369
- inlineDescription +
370
- ' */\n ' +
371
- readonlyPrefix +
372
- safeKey(key) +
373
- optional +
374
- ': ' +
375
- propType +
376
- ';'
377
- } else {
378
- properties += ' ' + readonlyPrefix + safeKey(key) + optional + ': ' + propType + ';'
379
- }
380
- }
381
- return '{\n' + properties + '\n}'
382
- }
383
-
384
- let properties = ''
385
- let first = true
386
- for (const key in schema.properties) {
387
- // schema.properties[key] is safe: key comes from iterating schema.properties
388
- const propSchema = schema.properties[key]!
389
- const isRequired = schema.required?.includes(key) ?? false
390
- const optional = isRequired ? '' : '?'
391
- const propType = getTypeScriptType(propSchema, options)
392
- if (!first) properties += '; '
393
- properties += readonlyPrefix + safeKey(key) + optional + ': ' + propType
394
- first = false
395
- }
396
- return '{ ' + properties + ' }'
397
- }
398
- // Handle additionalProperties with $ref or $dynamicRef
399
- if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
400
- const additionalPropType = getTypeScriptType(schema.additionalProperties, options)
401
- return recordType('string', additionalPropType, options)
402
- }
403
- // Handle patternProperties as a Record type
404
- if (schema.patternProperties && typeof schema.patternProperties === 'object') {
405
- const firstEntry = Object.entries(schema.patternProperties)[0]
406
- if (firstEntry) {
407
- const [pattern, patternVal] = firstEntry
408
- if (patternVal) {
409
- const valueType = getTypeScriptType(patternVal, options)
410
- if (pattern === '^x-') {
411
- return recordType('`x-${string}`', valueType, options)
412
- }
413
- return recordType('string', valueType, options)
414
- }
415
- }
416
- }
417
- return 'object'
418
-
419
- // Default to unknown
420
- default:
421
- return 'unknown'
422
- }
423
- }
424
-
425
- /**
426
- * Generates a TypeScript type definition from a JSON Schema.
427
- * Handles required vs optional properties based on the schema's required array.
428
- * Uses $comment as inline JSDoc description when present.
429
- */
430
- export const generateTypeDefinition = (schema: JSONSchema, typeName: string, options: TypeOptions = {}): string => {
431
- const readonlyPrefix = options.readonly ? 'readonly ' : ''
432
-
433
- // Handle non-object schemas first
434
- if (!isObjectLikeSchema(schema)) {
435
- const tsType = getTypeScriptType(schema, options)
436
- let result = ''
437
-
438
- const topLevelComment =
439
- (isSchemaObject(schema) && typeof schema.description === 'string' && schema.description) ||
440
- (isSchemaObject(schema) && typeof schema.$comment === 'string' && schema.$comment) ||
441
- undefined
442
- if (topLevelComment) {
443
- result += buildJsDocBlock(typeName, topLevelComment)
444
- }
445
-
446
- result += `export type ${typeName} = ${tsType};`
447
- return result
448
- }
449
-
450
- if (isObjectLikeSchema(schema)) {
451
- const conditionalResult = getConditionalObjectSchema(schema)
452
- const normalizedSchema = conditionalResult?.schema ?? schema
453
- const conditionalThenRef = conditionalResult?.thenRef ?? null
454
- let jsDocTitle: string | undefined
455
- let jsDocDescription: string | undefined
456
-
457
- const topLevelComment =
458
- (isSchemaObject(schema) && typeof schema.description === 'string' && schema.description) ||
459
- (isSchemaObject(schema) && typeof schema.$comment === 'string' && schema.$comment) ||
460
- undefined
461
- if (topLevelComment) {
462
- jsDocTitle = typeName
463
- jsDocDescription = topLevelComment
464
- }
465
-
466
- const hasProperties = normalizedSchema.properties && Object.keys(normalizedSchema.properties).length > 0
467
- const hasAdditionalProperties =
468
- normalizedSchema.additionalProperties && typeof normalizedSchema.additionalProperties === 'object'
469
- const hasPatternProperties =
470
- normalizedSchema.patternProperties &&
471
- typeof normalizedSchema.patternProperties === 'object' &&
472
- Object.keys(normalizedSchema.patternProperties).length > 0
473
-
474
- // Handle objects with only patternProperties (no fixed properties)
475
- if (!hasProperties && hasPatternProperties && normalizedSchema.patternProperties) {
476
- const firstEntry = Object.entries(normalizedSchema.patternProperties)[0]
477
- const firstPattern = firstEntry?.[0]
478
- const firstPatternProperty = firstEntry?.[1]
479
-
480
- if (firstPatternProperty === undefined) {
481
- return `export type ${typeName} = Record<string, unknown>;`
482
- }
483
-
484
- const patternPropType =
485
- typeof firstPatternProperty === 'boolean'
486
- ? getBooleanSubSchemaType(firstPatternProperty)
487
- : getTypeScriptType(firstPatternProperty, options)
488
-
489
- // The ^x- pattern is a common JSON Schema convention for vendor extensions
490
- // that maps naturally to the TypeScript template literal `x-${string}`
491
- const keyType = firstPattern === '^x-' ? '`x-${string}`' : 'string'
492
-
493
- let result = ''
494
- if (jsDocTitle && jsDocDescription) {
495
- result += buildJsDocBlock(jsDocTitle, jsDocDescription)
496
- }
497
- result += `export type ${typeName} = ${recordType(keyType, patternPropType, options)};`
498
-
499
- return result
500
- }
501
-
502
- // Handle objects with only additionalProperties (no fixed properties)
503
- if (!hasProperties && hasAdditionalProperties && normalizedSchema.additionalProperties) {
504
- const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties, options)
505
-
506
- let result = ''
507
- if (jsDocTitle && jsDocDescription) {
508
- result += buildJsDocBlock(jsDocTitle, jsDocDescription)
509
- }
510
- result += `export type ${typeName} = {\n ${readonlyPrefix}[key: string]: ${additionalPropType};\n};`
511
-
512
- return result
513
- }
514
-
515
- const schemaProps = normalizedSchema.properties ?? {}
516
- let properties = ''
517
- let isFirstProp = true
518
- for (const key in schemaProps) {
519
- // schemaProps[key] is safe: key comes from iterating schemaProps
520
- const propSchema = schemaProps[key]!
521
- const isRequired = normalizedSchema.required?.includes(key) ?? false
522
- const optional = isRequired ? '' : '?'
523
- const propType = getTypeScriptType(propSchema, options)
524
- const quotedKey = readonlyPrefix + safeKey(key)
525
-
526
- if (!isFirstProp) properties += '\n'
527
- isFirstProp = false
528
-
529
- // Add JSDoc comment from $comment or description if available
530
- const inlineDescription =
531
- isSchemaObject(propSchema) && typeof propSchema.description === 'string'
532
- ? propSchema.description
533
- : isSchemaObject(propSchema) && typeof propSchema.$comment === 'string'
534
- ? propSchema.$comment
535
- : undefined
536
- if (inlineDescription) {
537
- properties += ' /** ' + inlineDescription + ' */\n ' + quotedKey + optional + ': ' + propType + ';'
538
- } else {
539
- properties += ' ' + quotedKey + optional + ': ' + propType + ';'
540
- }
541
- }
542
-
543
- // Collect allOf $ref intersections
544
- const allOfIntersections: string[] = []
545
- if (isSchemaObject(schema) && Array.isArray(schema.allOf)) {
546
- for (const entry of schema.allOf) {
547
- if (isSchemaObject(entry) && entry.$ref) {
548
- allOfIntersections.push(refToName(entry.$ref, options.typeSuffix))
549
- }
550
- }
551
- }
552
-
553
- // JSON Schema 2019-09+ allows $ref as a sibling to other keywords.
554
- // Treat it as an additional intersection type (e.g. for specification-extensions).
555
- if (isSchemaObject(schema) && typeof schema.$ref === 'string' && schema.$ref.startsWith('#')) {
556
- allOfIntersections.push(refToName(schema.$ref, options.typeSuffix))
557
- }
558
-
559
- let result = ''
560
- if (jsDocTitle && jsDocDescription) {
561
- result += buildJsDocBlock(jsDocTitle, jsDocDescription)
562
- }
563
-
564
- let typeBody = '{\n' + properties + '\n}'
565
-
566
- if (conditionalThenRef) {
567
- typeBody += ' & ' + refToName(conditionalThenRef, options.typeSuffix)
568
- }
569
-
570
- for (const intersectionType of allOfIntersections) {
571
- typeBody += ' & ' + intersectionType
572
- }
573
-
574
- result += 'export type ' + typeName + ' = ' + typeBody + ';'
575
-
576
- return result
577
- }
578
-
579
- return 'export type ' + typeName + ' = unknown;'
580
- }
package/src/has-ref.ts DELETED
@@ -1,10 +0,0 @@
1
- /** Type guard to check if a value is a non-null, non-array object with a string $ref property */
2
- export const hasRef = (value: unknown): value is { $ref: string } & Record<string, unknown> => {
3
- return (
4
- typeof value === 'object' &&
5
- value !== null &&
6
- !Array.isArray(value) &&
7
- '$ref' in value &&
8
- typeof (value as { $ref: unknown }).$ref === 'string'
9
- )
10
- }
@@ -1,65 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
-
3
- import { isObject } from './is-object'
4
-
5
- describe('is-object', () => {
6
- it('returns true for plain object', () => {
7
- expect(isObject({})).toBe(true)
8
- })
9
-
10
- it('returns true for object with properties', () => {
11
- expect(isObject({ a: 1, b: 'hello' })).toBe(true)
12
- })
13
-
14
- it('returns false for null', () => {
15
- expect(isObject(null)).toBe(false)
16
- })
17
-
18
- it('returns false for undefined', () => {
19
- expect(isObject(undefined)).toBe(false)
20
- })
21
-
22
- it('returns false for array', () => {
23
- expect(isObject([])).toBe(false)
24
- expect(isObject([1, 2, 3])).toBe(false)
25
- })
26
-
27
- it('returns false for string', () => {
28
- expect(isObject('hello')).toBe(false)
29
- })
30
-
31
- it('returns false for number', () => {
32
- expect(isObject(42)).toBe(false)
33
- expect(isObject(0)).toBe(false)
34
- })
35
-
36
- it('returns false for boolean', () => {
37
- expect(isObject(true)).toBe(false)
38
- expect(isObject(false)).toBe(false)
39
- })
40
-
41
- it('returns true for Date object', () => {
42
- // This implementation returns true for Date since it is a simple typeof check
43
- expect(isObject(new Date())).toBe(true)
44
- })
45
-
46
- it('returns true for RegExp object', () => {
47
- expect(isObject(/test/)).toBe(true)
48
- })
49
-
50
- it('returns true for nested object', () => {
51
- expect(isObject({ nested: { deep: true } })).toBe(true)
52
- })
53
-
54
- it('returns true for Object.create(null)', () => {
55
- expect(isObject(Object.create(null))).toBe(true)
56
- })
57
-
58
- it('returns false for function', () => {
59
- expect(isObject(() => {})).toBe(false)
60
- })
61
-
62
- it('returns false for empty string', () => {
63
- expect(isObject('')).toBe(false)
64
- })
65
- })
package/src/is-object.ts DELETED
@@ -1,15 +0,0 @@
1
- /**
2
- * Returns true if the provided value is a plain object.
3
- * Optimized for JSON data validation: checks that value is truthy, typeof object,
4
- * and not an array. This correctly handles all JSON value types.
5
- *
6
- * Examples:
7
- * isObject({}) // true
8
- * isObject({ a: 1 }) // true
9
- * isObject([]) // false (Array)
10
- * isObject(null) // false
11
- * isObject(123) // false
12
- * isObject('string') // false
13
- */
14
- export const isObject = (value: unknown): value is Record<string, unknown> =>
15
- !!value && typeof value === 'object' && !Array.isArray(value)