@amritk/helpers 0.5.0 → 0.6.1

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.
@@ -3,6 +3,11 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
3
3
  export type TypeOptions = {
4
4
  /** When true, every property, array, and record in the generated types is emitted as readonly. */
5
5
  readonly readonly?: boolean;
6
+ /**
7
+ * Suffix appended to every generated type name derived from a `$ref`.
8
+ * Defaults to `''` (no suffix). Set to e.g. `'Object'` to emit `ContactObject`.
9
+ */
10
+ readonly typeSuffix?: string;
6
11
  };
7
12
  /**
8
13
  * Generates a TypeScript type definition from a JSON Schema.
@@ -158,15 +158,15 @@ var refToFilename = (ref) => {
158
158
  };
159
159
 
160
160
  // src/ref-to-name.ts
161
- var kebabToPascal = (kebab) => {
161
+ var kebabToPascal = (kebab, suffix) => {
162
162
  const words = kebab.split("-");
163
163
  let pascalCase = "";
164
164
  for (const word of words) {
165
165
  pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
166
166
  }
167
- return pascalCase + "Object";
167
+ return pascalCase + suffix;
168
168
  };
169
- var refToName = (ref) => kebabToPascal(refToFilename(ref));
169
+ var refToName = (ref, suffix = "") => kebabToPascal(refToFilename(ref), suffix);
170
170
 
171
171
  // src/safe-accessor.ts
172
172
  var JS_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
@@ -297,13 +297,13 @@ var getUnbrandedType = (schema, options = {}) => {
297
297
  if (!schema.$ref.startsWith("#")) {
298
298
  return "unknown";
299
299
  }
300
- return refToName(schema.$ref);
300
+ return refToName(schema.$ref, options.typeSuffix);
301
301
  }
302
302
  if (schema.$dynamicRef) {
303
303
  if (schema.$dynamicRef === "#meta") {
304
- return "Schema";
304
+ return `Schema${options.typeSuffix ?? ""}`;
305
305
  }
306
- return refToName(schema.$dynamicRef);
306
+ return refToName(schema.$dynamicRef, options.typeSuffix);
307
307
  }
308
308
  if (schema.const !== undefined) {
309
309
  return JSON.stringify(schema.const);
@@ -350,7 +350,7 @@ var getUnbrandedType = (schema, options = {}) => {
350
350
  if (conditionalResult) {
351
351
  const baseType = getTypeScriptType(conditionalResult.schema, options);
352
352
  if (conditionalResult.thenRef) {
353
- return `(${baseType}) & ${refToName(conditionalResult.thenRef)}`;
353
+ return `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}`;
354
354
  }
355
355
  return baseType;
356
356
  }
@@ -431,6 +431,31 @@ var getUnbrandedType = (schema, options = {}) => {
431
431
  case "object":
432
432
  if (schema.properties) {
433
433
  const readonlyPrefix = options.readonly ? "readonly " : "";
434
+ const hasDescriptions = Object.values(schema.properties).some((p) => isSchemaObject(p) && (typeof p.description === "string" || typeof p.$comment === "string"));
435
+ if (hasDescriptions) {
436
+ let properties2 = "";
437
+ let first2 = true;
438
+ for (const key in schema.properties) {
439
+ const propSchema = schema.properties[key];
440
+ const isRequired = schema.required?.includes(key) ?? false;
441
+ const optional = isRequired ? "" : "?";
442
+ const propType = getTypeScriptType(propSchema, options);
443
+ const inlineDescription = isSchemaObject(propSchema) && typeof propSchema.description === "string" ? propSchema.description : isSchemaObject(propSchema) && typeof propSchema.$comment === "string" ? propSchema.$comment : undefined;
444
+ if (!first2)
445
+ properties2 += `
446
+ `;
447
+ first2 = false;
448
+ if (inlineDescription) {
449
+ properties2 += " /** " + inlineDescription + ` */
450
+ ` + readonlyPrefix + safeKey(key) + optional + ": " + propType + ";";
451
+ } else {
452
+ properties2 += " " + readonlyPrefix + safeKey(key) + optional + ": " + propType + ";";
453
+ }
454
+ }
455
+ return `{
456
+ ` + properties2 + `
457
+ }`;
458
+ }
434
459
  let properties = "";
435
460
  let first = true;
436
461
  for (const key in schema.properties) {
@@ -472,8 +497,9 @@ var generateTypeDefinition = (schema, typeName, options = {}) => {
472
497
  if (!isObjectLikeSchema(schema)) {
473
498
  const tsType = getTypeScriptType(schema, options);
474
499
  let result = "";
475
- if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === "string") {
476
- result += buildJsDocBlock(typeName, schema.$comment);
500
+ const topLevelComment = isSchemaObject(schema) && typeof schema.description === "string" && schema.description || isSchemaObject(schema) && typeof schema.$comment === "string" && schema.$comment || undefined;
501
+ if (topLevelComment) {
502
+ result += buildJsDocBlock(typeName, topLevelComment);
477
503
  }
478
504
  result += `export type ${typeName} = ${tsType};`;
479
505
  return result;
@@ -484,9 +510,10 @@ var generateTypeDefinition = (schema, typeName, options = {}) => {
484
510
  const conditionalThenRef = conditionalResult?.thenRef ?? null;
485
511
  let jsDocTitle;
486
512
  let jsDocDescription;
487
- if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === "string") {
513
+ const topLevelComment = isSchemaObject(schema) && typeof schema.description === "string" && schema.description || isSchemaObject(schema) && typeof schema.$comment === "string" && schema.$comment || undefined;
514
+ if (topLevelComment) {
488
515
  jsDocTitle = typeName;
489
- jsDocDescription = schema.$comment;
516
+ jsDocDescription = topLevelComment;
490
517
  }
491
518
  const hasProperties2 = normalizedSchema.properties && Object.keys(normalizedSchema.properties).length > 0;
492
519
  const hasAdditionalProperties2 = normalizedSchema.additionalProperties && typeof normalizedSchema.additionalProperties === "object";
@@ -543,12 +570,12 @@ var generateTypeDefinition = (schema, typeName, options = {}) => {
543
570
  if (isSchemaObject(schema) && Array.isArray(schema.allOf)) {
544
571
  for (const entry of schema.allOf) {
545
572
  if (isSchemaObject(entry) && entry.$ref) {
546
- allOfIntersections.push(refToName(entry.$ref));
573
+ allOfIntersections.push(refToName(entry.$ref, options.typeSuffix));
547
574
  }
548
575
  }
549
576
  }
550
577
  if (isSchemaObject(schema) && typeof schema.$ref === "string" && schema.$ref.startsWith("#")) {
551
- allOfIntersections.push(refToName(schema.$ref));
578
+ allOfIntersections.push(refToName(schema.$ref, options.typeSuffix));
552
579
  }
553
580
  let result = "";
554
581
  if (jsDocTitle && jsDocDescription) {
@@ -558,7 +585,7 @@ var generateTypeDefinition = (schema, typeName, options = {}) => {
558
585
  ` + properties + `
559
586
  }`;
