@openpkg-ts/sdk 0.46.0 → 0.47.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +187 -98
  2. package/dist/index.js +770 -78
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1848,9 +1848,13 @@ import ts4 from "typescript";
1848
1848
 
1849
1849
  // src/types/schema-builder.ts
1850
1850
  import ts3 from "typescript";
1851
+
1852
+ // src/schema/builtins.ts
1851
1853
  var BUILTIN_TYPE_SCHEMAS = {
1854
+ Array: { type: "array" },
1855
+ ReadonlyArray: { type: "array" },
1852
1856
  Date: { type: "string", format: "date-time" },
1853
- RegExp: { type: "object", description: "RegExp" },
1857
+ RegExp: { type: "object" },
1854
1858
  Error: { type: "object" },
1855
1859
  Promise: { type: "object" },
1856
1860
  Map: { type: "object" },
@@ -1860,6 +1864,7 @@ var BUILTIN_TYPE_SCHEMAS = {
1860
1864
  Function: { type: "object" },
1861
1865
  ArrayBuffer: { type: "string", format: "binary" },
1862
1866
  ArrayBufferLike: { type: "string", format: "binary" },
1867
+ SharedArrayBuffer: { type: "string", format: "binary" },
1863
1868
  DataView: { type: "string", format: "binary" },
1864
1869
  Uint8Array: { type: "string", format: "byte" },
1865
1870
  Uint16Array: { type: "string", format: "byte" },
@@ -1872,6 +1877,32 @@ var BUILTIN_TYPE_SCHEMAS = {
1872
1877
  BigInt64Array: { type: "string", format: "byte" },
1873
1878
  BigUint64Array: { type: "string", format: "byte" }
1874
1879
  };
1880
+
1881
+ // src/types/schema-builder.ts
1882
+ function escapeRegex(text) {
1883
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1884
+ }
1885
+ function buildTemplatePattern(type) {
1886
+ const slotPattern = (slot) => {
1887
+ if (slot.flags & ts3.TypeFlags.NumberLike)
1888
+ return "-?\\d+(?:\\.\\d+)?";
1889
+ if (slot.flags & ts3.TypeFlags.BigIntLike)
1890
+ return "-?\\d+";
1891
+ if (slot.flags & ts3.TypeFlags.BooleanLike)
1892
+ return "(?:true|false)";
1893
+ return ".*";
1894
+ };
1895
+ let pattern = `^${escapeRegex(type.texts[0] ?? "")}`;
1896
+ type.types.forEach((slot, i) => {
1897
+ pattern += slotPattern(slot) + escapeRegex(type.texts[i + 1] ?? "");
1898
+ });
1899
+ return `${pattern}$`;
1900
+ }
1901
+ function builtinSchema(name) {
1902
+ const schema = { ...BUILTIN_TYPE_SCHEMAS[name] ?? { type: "object" } };
1903
+ setSchemaExtension(schema, "x-ts-type", name);
1904
+ return schema;
1905
+ }
1875
1906
  function setSchemaExtension(schema, key, value) {
1876
1907
  schema[key] = value;
1877
1908
  }
@@ -2169,9 +2200,15 @@ function buildSchema(type, checker, ctx) {
2169
2200
  return ensureNonEmptySchema(schema, type, checker);
2170
2201
  }
2171
2202
  function buildMaxDepthSchema(type, checker) {
2203
+ if (type.flags & ts3.TypeFlags.TypeParameter && type.isThisType !== true) {
2204
+ return { "x-ts-type": checker.typeToString(type) };
2205
+ }
2172
2206
  const symbol = type.getSymbol() || type.aliasSymbol;
2173
2207
  if (symbol && !isAnonymous(type)) {
2174
2208
  const name = symbol.getName();
2209
+ if (BUILTIN_TYPES.has(name) || isBuiltinGeneric(name)) {
2210
+ return builtinSchema(name);
2211
+ }
2175
2212
  if (!name.startsWith("__") && !isPrimitiveName(name)) {
2176
2213
  return { $ref: `#/types/${name}` };
2177
2214
  }
@@ -2188,6 +2225,13 @@ function buildMaxDepthSchema(type, checker) {
2188
2225
  return { type: "null" };
2189
2226
  if (type.flags & ts3.TypeFlags.Void)
2190
2227
  return { type: "void" };
2228
+ if (type.flags & ts3.TypeFlags.TemplateLiteral) {
2229
+ return {
2230
+ type: "string",
2231
+ pattern: buildTemplatePattern(type),
2232
+ "x-ts-type": renderTypeText(type, checker)
2233
+ };
2234
+ }
2191
2235
  if (type.isUnion()) {
2192
2236
  const schemas = type.types.map((t) => buildMaxDepthSchema(t, checker));
2193
2237
  return { anyOf: schemas };
@@ -2209,7 +2253,11 @@ function buildSchemaInternal(type, checker, ctx) {
2209
2253
  }
2210
2254
  const symbol = type.getSymbol() || type.aliasSymbol;
2211
2255
  if (symbol && !isAnonymous(type)) {
2212
- return { $ref: `#/types/${symbol.getName()}` };
2256
+ const name = symbol.getName();
2257
+ if (BUILTIN_TYPES.has(name) || isBuiltinGeneric(name)) {
2258
+ return builtinSchema(name);
2259
+ }
2260
+ return { $ref: `#/types/${name}` };
2213
2261
  }
2214
2262
  return { type: checker.typeToString(type) };
2215
2263
  }
@@ -2250,6 +2298,9 @@ function buildSchemaInternal(type, checker, ctx) {
2250
2298
  };
2251
2299
  }
2252
2300
  }
2301
+ if (type.flags & ts3.TypeFlags.TypeParameter) {
2302
+ return { "x-ts-type": checker.typeToString(type) };
2303
+ }
2253
2304
  if (type.flags & ts3.TypeFlags.StringLiteral) {
2254
2305
  const literal = type.value;
2255
2306
  return { type: "string", enum: [literal] };
@@ -2273,6 +2324,16 @@ function buildSchemaInternal(type, checker, ctx) {
2273
2324
  return schema;
2274
2325
  }
2275
2326
  }
2327
+ if (type.flags & ts3.TypeFlags.TemplateLiteral) {
2328
+ return {
2329
+ type: "string",
2330
+ pattern: buildTemplatePattern(type),
2331
+ "x-ts-type": renderTypeText(type, checker)
2332
+ };
2333
+ }
2334
+ if (type.flags & ts3.TypeFlags.StringMapping) {
2335
+ return { type: "string", "x-ts-type": renderTypeText(type, checker) };
2336
+ }
2276
2337
  if (type.isUnion()) {
2277
2338
  const types = type.types;
2278
2339
  const allStringLiterals = types.every((t) => t.flags & ts3.TypeFlags.StringLiteral);
@@ -2285,12 +2346,23 @@ function buildSchemaInternal(type, checker, ctx) {
2285
2346
  const enumValues = types.map((t) => t.value);
2286
2347
  return { type: "number", enum: enumValues };
2287
2348
  }
2349
+ const allBooleanLiterals = types.every((t) => t.flags & ts3.TypeFlags.BooleanLiteral);
2350
+ if (allBooleanLiterals) {
2351
+ return { type: "boolean" };
2352
+ }
2353
+ const isBoolLiteral = (t) => !!(t.flags & ts3.TypeFlags.BooleanLiteral);
2354
+ let members = types;
2355
+ if (types.filter(isBoolLiteral).length === 2) {
2356
+ const firstBool = types.findIndex(isBoolLiteral);
2357
+ members = types.filter((t, i) => !isBoolLiteral(t) || i === firstBool);
2358
+ }
2359
+ const buildBranch = (t) => isBoolLiteral(t) ? { type: "boolean" } : buildSchema(t, checker, ctx);
2288
2360
  if (ctx) {
2289
2361
  return withDepth(ctx, () => ({
2290
- anyOf: types.map((t) => buildSchema(t, checker, ctx))
2362
+ anyOf: members.map(buildBranch)
2291
2363
  }));
2292
2364
  }
2293
- return { anyOf: types.map((t) => buildSchema(t, checker, ctx)) };
2365
+ return { anyOf: members.map(buildBranch) };
2294
2366
  }
2295
2367
  const isIntersectionType = type.isIntersection() || !!(type.flags & ts3.TypeFlags.Intersection);
2296
2368
  if (isIntersectionType && "types" in type) {
@@ -2311,7 +2383,7 @@ function buildSchemaInternal(type, checker, ctx) {
2311
2383
  }
2312
2384
  const typeString = checker.typeToString(type);
2313
2385
  if (typeString === "never[]" || typeString === "[]") {
2314
- return { type: "array", prefixedItems: [], minItems: 0, maxItems: 0 };
2386
+ return { type: "array", prefixItems: [], minItems: 0, maxItems: 0 };
2315
2387
  }
2316
2388
  const symbol = type.getSymbol() || type.aliasSymbol;
2317
2389
  if (symbol?.getName() === "Array" && isBuiltinSymbol(symbol)) {
@@ -2348,7 +2420,7 @@ function buildSchemaInternal(type, checker, ctx) {
2348
2420
  try {
2349
2421
  return {
2350
2422
  type: "array",
2351
- prefixedItems: elementTypes.map((t) => buildSchema(t, checker, ctx)),
2423
+ prefixItems: elementTypes.map((t) => buildSchema(t, checker, ctx)),
2352
2424
  minItems: elementTypes.length,
2353
2425
  maxItems: elementTypes.length
2354
2426
  };
@@ -2359,7 +2431,7 @@ function buildSchemaInternal(type, checker, ctx) {
2359
2431
  }
2360
2432
  return {
2361
2433
  type: "array",
2362
- prefixedItems: elementTypes.map((t) => buildSchema(t, checker, ctx)),
2434
+ prefixItems: elementTypes.map((t) => buildSchema(t, checker, ctx)),
2363
2435
  minItems: elementTypes.length,
2364
2436
  maxItems: elementTypes.length
2365
2437
  };
@@ -2370,9 +2442,16 @@ function buildSchemaInternal(type, checker, ctx) {
2370
2442
  const symbol2 = typeRef.target.getSymbol();
2371
2443
  const name = symbol2?.getName();
2372
2444
  if (name && BUILTIN_TYPES.has(name)) {
2373
- return { $ref: `#/types/${name}` };
2445
+ return builtinSchema(name);
2374
2446
  }
2375
- if (name && (isBuiltinGeneric(name) || !isAnonymous(typeRef.target))) {
2447
+ if (name && isBuiltinGeneric(name)) {
2448
+ const build = () => ({
2449
+ ...builtinSchema(name),
2450
+ typeArguments: typeArgs.map((t) => buildSchema(t, checker, ctx))
2451
+ });
2452
+ return ctx ? withDepth(ctx, build) : build();
2453
+ }
2454
+ if (name && !isAnonymous(typeRef.target)) {
2376
2455
  const packageOrigin = getTypeOrigin(typeRef.target, checker);
2377
2456
  if (ctx) {
2378
2457
  return withDepth(ctx, () => {
@@ -2401,7 +2480,7 @@ function buildSchemaInternal(type, checker, ctx) {
2401
2480
  if (aliasSymbol && aliasTypeArgs && aliasTypeArgs.length > 0) {
2402
2481
  const name = aliasSymbol.getName();
2403
2482
  if (BUILTIN_TYPES.has(name)) {
2404
- return { $ref: `#/types/${name}` };
2483
+ return builtinSchema(name);
2405
2484
  }
2406
2485
  if (RESOLVED_UTILITY_TYPES.has(name) && type.flags & ts3.TypeFlags.Object) {
2407
2486
  const props = type.getProperties();
@@ -2410,7 +2489,14 @@ function buildSchemaInternal(type, checker, ctx) {
2410
2489
  return buildObjectSchema(props, checker, ctx, type);
2411
2490
  }
2412
2491
  }
2413
- if (isBuiltinGeneric(name) || !name.startsWith("__")) {
2492
+ if (isBuiltinGeneric(name)) {
2493
+ const build = () => ({
2494
+ ...builtinSchema(name),
2495
+ typeArguments: aliasTypeArgs.map((t) => buildSchema(t, checker, ctx))
2496
+ });
2497
+ return ctx ? withDepth(ctx, build) : build();
2498
+ }
2499
+ if (!name.startsWith("__")) {
2414
2500
  const packageOrigin = getTypeOrigin(type, checker);
2415
2501
  if (ctx) {
2416
2502
  return withDepth(ctx, () => {
@@ -2446,7 +2532,10 @@ function buildSchemaInternal(type, checker, ctx) {
2446
2532
  return { type: name };
2447
2533
  }
2448
2534
  if (BUILTIN_TYPES.has(name)) {
2449
- return { $ref: `#/types/${name}` };
2535
+ return builtinSchema(name);
2536
+ }
2537
+ if (isBuiltinGeneric(name) && isBuiltinSymbol(symbol)) {
2538
+ return builtinSchema(name);
2450
2539
  }
2451
2540
  if (!name.startsWith("__")) {
2452
2541
  const packageOrigin = getTypeOrigin(type, checker);
@@ -2460,7 +2549,7 @@ function buildSchemaInternal(type, checker, ctx) {
2460
2549
  if (type.flags & ts3.TypeFlags.Object) {
2461
2550
  const objectType = type;
2462
2551
  const properties = type.getProperties();
2463
- if (properties.length > 0 || objectType.objectFlags & ts3.ObjectFlags.Anonymous) {
2552
+ if (properties.length > 0 || objectType.objectFlags & ts3.ObjectFlags.Anonymous || checker.getIndexInfosOfType(type).length > 0) {
2464
2553
  return buildObjectSchema(properties, checker, ctx, type);
2465
2554
  }
2466
2555
  }
@@ -2480,9 +2569,10 @@ function buildFunctionSchema(callSignatures, checker, ctx) {
2480
2569
  return [];
2481
2570
  const paramType = checker.getTypeOfSymbolAtLocation(param, decl);
2482
2571
  const isOptional = !!decl?.questionToken || !!decl?.initializer;
2572
+ const effectiveType = isOptional ? stripUndefinedFromType(paramType, checker) : paramType;
2483
2573
  return {
2484
2574
  name: param.getName(),
2485
- schema: buildSchema(paramType, checker, ctx),
2575
+ schema: buildSchema(effectiveType, checker, ctx),
2486
2576
  required: !isOptional
2487
2577
  };
2488
2578
  });
@@ -2503,6 +2593,8 @@ function buildFunctionSchema(callSignatures, checker, ctx) {
2503
2593
  }
2504
2594
  function buildObjectSchema(properties, checker, ctx, originalType) {
2505
2595
  const isArrayLikeType = originalType ? checker.isArrayType(originalType) || checker.isTupleType(originalType) || originalType.symbol?.getName() === "Array" && isBuiltinSymbol(originalType.symbol) : false;
2596
+ const isStringLikeType = !!(originalType && originalType.flags & ts3.TypeFlags.StringLike);
2597
+ const isNumberLikeType = !!(originalType && originalType.flags & ts3.TypeFlags.NumberLike);
2506
2598
  const buildProps = () => {
2507
2599
  const props = {};
2508
2600
  const required = [];
@@ -2513,7 +2605,15 @@ function buildObjectSchema(properties, checker, ctx, originalType) {
2513
2605
  if (isArrayLikeType && ARRAY_PROTOTYPE_METHODS.has(propName)) {
2514
2606
  continue;
2515
2607
  }
2516
- const propType = checker.getTypeOfSymbol(prop);
2608
+ if (isStringLikeType && STRING_PROTOTYPE_METHODS.has(propName)) {
2609
+ continue;
2610
+ }
2611
+ if (isNumberLikeType && NUMBER_PROTOTYPE_METHODS.has(propName)) {
2612
+ continue;
2613
+ }
2614
+ const isOptionalProp = !!(prop.flags & ts3.SymbolFlags.Optional);
2615
+ const rawPropType = checker.getTypeOfSymbol(prop);
2616
+ const propType = isOptionalProp ? stripUndefinedFromType(rawPropType, checker) : rawPropType;
2517
2617
  let propSchema = buildSchema(propType, checker, ctx);
2518
2618
  const docComment = prop.getDocumentationComment(checker);
2519
2619
  if (docComment.length > 0) {
@@ -2538,11 +2638,19 @@ function buildObjectSchema(properties, checker, ctx, originalType) {
2538
2638
  properties: props,
2539
2639
  ...required.length > 0 ? { required } : {}
2540
2640
  };
2541
- const stringIndex = originalType ? checker.getIndexInfosOfType(originalType).find((i) => i.keyType.flags & ts3.TypeFlags.String) : undefined;
2641
+ const indexInfos = originalType ? checker.getIndexInfosOfType(originalType) : [];
2642
+ const stringIndex = indexInfos.find((i) => i.keyType.flags & ts3.TypeFlags.String);
2542
2643
  if (stringIndex) {
2543
2644
  schema.additionalProperties = buildSchema(stringIndex.type, checker, ctx);
2544
2645
  }
2545
- if (Object.keys(props).length === 0 && originalType && !stringIndex) {
2646
+ const numberIndex = indexInfos.find((i) => i.keyType.flags & ts3.TypeFlags.Number);
2647
+ if (numberIndex) {
2648
+ schema.patternProperties = {
2649
+ "^\\d+$": buildSchema(numberIndex.type, checker, ctx)
2650
+ };
2651
+ setSchemaExtension(schema, "x-ts-index-key", "number");
2652
+ }
2653
+ if (Object.keys(props).length === 0 && originalType && !stringIndex && !numberIndex) {
2546
2654
  setSchemaExtension(schema, "x-ts-type", checker.typeToString(originalType));
2547
2655
  }
2548
2656
  return schema;
@@ -2701,6 +2809,9 @@ function extractParameters(signature, ctx) {
2701
2809
  if (description) {
2702
2810
  paramResult.description = description;
2703
2811
  }
2812
+ if (decl.initializer) {
2813
+ applyDefault(paramResult, decl.initializer);
2814
+ }
2704
2815
  result.push(paramResult);
2705
2816
  }
2706
2817
  }
@@ -2733,7 +2844,7 @@ function expandBindingPattern(paramDecl, paramType, jsdocTags, ctx) {
2733
2844
  param.description = description;
2734
2845
  }
2735
2846
  if (element.initializer) {
2736
- param.default = extractDefaultValue(element.initializer);
2847
+ applyDefault(param, element.initializer);
2737
2848
  }
2738
2849
  result.push(param);
2739
2850
  }
@@ -2781,23 +2892,37 @@ function inferParamAlias(jsdocTags) {
2781
2892
  counts.set(p, (counts.get(p) ?? 0) + 1);
2782
2893
  return Array.from(counts.entries()).sort((a, b) => b[1] - a[1])[0]?.[0];
2783
2894
  }
2784
- function extractDefaultValue(initializer) {
2895
+ function extractLiteralDefault(initializer) {
2785
2896
  if (ts4.isStringLiteral(initializer)) {
2786
- return initializer.text;
2897
+ return { literal: true, value: initializer.text };
2787
2898
  }
2788
2899
  if (ts4.isNumericLiteral(initializer)) {
2789
- return Number(initializer.text);
2900
+ return { literal: true, value: Number(initializer.text) };
2901
+ }
2902
+ if (ts4.isPrefixUnaryExpression(initializer) && initializer.operator === ts4.SyntaxKind.MinusToken && ts4.isNumericLiteral(initializer.operand)) {
2903
+ return { literal: true, value: -Number(initializer.operand.text) };
2790
2904
  }
2791
2905
  if (initializer.kind === ts4.SyntaxKind.TrueKeyword) {
2792
- return true;
2906
+ return { literal: true, value: true };
2793
2907
  }
2794
2908
  if (initializer.kind === ts4.SyntaxKind.FalseKeyword) {
2795
- return false;
2909
+ return { literal: true, value: false };
2796
2910
  }
2797
2911
  if (initializer.kind === ts4.SyntaxKind.NullKeyword) {
2798
- return null;
2912
+ return { literal: true, value: null };
2913
+ }
2914
+ return { literal: false, text: initializer.getText() };
2915
+ }
2916
+ function applyDefault(param, initializer) {
2917
+ const extracted = extractLiteralDefault(initializer);
2918
+ if (extracted.literal) {
2919
+ param.default = extracted.value;
2920
+ if (param.schema && typeof param.schema === "object" && !Array.isArray(param.schema)) {
2921
+ param.schema.default = extracted.value;
2922
+ }
2923
+ } else if (param.schema && typeof param.schema === "object" && !Array.isArray(param.schema)) {
2924
+ param.schema["x-ts-default"] = extracted.text;
2799
2925
  }
2800
- return initializer.getText();
2801
2926
  }
2802
2927
  function registerReferencedTypes(type, ctx, depth = 0) {
2803
2928
  if (depth > ctx.maxTypeDepth)
@@ -2826,6 +2951,10 @@ function registerReferencedTypes(type, ctx, depth = 0) {
2826
2951
  registerReferencedTypes(t, ctx, depth + 1);
2827
2952
  }
2828
2953
  }
2954
+ const typeSymbol = type.aliasSymbol ?? type.getSymbol();
2955
+ if (typeSymbol && ctx.shouldExpandExternal && !typeSymbol.getName().startsWith("__") && !ctx.shouldExpandExternal(typeSymbol)) {
2956
+ return;
2957
+ }
2829
2958
  if (type.flags & ts4.TypeFlags.Object) {
2830
2959
  const props = type.getProperties();
2831
2960
  const limit = ctx.maxProperties;
@@ -2960,6 +3089,16 @@ class TypeRegistry {
2960
3089
  return;
2961
3090
  if (this.has(name))
2962
3091
  return name;
3092
+ if (ctx.shouldExpandExternal && !ctx.shouldExpandExternal(symbol)) {
3093
+ this.add({
3094
+ id: name,
3095
+ name,
3096
+ kind: "external",
3097
+ external: true,
3098
+ schema: { "x-ts-type": renderTypeText(type, ctx.typeChecker) }
3099
+ });
3100
+ return name;
3101
+ }
2963
3102
  if (this.processing.has(name))
2964
3103
  return name;
2965
3104
  this.processing.add(name);
@@ -3062,7 +3201,7 @@ class TypeRegistry {
3062
3201
  const elementTypes = checker.getTypeArguments(type) ?? [];
3063
3202
  return {
3064
3203
  type: "array",
3065
- prefixedItems: elementTypes.map((t) => buildSchema(t, checker, ctx)),
3204
+ prefixItems: elementTypes.map((t) => buildSchema(t, checker, ctx)),
3066
3205
  minItems: elementTypes.length,
3067
3206
  maxItems: elementTypes.length
3068
3207
  };
@@ -3071,6 +3210,9 @@ class TypeRegistry {
3071
3210
  const elementType = checker.getTypeArguments(type)?.[0];
3072
3211
  return elementType ? { type: "array", items: buildSchema(elementType, checker, ctx) } : { type: "array" };
3073
3212
  }
3213
+ if (type.flags & ts5.TypeFlags.Conditional) {
3214
+ return { "x-ts-type": renderTypeText(type, checker) };
3215
+ }
3074
3216
  return this.buildObjectSchemaFromProperties(type, checker, ctx);
3075
3217
  }
3076
3218
  buildEnumSchema(symbol, checker) {
@@ -3100,8 +3242,10 @@ class TypeRegistry {
3100
3242
  }
3101
3243
  buildObjectSchemaFromProperties(type, checker, ctx) {
3102
3244
  const properties = type.getProperties();
3103
- const stringIndex = checker.getIndexInfosOfType(type).find((i) => i.keyType.flags & ts5.TypeFlags.String);
3104
- if (properties.length === 0 && !stringIndex) {
3245
+ const indexInfos = checker.getIndexInfosOfType(type);
3246
+ const stringIndex = indexInfos.find((i) => i.keyType.flags & ts5.TypeFlags.String);
3247
+ const numberIndex = indexInfos.find((i) => i.keyType.flags & ts5.TypeFlags.Number);
3248
+ if (properties.length === 0 && !stringIndex && !numberIndex) {
3105
3249
  return { type: checker.typeToString(type) };
3106
3250
  }
3107
3251
  const props = {};
@@ -3128,7 +3272,8 @@ class TypeRegistry {
3128
3272
  }
3129
3273
  for (const prop of included.slice(0, limit)) {
3130
3274
  const propName = prop.getName();
3131
- const propType = checker.getTypeOfSymbol(prop);
3275
+ const rawPropType = checker.getTypeOfSymbol(prop);
3276
+ const propType = prop.flags & ts5.SymbolFlags.Optional ? stripUndefinedFromType(rawPropType, checker) : rawPropType;
3132
3277
  this.registerType(propType, ctx);
3133
3278
  let propSchema = buildSchema(propType, checker, ctx);
3134
3279
  const docComment = prop.getDocumentationComment(checker);
@@ -3153,7 +3298,11 @@ class TypeRegistry {
3153
3298
  type: "object",
3154
3299
  properties: props,
3155
3300
  ...required.length > 0 ? { required } : {},
3156
- ...stringIndex ? { additionalProperties: buildSchema(stringIndex.type, checker, ctx) } : {}
3301
+ ...stringIndex ? { additionalProperties: buildSchema(stringIndex.type, checker, ctx) } : {},
3302
+ ...numberIndex ? {
3303
+ patternProperties: { "^\\d+$": buildSchema(numberIndex.type, checker, ctx) },
3304
+ "x-ts-index-key": "number"
3305
+ } : {}
3157
3306
  };
3158
3307
  }
3159
3308
  }
@@ -3174,7 +3323,8 @@ function createContext(program, sourceFile, options = {}) {
3174
3323
  registeredTypes: new Set,
3175
3324
  includePrivate: options.includePrivate ?? false,
3176
3325
  maxProperties: options.maxProperties ?? 500,
3177
- onTruncation: options.onTruncation
3326
+ onTruncation: options.onTruncation,
3327
+ shouldExpandExternal: options.shouldExpandExternal
3178
3328
  };
3179
3329
  }
3180
3330
  function getInheritedMembers(classType, ownMemberNames, ctx, isStatic = false) {
@@ -3463,7 +3613,8 @@ function serializeProperty(node, ctx) {
3463
3613
  if (!ctx.includePrivate && (visibility === "private" || visibility === "protected")) {
3464
3614
  return null;
3465
3615
  }
3466
- const type = checker.getTypeAtLocation(node);
3616
+ const rawType = checker.getTypeAtLocation(node);
3617
+ const type = node.questionToken ? stripUndefinedFromType(rawType, checker) : rawType;
3467
3618
  registerReferencedTypes(type, ctx);
3468
3619
  let schema = buildSchema(type, checker, ctx);
3469
3620
  const flags = {};
@@ -3857,7 +4008,8 @@ function serializePropertySignature(node, ctx) {
3857
4008
  const { typeChecker: checker } = ctx;
3858
4009
  const name = node.name.getText();
3859
4010
  const { description, tags } = getJSDocComment(node);
3860
- const type = checker.getTypeAtLocation(node);
4011
+ const rawType = checker.getTypeAtLocation(node);
4012
+ const type = node.questionToken ? stripUndefinedFromType(rawType, checker) : rawType;
3861
4013
  let schema = buildSchema(type, checker, ctx);
3862
4014
  registerReferencedTypes(type, ctx);
3863
4015
  const flags = {};
@@ -3998,7 +4150,7 @@ function serializeTypeAlias(node, ctx) {
3998
4150
  }
3999
4151
  } else if (isInlineFunctionAlias(node.type) && type.getCallSignatures().length > 0) {
4000
4152
  schema = buildFunctionSchema(type.getCallSignatures(), ctx.typeChecker, ctx);
4001
- } else if ((ts10.isMappedTypeNode(node.type) || ts10.isConditionalTypeNode(node.type)) && type.getProperties().length > 0 && type.getCallSignatures().length === 0) {
4153
+ } else if ((ts10.isMappedTypeNode(node.type) || ts10.isConditionalTypeNode(node.type)) && type.getProperties().length > 0 && type.getCallSignatures().length === 0 && !(type.flags & ts10.TypeFlags.Conditional) && !(type.flags & (ts10.TypeFlags.StringLike | ts10.TypeFlags.NumberLike))) {
4002
4154
  schema = buildObjectSchema(type.getProperties(), ctx.typeChecker, ctx, type);
4003
4155
  members = serializeResolvedMembers(type, node, ctx);
4004
4156
  } else {
@@ -4094,7 +4246,8 @@ function serializeResolvedMembers(type, node, ctx) {
4094
4246
  const armDocs = buildConditionalArmDocs(node.type, checker);
4095
4247
  for (const prop of type.getProperties()) {
4096
4248
  const decl = prop.getDeclarations()?.[0] ?? node;
4097
- const propType = checker.getTypeOfSymbolAtLocation(prop, decl);
4249
+ const rawPropType = checker.getTypeOfSymbolAtLocation(prop, decl);
4250
+ const propType = prop.flags & ts10.SymbolFlags.Optional ? stripUndefinedFromType(rawPropType, checker) : rawPropType;
4098
4251
  registerReferencedTypes(propType, ctx);
4099
4252
  const callSigs = propType.getCallSignatures();
4100
4253
  const isMethodDecl = ts10.isMethodSignature(decl) || ts10.isMethodDeclaration(decl) || ts10.isFunctionDeclaration(decl);
@@ -4330,10 +4483,7 @@ function serializeVariable(node, statement, ctx) {
4330
4483
  }
4331
4484
 
4332
4485
  // src/types/schema-normalizer.ts
4333
- var SCHEMA_DIALECT_URLS = {
4334
- "draft-2020-12": "https://json-schema.org/draft/2020-12/schema",
4335
- "draft-07": "http://json-schema.org/draft-07/schema#"
4336
- };
4486
+ import { JSON_SCHEMA_DRAFT } from "@openpkg-ts/spec";
4337
4487
  var TS_PRIMITIVE_NORMALIZATIONS = {
4338
4488
  void: () => ({ type: "null", "x-ts-type": "void" }),
4339
4489
  never: () => ({ not: {} }),
@@ -4344,11 +4494,11 @@ var TS_PRIMITIVE_NORMALIZATIONS = {
4344
4494
  symbol: () => ({ type: "string", "x-ts-type": "symbol" })
4345
4495
  };
4346
4496
  function normalizeSchema(schema, options = {}) {
4347
- const { includeSchemaField = false, dialect = "draft-2020-12" } = options;
4497
+ const { includeSchemaField = false } = options;
4348
4498
  const normalized = normalizeSchemaInternal(schema, options);
4349
4499
  if (includeSchemaField && typeof normalized === "object") {
4350
4500
  return {
4351
- $schema: SCHEMA_DIALECT_URLS[dialect],
4501
+ $schema: JSON_SCHEMA_DRAFT,
4352
4502
  ...normalized
4353
4503
  };
4354
4504
  }
@@ -4369,6 +4519,9 @@ function normalizeSchemaInternal(schema, options) {
4369
4519
  result[key] = s[key];
4370
4520
  }
4371
4521
  }
4522
+ if (Array.isArray(s.typeArguments) && s.typeArguments.length > 0 && result["x-ts-type-arguments"] === undefined) {
4523
+ result["x-ts-type-arguments"] = s.typeArguments.map((arg) => normalizeSchemaInternal(arg, options));
4524
+ }
4372
4525
  }
4373
4526
  return result;
4374
4527
  }
@@ -4474,14 +4627,14 @@ function normalizeSignature(signature, options) {
4474
4627
  }
4475
4628
  function normalizeTupleType(schema, options) {
4476
4629
  const result = { type: "array" };
4477
- if ("items" in schema && Array.isArray(schema.items)) {
4478
- result.prefixedItems = schema.items.map((item) => normalizeSchemaInternal(item, options));
4630
+ const prefix = Array.isArray(schema.prefixItems) ? schema.prefixItems : Array.isArray(schema.prefixedItems) ? schema.prefixedItems : undefined;
4631
+ if (prefix) {
4632
+ result.prefixItems = prefix.map((item) => normalizeSchemaInternal(item, options));
4633
+ } else if ("items" in schema && Array.isArray(schema.items)) {
4634
+ result.prefixItems = schema.items.map((item) => normalizeSchemaInternal(item, options));
4479
4635
  result.minItems = schema.items.length;
4480
4636
  result.maxItems = schema.items.length;
4481
4637
  }
4482
- if ("prefixedItems" in schema && Array.isArray(schema.prefixedItems)) {
4483
- result.prefixedItems = schema.prefixedItems.map((item) => normalizeSchemaInternal(item, options));
4484
- }
4485
4638
  if ("minItems" in schema && typeof schema.minItems === "number") {
4486
4639
  result.minItems = schema.minItems;
4487
4640
  }
@@ -4498,8 +4651,9 @@ function normalizeArrayType(schema, options) {
4498
4651
  if ("items" in schema && schema.items && !Array.isArray(schema.items)) {
4499
4652
  result.items = normalizeSchemaInternal(schema.items, options);
4500
4653
  }
4501
- if ("prefixedItems" in schema && Array.isArray(schema.prefixedItems)) {
4502
- result.prefixedItems = schema.prefixedItems.map((item) => normalizeSchemaInternal(item, options));
4654
+ const arrayPrefix = Array.isArray(schema.prefixItems) ? schema.prefixItems : Array.isArray(schema.prefixedItems) ? schema.prefixedItems : undefined;
4655
+ if (arrayPrefix) {
4656
+ result.prefixItems = arrayPrefix.map((item) => normalizeSchemaInternal(item, options));
4503
4657
  }
4504
4658
  if ("minItems" in schema && typeof schema.minItems === "number") {
4505
4659
  result.minItems = schema.minItems;
@@ -4507,6 +4661,17 @@ function normalizeArrayType(schema, options) {
4507
4661
  if ("maxItems" in schema && typeof schema.maxItems === "number") {
4508
4662
  result.maxItems = schema.maxItems;
4509
4663
  }
4664
+ if (schema.uniqueItems === true) {
4665
+ result.uniqueItems = true;
4666
+ }
4667
+ if (schema.contains && typeof schema.contains === "object") {
4668
+ result.contains = normalizeSchemaInternal(schema.contains, options);
4669
+ }
4670
+ for (const keyword of ["title", "default"]) {
4671
+ if (keyword in schema && schema[keyword] !== undefined) {
4672
+ result[keyword] = schema[keyword];
4673
+ }
4674
+ }
4510
4675
  if ("description" in schema && schema.description) {
4511
4676
  result.description = schema.description;
4512
4677
  }
@@ -4531,6 +4696,23 @@ function normalizeObjectType(schema, options) {
4531
4696
  result.additionalProperties = normalizeSchemaInternal(schema.additionalProperties, options);
4532
4697
  }
4533
4698
  }
4699
+ for (const keyword of ["patternProperties", "$defs"]) {
4700
+ const value = schema[keyword];
4701
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4702
+ result[keyword] = Object.fromEntries(Object.entries(value).map(([key, nested]) => [
4703
+ key,
4704
+ normalizeSchemaInternal(nested, options)
4705
+ ]));
4706
+ }
4707
+ }
4708
+ if (schema.propertyNames && typeof schema.propertyNames === "object") {
4709
+ result.propertyNames = normalizeSchemaInternal(schema.propertyNames, options);
4710
+ }
4711
+ for (const keyword of ["title", "default", "examples", "minProperties", "maxProperties"]) {
4712
+ if (keyword in schema && schema[keyword] !== undefined) {
4713
+ result[keyword] = schema[keyword];
4714
+ }
4715
+ }
4534
4716
  if ("description" in schema && schema.description) {
4535
4717
  result.description = schema.description;
4536
4718
  }
@@ -4637,7 +4819,7 @@ function isSchemaLike(value) {
4637
4819
  if (typeof value === "string")
4638
4820
  return true;
4639
4821
  const obj = value;
4640
- return "type" in obj || "$ref" in obj || "anyOf" in obj || "allOf" in obj || "oneOf" in obj || "properties" in obj || "items" in obj || "prefixedItems" in obj;
4822
+ return "type" in obj || "$ref" in obj || "anyOf" in obj || "allOf" in obj || "oneOf" in obj || "properties" in obj || "items" in obj || "prefixItems" in obj || "prefixedItems" in obj;
4641
4823
  }
4642
4824
  function mergeSchemaFields(target, source, excludeKeys) {
4643
4825
  if (typeof source !== "object" || source == null) {
@@ -4654,9 +4836,13 @@ function mergeSchemaFields(target, source, excludeKeys) {
4654
4836
  }
4655
4837
  return result;
4656
4838
  }
4839
+ function isVendorSchemaExport(exp) {
4840
+ return !!exp.tags?.some((t) => t.name === "schema-source" && t.text === "standard-json-schema");
4841
+ }
4657
4842
  function normalizeExport(exp, options = {}) {
4658
4843
  const result = { ...exp };
4659
- if (exp.schema) {
4844
+ const vendorSchema = isVendorSchemaExport(exp);
4845
+ if (exp.schema && !vendorSchema) {
4660
4846
  result.schema = normalizeSchema(exp.schema, options);
4661
4847
  }
4662
4848
  if (exp.signatures) {
@@ -4665,7 +4851,7 @@ function normalizeExport(exp, options = {}) {
4665
4851
  if (exp.members) {
4666
4852
  result.members = exp.members.map((member) => normalizeMember(member, options));
4667
4853
  }
4668
- if (shouldGenerateMembersSchema(exp.kind) && exp.members && exp.members.length > 0) {
4854
+ if (!vendorSchema && shouldGenerateMembersSchema(exp.kind) && exp.members && exp.members.length > 0) {
4669
4855
  result.schema = normalizeMembers(exp.members, options);
4670
4856
  }
4671
4857
  return result;
@@ -4716,10 +4902,15 @@ function normalizeMembers(members, options = {}) {
4716
4902
  const properties = {};
4717
4903
  const required = [];
4718
4904
  let additionalProperties;
4905
+ let numberIndexSchema;
4719
4906
  for (const member of members) {
4720
4907
  const { name, kind } = member;
4721
4908
  if (kind === "index" || kind === "index-signature") {
4722
- additionalProperties = normalizeMemberToSchema(member, options);
4909
+ if (name === "[number]") {
4910
+ numberIndexSchema = normalizeMemberToSchema(member, options);
4911
+ } else {
4912
+ additionalProperties = normalizeMemberToSchema(member, options);
4913
+ }
4723
4914
  continue;
4724
4915
  }
4725
4916
  if (!name)
@@ -4740,6 +4931,10 @@ function normalizeMembers(members, options = {}) {
4740
4931
  if (additionalProperties !== undefined) {
4741
4932
  result.additionalProperties = additionalProperties;
4742
4933
  }
4934
+ if (numberIndexSchema !== undefined) {
4935
+ result.patternProperties = { "^\\d+$": numberIndexSchema };
4936
+ result["x-ts-index-key"] = "number";
4937
+ }
4743
4938
  return result;
4744
4939
  }
4745
4940
  function memberDocExtras(member) {
@@ -4858,9 +5053,9 @@ async function getExport(options) {
4858
5053
  const isNamespaceExportDecl = originalDecls.some((d) => ts11.isNamespaceExport(d) || ts11.isNamespaceImport(d));
4859
5054
  if (isNamespaceExportDecl) {
4860
5055
  const spec2 = serializeNamespaceForGet(targetSymbol, exportName, ctx);
4861
- const types2 = ctx.typeRegistry.getAll().map((t) => normalizeType(t, { dialect: "draft-2020-12" }));
5056
+ const types2 = ctx.typeRegistry.getAll().map((t) => normalizeType(t));
4862
5057
  return {
4863
- export: normalizeExport(spec2, { dialect: "draft-2020-12" }),
5058
+ export: normalizeExport(spec2),
4864
5059
  types: types2,
4865
5060
  errors
4866
5061
  };
@@ -4893,8 +5088,8 @@ async function getExport(options) {
4893
5088
  }
4894
5089
  return { export: null, types: [], errors: [`Could not serialize '${exportName}'`] };
4895
5090
  }
4896
- spec = normalizeExport(spec, { dialect: "draft-2020-12" });
4897
- const types = ctx.typeRegistry.getAll().map((t) => normalizeType(t, { dialect: "draft-2020-12" }));
5091
+ spec = normalizeExport(spec);
5092
+ const types = ctx.typeRegistry.getAll().map((t) => normalizeType(t));
4898
5093
  return { export: spec, types, errors };
4899
5094
  } catch (err) {
4900
5095
  errors.push(`Failed to serialize '${exportName}': ${err instanceof Error ? err.message : String(err)}`);
@@ -6022,12 +6217,7 @@ var NODE_MODULES_PKG = /node_modules\/(@[^/]+\/[^/]+|[^/]+)/;
6022
6217
  function isLibFile(fileName) {
6023
6218
  return fileName.includes("/typescript/lib/lib.") || fileName.includes("\\typescript\\lib\\lib.");
6024
6219
  }
6025
- function expandReachableTypes(exportedSymbols, ctx, opts) {
6026
- if (opts.followExternal === false)
6027
- return;
6028
- const checker = ctx.typeChecker;
6029
- const visited = new Set;
6030
- const MAX_DEPTH = 30;
6220
+ function createExternalExpansionPredicate(opts) {
6031
6221
  const packageAllowed = (pkg) => {
6032
6222
  if (pkg === "typescript")
6033
6223
  return false;
@@ -6037,6 +6227,25 @@ function expandReachableTypes(exportedSymbols, ctx, opts) {
6037
6227
  return true;
6038
6228
  return opts.workspacePackages.has(pkg);
6039
6229
  };
6230
+ return (symbol) => {
6231
+ const decl = symbol.declarations?.[0];
6232
+ if (!decl)
6233
+ return false;
6234
+ const fileName = decl.getSourceFile().fileName;
6235
+ if (isLibFile(fileName))
6236
+ return false;
6237
+ const match = fileName.match(NODE_MODULES_PKG);
6238
+ if (match)
6239
+ return packageAllowed(match[1]);
6240
+ return true;
6241
+ };
6242
+ }
6243
+ function expandReachableTypes(exportedSymbols, ctx, opts) {
6244
+ if (opts.followExternal === false)
6245
+ return;
6246
+ const checker = ctx.typeChecker;
6247
+ const visited = new Set;
6248
+ const MAX_DEPTH = 30;
6040
6249
  const entryPackageDir = findPackageDir(opts.entryFile);
6041
6250
  const packageLabel = (fileName) => {
6042
6251
  const match = fileName.match(NODE_MODULES_PKG);
@@ -6051,18 +6260,7 @@ function expandReachableTypes(exportedSymbols, ctx, opts) {
6051
6260
  }
6052
6261
  return (pkg ?? "local").replace(/^@/, "").replace(/\//g, "-");
6053
6262
  };
6054
- const symbolAllowed = (symbol) => {
6055
- const decl = symbol.declarations?.[0];
6056
- if (!decl)
6057
- return false;
6058
- const fileName = decl.getSourceFile().fileName;
6059
- if (isLibFile(fileName))
6060
- return false;
6061
- const match = fileName.match(NODE_MODULES_PKG);
6062
- if (match)
6063
- return packageAllowed(match[1]);
6064
- return true;
6065
- };
6263
+ const symbolAllowed = createExternalExpansionPredicate(opts);
6066
6264
  const visit = (type, depth) => {
6067
6265
  if (!type || depth > MAX_DEPTH || visited.has(type))
6068
6266
  return;
@@ -6574,7 +6772,11 @@ async function extract(options) {
6574
6772
  resolveExternalTypes,
6575
6773
  includePrivate,
6576
6774
  maxProperties,
6577
- onTruncation
6775
+ onTruncation,
6776
+ shouldExpandExternal: createExternalExpansionPredicate({
6777
+ followExternal: options.followExternal,
6778
+ workspacePackages: result.workspacePackages ?? new Map
6779
+ })
6578
6780
  });
6579
6781
  ctx.exportedIds = exportedIds;
6580
6782
  const filteredSymbols = exportedSymbols.filter((s) => shouldIncludeExport(s.getName(), only, ignore));
@@ -6744,7 +6946,7 @@ async function extract(options) {
6744
6946
  if (options.schemaExtraction === "hybrid") {
6745
6947
  const projectBaseDir2 = baseDir || path9.dirname(entryFile);
6746
6948
  const runtimeResult = await extractStandardSchemasFromProject(entryFile, projectBaseDir2, {
6747
- target: options.schemaTarget || "draft-2020-12",
6949
+ target: "draft-2020-12",
6748
6950
  timeout: 15000
6749
6951
  });
6750
6952
  if (runtimeResult.schemas.size > 0) {
@@ -6775,8 +6977,8 @@ async function extract(options) {
6775
6977
  });
6776
6978
  }
6777
6979
  }
6778
- const normalizedExports = exports.map((exp) => normalizeExport(exp, { dialect: "draft-2020-12" }));
6779
- const normalizedTypes = types.map((t) => normalizeType(t, { dialect: "draft-2020-12" }));
6980
+ const normalizedExports = exports.map((exp) => normalizeExport(exp));
6981
+ const normalizedTypes = types.map((t) => normalizeType(t));
6780
6982
  const spec = {
6781
6983
  ...includeSchema ? { $schema: SCHEMA_URL } : {},
6782
6984
  openpkg: SCHEMA_VERSION,
@@ -7083,6 +7285,485 @@ async function getPackageMeta(entryFile, baseDir) {
7083
7285
 
7084
7286
  // src/primitives/spec.ts
7085
7287
  var extractSpec = extract;
7288
+ // src/primitives/validate.ts
7289
+ import {
7290
+ assertSpec,
7291
+ getAvailableVersions,
7292
+ getValidationErrors,
7293
+ LATEST_VERSION,
7294
+ validateSpec as validateSpec2
7295
+ } from "@openpkg-ts/spec";
7296
+ // src/schema/json-schema.ts
7297
+ import { JSON_SCHEMA_DRAFT as JSON_SCHEMA_DRAFT2 } from "@openpkg-ts/spec";
7298
+
7299
+ // src/schema/ref-walker.ts
7300
+ var INTERNAL_REF_PREFIX = "#/types/";
7301
+ function isTsExtensionKey(key) {
7302
+ return (key.startsWith("x-ts-") || key === "x-enum-members") && key !== "x-deprecated-reason";
7303
+ }
7304
+ function stripTsExtensions(schema) {
7305
+ const walk = (value) => {
7306
+ if (Array.isArray(value))
7307
+ return value.map(walk);
7308
+ if (value && typeof value === "object") {
7309
+ const out = {};
7310
+ for (const [key, nested] of Object.entries(value)) {
7311
+ if (isTsExtensionKey(key))
7312
+ continue;
7313
+ out[key] = walk(nested);
7314
+ }
7315
+ return out;
7316
+ }
7317
+ return value;
7318
+ };
7319
+ return walk(schema);
7320
+ }
7321
+ function escapePointerToken(name) {
7322
+ return name.replace(/~/g, "~0").replace(/\//g, "~1");
7323
+ }
7324
+ function bundleRefs(root, spec, options = {}) {
7325
+ const { keepExtensions = false, typeParameterNames = [], onUnresolved = "permissive" } = options;
7326
+ const typeParams = new Set(typeParameterNames);
7327
+ const warnings = [];
7328
+ const defs = {};
7329
+ const defKeyByName = new Map;
7330
+ const lookupType = (name) => {
7331
+ const types = spec.types ?? [];
7332
+ return types.find((t) => t.id === name) ?? types.find((t) => t.name === name);
7333
+ };
7334
+ const assignDefKey = (name) => {
7335
+ const existing = defKeyByName.get(name);
7336
+ if (existing)
7337
+ return existing;
7338
+ let key = escapePointerToken(name);
7339
+ if (Object.hasOwn(defs, key) || Object.values(defKeyByName).includes(key)) {
7340
+ let n = 2;
7341
+ while (Object.hasOwn(defs, `${key}_${n}`) || Object.values(defKeyByName).includes(`${key}_${n}`)) {
7342
+ n++;
7343
+ }
7344
+ warnings.push(`def key collision for "${name}" — using "${key}_${n}"`);
7345
+ key = `${key}_${n}`;
7346
+ }
7347
+ defKeyByName.set(name, key);
7348
+ return key;
7349
+ };
7350
+ const bodyOfType = (type) => {
7351
+ if (type.schema)
7352
+ return normalizeSchema(type.schema);
7353
+ if (type.members && type.members.length > 0)
7354
+ return normalizeMembers(type.members);
7355
+ return {};
7356
+ };
7357
+ const rewrite = (node) => {
7358
+ if (Array.isArray(node))
7359
+ return node.map(rewrite);
7360
+ if (!node || typeof node !== "object")
7361
+ return node;
7362
+ const obj = node;
7363
+ const ref = obj.$ref;
7364
+ if (typeof ref === "string" && ref.startsWith(INTERNAL_REF_PREFIX)) {
7365
+ const name = ref.slice(INTERNAL_REF_PREFIX.length);
7366
+ const siblings = {};
7367
+ for (const [key2, value] of Object.entries(obj)) {
7368
+ if (key2 === "$ref")
7369
+ continue;
7370
+ siblings[key2] = rewrite(value);
7371
+ }
7372
+ if (typeParams.has(name)) {
7373
+ warnings.push(`type parameter "${name}" is not an addressable schema`);
7374
+ return keepExtensions ? { ...siblings, "x-ts-type": name } : {};
7375
+ }
7376
+ const builtin = BUILTIN_TYPE_SCHEMAS[name];
7377
+ if (builtin) {
7378
+ return { ...builtin, ...keepExtensions ? siblings : {} };
7379
+ }
7380
+ const type = lookupType(name);
7381
+ if (!type) {
7382
+ warnings.push(`unresolved ref "${ref}"`);
7383
+ if (onUnresolved === "error") {
7384
+ throw new Error(`bundleRefs: cannot resolve ${ref}`);
7385
+ }
7386
+ return keepExtensions ? { ...siblings, "x-ts-type": name } : {};
7387
+ }
7388
+ const key = assignDefKey(name);
7389
+ if (!Object.hasOwn(defs, key)) {
7390
+ defs[key] = {};
7391
+ defs[key] = rewrite(bodyOfType(type));
7392
+ }
7393
+ const refNode = { $ref: `#/$defs/${key}` };
7394
+ return { ...siblings, ...refNode };
7395
+ }
7396
+ const out = {};
7397
+ for (const [key, value] of Object.entries(obj)) {
7398
+ out[key] = rewrite(value);
7399
+ }
7400
+ return out;
7401
+ };
7402
+ let schema = rewrite(normalizeSchema(root));
7403
+ if (!keepExtensions) {
7404
+ schema = stripTsExtensions(schema);
7405
+ for (const key of Object.keys(defs)) {
7406
+ defs[key] = stripTsExtensions(defs[key]);
7407
+ }
7408
+ }
7409
+ return { schema, defs, warnings };
7410
+ }
7411
+
7412
+ // src/schema/json-schema.ts
7413
+ function typeParamNames(subject) {
7414
+ return (subject.typeParameters ?? []).map((p) => p.name);
7415
+ }
7416
+ function subjectSchema(subject) {
7417
+ if (subject.schema)
7418
+ return normalizeSchema(subject.schema);
7419
+ if (subject.members && subject.members.length > 0)
7420
+ return normalizeMembers(subject.members);
7421
+ return {};
7422
+ }
7423
+ function exportToJsonSchema(subject, spec, options = {}) {
7424
+ const { keepExtensions = false, includeSchemaField = true } = options;
7425
+ const { schema, defs } = bundleRefs(subjectSchema(subject), spec, {
7426
+ keepExtensions,
7427
+ typeParameterNames: typeParamNames(subject)
7428
+ });
7429
+ const doc = { ...schema };
7430
+ if (Object.keys(defs).length > 0)
7431
+ doc.$defs = defs;
7432
+ if (includeSchemaField)
7433
+ return { $schema: JSON_SCHEMA_DRAFT2, ...doc };
7434
+ return doc;
7435
+ }
7436
+ function toJsonSchema(spec, options = {}) {
7437
+ const { root, keepExtensions = false, includeSchemaField = true } = options;
7438
+ if (root) {
7439
+ const subject = spec.exports.find((e) => e.name === root) ?? (spec.types ?? []).find((t) => t.name === root);
7440
+ if (!subject) {
7441
+ throw new Error(`toJsonSchema: no export or type named "${root}"`);
7442
+ }
7443
+ return exportToJsonSchema(subject, spec, { keepExtensions, includeSchemaField });
7444
+ }
7445
+ const defs = {};
7446
+ const mergeInto = (name, bundled) => {
7447
+ for (const [key, value] of Object.entries(bundled.defs)) {
7448
+ if (!Object.hasOwn(defs, key))
7449
+ defs[key] = value;
7450
+ }
7451
+ if (!Object.hasOwn(defs, name))
7452
+ defs[name] = bundled.schema;
7453
+ };
7454
+ for (const type of spec.types ?? []) {
7455
+ mergeInto(type.name, bundleRefs(subjectSchema(type), spec, {
7456
+ keepExtensions,
7457
+ typeParameterNames: typeParamNames(type)
7458
+ }));
7459
+ }
7460
+ for (const exp of spec.exports) {
7461
+ if (!exp.schema && !(exp.members && exp.members.length > 0))
7462
+ continue;
7463
+ mergeInto(exp.name, bundleRefs(subjectSchema(exp), spec, {
7464
+ keepExtensions,
7465
+ typeParameterNames: typeParamNames(exp)
7466
+ }));
7467
+ }
7468
+ const doc = { $defs: defs };
7469
+ if (includeSchemaField)
7470
+ return { $schema: JSON_SCHEMA_DRAFT2, ...doc };
7471
+ return doc;
7472
+ }
7473
+
7474
+ // src/schema/as-standard-schema.ts
7475
+ var DRAFT_07_URL = "http://json-schema.org/draft-07/schema#";
7476
+ function rewriteDefsPointers(value) {
7477
+ if (Array.isArray(value))
7478
+ return value.map(rewriteDefsPointers);
7479
+ if (value && typeof value === "object") {
7480
+ const out = {};
7481
+ for (const [key, nested] of Object.entries(value)) {
7482
+ if (key === "$ref" && typeof nested === "string") {
7483
+ out.$ref = nested.replace("#/$defs/", "#/definitions/");
7484
+ } else {
7485
+ out[key] = rewriteDefsPointers(nested);
7486
+ }
7487
+ }
7488
+ return out;
7489
+ }
7490
+ return value;
7491
+ }
7492
+ function downlevelToDraft07(doc) {
7493
+ const convert = (value) => {
7494
+ if (Array.isArray(value))
7495
+ return value.map(convert);
7496
+ if (value && typeof value === "object") {
7497
+ const obj = value;
7498
+ const out = {};
7499
+ for (const [key, nested] of Object.entries(obj)) {
7500
+ if (key === "$defs") {
7501
+ out.definitions = convert(nested);
7502
+ } else if (key === "prefixItems" && Array.isArray(nested)) {
7503
+ out.items = convert(nested);
7504
+ } else {
7505
+ out[key] = convert(nested);
7506
+ }
7507
+ }
7508
+ return out;
7509
+ }
7510
+ return value;
7511
+ };
7512
+ const converted = rewriteDefsPointers(convert(doc));
7513
+ converted.$schema = DRAFT_07_URL;
7514
+ return converted;
7515
+ }
7516
+ function downlevelToOpenApi30(doc) {
7517
+ const convert = (value) => {
7518
+ if (Array.isArray(value))
7519
+ return value.map(convert);
7520
+ if (!value || typeof value !== "object")
7521
+ return value;
7522
+ const obj = value;
7523
+ const out = {};
7524
+ if (Array.isArray(obj.anyOf)) {
7525
+ const branches = obj.anyOf;
7526
+ const nulls = branches.filter((b) => b && b.type === "null");
7527
+ const rest = branches.filter((b) => !(b && b.type === "null"));
7528
+ if (nulls.length > 0 && rest.length === 1) {
7529
+ Object.assign(out, convert(rest[0]));
7530
+ out.nullable = true;
7531
+ for (const [key, nested] of Object.entries(obj)) {
7532
+ if (key !== "anyOf")
7533
+ out[key] = convert(nested);
7534
+ }
7535
+ return out;
7536
+ }
7537
+ }
7538
+ for (const [key, nested] of Object.entries(obj)) {
7539
+ if (key === "$schema")
7540
+ continue;
7541
+ if (key === "$defs") {
7542
+ out.definitions = convert(nested);
7543
+ } else if (key === "const") {
7544
+ out.enum = [nested];
7545
+ } else {
7546
+ out[key] = convert(nested);
7547
+ }
7548
+ }
7549
+ return out;
7550
+ };
7551
+ return rewriteDefsPointers(convert(doc));
7552
+ }
7553
+ function asStandardSchema(subject, spec, options = {}) {
7554
+ const resolved = typeof subject === "string" ? spec.exports.find((e) => e.name === subject) ?? (spec.types ?? []).find((t) => t.name === subject) : subject;
7555
+ if (!resolved) {
7556
+ throw new Error(`asStandardSchema: no export or type named "${subject}"`);
7557
+ }
7558
+ const cache = new Map;
7559
+ const build = (opts) => {
7560
+ const target = opts.target;
7561
+ const cached = cache.get(target);
7562
+ if (cached)
7563
+ return cached;
7564
+ const base = exportToJsonSchema(resolved, spec, {
7565
+ keepExtensions: options.keepExtensions,
7566
+ includeSchemaField: true
7567
+ });
7568
+ let result;
7569
+ switch (target) {
7570
+ case "draft-2020-12":
7571
+ result = base;
7572
+ break;
7573
+ case "draft-07":
7574
+ result = downlevelToDraft07(base);
7575
+ break;
7576
+ case "openapi-3.0":
7577
+ result = downlevelToOpenApi30(base);
7578
+ break;
7579
+ default:
7580
+ throw new Error(`asStandardSchema: unsupported target "${target}". Supported: draft-2020-12, draft-07, openapi-3.0`);
7581
+ }
7582
+ cache.set(target, result);
7583
+ return result;
7584
+ };
7585
+ return {
7586
+ "~standard": {
7587
+ version: 1,
7588
+ vendor: "openpkg",
7589
+ jsonSchema: {
7590
+ input: build,
7591
+ output: build
7592
+ }
7593
+ }
7594
+ };
7595
+ }
7596
+ // src/schema/tool-schema.ts
7597
+ var OPENAI_ALLOWED_KEYWORDS = new Set([
7598
+ "type",
7599
+ "properties",
7600
+ "required",
7601
+ "additionalProperties",
7602
+ "items",
7603
+ "prefixItems",
7604
+ "anyOf",
7605
+ "enum",
7606
+ "const",
7607
+ "description",
7608
+ "title",
7609
+ "$ref",
7610
+ "$defs",
7611
+ "format"
7612
+ ]);
7613
+ function isObject(v) {
7614
+ return !!v && typeof v === "object" && !Array.isArray(v);
7615
+ }
7616
+ function isObjectNode(node) {
7617
+ return node.type === "object" || "properties" in node;
7618
+ }
7619
+ function isFunctionOnly(schema) {
7620
+ if (!isObject(schema))
7621
+ return false;
7622
+ if (!("x-ts-function" in schema))
7623
+ return false;
7624
+ const keys = Object.keys(schema).filter((k) => !k.startsWith("x-ts-"));
7625
+ return keys.length === 0;
7626
+ }
7627
+ function openAiStrict(node, warnings) {
7628
+ if (Array.isArray(node))
7629
+ return node.map((n) => openAiStrict(n, warnings));
7630
+ if (!isObject(node))
7631
+ return node;
7632
+ const src = { ...node };
7633
+ if ("oneOf" in src && !("anyOf" in src)) {
7634
+ src.anyOf = src.oneOf;
7635
+ delete src.oneOf;
7636
+ }
7637
+ if (Array.isArray(src.allOf)) {
7638
+ const branches = src.allOf;
7639
+ warnings.push("openai-strict: allOf is unsupported — using first branch");
7640
+ delete src.allOf;
7641
+ if (isObject(branches[0]))
7642
+ Object.assign(src, branches[0]);
7643
+ }
7644
+ const out = {};
7645
+ for (const [key, value] of Object.entries(src)) {
7646
+ if (key.startsWith("x-"))
7647
+ continue;
7648
+ if (key === "properties" && isObject(value)) {
7649
+ const props = {};
7650
+ const kept = [];
7651
+ for (const [propName, propSchema] of Object.entries(value)) {
7652
+ if (isFunctionOnly(propSchema)) {
7653
+ warnings.push(`openai-strict: pruned function-typed property "${propName}"`);
7654
+ continue;
7655
+ }
7656
+ props[propName] = openAiStrict(propSchema, warnings);
7657
+ kept.push(propName);
7658
+ }
7659
+ out.properties = props;
7660
+ out.required = kept;
7661
+ continue;
7662
+ }
7663
+ if (key === "required")
7664
+ continue;
7665
+ if (key === "$defs" && isObject(value)) {
7666
+ out.$defs = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, openAiStrict(v, warnings)]));
7667
+ continue;
7668
+ }
7669
+ if (!OPENAI_ALLOWED_KEYWORDS.has(key) && key !== "anyOf" && !key.startsWith("$")) {
7670
+ warnings.push(`openai-strict: dropped unsupported keyword "${key}"`);
7671
+ continue;
7672
+ }
7673
+ out[key] = openAiStrict(value, warnings);
7674
+ }
7675
+ if (isObjectNode(out)) {
7676
+ out.type = "object";
7677
+ if (!("properties" in out))
7678
+ out.properties = {};
7679
+ if (!("required" in out))
7680
+ out.required = Object.keys(out.properties);
7681
+ if (out.additionalProperties !== undefined && out.additionalProperties !== false) {
7682
+ warnings.push("openai-strict: open-ended additionalProperties dropped (record types unsupported)");
7683
+ }
7684
+ out.additionalProperties = false;
7685
+ }
7686
+ return out;
7687
+ }
7688
+ function anthropic(node, warnings) {
7689
+ if (Array.isArray(node))
7690
+ return node.map((n) => anthropic(n, warnings));
7691
+ if (!isObject(node))
7692
+ return node;
7693
+ const out = {};
7694
+ for (const [key, value] of Object.entries(node)) {
7695
+ if (key.startsWith("x-ts-") || key === "x-enum-members")
7696
+ continue;
7697
+ if (key === "properties" && isObject(value)) {
7698
+ const props = {};
7699
+ const dropped = new Set;
7700
+ for (const [propName, propSchema] of Object.entries(value)) {
7701
+ if (isFunctionOnly(propSchema)) {
7702
+ warnings.push(`anthropic: pruned function-typed property "${propName}"`);
7703
+ dropped.add(propName);
7704
+ continue;
7705
+ }
7706
+ props[propName] = anthropic(propSchema, warnings);
7707
+ }
7708
+ out.properties = props;
7709
+ if (Array.isArray(node.required)) {
7710
+ out.required = node.required.filter((r) => !dropped.has(r));
7711
+ }
7712
+ continue;
7713
+ }
7714
+ if (key === "required")
7715
+ continue;
7716
+ out[key] = anthropic(value, warnings);
7717
+ }
7718
+ return out;
7719
+ }
7720
+ function toToolSchema(exp, spec, options) {
7721
+ if (exp.kind !== "function" || !exp.signatures || exp.signatures.length === 0) {
7722
+ throw new TypeError(`toToolSchema: export "${exp.name}" is not a function with signatures (kind: ${exp.kind})`);
7723
+ }
7724
+ const sig = exp.signatures[options.signatureIndex ?? 0] ?? exp.signatures[0];
7725
+ const warnings = [];
7726
+ const properties = {};
7727
+ const required = [];
7728
+ for (const param of sig.parameters ?? []) {
7729
+ let paramSchema = normalizeSchema(param.schema);
7730
+ if (param.rest) {
7731
+ paramSchema = { type: "array", items: paramSchema };
7732
+ }
7733
+ if (param.description && !paramSchema.description) {
7734
+ paramSchema.description = param.description;
7735
+ }
7736
+ properties[param.name] = paramSchema;
7737
+ if (param.required !== false)
7738
+ required.push(param.name);
7739
+ }
7740
+ const wrapper = {
7741
+ type: "object",
7742
+ properties,
7743
+ ...required.length > 0 ? { required } : {}
7744
+ };
7745
+ const typeParameterNames = [
7746
+ ...(exp.typeParameters ?? []).map((p) => p.name),
7747
+ ...(sig.typeParameters ?? []).map((p) => p.name)
7748
+ ];
7749
+ const bundled = bundleRefs(wrapper, spec, { keepExtensions: true, typeParameterNames });
7750
+ warnings.push(...bundled.warnings);
7751
+ let parameters = { ...bundled.schema };
7752
+ if (Object.keys(bundled.defs).length > 0)
7753
+ parameters.$defs = bundled.defs;
7754
+ if (options.provider === "openai-strict") {
7755
+ parameters = openAiStrict(parameters, warnings);
7756
+ } else {
7757
+ parameters = stripTsExtensions(anthropic(parameters, warnings));
7758
+ }
7759
+ const description = exp.description ?? sig.description;
7760
+ return {
7761
+ name: exp.name,
7762
+ ...description ? { description } : {},
7763
+ parameters,
7764
+ warnings
7765
+ };
7766
+ }
7086
7767
  // src/types/utils.ts
7087
7768
  import ts18 from "typescript";
7088
7769
  function isExported(node) {
@@ -7102,13 +7783,16 @@ export {
7102
7783
  zodAdapter,
7103
7784
  withDescription,
7104
7785
  withDeprecated,
7786
+ validateSpec2 as validateSpec,
7105
7787
  valibotAdapter,
7106
7788
  typeboxAdapter,
7789
+ toToolSchema,
7107
7790
  toSearchIndexJSON,
7108
7791
  toSearchIndex,
7109
7792
  toPagefindRecords,
7110
7793
  toNavigation,
7111
7794
  toMarkdown,
7795
+ toJsonSchema,
7112
7796
  toJSONString,
7113
7797
  toJSON,
7114
7798
  toHTML,
@@ -7116,6 +7800,7 @@ export {
7116
7800
  toDocusaurusSidebarJS,
7117
7801
  toAlgoliaRecords,
7118
7802
  stripUndefinedFromType,
7803
+ stripTsExtensions,
7119
7804
  sortByName,
7120
7805
  shouldEmitAliasTypeText,
7121
7806
  serializeVariable,
@@ -7159,6 +7844,7 @@ export {
7159
7844
  isAnonymous,
7160
7845
  hasDeprecatedTag,
7161
7846
  groupByVisibility,
7847
+ getValidationErrors,
7162
7848
  getTypeOrigin,
7163
7849
  getSourceLocation,
7164
7850
  getProperties,
@@ -7171,6 +7857,7 @@ export {
7171
7857
  getExportKind,
7172
7858
  getExport,
7173
7859
  getDeprecationMessage,
7860
+ getAvailableVersions,
7174
7861
  toMarkdown as generateDocs,
7175
7862
  formatTypeParameters,
7176
7863
  formatSchema,
@@ -7192,6 +7879,7 @@ export {
7192
7879
  extractParameters,
7193
7880
  extract,
7194
7881
  exportToMarkdown,
7882
+ exportToJsonSchema,
7195
7883
  ensureNonEmptySchema,
7196
7884
  diffSpec2 as diffSpecs,
7197
7885
  diffSpec,
@@ -7202,10 +7890,13 @@ export {
7202
7890
  createDocs,
7203
7891
  categorizeBreakingChanges,
7204
7892
  calculateNextVersion,
7893
+ bundleRefs,
7205
7894
  buildSignatureString,
7206
7895
  buildSchema,
7207
7896
  buildObjectSchema,
7208
7897
  buildFunctionSchema,
7898
+ assertSpec,
7899
+ asStandardSchema,
7209
7900
  arktypeAdapter,
7210
7901
  analyzeSpec,
7211
7902
  TypeRegistry,
@@ -7213,6 +7904,7 @@ export {
7213
7904
  QueryBuilder,
7214
7905
  PRIMITIVES,
7215
7906
  NUMBER_PROTOTYPE_METHODS,
7907
+ LATEST_VERSION,
7216
7908
  CacheManager,
7217
7909
  CONFIG_FILENAME,
7218
7910
  BUILTIN_TYPE_SCHEMAS,