560
587
  if (conditionalThenRef) {
561
- typeBody += " & " + refToName(conditionalThenRef);
588
+ typeBody += " & " + refToName(conditionalThenRef, options.typeSuffix);
562
589
  }
563
590
  for (const intersectionType of allOfIntersections) {
564
591
  typeBody += " & " + intersectionType;
@@ -1,18 +1,21 @@
1
1
  /**
2
2
  * Converts a JSON Schema $ref to a type name.
3
- * Derives the filename via `refToFilename` then converts to PascalCase with
4
- * an "Object" suffix.
3
+ * Derives the filename via `refToFilename` then converts to PascalCase,
4
+ * appending an optional suffix.
5
5
  *
6
6
  * Handles all ref forms: internal `#/$defs/...`, `#/definitions/...`, and URI refs.
7
7
  *
8
8
  * @param ref - The $ref string
9
- * @returns The type name in PascalCase with "Object" suffix
9
+ * @param suffix - Optional suffix appended to the PascalCase name. Defaults to
10
+ * `''` (no suffix). Pass e.g. `'Object'` to get `ContactObject`.
11
+ * @returns The type name in PascalCase with the suffix applied
10
12
  *
11
13
  * @example
12
14
  * ```ts
13
- * refToName('#/$defs/contact') // 'ContactObject'
14
- * refToName('#/$defs/server-variable') // 'ServerVariableObject'
15
- * refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'ChannelObject'
15
+ * refToName('#/$defs/contact') // 'Contact'
16
+ * refToName('#/$defs/server-variable') // 'ServerVariable'
17
+ * refToName('#/$defs/contact', 'Object') // 'ContactObject'
18
+ * refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'Channel'
16
19
  * ```
17
20
  */
18
- export declare const refToName: (ref: string) => string;
21
+ export declare const refToName: (ref: string, suffix?: string) => string;
@@ -40,15 +40,15 @@ var refToFilename = (ref) => {
40
40
  };
41
41
 
42
42
  // src/ref-to-name.ts
43
- var kebabToPascal = (kebab) => {
43
+ var kebabToPascal = (kebab, suffix) => {
44
44
  const words = kebab.split("-");
45
45
  let pascalCase = "";
46
46
  for (const word of words) {
47
47
  pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
48
48
  }
49
- return pascalCase + "Object";
49
+ return pascalCase + suffix;
50
50
  };
51
- var refToName = (ref) => kebabToPascal(refToFilename(ref));
51
+ var refToName = (ref, suffix = "") => kebabToPascal(refToFilename(ref), suffix);
52
52
  export {
53
53
  refToName
54
54
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -164,9 +164,9 @@ describe('generateTypeDefinition', () => {
164
164
  },
165
165
  }
166
166
 
167
- const result = generateTypeDefinition(schema, 'GenericObject')
167
+ const result = generateTypeDefinition(schema, 'Generic')
168
168
 
169
- expect(result).toStrictEqual('export type GenericObject = {\n' + ' metadata?: object;\n' + '};')
169
+ expect(result).toStrictEqual('export type Generic = {\n' + ' metadata?: object;\n' + '};')
170
170
  })
171
171
 
172
172
  it('generates type for complex nested structure with arrays and objects', () => {
@@ -220,9 +220,9 @@ describe('generateTypeDefinition', () => {
220
220
  properties: {},
221
221
  }
222
222
 
223
- const result = generateTypeDefinition(schema, 'EmptyObject')
223
+ const result = generateTypeDefinition(schema, 'Empty')
224
224
 
225
- expect(result).toStrictEqual('export type EmptyObject = {\n' + '\n' + '};')
225
+ expect(result).toStrictEqual('export type Empty = {\n' + '\n' + '};')
226
226
  })
227
227
 
228
228
  it('generates type for object with no type specified', () => {
@@ -575,18 +575,18 @@ describe('generateTypeDefinition', () => {
575
575
  required: ['title', 'version'],
576
576
  }
577
577
 
578
- const result = generateTypeDefinition(info, 'InfoObject')
578
+ const result = generateTypeDefinition(info, 'Info')
579
579
 
580
580
  expect(result).toStrictEqual(
581
581
  '/**\n' +
582
- '* InfoObject\n' +
582
+ '* Info\n' +
583
583
  '*\n' +
584
584
  '* https://spec.openapis.org/oas/v3.1#info-object\n' +
585
585
  '*/\n' +
586
- 'export type InfoObject = {\n' +
586
+ 'export type Info = {\n' +
587
587
  ' title: string;\n' +
588
588
  ' summary?: string;\n' +
589
- ' contact?: ContactObject;\n' +
589
+ ' contact?: Contact;\n' +
590
590
  ' version: string;\n' +
591
591
  '};',
592
592
  )
@@ -611,18 +611,18 @@ describe('generateTypeDefinition', () => {
611
611
  },
612
612
  }
613
613
 
614
- const result = generateTypeDefinition(components, 'ComponentsObject')
614
+ const result = generateTypeDefinition(components, 'Components')
615
615
 
616
616
  expect(result).toStrictEqual(
617
- 'export type ComponentsObject = {\n' +
618
- ' responses?: Record<string, ResponseObject>;\n' +
619
- ' parameters?: Record<string, ParameterObject>;\n' +
620
- ' pathItems?: Record<string, PathItemObject>;\n' +
617
+ 'export type Components = {\n' +
618
+ ' responses?: Record<string, Response>;\n' +
619
+ ' parameters?: Record<string, Parameter>;\n' +
620
+ ' pathItems?: Record<string, PathItem>;\n' +
621
621
  '};',
622
622
  )
623
623
  })
624
624
 
625
- it('generates type for object with paths property as Record<string, PathItemObject>', () => {
625
+ it('generates type for object with paths property as Record<string, PathItem>', () => {
626
626
  const document: JSONSchema.Object = {
627
627
  $comment: 'https://spec.openapis.org/oas/v3.1#openapi-object',
628
628
  type: 'object',
@@ -647,8 +647,8 @@ describe('generateTypeDefinition', () => {
647
647
  '*/\n' +
648
648
  'export type Document = {\n' +
649
649
  ' openapi: string;\n' +
650
- ' info: InfoObject;\n' +
651
- ' paths?: Record<string, PathItemObject>;\n' +
650
+ ' info: Info;\n' +
651
+ ' paths?: Record<string, PathItem>;\n' +
652
652
  '};',
653
653
  )
654
654
  })
@@ -702,12 +702,12 @@ describe('generateTypeDefinition', () => {
702
702
  '*/\n' +
703
703
  'export type Document = {\n' +
704
704
  ' openapi: string;\n' +
705
- ' info: InfoObject;\n' +
705
+ ' info: Info;\n' +
706
706
  ' jsonSchemaDialect?: string;\n' +
707
- ' servers?: ServerObject[];\n' +
708
- ' paths?: Record<string, PathItemObject>;\n' +
709
- ' webhooks?: Record<string, PathItemObject>;\n' +
710
- ' components?: ComponentsObject;\n' +
707
+ ' servers?: Server[];\n' +
708
+ ' paths?: Record<string, PathItem>;\n' +
709
+ ' webhooks?: Record<string, PathItem>;\n' +
710
+ ' components?: Components;\n' +
711
711
  '};',
712
712
  )
713
713
  })
@@ -723,15 +723,15 @@ describe('generateTypeDefinition', () => {
723
723
  },
724
724
  }
725
725
 
726
- const result = generateTypeDefinition(paths, 'PathsObject')
726
+ const result = generateTypeDefinition(paths, 'Paths')
727
727
 
728
728
  expect(result).toStrictEqual(
729
729
  '/**\n' +
730
- '* PathsObject\n' +
730
+ '* Paths\n' +
731
731
  '*\n' +
732
732
  '* https://spec.openapis.org/oas/v3.1#paths-object\n' +
733
733
  '*/\n' +
734
- 'export type PathsObject = Record<string, PathItemObject>;',
734
+ 'export type Paths = Record<string, PathItem>;',
735
735
  )
736
736
  })
737
737
 
@@ -743,7 +743,7 @@ describe('generateTypeDefinition', () => {
743
743
  name: { type: 'string' as const },
744
744
  },
745
745
  }
746
- const result = generateTypeDefinition(schema, 'InfoExtensionsObject')
746
+ const result = generateTypeDefinition(schema, 'InfoExtensions')
747
747
  expect(result).toContain("'x-linkedin'?: string;")
748
748
  expect(result).toContain('name?: string;')
749
749
  })
@@ -767,11 +767,9 @@ describe('generateTypeDefinition', () => {
767
767
  },
768
768
  }
769
769
 
770
- const result = generateTypeDefinition(schema, 'TypeHttpObject')
770
+ const result = generateTypeDefinition(schema, 'TypeHttp')
771
771
 
772
- expect(result).toStrictEqual(
773
- 'export type TypeHttpObject = {\n' + ' type: "http";\n' + ' scheme: string;\n' + '};',
774
- )
772
+ expect(result).toStrictEqual('export type TypeHttp = {\n' + ' type: "http";\n' + ' scheme: string;\n' + '};')
775
773
  })
776
774
 
777
775
  it('generates required property from then properties without explicit required', () => {
@@ -792,10 +790,10 @@ describe('generateTypeDefinition', () => {
792
790
  },
793
791
  }
794
792
 
795
- const result = generateTypeDefinition(schema, 'TypeHttpObject')
793
+ const result = generateTypeDefinition(schema, 'TypeHttp')
796
794
 
797
795
  expect(result).toStrictEqual(
798
- 'export type TypeHttpObject = {\n' + ' type: "http";\n' + ' bearerFormat: string;\n' + '};',
796
+ 'export type TypeHttp = {\n' + ' type: "http";\n' + ' bearerFormat: string;\n' + '};',
799
797
  )
800
798
  })
801
799
 
@@ -823,9 +821,9 @@ describe('generateTypeDefinition', () => {
823
821
  },
824
822
  }
825
823
 
826
- const result = generateTypeDefinition(schema, 'TypeHttpObject')
824
+ const result = generateTypeDefinition(schema, 'TypeHttp')
827
825
 
828
- expect(result).toContain('* TypeHttpObject')
826
+ expect(result).toContain('* TypeHttp')
829
827
  expect(result).toContain('* https://spec.openapis.org/oas/v3.1#security-scheme-object')
830
828
  expect(result).toContain('type: "http";')
831
829
  expect(result).toContain('scheme: string;')
@@ -847,13 +845,13 @@ describe('generateTypeDefinition', () => {
847
845
  allOf: [{ $ref: '#/$defs/type-apikey' }, { $ref: '#/$defs/type-http' }, { $ref: '#/$defs/type-oauth2' }],
848
846
  }
849
847
 
850
- const result = generateTypeDefinition(securityScheme, 'SecuritySchemeObject')
848
+ const result = generateTypeDefinition(securityScheme, 'SecurityScheme')
851
849
 
852
850
  expect(result).toStrictEqual(
853
- 'export type SecuritySchemeObject = {\n' +
851
+ 'export type SecurityScheme = {\n' +
854
852
  ' type: "apiKey" | "http" | "oauth2";\n' +
855
853
  ' description?: string;\n' +
856
- '} & TypeApikeyObject & TypeHttpObject & TypeOauth2Object;',
854
+ '} & TypeApikey & TypeHttp & TypeOauth2;',
857
855
  )
858
856
  })
859
857
 
@@ -870,12 +868,45 @@ describe('generateTypeDefinition', () => {
870
868
  allOf: [{ $ref: '#/$defs/type-apikey' }, { $ref: '#/$defs/type-http' }],
871
869
  }
872
870
 
873
- const result = generateTypeDefinition(securityScheme, 'SecuritySchemeObject')
871
+ const result = generateTypeDefinition(securityScheme, 'SecurityScheme')
874
872
 
875
- expect(result).toContain('* SecuritySchemeObject')
873
+ expect(result).toContain('* SecurityScheme')
876
874
  expect(result).toContain('* https://spec.openapis.org/oas/v3.1#security-scheme-object')
877
875
  expect(result).toContain('type: "apiKey" | "http" | "oauth2";')
878
- expect(result).toContain('} & TypeApikeyObject & TypeHttpObject;')
876
+ expect(result).toContain('} & TypeApikey & TypeHttp;')
877
+ })
878
+
879
+ it('preserves property descriptions as JSDoc comments when allOf contains an inline object schema', () => {
880
+ const schema: JSONSchema = {
881
+ allOf: [
882
+ { $ref: '#/$defs/baseTargetConfig' },
883
+ {
884
+ type: 'object',
885
+ additionalProperties: false,
886
+ properties: {
887
+ packageName: {
888
+ type: 'string',
889
+ description: 'Import/package name for TypeScript and Node packages.',
890
+ },
891
+ packageManager: {
892
+ type: 'string',
893
+ description: 'TypeScript package manager preference for generated package metadata.',
894
+ },
895
+ publish: {
896
+ $ref: '#/$defs/npmPublishConfig',
897
+ description: 'npm publishing configuration.',
898
+ },
899
+ },
900
+ required: ['publish'],
901
+ },
902
+ ],
903
+ }
904
+
905
+ const result = generateTypeDefinition(schema, 'TypeScriptTargetConfig')
906
+
907
+ expect(result).toContain('/** Import/package name for TypeScript and Node packages. */')
908
+ expect(result).toContain('/** TypeScript package manager preference for generated package metadata. */')
909
+ expect(result).toContain('/** npm publishing configuration. */')
879
910
  })
880
911
 
881
912
  it('generates record type for patternProperties-only schema without explicit type', () => {
@@ -885,9 +916,9 @@ describe('generateTypeDefinition', () => {
885
916
  },
886
917
  }
887
918
 
888
- const result = generateTypeDefinition(schema, 'SpecificationExtensionsObject')
919
+ const result = generateTypeDefinition(schema, 'SpecificationExtensions')
889
920
 
890
- expect(result).toStrictEqual('export type SpecificationExtensionsObject = Record<`x-${string}`, unknown>;')
921
+ expect(result).toStrictEqual('export type SpecificationExtensions = Record<`x-${string}`, unknown>;')
891
922
  })
892
923
 
893
924
  it('generates Record<string, never> for patternProperties-only schema with false boolean value', () => {
@@ -899,9 +930,9 @@ describe('generateTypeDefinition', () => {
899
930
  },
900
931
  }
901
932
 
902
- const result = generateTypeDefinition(schema, 'RestrictedObject')
933
+ const result = generateTypeDefinition(schema, 'Restricted')
903
934
 
904
- expect(result).toStrictEqual('export type RestrictedObject = Record<`x-${string}`, never>;')
935
+ expect(result).toStrictEqual('export type Restricted = Record<`x-${string}`, never>;')
905
936
  })
906
937
 
907
938
  it('generates Schema type for property with $dynamicRef pointing to #meta', () => {
@@ -930,7 +961,7 @@ describe('generateTypeDefinition', () => {
930
961
 
931
962
  const result = generateTypeDefinition(schema, 'ContentContainer')
932
963
 
933
- expect(result).toContain('content?: SchemaObject')
964
+ expect(result).toContain('content?: Schema')
934
965
  })
935
966
 
936
967
  it('generates union type for schema with array of types', () => {
@@ -1058,12 +1089,12 @@ describe('generateTypeDefinition', () => {
1058
1089
  },
1059
1090
  }
1060
1091
 
1061
- const result = generateTypeDefinition(schema, 'CallbackObject')
1092
+ const result = generateTypeDefinition(schema, 'Callback')
1062
1093
 
1063
1094
  expect(result).toContain('/**')
1064
- expect(result).toContain('* CallbackObject')
1095
+ expect(result).toContain('* Callback')
1065
1096
  expect(result).toContain('* https://spec.openapis.org/oas/v3.1#callback-object')
1066
- expect(result).toContain('[key: string]: PathItemObject')
1097
+ expect(result).toContain('[key: string]: PathItem')
1067
1098
  })
1068
1099
 
1069
1100
  it('generates type for product schema with required, optional, and array fields', () => {
@@ -1087,7 +1118,12 @@ describe('generateTypeDefinition', () => {
1087
1118
  const result = generateTypeDefinition(schema, 'Product')
1088
1119
 
1089
1120
  expect(result).toBe(
1090
- 'export type Product = {\n' +
1121
+ '/**\n' +
1122
+ '* Product\n' +
1123
+ '*\n' +
1124
+ '* A product available for purchase in the catalog.\n' +
1125
+ '*/\n' +
1126
+ 'export type Product = {\n' +
1091
1127
  ' /** Unique product identifier (UUID). */\n' +
1092
1128
  ' id: string;\n' +
1093
1129
  ' /** Display name shown to customers. */\n' +
@@ -1111,7 +1147,14 @@ describe('generateTypeDefinition', () => {
1111
1147
 
1112
1148
  const result = generateTypeDefinition(schema, 'ThemeColor')
1113
1149
 
1114
- expect(result).toBe('export type ThemeColor = "red" | "green" | "blue" | "yellow" | "purple";')
1150
+ expect(result).toBe(
1151
+ '/**\n' +
1152
+ '* ThemeColor\n' +
1153
+ '*\n' +
1154
+ '* One of the supported theme colors.\n' +
1155
+ '*/\n' +
1156
+ 'export type ThemeColor = "red" | "green" | "blue" | "yellow" | "purple";',
1157
+ )
1115
1158
  })
1116
1159
 
1117
1160
  it('generates type for geo coordinate with min/max constraints on required number fields', () => {
@@ -1130,7 +1173,12 @@ describe('generateTypeDefinition', () => {
1130
1173
  const result = generateTypeDefinition(schema, 'GeoCoordinate')
1131
1174
 
1132
1175
  expect(result).toBe(
1133
- 'export type GeoCoordinate = {\n' +
1176
+ '/**\n' +
1177
+ '* GeoCoordinate\n' +
1178
+ '*\n' +
1179
+ '* A geographic coordinate pair.\n' +
1180
+ '*/\n' +
1181
+ 'export type GeoCoordinate = {\n' +
1134
1182
  ' /** Degrees latitude, from -90 to 90. */\n' +
1135
1183
  ' latitude: number;\n' +
1136
1184
  ' /** Degrees longitude, from -180 to 180. */\n' +
@@ -1151,7 +1199,7 @@ describe('generateTypeDefinition', () => {
1151
1199
 
1152
1200
  const result = generateTypeDefinition(schema, 'Parameters')
1153
1201
 
1154
- expect(result).toBe('export type Parameters = (ParameterObject | ReferenceObject)[];')
1202
+ expect(result).toBe('export type Parameters = (Parameter | Reference)[];')
1155
1203
  })
1156
1204
 
1157
1205
  it('emits JSDoc for non-object schemas with a $comment URL', () => {
@@ -1165,7 +1213,7 @@ describe('generateTypeDefinition', () => {
1165
1213
 
1166
1214
  expect(result).toContain('/**')
1167
1215
  expect(result).toContain('* https://spec.openapis.org/oas/v3.1#contact-object')
1168
- expect(result).toContain('export type Contacts = ServerObject[];')
1216
+ expect(result).toContain('export type Contacts = Server[];')
1169
1217
  })
1170
1218
 
1171
1219
  it('emits JSDoc for non-object schemas with a plain-text $comment', () => {
@@ -1179,7 +1227,7 @@ describe('generateTypeDefinition', () => {
1179
1227
 
1180
1228
  expect(result).toContain('/**')
1181
1229
  expect(result).toContain('A list of parameters applicable to the operation.')
1182
- expect(result).toContain('export type Parameters = ParameterObject[];')
1230
+ expect(result).toContain('export type Parameters = Parameter[];')
1183
1231
  })
1184
1232
 
1185
1233
  it('generates unknown for external $ref', () => {
@@ -1188,9 +1236,9 @@ describe('generateTypeDefinition', () => {
1188
1236
  $ref: 'http://json-schema.org/draft-04/schema#/properties/maximum',
1189
1237
  }
1190
1238
 
1191
- const result = generateTypeDefinition(schema, 'MaximumObject')
1239
+ const result = generateTypeDefinition(schema, 'Maximum')
1192
1240
 
1193
- expect(result).toBe('export type MaximumObject = unknown;')
1241
+ expect(result).toBe('export type Maximum = unknown;')
1194
1242
  })
1195
1243
 
1196
1244
  it('does not emit a trailing blank line in JSDoc when there is no @see link', () => {
@@ -1202,7 +1250,7 @@ describe('generateTypeDefinition', () => {
1202
1250
  },
1203
1251
  }
1204
1252
 
1205
- const result = generateTypeDefinition(schema, 'PlainCommentObject')
1253
+ const result = generateTypeDefinition(schema, 'PlainComment')
1206
1254
 
1207
1255
  expect(result).toMatch(/\* A plain-text description with no URL\.\n\*\//)
1208
1256
  expect(result).not.toContain('* \n*/')
@@ -1314,4 +1362,25 @@ describe('generateTypeDefinition', () => {
1314
1362
  expect(result).toContain('id: string;')
1315
1363
  })
1316
1364
  })
1365
+
1366
+ describe('typeSuffix', () => {
1367
+ const schema: JSONSchema = {
1368
+ type: 'object',
1369
+ properties: {
1370
+ contact: { $ref: '#/$defs/contact' },
1371
+ },
1372
+ required: ['contact'],
1373
+ }
1374
+
1375
+ it('appends the suffix to ref-derived type names', () => {
1376
+ const result = generateTypeDefinition(schema, 'Document', { typeSuffix: 'Object' })
1377
+ expect(result).toContain('contact: ContactObject;')
1378
+ })
1379
+
1380
+ it('emits no suffix by default', () => {
1381
+ const result = generateTypeDefinition(schema, 'Document')
1382
+ expect(result).toContain('contact: Contact;')
1383
+ expect(result).not.toContain('ContactObject')
1384
+ })
1385
+ })
1317
1386
  })
@@ -14,6 +14,11 @@ type ConditionalObjectResult = {
14
14
  export type TypeOptions = {
15
15
  /** When true, every property, array, and record in the generated types is emitted as readonly. */
16
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
17
22
  }
18
23
 
19
24
  const getConditionalObjectSchema = (schema: JSONSchema): ConditionalObjectResult | null => {
@@ -164,16 +169,16 @@ const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string
164
169
  if (!schema.$ref.startsWith('#')) {
165
170
  return 'unknown'
166
171
  }
167
- return refToName(schema.$ref)
172
+ return refToName(schema.$ref, options.typeSuffix)
168
173
  }
169
174
 
170
175
  // Handle $dynamicRef (used for recursive schemas)
171
176
  if (schema.$dynamicRef) {
172
177
  // For #meta, this refers to the Schema type itself (JSON Schema 2020-12 $dynamicAnchor pattern)
173
178
  if (schema.$dynamicRef === '#meta') {
174
- return 'Schema'
179
+ return `Schema${options.typeSuffix ?? ''}`
175
180
  }
176
- return refToName(schema.$dynamicRef)
181
+ return refToName(schema.$dynamicRef, options.typeSuffix)
177
182
  }
178
183
 
179
184
  // Handle const - literal type
@@ -235,7 +240,7 @@ const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string
235
240
  if (conditionalResult) {
236
241
  const baseType = getTypeScriptType(conditionalResult.schema, options)
237
242
  if (conditionalResult.thenRef) {
238
- return `(${baseType}) & ${refToName(conditionalResult.thenRef)}`
243
+ return `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}`
239
244
  }
240
245
  return baseType
241
246
  }
@@ -337,6 +342,45 @@ const getUnbrandedType = (schema: JSONSchema, options: TypeOptions = {}): string
337
342
  case 'object':
338
343
  if (schema.properties) {
339
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
+
340
384
  let properties = ''
341
385
  let first = true
342
386
  for (const key in schema.properties) {
@@ -391,8 +435,12 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string, opt
391
435
  const tsType = getTypeScriptType(schema, options)
392
436
  let result = ''
393
437
 
394
- if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === 'string') {
395
- result += buildJsDocBlock(typeName, schema.$comment)
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)
396
444
  }
397
445
 
398
446
  result += `export type ${typeName} = ${tsType};`
@@ -406,9 +454,13 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string, opt
406
454
  let jsDocTitle: string | undefined
407
455
  let jsDocDescription: string | undefined
408
456
 
409
- if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === 'string') {
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) {
410
462
  jsDocTitle = typeName
411
- jsDocDescription = schema.$comment
463
+ jsDocDescription = topLevelComment
412
464
  }
413
465
 
414
466
  const hasProperties = normalizedSchema.properties && Object.keys(normalizedSchema.properties).length > 0
@@ -493,7 +545,7 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string, opt
493
545
  if (isSchemaObject(schema) && Array.isArray(schema.allOf)) {
494
546
  for (const entry of schema.allOf) {
495
547
  if (isSchemaObject(entry) && entry.$ref) {
496
- allOfIntersections.push(refToName(entry.$ref))
548
+ allOfIntersections.push(refToName(entry.$ref, options.typeSuffix))
497
549
  }
498
550
  }
499
551
  }
@@ -501,7 +553,7 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string, opt
501
553
  // JSON Schema 2019-09+ allows $ref as a sibling to other keywords.
502
554
  // Treat it as an additional intersection type (e.g. for specification-extensions).
503
555
  if (isSchemaObject(schema) && typeof schema.$ref === 'string' && schema.$ref.startsWith('#')) {
504
- allOfIntersections.push(refToName(schema.$ref))
556
+ allOfIntersections.push(refToName(schema.$ref, options.typeSuffix))
505
557
  }
506
558
 
507
559
  let result = ''
@@ -512,7 +564,7 @@ export const generateTypeDefinition = (schema: JSONSchema, typeName: string, opt
512
564
  let typeBody = '{\n' + properties + '\n}'
513
565
 
514
566
  if (conditionalThenRef) {
515
- typeBody += ' & ' + refToName(conditionalThenRef)
567
+ typeBody += ' & ' + refToName(conditionalThenRef, options.typeSuffix)
516
568
  }
517
569
 
518
570
  for (const intersectionType of allOfIntersections) {
@@ -4,45 +4,54 @@ import { refToName } from './ref-to-name'
4
4
 
5
5
  describe('ref-to-name', () => {
6
6
  it('converts simple ref to PascalCase', () => {
7
- expect(refToName('#/$defs/contact')).toBe('ContactObject')
7
+ expect(refToName('#/$defs/contact')).toBe('Contact')
8
8
  })
9
9
 
10
10
  it('converts kebab-case ref to PascalCase', () => {
11
- expect(refToName('#/$defs/server-variable')).toBe('ServerVariableObject')
11
+ expect(refToName('#/$defs/server-variable')).toBe('ServerVariable')
12
12
  })
13
13
 
14
14
  it('converts multi-word kebab-case ref to PascalCase', () => {
15
- expect(refToName('#/$defs/external-documentation')).toBe('ExternalDocumentationObject')
15
+ expect(refToName('#/$defs/external-documentation')).toBe('ExternalDocumentation')
16
16
  })
17
17
 
18
18
  it('handles refs with multiple path segments', () => {
19
- expect(refToName('#/components/schemas/user-profile')).toBe('UserProfileObject')
19
+ expect(refToName('#/components/schemas/user-profile')).toBe('UserProfile')
20
20
  })
21
21
 
22
22
  it('handles single word refs', () => {
23
- expect(refToName('#/$defs/info')).toBe('InfoObject')
23
+ expect(refToName('#/$defs/info')).toBe('Info')
24
24
  })
25
25
 
26
26
  it('handles refs with numbers', () => {
27
- expect(refToName('#/$defs/oauth2-flow')).toBe('Oauth2FlowObject')
27
+ expect(refToName('#/$defs/oauth2-flow')).toBe('Oauth2Flow')
28
28
  })
29
29
 
30
30
  it('converts uppercase acronym keys to PascalCase via kebab normalization', () => {
31
- expect(refToName('#/$defs/APIKey')).toBe('ApiKeyObject')
31
+ expect(refToName('#/$defs/APIKey')).toBe('ApiKey')
32
32
  })
33
33
 
34
34
  it('derives type name from a URI ref', () => {
35
- expect(refToName('http://asyncapi.com/definitions/3.1.0/channel.json')).toBe('ChannelObject')
36
- expect(refToName('http://asyncapi.com/definitions/3.1.0/info.json')).toBe('InfoObject')
35
+ expect(refToName('http://asyncapi.com/definitions/3.1.0/channel.json')).toBe('Channel')
36
+ expect(refToName('http://asyncapi.com/definitions/3.1.0/info.json')).toBe('Info')
37
37
  })
38
38
 
39
39
  it('derives type name from a URI ref with a fragment', () => {
40
40
  expect(refToName('http://asyncapi.com/bindings/sns/0.1.0/channel.json#/definitions/queue')).toBe(
41
- 'BindingsSns010ChannelQueueObject',
41
+ 'BindingsSns010ChannelQueue',
42
42
  )
43
43
  })
44
44
 
45
45
  it('handles draft-07 schema URI', () => {
46
- expect(refToName('http://json-schema.org/draft-07/schema')).toBe('Draft07SchemaObject')
46
+ expect(refToName('http://json-schema.org/draft-07/schema')).toBe('Draft07Schema')
47
+ })
48
+
49
+ it('appends the suffix when one is provided', () => {
50
+ expect(refToName('#/$defs/contact', 'Object')).toBe('ContactObject')
51
+ expect(refToName('#/$defs/server-variable', 'Object')).toBe('ServerVariableObject')
52
+ })
53
+
54
+ it('treats an empty suffix the same as omitting it', () => {
55
+ expect(refToName('#/$defs/contact', '')).toBe('Contact')
47
56
  })
48
57
  })
@@ -1,38 +1,42 @@
1
1
  import { refToFilename } from './ref-to-filename'
2
2
 
3
3
  /**
4
- * Converts a kebab-case filename to PascalCase with an "Object" suffix.
4
+ * Converts a kebab-case filename to PascalCase, appending an optional suffix.
5
5
  *
6
6
  * @example
7
7
  * ```ts
8
- * kebabToPascal('server-variable') // 'ServerVariableObject'
9
- * kebabToPascal('channel') // 'ChannelObject'
8
+ * kebabToPascal('server-variable') // 'ServerVariable'
9
+ * kebabToPascal('channel') // 'Channel'
10
+ * kebabToPascal('channel', 'Object') // 'ChannelObject'
10
11
  * ```
11
12
  */
12
- const kebabToPascal = (kebab: string): string => {
13
+ const kebabToPascal = (kebab: string, suffix: string): string => {
13
14
  const words = kebab.split('-')
14
15
  let pascalCase = ''
15
16
  for (const word of words) {
16
17
  pascalCase += word.charAt(0).toUpperCase() + word.slice(1)
17
18
  }
18
- return pascalCase + 'Object'
19
+ return pascalCase + suffix
19
20
  }
20
21
 
21
22
  /**
22
23
  * Converts a JSON Schema $ref to a type name.
23
- * Derives the filename via `refToFilename` then converts to PascalCase with
24
- * an "Object" suffix.
24
+ * Derives the filename via `refToFilename` then converts to PascalCase,
25
+ * appending an optional suffix.
25
26
  *
26
27
  * Handles all ref forms: internal `#/$defs/...`, `#/definitions/...`, and URI refs.
27
28
  *
28
29
  * @param ref - The $ref string
29
- * @returns The type name in PascalCase with "Object" suffix
30
+ * @param suffix - Optional suffix appended to the PascalCase name. Defaults to
31
+ * `''` (no suffix). Pass e.g. `'Object'` to get `ContactObject`.
32
+ * @returns The type name in PascalCase with the suffix applied
30
33
  *
31
34
  * @example
32
35
  * ```ts
33
- * refToName('#/$defs/contact') // 'ContactObject'
34
- * refToName('#/$defs/server-variable') // 'ServerVariableObject'
35
- * refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'ChannelObject'
36
+ * refToName('#/$defs/contact') // 'Contact'
37
+ * refToName('#/$defs/server-variable') // 'ServerVariable'
38
+ * refToName('#/$defs/contact', 'Object') // 'ContactObject'
39
+ * refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'Channel'
36
40
  * ```
37
41
  */
38
- export const refToName = (ref: string): string => kebabToPascal(refToFilename(ref))
42
+ export const refToName = (ref: string, suffix = ''): string => kebabToPascal(refToFilename(ref), suffix)