@discomedia/utils 1.0.61 → 1.0.63

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.
package/dist/index.cjs CHANGED
@@ -1150,6 +1150,8 @@ function isOpenRouterModel(model) {
1150
1150
  'openai/gpt-5-mini',
1151
1151
  'openai/gpt-5-nano',
1152
1152
  'openai/gpt-5.1',
1153
+ 'openai/gpt-5.4',
1154
+ 'openai/gpt-5.4-pro',
1153
1155
  'openai/gpt-5.2',
1154
1156
  'openai/gpt-5.2-pro',
1155
1157
  'openai/gpt-5.1-codex',
@@ -1579,7 +1581,7 @@ function maybeObj(x) {
1579
1581
  return x ?? {};
1580
1582
  }
1581
1583
  // https://stackoverflow.com/a/34491287
1582
- function isEmptyObj(obj) {
1584
+ function isEmptyObj$1(obj) {
1583
1585
  if (!obj)
1584
1586
  return true;
1585
1587
  for (const _k in obj)
@@ -3318,6 +3320,20 @@ let Messages$1 = class Messages extends APIResource {
3318
3320
  function isChatCompletionFunctionTool(tool) {
3319
3321
  return tool !== undefined && 'function' in tool && tool.function !== undefined;
3320
3322
  }
3323
+ function makeParseableTextFormat(response_format, parser) {
3324
+ const obj = { ...response_format };
3325
+ Object.defineProperties(obj, {
3326
+ $brand: {
3327
+ value: 'auto-parseable-response-format',
3328
+ enumerable: false,
3329
+ },
3330
+ $parseRaw: {
3331
+ value: parser,
3332
+ enumerable: false,
3333
+ },
3334
+ });
3335
+ return obj;
3336
+ }
3321
3337
  function isAutoParsableResponseFormat(response_format) {
3322
3338
  return response_format?.['$brand'] === 'auto-parseable-response-format';
3323
3339
  }
@@ -5330,7 +5346,7 @@ const readEnv = (env) => {
5330
5346
  return undefined;
5331
5347
  };
5332
5348
 
5333
- var _AssistantStream_instances, _a$1, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun;
5349
+ var _AssistantStream_instances, _a$2, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun;
5334
5350
  class AssistantStream extends EventStream {
5335
5351
  constructor() {
5336
5352
  super(...arguments);
@@ -5405,7 +5421,7 @@ class AssistantStream extends EventStream {
5405
5421
  };
5406
5422
  }
5407
5423
  static fromReadableStream(stream) {
5408
- const runner = new _a$1();
5424
+ const runner = new _a$2();
5409
5425
  runner._run(() => runner._fromReadableStream(stream));
5410
5426
  return runner;
5411
5427
  }
@@ -5431,7 +5447,7 @@ class AssistantStream extends EventStream {
5431
5447
  return stream.toReadableStream();
5432
5448
  }
5433
5449
  static createToolAssistantStream(runId, runs, params, options) {
5434
- const runner = new _a$1();
5450
+ const runner = new _a$2();
5435
5451
  runner._run(() => runner._runToolAssistantStream(runId, runs, params, {
5436
5452
  ...options,
5437
5453
  headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },
@@ -5460,7 +5476,7 @@ class AssistantStream extends EventStream {
5460
5476
  return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
5461
5477
  }
5462
5478
  static createThreadAssistantStream(params, thread, options) {
5463
- const runner = new _a$1();
5479
+ const runner = new _a$2();
5464
5480
  runner._run(() => runner._threadAssistantStream(params, thread, {
5465
5481
  ...options,
5466
5482
  headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },
@@ -5468,7 +5484,7 @@ class AssistantStream extends EventStream {
5468
5484
  return runner;
5469
5485
  }
5470
5486
  static createAssistantStream(threadId, runs, params, options) {
5471
- const runner = new _a$1();
5487
+ const runner = new _a$2();
5472
5488
  runner._run(() => runner._runAssistantStream(threadId, runs, params, {
5473
5489
  ...options,
5474
5490
  headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },
@@ -5610,7 +5626,7 @@ class AssistantStream extends EventStream {
5610
5626
  return await this._createToolAssistantStream(runs, runId, params, options);
5611
5627
  }
5612
5628
  }
5613
- _a$1 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
5629
+ _a$2 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) {
5614
5630
  if (this.ended)
5615
5631
  return;
5616
5632
  __classPrivateFieldSet(this, _AssistantStream_currentEvent, event);
@@ -5788,7 +5804,7 @@ _a$1 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_ad
5788
5804
  }
5789
5805
  let data = event.data;
5790
5806
  if (data.delta) {
5791
- const accumulated = _a$1.accumulateDelta(snapshot, data.delta);
5807
+ const accumulated = _a$2.accumulateDelta(snapshot, data.delta);
5792
5808
  __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
5793
5809
  }
5794
5810
  return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
@@ -5842,7 +5858,7 @@ _a$1 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_ad
5842
5858
  }
5843
5859
  throw Error('Tried to accumulate a non-message event');
5844
5860
  }, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) {
5845
- return _a$1.accumulateDelta(currentContent, contentElement);
5861
+ return _a$2.accumulateDelta(currentContent, contentElement);
5846
5862
  }, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) {
5847
5863
  __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data);
5848
5864
  switch (event.event) {
@@ -8260,7 +8276,7 @@ _Webhooks_instances = new WeakSet(), _Webhooks_validateSecret = function _Webhoo
8260
8276
  };
8261
8277
 
8262
8278
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8263
- var _OpenAI_instances, _a, _OpenAI_encoder, _OpenAI_baseURLOverridden;
8279
+ var _OpenAI_instances, _a$1, _OpenAI_encoder, _OpenAI_baseURLOverridden;
8264
8280
  /**
8265
8281
  * API Client for interfacing with the OpenAI API.
8266
8282
  */
@@ -8351,7 +8367,7 @@ class OpenAI {
8351
8367
  throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
8352
8368
  }
8353
8369
  this.baseURL = options.baseURL;
8354
- this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
8370
+ this.timeout = options.timeout ?? _a$1.DEFAULT_TIMEOUT /* 10 minutes */;
8355
8371
  this.logger = options.logger ?? console;
8356
8372
  const defaultLogLevel = 'warn';
8357
8373
  // Set default logLevel early so that we can log a warning in parseLogLevel.
@@ -8439,7 +8455,7 @@ class OpenAI {
8439
8455
  new URL(path)
8440
8456
  : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
8441
8457
  const defaultQuery = this.defaultQuery();
8442
- if (!isEmptyObj(defaultQuery)) {
8458
+ if (!isEmptyObj$1(defaultQuery)) {
8443
8459
  query = { ...defaultQuery, ...query };
8444
8460
  }
8445
8461
  if (typeof query === 'object' && query && !Array.isArray(query)) {
@@ -8781,10 +8797,10 @@ class OpenAI {
8781
8797
  }
8782
8798
  }
8783
8799
  }
8784
- _a = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() {
8800
+ _a$1 = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() {
8785
8801
  return this.baseURL !== 'https://api.openai.com/v1';
8786
8802
  };
8787
- OpenAI.OpenAI = _a;
8803
+ OpenAI.OpenAI = _a$1;
8788
8804
  OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes
8789
8805
  OpenAI.OpenAIError = OpenAIError;
8790
8806
  OpenAI.APIError = APIError;
@@ -8824,238 +8840,3050 @@ OpenAI.Containers = Containers;
8824
8840
  OpenAI.Skills = Skills;
8825
8841
  OpenAI.Videos = Videos;
8826
8842
 
8827
- // llm-openai-config.ts
8828
- const DEFAULT_MODEL = 'gpt-4.1-mini';
8829
- /** Token costs in USD per 1M tokens. Last updated Feb 2025. */
8830
- const openAiModelCosts = {
8831
- 'gpt-4o': {
8832
- inputCost: 2.5 / 1_000_000,
8833
- outputCost: 10 / 1_000_000,
8834
- },
8835
- 'gpt-4o-mini': {
8836
- inputCost: 0.15 / 1_000_000,
8837
- outputCost: 0.6 / 1_000_000,
8838
- },
8839
- 'o1-mini': {
8840
- inputCost: 1.1 / 1_000_000,
8841
- outputCost: 4.4 / 1_000_000,
8842
- },
8843
- 'o1': {
8844
- inputCost: 15 / 1_000_000,
8845
- outputCost: 60 / 1_000_000,
8846
- },
8847
- 'o3-mini': {
8848
- inputCost: 1.1 / 1_000_000,
8849
- outputCost: 4.4 / 1_000_000,
8850
- },
8851
- 'o3': {
8852
- inputCost: 2 / 1_000_000,
8853
- outputCost: 8 / 1_000_000,
8854
- },
8855
- 'gpt-4.1': {
8856
- inputCost: 2 / 1_000_000,
8857
- outputCost: 8 / 1_000_000,
8858
- },
8859
- 'gpt-4.1-mini': {
8860
- inputCost: 0.4 / 1_000_000,
8861
- outputCost: 1.6 / 1_000_000,
8862
- },
8863
- 'gpt-4.1-nano': {
8864
- inputCost: 0.1 / 1_000_000,
8865
- outputCost: 0.4 / 1_000_000,
8866
- },
8867
- 'gpt-5': {
8868
- inputCost: 1.25 / 1_000_000,
8869
- outputCost: 10 / 1_000_000,
8870
- },
8871
- 'gpt-5-mini': {
8872
- inputCost: 0.25 / 1_000_000,
8873
- outputCost: 2 / 1_000_000,
8874
- },
8875
- 'gpt-5-nano': {
8876
- inputCost: 0.05 / 1_000_000,
8877
- outputCost: 0.4 / 1_000_000,
8878
- },
8879
- 'gpt-5.1': {
8880
- inputCost: 1.25 / 1_000_000,
8881
- outputCost: 10 / 1_000_000,
8882
- },
8883
- 'gpt-5.2': {
8884
- inputCost: 1.5 / 1_000_000,
8885
- outputCost: 12 / 1_000_000,
8886
- },
8887
- 'gpt-5.2-pro': {
8888
- inputCost: 3 / 1_000_000,
8889
- outputCost: 24 / 1_000_000,
8890
- },
8891
- 'gpt-5.1-codex': {
8892
- inputCost: 1.1 / 1_000_000,
8893
- outputCost: 8.8 / 1_000_000,
8894
- },
8895
- 'gpt-5.1-codex-max': {
8896
- inputCost: 1.8 / 1_000_000,
8897
- outputCost: 14.4 / 1_000_000,
8898
- },
8899
- 'o4-mini': {
8900
- inputCost: 1.1 / 1_000_000,
8901
- outputCost: 4.4 / 1_000_000,
8902
- },
8903
- };
8904
- const deepseekModelCosts = {
8905
- 'deepseek-chat': {
8906
- inputCost: 0.27 / 1_000_000, // $0.27 per 1M tokens (Cache miss price)
8907
- cacheHitCost: 0.07 / 1_000_000, // $0.07 per 1M tokens (Cache hit price)
8908
- outputCost: 1.1 / 1_000_000, // $1.10 per 1M tokens
8909
- },
8910
- 'deepseek-reasoner': {
8911
- inputCost: 0.55 / 1_000_000, // $0.55 per 1M tokens (Cache miss price)
8912
- cacheHitCost: 0.14 / 1_000_000, // $0.14 per 1M tokens (Cache hit price)
8913
- outputCost: 2.19 / 1_000_000, // $2.19 per 1M tokens
8914
- },
8915
- };
8916
- /** Image generation costs in USD per image. Based on OpenAI pricing as of Feb 2025. */
8917
- const openAiImageCosts = {
8918
- 'gpt-image-1': 0.0075, // $0.0075 per image for gpt-image-1
8919
- 'gpt-image-1.5': 0.0075, // Assumes parity pricing with gpt-image-1 until OpenAI publishes updated rates
8920
- };
8921
- /**
8922
- * Calculates the cost of generating images using OpenAI's Images API.
8923
- *
8924
- * @param model The image generation model name.
8925
- * @param imageCount The number of images generated.
8926
- * @returns The cost of generating the images in USD.
8927
- */
8928
- function calculateImageCost(model, imageCount) {
8929
- if (typeof model !== 'string' || typeof imageCount !== 'number' || imageCount <= 0) {
8930
- return 0;
8843
+ // functions
8844
+ function getEnumValues(entries) {
8845
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
8846
+ const values = Object.entries(entries)
8847
+ .filter(([k, _]) => numericValues.indexOf(+k) === -1)
8848
+ .map(([_, v]) => v);
8849
+ return values;
8850
+ }
8851
+
8852
+ var _a;
8853
+ class $ZodRegistry {
8854
+ constructor() {
8855
+ this._map = new WeakMap();
8856
+ this._idmap = new Map();
8857
+ }
8858
+ add(schema, ..._meta) {
8859
+ const meta = _meta[0];
8860
+ this._map.set(schema, meta);
8861
+ if (meta && typeof meta === "object" && "id" in meta) {
8862
+ this._idmap.set(meta.id, schema);
8863
+ }
8864
+ return this;
8865
+ }
8866
+ clear() {
8867
+ this._map = new WeakMap();
8868
+ this._idmap = new Map();
8869
+ return this;
8870
+ }
8871
+ remove(schema) {
8872
+ const meta = this._map.get(schema);
8873
+ if (meta && typeof meta === "object" && "id" in meta) {
8874
+ this._idmap.delete(meta.id);
8875
+ }
8876
+ this._map.delete(schema);
8877
+ return this;
8878
+ }
8879
+ get(schema) {
8880
+ // return this._map.get(schema) as any;
8881
+ // inherit metadata
8882
+ const p = schema._zod.parent;
8883
+ if (p) {
8884
+ const pm = { ...(this.get(p) ?? {}) };
8885
+ delete pm.id; // do not inherit id
8886
+ const f = { ...pm, ...this._map.get(schema) };
8887
+ return Object.keys(f).length ? f : undefined;
8888
+ }
8889
+ return this._map.get(schema);
8890
+ }
8891
+ has(schema) {
8892
+ return this._map.has(schema);
8931
8893
  }
8932
- const costPerImage = openAiImageCosts[model];
8933
- if (!costPerImage)
8934
- return 0;
8935
- return imageCount * costPerImage;
8936
8894
  }
8937
- /**
8938
- * Calculates the cost of calling a language model in USD based on the provider and model, tokens, and given costs per 1M tokens.
8939
- *
8940
- * @param provider The provider of the language model. Supported providers are 'openai' and 'deepseek'.
8941
- * @param model The name of the language model. Supported models are listed in the `openAiModelCosts` and `deepseekModelCosts` objects.
8942
- * @param inputTokens The number of input tokens passed to the language model.
8943
- * @param outputTokens The number of output tokens generated by the language model.
8944
- * @param reasoningTokens The number of output tokens generated by the language model for reasoning. This is only used for Deepseek models.
8945
- * @param cacheHitTokens The number of input tokens that were cache hits for Deepseek models.
8946
- * @returns The cost of calling the language model in USD.
8947
- */
8948
- function calculateCost(provider, model, inputTokens, outputTokens, reasoningTokens, cacheHitTokens) {
8949
- if (typeof provider !== 'string' ||
8950
- typeof model !== 'string' ||
8951
- typeof inputTokens !== 'number' ||
8952
- typeof outputTokens !== 'number' ||
8953
- (reasoningTokens !== undefined && typeof reasoningTokens !== 'number') ||
8954
- (cacheHitTokens !== undefined && typeof cacheHitTokens !== 'number')) {
8955
- return 0;
8895
+ // registries
8896
+ function registry() {
8897
+ return new $ZodRegistry();
8898
+ }
8899
+ (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
8900
+ const globalRegistry = globalThis.__zod_globalRegistry;
8901
+
8902
+ // function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {
8903
+ // return {
8904
+ // processor: inputs.processor,
8905
+ // metadataRegistry: inputs.metadata ?? globalRegistry,
8906
+ // target: inputs.target ?? "draft-2020-12",
8907
+ // unrepresentable: inputs.unrepresentable ?? "throw",
8908
+ // };
8909
+ // }
8910
+ function initializeContext(params) {
8911
+ // Normalize target: convert old non-hyphenated versions to hyphenated versions
8912
+ let target = params?.target ?? "draft-2020-12";
8913
+ if (target === "draft-4")
8914
+ target = "draft-04";
8915
+ if (target === "draft-7")
8916
+ target = "draft-07";
8917
+ return {
8918
+ processors: params.processors ?? {},
8919
+ metadataRegistry: params?.metadata ?? globalRegistry,
8920
+ target,
8921
+ unrepresentable: params?.unrepresentable ?? "throw",
8922
+ override: params?.override ?? (() => { }),
8923
+ io: params?.io ?? "output",
8924
+ counter: 0,
8925
+ seen: new Map(),
8926
+ cycles: params?.cycles ?? "ref",
8927
+ reused: params?.reused ?? "inline",
8928
+ external: params?.external ?? undefined,
8929
+ };
8930
+ }
8931
+ function process$1(schema, ctx, _params = { path: [], schemaPath: [] }) {
8932
+ var _a;
8933
+ const def = schema._zod.def;
8934
+ // check for schema in seens
8935
+ const seen = ctx.seen.get(schema);
8936
+ if (seen) {
8937
+ seen.count++;
8938
+ // check if cycle
8939
+ const isCycle = _params.schemaPath.includes(schema);
8940
+ if (isCycle) {
8941
+ seen.cycle = _params.path;
8942
+ }
8943
+ return seen.schema;
8944
+ }
8945
+ // initialize
8946
+ const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
8947
+ ctx.seen.set(schema, result);
8948
+ // custom method overrides default behavior
8949
+ const overrideSchema = schema._zod.toJSONSchema?.();
8950
+ if (overrideSchema) {
8951
+ result.schema = overrideSchema;
8956
8952
  }
8957
- const modelCosts = provider === 'deepseek' ? deepseekModelCosts[model] : openAiModelCosts[model];
8958
- if (!modelCosts)
8959
- return 0;
8960
- // Calculate input cost based on cache hit/miss for Deepseek
8961
- const inputCost = provider === 'deepseek' && modelCosts.cacheHitCost
8962
- ? (cacheHitTokens || 0) * modelCosts.cacheHitCost + (inputTokens - (cacheHitTokens || 0)) * modelCosts.inputCost
8963
- : inputTokens * modelCosts.inputCost;
8964
- const outputCost = outputTokens * modelCosts.outputCost;
8965
- const reasoningCost = (reasoningTokens || 0) * modelCosts.outputCost;
8966
- return inputCost + outputCost + reasoningCost;
8953
+ else {
8954
+ const params = {
8955
+ ..._params,
8956
+ schemaPath: [..._params.schemaPath, schema],
8957
+ path: _params.path,
8958
+ };
8959
+ if (schema._zod.processJSONSchema) {
8960
+ schema._zod.processJSONSchema(ctx, result.schema, params);
8961
+ }
8962
+ else {
8963
+ const _json = result.schema;
8964
+ const processor = ctx.processors[def.type];
8965
+ if (!processor) {
8966
+ throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
8967
+ }
8968
+ processor(schema, ctx, _json, params);
8969
+ }
8970
+ const parent = schema._zod.parent;
8971
+ if (parent) {
8972
+ // Also set ref if processor didn't (for inheritance)
8973
+ if (!result.ref)
8974
+ result.ref = parent;
8975
+ process$1(parent, ctx, params);
8976
+ ctx.seen.get(parent).isParent = true;
8977
+ }
8978
+ }
8979
+ // metadata
8980
+ const meta = ctx.metadataRegistry.get(schema);
8981
+ if (meta)
8982
+ Object.assign(result.schema, meta);
8983
+ if (ctx.io === "input" && isTransforming(schema)) {
8984
+ // examples/defaults only apply to output type of pipe
8985
+ delete result.schema.examples;
8986
+ delete result.schema.default;
8987
+ }
8988
+ // set prefault as default
8989
+ if (ctx.io === "input" && result.schema._prefault)
8990
+ (_a = result.schema).default ?? (_a.default = result.schema._prefault);
8991
+ delete result.schema._prefault;
8992
+ // pulling fresh from ctx.seen in case it was overwritten
8993
+ const _result = ctx.seen.get(schema);
8994
+ return _result.schema;
8967
8995
  }
8968
-
8969
- /**
8970
- * Fix a broken JSON string by attempting to extract and parse valid JSON content. This function is very lenient and will attempt to fix many types of JSON errors, including unbalanced brackets, missing or extra commas, improperly escaped $ signs, unquoted strings, trailing commas, missing closing brackets or braces, etc.
8971
- * @param {string} jsonStr - The broken JSON string to fix
8972
- * @returns {JsonValue} - The parsed JSON value
8973
- */
8974
- function fixBrokenJson(jsonStr) {
8975
- // Pre-process: Fix improperly escaped $ signs
8976
- jsonStr = jsonStr.replace(/\\\$/g, '$');
8977
- let index = 0;
8978
- function parse() {
8979
- const results = [];
8980
- while (index < jsonStr.length) {
8981
- skipWhitespace();
8982
- const value = parseValue();
8983
- if (value !== undefined) {
8984
- results.push(value);
8996
+ function extractDefs(ctx, schema
8997
+ // params: EmitParams
8998
+ ) {
8999
+ // iterate over seen map;
9000
+ const root = ctx.seen.get(schema);
9001
+ if (!root)
9002
+ throw new Error("Unprocessed schema. This is a bug in Zod.");
9003
+ // Track ids to detect duplicates across different schemas
9004
+ const idToSchema = new Map();
9005
+ for (const entry of ctx.seen.entries()) {
9006
+ const id = ctx.metadataRegistry.get(entry[0])?.id;
9007
+ if (id) {
9008
+ const existing = idToSchema.get(id);
9009
+ if (existing && existing !== entry[0]) {
9010
+ throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
8985
9011
  }
8986
- else {
8987
- index++; // Skip invalid character
9012
+ idToSchema.set(id, entry[0]);
9013
+ }
9014
+ }
9015
+ // returns a ref to the schema
9016
+ // defId will be empty if the ref points to an external schema (or #)
9017
+ const makeURI = (entry) => {
9018
+ // comparing the seen objects because sometimes
9019
+ // multiple schemas map to the same seen object.
9020
+ // e.g. lazy
9021
+ // external is configured
9022
+ const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
9023
+ if (ctx.external) {
9024
+ const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`;
9025
+ // check if schema is in the external registry
9026
+ const uriGenerator = ctx.external.uri ?? ((id) => id);
9027
+ if (externalId) {
9028
+ return { ref: uriGenerator(externalId) };
9029
+ }
9030
+ // otherwise, add to __shared
9031
+ const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
9032
+ entry[1].defId = id; // set defId so it will be reused if needed
9033
+ return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
9034
+ }
9035
+ if (entry[1] === root) {
9036
+ return { ref: "#" };
9037
+ }
9038
+ // self-contained schema
9039
+ const uriPrefix = `#`;
9040
+ const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
9041
+ const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
9042
+ return { defId, ref: defUriPrefix + defId };
9043
+ };
9044
+ // stored cached version in `def` property
9045
+ // remove all properties, set $ref
9046
+ const extractToDef = (entry) => {
9047
+ // if the schema is already a reference, do not extract it
9048
+ if (entry[1].schema.$ref) {
9049
+ return;
9050
+ }
9051
+ const seen = entry[1];
9052
+ const { ref, defId } = makeURI(entry);
9053
+ seen.def = { ...seen.schema };
9054
+ // defId won't be set if the schema is a reference to an external schema
9055
+ // or if the schema is the root schema
9056
+ if (defId)
9057
+ seen.defId = defId;
9058
+ // wipe away all properties except $ref
9059
+ const schema = seen.schema;
9060
+ for (const key in schema) {
9061
+ delete schema[key];
9062
+ }
9063
+ schema.$ref = ref;
9064
+ };
9065
+ // throw on cycles
9066
+ // break cycles
9067
+ if (ctx.cycles === "throw") {
9068
+ for (const entry of ctx.seen.entries()) {
9069
+ const seen = entry[1];
9070
+ if (seen.cycle) {
9071
+ throw new Error("Cycle detected: " +
9072
+ `#/${seen.cycle?.join("/")}/<root>` +
9073
+ '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
8988
9074
  }
8989
9075
  }
8990
- return results.length === 1 ? results[0] : results;
8991
9076
  }
8992
- function parseValue() {
8993
- skipWhitespace();
8994
- const char = getChar();
8995
- if (!char)
8996
- return undefined;
8997
- if (char === '{')
8998
- return parseObject();
8999
- if (char === '[')
9000
- return parseArray();
9001
- if (char === '"' || char === "'")
9002
- return parseString();
9003
- if (char === 't' && jsonStr.slice(index, index + 4).toLowerCase() === 'true') {
9004
- index += 4;
9005
- return true;
9077
+ // extract schemas into $defs
9078
+ for (const entry of ctx.seen.entries()) {
9079
+ const seen = entry[1];
9080
+ // convert root schema to # $ref
9081
+ if (schema === entry[0]) {
9082
+ extractToDef(entry); // this has special handling for the root schema
9083
+ continue;
9006
9084
  }
9007
- if (char === 'f' && jsonStr.slice(index, index + 5).toLowerCase() === 'false') {
9008
- index += 5;
9009
- return false;
9085
+ // extract schemas that are in the external registry
9086
+ if (ctx.external) {
9087
+ const ext = ctx.external.registry.get(entry[0])?.id;
9088
+ if (schema !== entry[0] && ext) {
9089
+ extractToDef(entry);
9090
+ continue;
9091
+ }
9010
9092
  }
9011
- if (char === 'n' && jsonStr.slice(index, index + 4).toLowerCase() === 'null') {
9012
- index += 4;
9013
- return null;
9093
+ // extract schemas with `id` meta
9094
+ const id = ctx.metadataRegistry.get(entry[0])?.id;
9095
+ if (id) {
9096
+ extractToDef(entry);
9097
+ continue;
9014
9098
  }
9015
- if (/[a-zA-Z]/.test(char))
9016
- return parseString(); // Unquoted string
9017
- if (char === '-' || char === '.' || /\d/.test(char))
9018
- return parseNumber();
9019
- return undefined; // Unknown character
9020
- }
9021
- function parseObject() {
9022
- const obj = {};
9023
- index++; // Skip opening brace
9024
- skipWhitespace();
9025
- while (index < jsonStr.length && getChar() !== '}') {
9026
- skipWhitespace();
9027
- const key = parseString();
9028
- if (key === undefined) {
9029
- console.warn(`Expected key at position ${index}`);
9030
- index++;
9099
+ // break cycles
9100
+ if (seen.cycle) {
9101
+ // any
9102
+ extractToDef(entry);
9103
+ continue;
9104
+ }
9105
+ // extract reused schemas
9106
+ if (seen.count > 1) {
9107
+ if (ctx.reused === "ref") {
9108
+ extractToDef(entry);
9109
+ // biome-ignore lint:
9031
9110
  continue;
9032
9111
  }
9033
- skipWhitespace();
9034
- if (getChar() === ':') {
9035
- index++; // Skip colon
9112
+ }
9113
+ }
9114
+ }
9115
+ function finalize(ctx, schema) {
9116
+ const root = ctx.seen.get(schema);
9117
+ if (!root)
9118
+ throw new Error("Unprocessed schema. This is a bug in Zod.");
9119
+ // flatten refs - inherit properties from parent schemas
9120
+ const flattenRef = (zodSchema) => {
9121
+ const seen = ctx.seen.get(zodSchema);
9122
+ // already processed
9123
+ if (seen.ref === null)
9124
+ return;
9125
+ const schema = seen.def ?? seen.schema;
9126
+ const _cached = { ...schema };
9127
+ const ref = seen.ref;
9128
+ seen.ref = null; // prevent infinite recursion
9129
+ if (ref) {
9130
+ flattenRef(ref);
9131
+ const refSeen = ctx.seen.get(ref);
9132
+ const refSchema = refSeen.schema;
9133
+ // merge referenced schema into current
9134
+ if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
9135
+ // older drafts can't combine $ref with other properties
9136
+ schema.allOf = schema.allOf ?? [];
9137
+ schema.allOf.push(refSchema);
9036
9138
  }
9037
9139
  else {
9038
- console.warn(`Missing colon after key "${key}" at position ${index}`);
9140
+ Object.assign(schema, refSchema);
9039
9141
  }
9040
- skipWhitespace();
9041
- const value = parseValue();
9042
- if (value === undefined) {
9043
- console.warn(`Expected value for key "${key}" at position ${index}`);
9044
- index++;
9045
- continue;
9142
+ // restore child's own properties (child wins)
9143
+ Object.assign(schema, _cached);
9144
+ const isParentRef = zodSchema._zod.parent === ref;
9145
+ // For parent chain, child is a refinement - remove parent-only properties
9146
+ if (isParentRef) {
9147
+ for (const key in schema) {
9148
+ if (key === "$ref" || key === "allOf")
9149
+ continue;
9150
+ if (!(key in _cached)) {
9151
+ delete schema[key];
9152
+ }
9153
+ }
9046
9154
  }
9047
- obj[key] = value;
9048
- skipWhitespace();
9049
- if (getChar() === ',') {
9050
- index++; // Skip comma
9155
+ // When ref was extracted to $defs, remove properties that match the definition
9156
+ if (refSchema.$ref && refSeen.def) {
9157
+ for (const key in schema) {
9158
+ if (key === "$ref" || key === "allOf")
9159
+ continue;
9160
+ if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {
9161
+ delete schema[key];
9162
+ }
9163
+ }
9051
9164
  }
9052
- else {
9053
- break;
9165
+ }
9166
+ // If parent was extracted (has $ref), propagate $ref to this schema
9167
+ // This handles cases like: readonly().meta({id}).describe()
9168
+ // where processor sets ref to innerType but parent should be referenced
9169
+ const parent = zodSchema._zod.parent;
9170
+ if (parent && parent !== ref) {
9171
+ // Ensure parent is processed first so its def has inherited properties
9172
+ flattenRef(parent);
9173
+ const parentSeen = ctx.seen.get(parent);
9174
+ if (parentSeen?.schema.$ref) {
9175
+ schema.$ref = parentSeen.schema.$ref;
9176
+ // De-duplicate with parent's definition
9177
+ if (parentSeen.def) {
9178
+ for (const key in schema) {
9179
+ if (key === "$ref" || key === "allOf")
9180
+ continue;
9181
+ if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {
9182
+ delete schema[key];
9183
+ }
9184
+ }
9185
+ }
9054
9186
  }
9055
- skipWhitespace();
9056
9187
  }
9057
- if (getChar() === '}') {
9058
- index++; // Skip closing brace
9188
+ // execute overrides
9189
+ ctx.override({
9190
+ zodSchema: zodSchema,
9191
+ jsonSchema: schema,
9192
+ path: seen.path ?? [],
9193
+ });
9194
+ };
9195
+ for (const entry of [...ctx.seen.entries()].reverse()) {
9196
+ flattenRef(entry[0]);
9197
+ }
9198
+ const result = {};
9199
+ if (ctx.target === "draft-2020-12") {
9200
+ result.$schema = "https://json-schema.org/draft/2020-12/schema";
9201
+ }
9202
+ else if (ctx.target === "draft-07") {
9203
+ result.$schema = "http://json-schema.org/draft-07/schema#";
9204
+ }
9205
+ else if (ctx.target === "draft-04") {
9206
+ result.$schema = "http://json-schema.org/draft-04/schema#";
9207
+ }
9208
+ else if (ctx.target === "openapi-3.0") ;
9209
+ else ;
9210
+ if (ctx.external?.uri) {
9211
+ const id = ctx.external.registry.get(schema)?.id;
9212
+ if (!id)
9213
+ throw new Error("Schema is missing an `id` property");
9214
+ result.$id = ctx.external.uri(id);
9215
+ }
9216
+ Object.assign(result, root.def ?? root.schema);
9217
+ // build defs object
9218
+ const defs = ctx.external?.defs ?? {};
9219
+ for (const entry of ctx.seen.entries()) {
9220
+ const seen = entry[1];
9221
+ if (seen.def && seen.defId) {
9222
+ defs[seen.defId] = seen.def;
9223
+ }
9224
+ }
9225
+ // set definitions in result
9226
+ if (ctx.external) ;
9227
+ else {
9228
+ if (Object.keys(defs).length > 0) {
9229
+ if (ctx.target === "draft-2020-12") {
9230
+ result.$defs = defs;
9231
+ }
9232
+ else {
9233
+ result.definitions = defs;
9234
+ }
9235
+ }
9236
+ }
9237
+ try {
9238
+ // this "finalizes" this schema and ensures all cycles are removed
9239
+ // each call to finalize() is functionally independent
9240
+ // though the seen map is shared
9241
+ const finalized = JSON.parse(JSON.stringify(result));
9242
+ Object.defineProperty(finalized, "~standard", {
9243
+ value: {
9244
+ ...schema["~standard"],
9245
+ jsonSchema: {
9246
+ input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
9247
+ output: createStandardJSONSchemaMethod(schema, "output", ctx.processors),
9248
+ },
9249
+ },
9250
+ enumerable: false,
9251
+ writable: false,
9252
+ });
9253
+ return finalized;
9254
+ }
9255
+ catch (_err) {
9256
+ throw new Error("Error converting schema to JSON.");
9257
+ }
9258
+ }
9259
+ function isTransforming(_schema, _ctx) {
9260
+ const ctx = _ctx ?? { seen: new Set() };
9261
+ if (ctx.seen.has(_schema))
9262
+ return false;
9263
+ ctx.seen.add(_schema);
9264
+ const def = _schema._zod.def;
9265
+ if (def.type === "transform")
9266
+ return true;
9267
+ if (def.type === "array")
9268
+ return isTransforming(def.element, ctx);
9269
+ if (def.type === "set")
9270
+ return isTransforming(def.valueType, ctx);
9271
+ if (def.type === "lazy")
9272
+ return isTransforming(def.getter(), ctx);
9273
+ if (def.type === "promise" ||
9274
+ def.type === "optional" ||
9275
+ def.type === "nonoptional" ||
9276
+ def.type === "nullable" ||
9277
+ def.type === "readonly" ||
9278
+ def.type === "default" ||
9279
+ def.type === "prefault") {
9280
+ return isTransforming(def.innerType, ctx);
9281
+ }
9282
+ if (def.type === "intersection") {
9283
+ return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
9284
+ }
9285
+ if (def.type === "record" || def.type === "map") {
9286
+ return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
9287
+ }
9288
+ if (def.type === "pipe") {
9289
+ return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
9290
+ }
9291
+ if (def.type === "object") {
9292
+ for (const key in def.shape) {
9293
+ if (isTransforming(def.shape[key], ctx))
9294
+ return true;
9295
+ }
9296
+ return false;
9297
+ }
9298
+ if (def.type === "union") {
9299
+ for (const option of def.options) {
9300
+ if (isTransforming(option, ctx))
9301
+ return true;
9302
+ }
9303
+ return false;
9304
+ }
9305
+ if (def.type === "tuple") {
9306
+ for (const item of def.items) {
9307
+ if (isTransforming(item, ctx))
9308
+ return true;
9309
+ }
9310
+ if (def.rest && isTransforming(def.rest, ctx))
9311
+ return true;
9312
+ return false;
9313
+ }
9314
+ return false;
9315
+ }
9316
+ const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
9317
+ const { libraryOptions, target } = params ?? {};
9318
+ const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });
9319
+ process$1(schema, ctx);
9320
+ extractDefs(ctx, schema);
9321
+ return finalize(ctx, schema);
9322
+ };
9323
+
9324
+ const formatMap = {
9325
+ guid: "uuid",
9326
+ url: "uri",
9327
+ datetime: "date-time",
9328
+ json_string: "json-string",
9329
+ regex: "", // do not set
9330
+ };
9331
+ // ==================== SIMPLE TYPE PROCESSORS ====================
9332
+ const stringProcessor = (schema, ctx, _json, _params) => {
9333
+ const json = _json;
9334
+ json.type = "string";
9335
+ const { minimum, maximum, format, patterns, contentEncoding } = schema._zod
9336
+ .bag;
9337
+ if (typeof minimum === "number")
9338
+ json.minLength = minimum;
9339
+ if (typeof maximum === "number")
9340
+ json.maxLength = maximum;
9341
+ // custom pattern overrides format
9342
+ if (format) {
9343
+ json.format = formatMap[format] ?? format;
9344
+ if (json.format === "")
9345
+ delete json.format; // empty format is not valid
9346
+ // JSON Schema format: "time" requires a full time with offset or Z
9347
+ // z.iso.time() does not include timezone information, so format: "time" should never be used
9348
+ if (format === "time") {
9349
+ delete json.format;
9350
+ }
9351
+ }
9352
+ if (contentEncoding)
9353
+ json.contentEncoding = contentEncoding;
9354
+ if (patterns && patterns.size > 0) {
9355
+ const regexes = [...patterns];
9356
+ if (regexes.length === 1)
9357
+ json.pattern = regexes[0].source;
9358
+ else if (regexes.length > 1) {
9359
+ json.allOf = [
9360
+ ...regexes.map((regex) => ({
9361
+ ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0"
9362
+ ? { type: "string" }
9363
+ : {}),
9364
+ pattern: regex.source,
9365
+ })),
9366
+ ];
9367
+ }
9368
+ }
9369
+ };
9370
+ const numberProcessor = (schema, ctx, _json, _params) => {
9371
+ const json = _json;
9372
+ const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
9373
+ if (typeof format === "string" && format.includes("int"))
9374
+ json.type = "integer";
9375
+ else
9376
+ json.type = "number";
9377
+ if (typeof exclusiveMinimum === "number") {
9378
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
9379
+ json.minimum = exclusiveMinimum;
9380
+ json.exclusiveMinimum = true;
9381
+ }
9382
+ else {
9383
+ json.exclusiveMinimum = exclusiveMinimum;
9384
+ }
9385
+ }
9386
+ if (typeof minimum === "number") {
9387
+ json.minimum = minimum;
9388
+ if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") {
9389
+ if (exclusiveMinimum >= minimum)
9390
+ delete json.minimum;
9391
+ else
9392
+ delete json.exclusiveMinimum;
9393
+ }
9394
+ }
9395
+ if (typeof exclusiveMaximum === "number") {
9396
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
9397
+ json.maximum = exclusiveMaximum;
9398
+ json.exclusiveMaximum = true;
9399
+ }
9400
+ else {
9401
+ json.exclusiveMaximum = exclusiveMaximum;
9402
+ }
9403
+ }
9404
+ if (typeof maximum === "number") {
9405
+ json.maximum = maximum;
9406
+ if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") {
9407
+ if (exclusiveMaximum <= maximum)
9408
+ delete json.maximum;
9409
+ else
9410
+ delete json.exclusiveMaximum;
9411
+ }
9412
+ }
9413
+ if (typeof multipleOf === "number")
9414
+ json.multipleOf = multipleOf;
9415
+ };
9416
+ const booleanProcessor = (_schema, _ctx, json, _params) => {
9417
+ json.type = "boolean";
9418
+ };
9419
+ const bigintProcessor = (_schema, ctx, _json, _params) => {
9420
+ if (ctx.unrepresentable === "throw") {
9421
+ throw new Error("BigInt cannot be represented in JSON Schema");
9422
+ }
9423
+ };
9424
+ const symbolProcessor = (_schema, ctx, _json, _params) => {
9425
+ if (ctx.unrepresentable === "throw") {
9426
+ throw new Error("Symbols cannot be represented in JSON Schema");
9427
+ }
9428
+ };
9429
+ const nullProcessor = (_schema, ctx, json, _params) => {
9430
+ if (ctx.target === "openapi-3.0") {
9431
+ json.type = "string";
9432
+ json.nullable = true;
9433
+ json.enum = [null];
9434
+ }
9435
+ else {
9436
+ json.type = "null";
9437
+ }
9438
+ };
9439
+ const undefinedProcessor = (_schema, ctx, _json, _params) => {
9440
+ if (ctx.unrepresentable === "throw") {
9441
+ throw new Error("Undefined cannot be represented in JSON Schema");
9442
+ }
9443
+ };
9444
+ const voidProcessor = (_schema, ctx, _json, _params) => {
9445
+ if (ctx.unrepresentable === "throw") {
9446
+ throw new Error("Void cannot be represented in JSON Schema");
9447
+ }
9448
+ };
9449
+ const neverProcessor = (_schema, _ctx, json, _params) => {
9450
+ json.not = {};
9451
+ };
9452
+ const anyProcessor = (_schema, _ctx, _json, _params) => {
9453
+ // empty schema accepts anything
9454
+ };
9455
+ const unknownProcessor = (_schema, _ctx, _json, _params) => {
9456
+ // empty schema accepts anything
9457
+ };
9458
+ const dateProcessor = (_schema, ctx, _json, _params) => {
9459
+ if (ctx.unrepresentable === "throw") {
9460
+ throw new Error("Date cannot be represented in JSON Schema");
9461
+ }
9462
+ };
9463
+ const enumProcessor = (schema, _ctx, json, _params) => {
9464
+ const def = schema._zod.def;
9465
+ const values = getEnumValues(def.entries);
9466
+ // Number enums can have both string and number values
9467
+ if (values.every((v) => typeof v === "number"))
9468
+ json.type = "number";
9469
+ if (values.every((v) => typeof v === "string"))
9470
+ json.type = "string";
9471
+ json.enum = values;
9472
+ };
9473
+ const literalProcessor = (schema, ctx, json, _params) => {
9474
+ const def = schema._zod.def;
9475
+ const vals = [];
9476
+ for (const val of def.values) {
9477
+ if (val === undefined) {
9478
+ if (ctx.unrepresentable === "throw") {
9479
+ throw new Error("Literal `undefined` cannot be represented in JSON Schema");
9480
+ }
9481
+ }
9482
+ else if (typeof val === "bigint") {
9483
+ if (ctx.unrepresentable === "throw") {
9484
+ throw new Error("BigInt literals cannot be represented in JSON Schema");
9485
+ }
9486
+ else {
9487
+ vals.push(Number(val));
9488
+ }
9489
+ }
9490
+ else {
9491
+ vals.push(val);
9492
+ }
9493
+ }
9494
+ if (vals.length === 0) ;
9495
+ else if (vals.length === 1) {
9496
+ const val = vals[0];
9497
+ json.type = val === null ? "null" : typeof val;
9498
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
9499
+ json.enum = [val];
9500
+ }
9501
+ else {
9502
+ json.const = val;
9503
+ }
9504
+ }
9505
+ else {
9506
+ if (vals.every((v) => typeof v === "number"))
9507
+ json.type = "number";
9508
+ if (vals.every((v) => typeof v === "string"))
9509
+ json.type = "string";
9510
+ if (vals.every((v) => typeof v === "boolean"))
9511
+ json.type = "boolean";
9512
+ if (vals.every((v) => v === null))
9513
+ json.type = "null";
9514
+ json.enum = vals;
9515
+ }
9516
+ };
9517
+ const nanProcessor = (_schema, ctx, _json, _params) => {
9518
+ if (ctx.unrepresentable === "throw") {
9519
+ throw new Error("NaN cannot be represented in JSON Schema");
9520
+ }
9521
+ };
9522
+ const templateLiteralProcessor = (schema, _ctx, json, _params) => {
9523
+ const _json = json;
9524
+ const pattern = schema._zod.pattern;
9525
+ if (!pattern)
9526
+ throw new Error("Pattern not found in template literal");
9527
+ _json.type = "string";
9528
+ _json.pattern = pattern.source;
9529
+ };
9530
+ const fileProcessor = (schema, _ctx, json, _params) => {
9531
+ const _json = json;
9532
+ const file = {
9533
+ type: "string",
9534
+ format: "binary",
9535
+ contentEncoding: "binary",
9536
+ };
9537
+ const { minimum, maximum, mime } = schema._zod.bag;
9538
+ if (minimum !== undefined)
9539
+ file.minLength = minimum;
9540
+ if (maximum !== undefined)
9541
+ file.maxLength = maximum;
9542
+ if (mime) {
9543
+ if (mime.length === 1) {
9544
+ file.contentMediaType = mime[0];
9545
+ Object.assign(_json, file);
9546
+ }
9547
+ else {
9548
+ Object.assign(_json, file); // shared props at root
9549
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs
9550
+ }
9551
+ }
9552
+ else {
9553
+ Object.assign(_json, file);
9554
+ }
9555
+ };
9556
+ const successProcessor = (_schema, _ctx, json, _params) => {
9557
+ json.type = "boolean";
9558
+ };
9559
+ const customProcessor = (_schema, ctx, _json, _params) => {
9560
+ if (ctx.unrepresentable === "throw") {
9561
+ throw new Error("Custom types cannot be represented in JSON Schema");
9562
+ }
9563
+ };
9564
+ const functionProcessor = (_schema, ctx, _json, _params) => {
9565
+ if (ctx.unrepresentable === "throw") {
9566
+ throw new Error("Function types cannot be represented in JSON Schema");
9567
+ }
9568
+ };
9569
+ const transformProcessor = (_schema, ctx, _json, _params) => {
9570
+ if (ctx.unrepresentable === "throw") {
9571
+ throw new Error("Transforms cannot be represented in JSON Schema");
9572
+ }
9573
+ };
9574
+ const mapProcessor = (_schema, ctx, _json, _params) => {
9575
+ if (ctx.unrepresentable === "throw") {
9576
+ throw new Error("Map cannot be represented in JSON Schema");
9577
+ }
9578
+ };
9579
+ const setProcessor = (_schema, ctx, _json, _params) => {
9580
+ if (ctx.unrepresentable === "throw") {
9581
+ throw new Error("Set cannot be represented in JSON Schema");
9582
+ }
9583
+ };
9584
+ // ==================== COMPOSITE TYPE PROCESSORS ====================
9585
+ const arrayProcessor = (schema, ctx, _json, params) => {
9586
+ const json = _json;
9587
+ const def = schema._zod.def;
9588
+ const { minimum, maximum } = schema._zod.bag;
9589
+ if (typeof minimum === "number")
9590
+ json.minItems = minimum;
9591
+ if (typeof maximum === "number")
9592
+ json.maxItems = maximum;
9593
+ json.type = "array";
9594
+ json.items = process$1(def.element, ctx, { ...params, path: [...params.path, "items"] });
9595
+ };
9596
+ const objectProcessor = (schema, ctx, _json, params) => {
9597
+ const json = _json;
9598
+ const def = schema._zod.def;
9599
+ json.type = "object";
9600
+ json.properties = {};
9601
+ const shape = def.shape;
9602
+ for (const key in shape) {
9603
+ json.properties[key] = process$1(shape[key], ctx, {
9604
+ ...params,
9605
+ path: [...params.path, "properties", key],
9606
+ });
9607
+ }
9608
+ // required keys
9609
+ const allKeys = new Set(Object.keys(shape));
9610
+ const requiredKeys = new Set([...allKeys].filter((key) => {
9611
+ const v = def.shape[key]._zod;
9612
+ if (ctx.io === "input") {
9613
+ return v.optin === undefined;
9614
+ }
9615
+ else {
9616
+ return v.optout === undefined;
9617
+ }
9618
+ }));
9619
+ if (requiredKeys.size > 0) {
9620
+ json.required = Array.from(requiredKeys);
9621
+ }
9622
+ // catchall
9623
+ if (def.catchall?._zod.def.type === "never") {
9624
+ // strict
9625
+ json.additionalProperties = false;
9626
+ }
9627
+ else if (!def.catchall) {
9628
+ // regular
9629
+ if (ctx.io === "output")
9630
+ json.additionalProperties = false;
9631
+ }
9632
+ else if (def.catchall) {
9633
+ json.additionalProperties = process$1(def.catchall, ctx, {
9634
+ ...params,
9635
+ path: [...params.path, "additionalProperties"],
9636
+ });
9637
+ }
9638
+ };
9639
+ const unionProcessor = (schema, ctx, json, params) => {
9640
+ const def = schema._zod.def;
9641
+ // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)
9642
+ // This includes both z.xor() and discriminated unions
9643
+ const isExclusive = def.inclusive === false;
9644
+ const options = def.options.map((x, i) => process$1(x, ctx, {
9645
+ ...params,
9646
+ path: [...params.path, isExclusive ? "oneOf" : "anyOf", i],
9647
+ }));
9648
+ if (isExclusive) {
9649
+ json.oneOf = options;
9650
+ }
9651
+ else {
9652
+ json.anyOf = options;
9653
+ }
9654
+ };
9655
+ const intersectionProcessor = (schema, ctx, json, params) => {
9656
+ const def = schema._zod.def;
9657
+ const a = process$1(def.left, ctx, {
9658
+ ...params,
9659
+ path: [...params.path, "allOf", 0],
9660
+ });
9661
+ const b = process$1(def.right, ctx, {
9662
+ ...params,
9663
+ path: [...params.path, "allOf", 1],
9664
+ });
9665
+ const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
9666
+ const allOf = [
9667
+ ...(isSimpleIntersection(a) ? a.allOf : [a]),
9668
+ ...(isSimpleIntersection(b) ? b.allOf : [b]),
9669
+ ];
9670
+ json.allOf = allOf;
9671
+ };
9672
+ const tupleProcessor = (schema, ctx, _json, params) => {
9673
+ const json = _json;
9674
+ const def = schema._zod.def;
9675
+ json.type = "array";
9676
+ const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
9677
+ const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
9678
+ const prefixItems = def.items.map((x, i) => process$1(x, ctx, {
9679
+ ...params,
9680
+ path: [...params.path, prefixPath, i],
9681
+ }));
9682
+ const rest = def.rest
9683
+ ? process$1(def.rest, ctx, {
9684
+ ...params,
9685
+ path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])],
9686
+ })
9687
+ : null;
9688
+ if (ctx.target === "draft-2020-12") {
9689
+ json.prefixItems = prefixItems;
9690
+ if (rest) {
9691
+ json.items = rest;
9692
+ }
9693
+ }
9694
+ else if (ctx.target === "openapi-3.0") {
9695
+ json.items = {
9696
+ anyOf: prefixItems,
9697
+ };
9698
+ if (rest) {
9699
+ json.items.anyOf.push(rest);
9700
+ }
9701
+ json.minItems = prefixItems.length;
9702
+ if (!rest) {
9703
+ json.maxItems = prefixItems.length;
9704
+ }
9705
+ }
9706
+ else {
9707
+ json.items = prefixItems;
9708
+ if (rest) {
9709
+ json.additionalItems = rest;
9710
+ }
9711
+ }
9712
+ // length
9713
+ const { minimum, maximum } = schema._zod.bag;
9714
+ if (typeof minimum === "number")
9715
+ json.minItems = minimum;
9716
+ if (typeof maximum === "number")
9717
+ json.maxItems = maximum;
9718
+ };
9719
+ const recordProcessor = (schema, ctx, _json, params) => {
9720
+ const json = _json;
9721
+ const def = schema._zod.def;
9722
+ json.type = "object";
9723
+ // For looseRecord with regex patterns, use patternProperties
9724
+ // This correctly represents "only validate keys matching the pattern" semantics
9725
+ // and composes well with allOf (intersections)
9726
+ const keyType = def.keyType;
9727
+ const keyBag = keyType._zod.bag;
9728
+ const patterns = keyBag?.patterns;
9729
+ if (def.mode === "loose" && patterns && patterns.size > 0) {
9730
+ // Use patternProperties for looseRecord with regex patterns
9731
+ const valueSchema = process$1(def.valueType, ctx, {
9732
+ ...params,
9733
+ path: [...params.path, "patternProperties", "*"],
9734
+ });
9735
+ json.patternProperties = {};
9736
+ for (const pattern of patterns) {
9737
+ json.patternProperties[pattern.source] = valueSchema;
9738
+ }
9739
+ }
9740
+ else {
9741
+ // Default behavior: use propertyNames + additionalProperties
9742
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
9743
+ json.propertyNames = process$1(def.keyType, ctx, {
9744
+ ...params,
9745
+ path: [...params.path, "propertyNames"],
9746
+ });
9747
+ }
9748
+ json.additionalProperties = process$1(def.valueType, ctx, {
9749
+ ...params,
9750
+ path: [...params.path, "additionalProperties"],
9751
+ });
9752
+ }
9753
+ // Add required for keys with discrete values (enum, literal, etc.)
9754
+ const keyValues = keyType._zod.values;
9755
+ if (keyValues) {
9756
+ const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
9757
+ if (validKeyValues.length > 0) {
9758
+ json.required = validKeyValues;
9759
+ }
9760
+ }
9761
+ };
9762
+ const nullableProcessor = (schema, ctx, json, params) => {
9763
+ const def = schema._zod.def;
9764
+ const inner = process$1(def.innerType, ctx, params);
9765
+ const seen = ctx.seen.get(schema);
9766
+ if (ctx.target === "openapi-3.0") {
9767
+ seen.ref = def.innerType;
9768
+ json.nullable = true;
9769
+ }
9770
+ else {
9771
+ json.anyOf = [inner, { type: "null" }];
9772
+ }
9773
+ };
9774
+ const nonoptionalProcessor = (schema, ctx, _json, params) => {
9775
+ const def = schema._zod.def;
9776
+ process$1(def.innerType, ctx, params);
9777
+ const seen = ctx.seen.get(schema);
9778
+ seen.ref = def.innerType;
9779
+ };
9780
+ const defaultProcessor = (schema, ctx, json, params) => {
9781
+ const def = schema._zod.def;
9782
+ process$1(def.innerType, ctx, params);
9783
+ const seen = ctx.seen.get(schema);
9784
+ seen.ref = def.innerType;
9785
+ json.default = JSON.parse(JSON.stringify(def.defaultValue));
9786
+ };
9787
+ const prefaultProcessor = (schema, ctx, json, params) => {
9788
+ const def = schema._zod.def;
9789
+ process$1(def.innerType, ctx, params);
9790
+ const seen = ctx.seen.get(schema);
9791
+ seen.ref = def.innerType;
9792
+ if (ctx.io === "input")
9793
+ json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
9794
+ };
9795
+ const catchProcessor = (schema, ctx, json, params) => {
9796
+ const def = schema._zod.def;
9797
+ process$1(def.innerType, ctx, params);
9798
+ const seen = ctx.seen.get(schema);
9799
+ seen.ref = def.innerType;
9800
+ let catchValue;
9801
+ try {
9802
+ catchValue = def.catchValue(undefined);
9803
+ }
9804
+ catch {
9805
+ throw new Error("Dynamic catch values are not supported in JSON Schema");
9806
+ }
9807
+ json.default = catchValue;
9808
+ };
9809
+ const pipeProcessor = (schema, ctx, _json, params) => {
9810
+ const def = schema._zod.def;
9811
+ const innerType = ctx.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out;
9812
+ process$1(innerType, ctx, params);
9813
+ const seen = ctx.seen.get(schema);
9814
+ seen.ref = innerType;
9815
+ };
9816
+ const readonlyProcessor = (schema, ctx, json, params) => {
9817
+ const def = schema._zod.def;
9818
+ process$1(def.innerType, ctx, params);
9819
+ const seen = ctx.seen.get(schema);
9820
+ seen.ref = def.innerType;
9821
+ json.readOnly = true;
9822
+ };
9823
+ const promiseProcessor = (schema, ctx, _json, params) => {
9824
+ const def = schema._zod.def;
9825
+ process$1(def.innerType, ctx, params);
9826
+ const seen = ctx.seen.get(schema);
9827
+ seen.ref = def.innerType;
9828
+ };
9829
+ const optionalProcessor = (schema, ctx, _json, params) => {
9830
+ const def = schema._zod.def;
9831
+ process$1(def.innerType, ctx, params);
9832
+ const seen = ctx.seen.get(schema);
9833
+ seen.ref = def.innerType;
9834
+ };
9835
+ const lazyProcessor = (schema, ctx, _json, params) => {
9836
+ const innerType = schema._zod.innerType;
9837
+ process$1(innerType, ctx, params);
9838
+ const seen = ctx.seen.get(schema);
9839
+ seen.ref = innerType;
9840
+ };
9841
+ // ==================== ALL PROCESSORS ====================
9842
+ const allProcessors = {
9843
+ string: stringProcessor,
9844
+ number: numberProcessor,
9845
+ boolean: booleanProcessor,
9846
+ bigint: bigintProcessor,
9847
+ symbol: symbolProcessor,
9848
+ null: nullProcessor,
9849
+ undefined: undefinedProcessor,
9850
+ void: voidProcessor,
9851
+ never: neverProcessor,
9852
+ any: anyProcessor,
9853
+ unknown: unknownProcessor,
9854
+ date: dateProcessor,
9855
+ enum: enumProcessor,
9856
+ literal: literalProcessor,
9857
+ nan: nanProcessor,
9858
+ template_literal: templateLiteralProcessor,
9859
+ file: fileProcessor,
9860
+ success: successProcessor,
9861
+ custom: customProcessor,
9862
+ function: functionProcessor,
9863
+ transform: transformProcessor,
9864
+ map: mapProcessor,
9865
+ set: setProcessor,
9866
+ array: arrayProcessor,
9867
+ object: objectProcessor,
9868
+ union: unionProcessor,
9869
+ intersection: intersectionProcessor,
9870
+ tuple: tupleProcessor,
9871
+ record: recordProcessor,
9872
+ nullable: nullableProcessor,
9873
+ nonoptional: nonoptionalProcessor,
9874
+ default: defaultProcessor,
9875
+ prefault: prefaultProcessor,
9876
+ catch: catchProcessor,
9877
+ pipe: pipeProcessor,
9878
+ readonly: readonlyProcessor,
9879
+ promise: promiseProcessor,
9880
+ optional: optionalProcessor,
9881
+ lazy: lazyProcessor,
9882
+ };
9883
+ function toJSONSchema(input, params) {
9884
+ if ("_idmap" in input) {
9885
+ // Registry case
9886
+ const registry = input;
9887
+ const ctx = initializeContext({ ...params, processors: allProcessors });
9888
+ const defs = {};
9889
+ // First pass: process all schemas to build the seen map
9890
+ for (const entry of registry._idmap.entries()) {
9891
+ const [_, schema] = entry;
9892
+ process$1(schema, ctx);
9893
+ }
9894
+ const schemas = {};
9895
+ const external = {
9896
+ registry,
9897
+ uri: params?.uri,
9898
+ defs,
9899
+ };
9900
+ // Update the context with external configuration
9901
+ ctx.external = external;
9902
+ // Second pass: emit each schema
9903
+ for (const entry of registry._idmap.entries()) {
9904
+ const [key, schema] = entry;
9905
+ extractDefs(ctx, schema);
9906
+ schemas[key] = finalize(ctx, schema);
9907
+ }
9908
+ if (Object.keys(defs).length > 0) {
9909
+ const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
9910
+ schemas.__shared = {
9911
+ [defsSegment]: defs,
9912
+ };
9913
+ }
9914
+ return { schemas };
9915
+ }
9916
+ // Single schema case
9917
+ const ctx = initializeContext({ ...params, processors: allProcessors });
9918
+ process$1(input, ctx);
9919
+ extractDefs(ctx, input);
9920
+ return finalize(ctx, input);
9921
+ }
9922
+
9923
+ const ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use');
9924
+ const defaultOptions = {
9925
+ name: undefined,
9926
+ $refStrategy: 'root',
9927
+ effectStrategy: 'input',
9928
+ pipeStrategy: 'all',
9929
+ dateStrategy: 'format:date-time',
9930
+ mapStrategy: 'entries',
9931
+ nullableStrategy: 'from-target',
9932
+ removeAdditionalStrategy: 'passthrough',
9933
+ definitionPath: 'definitions',
9934
+ target: 'jsonSchema7',
9935
+ strictUnions: false,
9936
+ errorMessages: false,
9937
+ markdownDescription: false,
9938
+ patternStrategy: 'escape',
9939
+ applyRegexFlags: false,
9940
+ emailStrategy: 'format:email',
9941
+ base64Strategy: 'contentEncoding:base64',
9942
+ nameStrategy: 'ref',
9943
+ };
9944
+ const getDefaultOptions = (options) => {
9945
+ // We need to add `definitions` here as we may mutate it
9946
+ return (typeof options === 'string' ?
9947
+ {
9948
+ ...defaultOptions,
9949
+ basePath: ['#'],
9950
+ definitions: {},
9951
+ name: options,
9952
+ }
9953
+ : {
9954
+ ...defaultOptions,
9955
+ basePath: ['#'],
9956
+ definitions: {},
9957
+ ...options,
9958
+ });
9959
+ };
9960
+
9961
+ const zodDef = (zodSchema) => {
9962
+ return '_def' in zodSchema ? zodSchema._def : zodSchema;
9963
+ };
9964
+ function isEmptyObj(obj) {
9965
+ if (!obj)
9966
+ return true;
9967
+ for (const _k in obj)
9968
+ return false;
9969
+ return true;
9970
+ }
9971
+
9972
+ const getRefs = (options) => {
9973
+ const _options = getDefaultOptions(options);
9974
+ const currentPath = _options.name !== undefined ?
9975
+ [..._options.basePath, _options.definitionPath, _options.name]
9976
+ : _options.basePath;
9977
+ return {
9978
+ ..._options,
9979
+ currentPath: currentPath,
9980
+ propertyPath: undefined,
9981
+ seenRefs: new Set(),
9982
+ seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
9983
+ zodDef(def),
9984
+ {
9985
+ def: zodDef(def),
9986
+ path: [..._options.basePath, _options.definitionPath, name],
9987
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
9988
+ jsonSchema: undefined,
9989
+ },
9990
+ ])),
9991
+ };
9992
+ };
9993
+
9994
+ function addErrorMessage(res, key, errorMessage, refs) {
9995
+ if (!refs?.errorMessages)
9996
+ return;
9997
+ if (errorMessage) {
9998
+ res.errorMessage = {
9999
+ ...res.errorMessage,
10000
+ [key]: errorMessage,
10001
+ };
10002
+ }
10003
+ }
10004
+ function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
10005
+ res[key] = value;
10006
+ addErrorMessage(res, key, errorMessage, refs);
10007
+ }
10008
+
10009
+ var util;
10010
+ (function (util) {
10011
+ util.assertEqual = (_) => { };
10012
+ function assertIs(_arg) { }
10013
+ util.assertIs = assertIs;
10014
+ function assertNever(_x) {
10015
+ throw new Error();
10016
+ }
10017
+ util.assertNever = assertNever;
10018
+ util.arrayToEnum = (items) => {
10019
+ const obj = {};
10020
+ for (const item of items) {
10021
+ obj[item] = item;
10022
+ }
10023
+ return obj;
10024
+ };
10025
+ util.getValidEnumValues = (obj) => {
10026
+ const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
10027
+ const filtered = {};
10028
+ for (const k of validKeys) {
10029
+ filtered[k] = obj[k];
10030
+ }
10031
+ return util.objectValues(filtered);
10032
+ };
10033
+ util.objectValues = (obj) => {
10034
+ return util.objectKeys(obj).map(function (e) {
10035
+ return obj[e];
10036
+ });
10037
+ };
10038
+ util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
10039
+ ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
10040
+ : (object) => {
10041
+ const keys = [];
10042
+ for (const key in object) {
10043
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
10044
+ keys.push(key);
10045
+ }
10046
+ }
10047
+ return keys;
10048
+ };
10049
+ util.find = (arr, checker) => {
10050
+ for (const item of arr) {
10051
+ if (checker(item))
10052
+ return item;
10053
+ }
10054
+ return undefined;
10055
+ };
10056
+ util.isInteger = typeof Number.isInteger === "function"
10057
+ ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
10058
+ : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
10059
+ function joinValues(array, separator = " | ") {
10060
+ return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
10061
+ }
10062
+ util.joinValues = joinValues;
10063
+ util.jsonStringifyReplacer = (_, value) => {
10064
+ if (typeof value === "bigint") {
10065
+ return value.toString();
10066
+ }
10067
+ return value;
10068
+ };
10069
+ })(util || (util = {}));
10070
+ var objectUtil;
10071
+ (function (objectUtil) {
10072
+ objectUtil.mergeShapes = (first, second) => {
10073
+ return {
10074
+ ...first,
10075
+ ...second, // second overwrites first
10076
+ };
10077
+ };
10078
+ })(objectUtil || (objectUtil = {}));
10079
+ util.arrayToEnum([
10080
+ "string",
10081
+ "nan",
10082
+ "number",
10083
+ "integer",
10084
+ "float",
10085
+ "boolean",
10086
+ "date",
10087
+ "bigint",
10088
+ "symbol",
10089
+ "function",
10090
+ "undefined",
10091
+ "null",
10092
+ "array",
10093
+ "object",
10094
+ "unknown",
10095
+ "promise",
10096
+ "void",
10097
+ "never",
10098
+ "map",
10099
+ "set",
10100
+ ]);
10101
+
10102
+ util.arrayToEnum([
10103
+ "invalid_type",
10104
+ "invalid_literal",
10105
+ "custom",
10106
+ "invalid_union",
10107
+ "invalid_union_discriminator",
10108
+ "invalid_enum_value",
10109
+ "unrecognized_keys",
10110
+ "invalid_arguments",
10111
+ "invalid_return_type",
10112
+ "invalid_date",
10113
+ "invalid_string",
10114
+ "too_small",
10115
+ "too_big",
10116
+ "invalid_intersection_types",
10117
+ "not_multiple_of",
10118
+ "not_finite",
10119
+ ]);
10120
+ class ZodError extends Error {
10121
+ get errors() {
10122
+ return this.issues;
10123
+ }
10124
+ constructor(issues) {
10125
+ super();
10126
+ this.issues = [];
10127
+ this.addIssue = (sub) => {
10128
+ this.issues = [...this.issues, sub];
10129
+ };
10130
+ this.addIssues = (subs = []) => {
10131
+ this.issues = [...this.issues, ...subs];
10132
+ };
10133
+ const actualProto = new.target.prototype;
10134
+ if (Object.setPrototypeOf) {
10135
+ // eslint-disable-next-line ban/ban
10136
+ Object.setPrototypeOf(this, actualProto);
10137
+ }
10138
+ else {
10139
+ this.__proto__ = actualProto;
10140
+ }
10141
+ this.name = "ZodError";
10142
+ this.issues = issues;
10143
+ }
10144
+ format(_mapper) {
10145
+ const mapper = _mapper ||
10146
+ function (issue) {
10147
+ return issue.message;
10148
+ };
10149
+ const fieldErrors = { _errors: [] };
10150
+ const processError = (error) => {
10151
+ for (const issue of error.issues) {
10152
+ if (issue.code === "invalid_union") {
10153
+ issue.unionErrors.map(processError);
10154
+ }
10155
+ else if (issue.code === "invalid_return_type") {
10156
+ processError(issue.returnTypeError);
10157
+ }
10158
+ else if (issue.code === "invalid_arguments") {
10159
+ processError(issue.argumentsError);
10160
+ }
10161
+ else if (issue.path.length === 0) {
10162
+ fieldErrors._errors.push(mapper(issue));
10163
+ }
10164
+ else {
10165
+ let curr = fieldErrors;
10166
+ let i = 0;
10167
+ while (i < issue.path.length) {
10168
+ const el = issue.path[i];
10169
+ const terminal = i === issue.path.length - 1;
10170
+ if (!terminal) {
10171
+ curr[el] = curr[el] || { _errors: [] };
10172
+ // if (typeof el === "string") {
10173
+ // curr[el] = curr[el] || { _errors: [] };
10174
+ // } else if (typeof el === "number") {
10175
+ // const errorArray: any = [];
10176
+ // errorArray._errors = [];
10177
+ // curr[el] = curr[el] || errorArray;
10178
+ // }
10179
+ }
10180
+ else {
10181
+ curr[el] = curr[el] || { _errors: [] };
10182
+ curr[el]._errors.push(mapper(issue));
10183
+ }
10184
+ curr = curr[el];
10185
+ i++;
10186
+ }
10187
+ }
10188
+ }
10189
+ };
10190
+ processError(this);
10191
+ return fieldErrors;
10192
+ }
10193
+ static assert(value) {
10194
+ if (!(value instanceof ZodError)) {
10195
+ throw new Error(`Not a ZodError: ${value}`);
10196
+ }
10197
+ }
10198
+ toString() {
10199
+ return this.message;
10200
+ }
10201
+ get message() {
10202
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
10203
+ }
10204
+ get isEmpty() {
10205
+ return this.issues.length === 0;
10206
+ }
10207
+ flatten(mapper = (issue) => issue.message) {
10208
+ const fieldErrors = Object.create(null);
10209
+ const formErrors = [];
10210
+ for (const sub of this.issues) {
10211
+ if (sub.path.length > 0) {
10212
+ const firstEl = sub.path[0];
10213
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
10214
+ fieldErrors[firstEl].push(mapper(sub));
10215
+ }
10216
+ else {
10217
+ formErrors.push(mapper(sub));
10218
+ }
10219
+ }
10220
+ return { formErrors, fieldErrors };
10221
+ }
10222
+ get formErrors() {
10223
+ return this.flatten();
10224
+ }
10225
+ }
10226
+ ZodError.create = (issues) => {
10227
+ const error = new ZodError(issues);
10228
+ return error;
10229
+ };
10230
+
10231
+ var errorUtil;
10232
+ (function (errorUtil) {
10233
+ errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
10234
+ // biome-ignore lint:
10235
+ errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
10236
+ })(errorUtil || (errorUtil = {}));
10237
+
10238
+ var ZodFirstPartyTypeKind;
10239
+ (function (ZodFirstPartyTypeKind) {
10240
+ ZodFirstPartyTypeKind["ZodString"] = "ZodString";
10241
+ ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
10242
+ ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
10243
+ ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
10244
+ ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
10245
+ ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
10246
+ ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
10247
+ ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
10248
+ ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
10249
+ ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
10250
+ ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
10251
+ ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
10252
+ ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
10253
+ ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
10254
+ ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
10255
+ ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
10256
+ ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
10257
+ ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
10258
+ ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
10259
+ ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
10260
+ ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
10261
+ ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
10262
+ ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
10263
+ ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
10264
+ ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
10265
+ ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
10266
+ ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
10267
+ ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
10268
+ ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
10269
+ ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
10270
+ ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
10271
+ ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
10272
+ ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
10273
+ ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
10274
+ ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
10275
+ ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
10276
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
10277
+
10278
+ function parseAnyDef() {
10279
+ return {};
10280
+ }
10281
+
10282
+ function parseArrayDef(def, refs) {
10283
+ const res = {
10284
+ type: 'array',
10285
+ };
10286
+ if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
10287
+ res.items = parseDef(def.type._def, {
10288
+ ...refs,
10289
+ currentPath: [...refs.currentPath, 'items'],
10290
+ });
10291
+ }
10292
+ if (def.minLength) {
10293
+ setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs);
10294
+ }
10295
+ if (def.maxLength) {
10296
+ setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs);
10297
+ }
10298
+ if (def.exactLength) {
10299
+ setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs);
10300
+ setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs);
10301
+ }
10302
+ return res;
10303
+ }
10304
+
10305
+ function parseBigintDef(def, refs) {
10306
+ const res = {
10307
+ type: 'integer',
10308
+ format: 'int64',
10309
+ };
10310
+ if (!def.checks)
10311
+ return res;
10312
+ for (const check of def.checks) {
10313
+ switch (check.kind) {
10314
+ case 'min':
10315
+ if (refs.target === 'jsonSchema7') {
10316
+ if (check.inclusive) {
10317
+ setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);
10318
+ }
10319
+ else {
10320
+ setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);
10321
+ }
10322
+ }
10323
+ else {
10324
+ if (!check.inclusive) {
10325
+ res.exclusiveMinimum = true;
10326
+ }
10327
+ setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);
10328
+ }
10329
+ break;
10330
+ case 'max':
10331
+ if (refs.target === 'jsonSchema7') {
10332
+ if (check.inclusive) {
10333
+ setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);
10334
+ }
10335
+ else {
10336
+ setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);
10337
+ }
10338
+ }
10339
+ else {
10340
+ if (!check.inclusive) {
10341
+ res.exclusiveMaximum = true;
10342
+ }
10343
+ setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);
10344
+ }
10345
+ break;
10346
+ case 'multipleOf':
10347
+ setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);
10348
+ break;
10349
+ }
10350
+ }
10351
+ return res;
10352
+ }
10353
+
10354
+ function parseBooleanDef() {
10355
+ return {
10356
+ type: 'boolean',
10357
+ };
10358
+ }
10359
+
10360
+ function parseBrandedDef(_def, refs) {
10361
+ return parseDef(_def.type._def, refs);
10362
+ }
10363
+
10364
+ const parseCatchDef = (def, refs) => {
10365
+ return parseDef(def.innerType._def, refs);
10366
+ };
10367
+
10368
+ function parseDateDef(def, refs, overrideDateStrategy) {
10369
+ const strategy = overrideDateStrategy ?? refs.dateStrategy;
10370
+ if (Array.isArray(strategy)) {
10371
+ return {
10372
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),
10373
+ };
10374
+ }
10375
+ switch (strategy) {
10376
+ case 'string':
10377
+ case 'format:date-time':
10378
+ return {
10379
+ type: 'string',
10380
+ format: 'date-time',
10381
+ };
10382
+ case 'format:date':
10383
+ return {
10384
+ type: 'string',
10385
+ format: 'date',
10386
+ };
10387
+ case 'integer':
10388
+ return integerDateParser(def, refs);
10389
+ }
10390
+ }
10391
+ const integerDateParser = (def, refs) => {
10392
+ const res = {
10393
+ type: 'integer',
10394
+ format: 'unix-time',
10395
+ };
10396
+ if (refs.target === 'openApi3') {
10397
+ return res;
10398
+ }
10399
+ for (const check of def.checks) {
10400
+ switch (check.kind) {
10401
+ case 'min':
10402
+ setResponseValueAndErrors(res, 'minimum', check.value, // This is in milliseconds
10403
+ check.message, refs);
10404
+ break;
10405
+ case 'max':
10406
+ setResponseValueAndErrors(res, 'maximum', check.value, // This is in milliseconds
10407
+ check.message, refs);
10408
+ break;
10409
+ }
10410
+ }
10411
+ return res;
10412
+ };
10413
+
10414
+ function parseDefaultDef(_def, refs) {
10415
+ return {
10416
+ ...parseDef(_def.innerType._def, refs),
10417
+ default: _def.defaultValue(),
10418
+ };
10419
+ }
10420
+
10421
+ function parseEffectsDef(_def, refs, forceResolution) {
10422
+ return refs.effectStrategy === 'input' ? parseDef(_def.schema._def, refs, forceResolution) : {};
10423
+ }
10424
+
10425
+ function parseEnumDef(def) {
10426
+ return {
10427
+ type: 'string',
10428
+ enum: [...def.values],
10429
+ };
10430
+ }
10431
+
10432
+ const isJsonSchema7AllOfType = (type) => {
10433
+ if ('type' in type && type.type === 'string')
10434
+ return false;
10435
+ return 'allOf' in type;
10436
+ };
10437
+ function parseIntersectionDef(def, refs) {
10438
+ const allOf = [
10439
+ parseDef(def.left._def, {
10440
+ ...refs,
10441
+ currentPath: [...refs.currentPath, 'allOf', '0'],
10442
+ }),
10443
+ parseDef(def.right._def, {
10444
+ ...refs,
10445
+ currentPath: [...refs.currentPath, 'allOf', '1'],
10446
+ }),
10447
+ ].filter((x) => !!x);
10448
+ let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined;
10449
+ const mergedAllOf = [];
10450
+ // If either of the schemas is an allOf, merge them into a single allOf
10451
+ allOf.forEach((schema) => {
10452
+ if (isJsonSchema7AllOfType(schema)) {
10453
+ mergedAllOf.push(...schema.allOf);
10454
+ if (schema.unevaluatedProperties === undefined) {
10455
+ // If one of the schemas has no unevaluatedProperties set,
10456
+ // the merged schema should also have no unevaluatedProperties set
10457
+ unevaluatedProperties = undefined;
10458
+ }
10459
+ }
10460
+ else {
10461
+ let nestedSchema = schema;
10462
+ if ('additionalProperties' in schema && schema.additionalProperties === false) {
10463
+ const { additionalProperties, ...rest } = schema;
10464
+ nestedSchema = rest;
10465
+ }
10466
+ else {
10467
+ // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties
10468
+ unevaluatedProperties = undefined;
10469
+ }
10470
+ mergedAllOf.push(nestedSchema);
10471
+ }
10472
+ });
10473
+ return mergedAllOf.length ?
10474
+ {
10475
+ allOf: mergedAllOf,
10476
+ ...unevaluatedProperties,
10477
+ }
10478
+ : undefined;
10479
+ }
10480
+
10481
+ function parseLiteralDef(def, refs) {
10482
+ const parsedType = typeof def.value;
10483
+ if (parsedType !== 'bigint' &&
10484
+ parsedType !== 'number' &&
10485
+ parsedType !== 'boolean' &&
10486
+ parsedType !== 'string') {
10487
+ return {
10488
+ type: Array.isArray(def.value) ? 'array' : 'object',
10489
+ };
10490
+ }
10491
+ if (refs.target === 'openApi3') {
10492
+ return {
10493
+ type: parsedType === 'bigint' ? 'integer' : parsedType,
10494
+ enum: [def.value],
10495
+ };
10496
+ }
10497
+ return {
10498
+ type: parsedType === 'bigint' ? 'integer' : parsedType,
10499
+ const: def.value,
10500
+ };
10501
+ }
10502
+
10503
+ let emojiRegex;
10504
+ /**
10505
+ * Generated from the regular expressions found here as of 2024-05-22:
10506
+ * https://github.com/colinhacks/zod/blob/master/src/types.ts.
10507
+ *
10508
+ * Expressions with /i flag have been changed accordingly.
10509
+ */
10510
+ const zodPatterns = {
10511
+ /**
10512
+ * `c` was changed to `[cC]` to replicate /i flag
10513
+ */
10514
+ cuid: /^[cC][^\s-]{8,}$/,
10515
+ cuid2: /^[0-9a-z]+$/,
10516
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
10517
+ /**
10518
+ * `a-z` was added to replicate /i flag
10519
+ */
10520
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
10521
+ /**
10522
+ * Constructed a valid Unicode RegExp
10523
+ *
10524
+ * Lazily instantiate since this type of regex isn't supported
10525
+ * in all envs (e.g. React Native).
10526
+ *
10527
+ * See:
10528
+ * https://github.com/colinhacks/zod/issues/2433
10529
+ * Fix in Zod:
10530
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
10531
+ */
10532
+ emoji: () => {
10533
+ if (emojiRegex === undefined) {
10534
+ emojiRegex = RegExp('^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$', 'u');
10535
+ }
10536
+ return emojiRegex;
10537
+ },
10538
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
10539
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
10540
+ };
10541
+ function parseStringDef(def, refs) {
10542
+ const res = {
10543
+ type: 'string',
10544
+ };
10545
+ function processPattern(value) {
10546
+ return refs.patternStrategy === 'escape' ? escapeNonAlphaNumeric(value) : value;
10547
+ }
10548
+ if (def.checks) {
10549
+ for (const check of def.checks) {
10550
+ switch (check.kind) {
10551
+ case 'min':
10552
+ setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
10553
+ break;
10554
+ case 'max':
10555
+ setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
10556
+ break;
10557
+ case 'email':
10558
+ switch (refs.emailStrategy) {
10559
+ case 'format:email':
10560
+ addFormat(res, 'email', check.message, refs);
10561
+ break;
10562
+ case 'format:idn-email':
10563
+ addFormat(res, 'idn-email', check.message, refs);
10564
+ break;
10565
+ case 'pattern:zod':
10566
+ addPattern(res, zodPatterns.email, check.message, refs);
10567
+ break;
10568
+ }
10569
+ break;
10570
+ case 'url':
10571
+ addFormat(res, 'uri', check.message, refs);
10572
+ break;
10573
+ case 'uuid':
10574
+ addFormat(res, 'uuid', check.message, refs);
10575
+ break;
10576
+ case 'regex':
10577
+ addPattern(res, check.regex, check.message, refs);
10578
+ break;
10579
+ case 'cuid':
10580
+ addPattern(res, zodPatterns.cuid, check.message, refs);
10581
+ break;
10582
+ case 'cuid2':
10583
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
10584
+ break;
10585
+ case 'startsWith':
10586
+ addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs);
10587
+ break;
10588
+ case 'endsWith':
10589
+ addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs);
10590
+ break;
10591
+ case 'datetime':
10592
+ addFormat(res, 'date-time', check.message, refs);
10593
+ break;
10594
+ case 'date':
10595
+ addFormat(res, 'date', check.message, refs);
10596
+ break;
10597
+ case 'time':
10598
+ addFormat(res, 'time', check.message, refs);
10599
+ break;
10600
+ case 'duration':
10601
+ addFormat(res, 'duration', check.message, refs);
10602
+ break;
10603
+ case 'length':
10604
+ setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
10605
+ setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
10606
+ break;
10607
+ case 'includes': {
10608
+ addPattern(res, RegExp(processPattern(check.value)), check.message, refs);
10609
+ break;
10610
+ }
10611
+ case 'ip': {
10612
+ if (check.version !== 'v6') {
10613
+ addFormat(res, 'ipv4', check.message, refs);
10614
+ }
10615
+ if (check.version !== 'v4') {
10616
+ addFormat(res, 'ipv6', check.message, refs);
10617
+ }
10618
+ break;
10619
+ }
10620
+ case 'emoji':
10621
+ addPattern(res, zodPatterns.emoji, check.message, refs);
10622
+ break;
10623
+ case 'ulid': {
10624
+ addPattern(res, zodPatterns.ulid, check.message, refs);
10625
+ break;
10626
+ }
10627
+ case 'base64': {
10628
+ switch (refs.base64Strategy) {
10629
+ case 'format:binary': {
10630
+ addFormat(res, 'binary', check.message, refs);
10631
+ break;
10632
+ }
10633
+ case 'contentEncoding:base64': {
10634
+ setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs);
10635
+ break;
10636
+ }
10637
+ case 'pattern:zod': {
10638
+ addPattern(res, zodPatterns.base64, check.message, refs);
10639
+ break;
10640
+ }
10641
+ }
10642
+ break;
10643
+ }
10644
+ case 'nanoid': {
10645
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
10646
+ }
10647
+ }
10648
+ }
10649
+ }
10650
+ return res;
10651
+ }
10652
+ const escapeNonAlphaNumeric = (value) => Array.from(value)
10653
+ .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`))
10654
+ .join('');
10655
+ const addFormat = (schema, value, message, refs) => {
10656
+ if (schema.format || schema.anyOf?.some((x) => x.format)) {
10657
+ if (!schema.anyOf) {
10658
+ schema.anyOf = [];
10659
+ }
10660
+ if (schema.format) {
10661
+ schema.anyOf.push({
10662
+ format: schema.format,
10663
+ ...(schema.errorMessage &&
10664
+ refs.errorMessages && {
10665
+ errorMessage: { format: schema.errorMessage.format },
10666
+ }),
10667
+ });
10668
+ delete schema.format;
10669
+ if (schema.errorMessage) {
10670
+ delete schema.errorMessage.format;
10671
+ if (Object.keys(schema.errorMessage).length === 0) {
10672
+ delete schema.errorMessage;
10673
+ }
10674
+ }
10675
+ }
10676
+ schema.anyOf.push({
10677
+ format: value,
10678
+ ...(message && refs.errorMessages && { errorMessage: { format: message } }),
10679
+ });
10680
+ }
10681
+ else {
10682
+ setResponseValueAndErrors(schema, 'format', value, message, refs);
10683
+ }
10684
+ };
10685
+ const addPattern = (schema, regex, message, refs) => {
10686
+ if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
10687
+ if (!schema.allOf) {
10688
+ schema.allOf = [];
10689
+ }
10690
+ if (schema.pattern) {
10691
+ schema.allOf.push({
10692
+ pattern: schema.pattern,
10693
+ ...(schema.errorMessage &&
10694
+ refs.errorMessages && {
10695
+ errorMessage: { pattern: schema.errorMessage.pattern },
10696
+ }),
10697
+ });
10698
+ delete schema.pattern;
10699
+ if (schema.errorMessage) {
10700
+ delete schema.errorMessage.pattern;
10701
+ if (Object.keys(schema.errorMessage).length === 0) {
10702
+ delete schema.errorMessage;
10703
+ }
10704
+ }
10705
+ }
10706
+ schema.allOf.push({
10707
+ pattern: processRegExp(regex, refs),
10708
+ ...(message && refs.errorMessages && { errorMessage: { pattern: message } }),
10709
+ });
10710
+ }
10711
+ else {
10712
+ setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs);
10713
+ }
10714
+ };
10715
+ // Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true
10716
+ const processRegExp = (regexOrFunction, refs) => {
10717
+ const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction;
10718
+ if (!refs.applyRegexFlags || !regex.flags)
10719
+ return regex.source;
10720
+ // Currently handled flags
10721
+ const flags = {
10722
+ i: regex.flags.includes('i'), // Case-insensitive
10723
+ m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters
10724
+ s: regex.flags.includes('s'), // `.` matches newlines
10725
+ };
10726
+ // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!
10727
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
10728
+ let pattern = '';
10729
+ let isEscaped = false;
10730
+ let inCharGroup = false;
10731
+ let inCharRange = false;
10732
+ for (let i = 0; i < source.length; i++) {
10733
+ if (isEscaped) {
10734
+ pattern += source[i];
10735
+ isEscaped = false;
10736
+ continue;
10737
+ }
10738
+ if (flags.i) {
10739
+ if (inCharGroup) {
10740
+ if (source[i].match(/[a-z]/)) {
10741
+ if (inCharRange) {
10742
+ pattern += source[i];
10743
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
10744
+ inCharRange = false;
10745
+ }
10746
+ else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {
10747
+ pattern += source[i];
10748
+ inCharRange = true;
10749
+ }
10750
+ else {
10751
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
10752
+ }
10753
+ continue;
10754
+ }
10755
+ }
10756
+ else if (source[i].match(/[a-z]/)) {
10757
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
10758
+ continue;
10759
+ }
10760
+ }
10761
+ if (flags.m) {
10762
+ if (source[i] === '^') {
10763
+ pattern += `(^|(?<=[\r\n]))`;
10764
+ continue;
10765
+ }
10766
+ else if (source[i] === '$') {
10767
+ pattern += `($|(?=[\r\n]))`;
10768
+ continue;
10769
+ }
10770
+ }
10771
+ if (flags.s && source[i] === '.') {
10772
+ pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`;
10773
+ continue;
10774
+ }
10775
+ pattern += source[i];
10776
+ if (source[i] === '\\') {
10777
+ isEscaped = true;
10778
+ }
10779
+ else if (inCharGroup && source[i] === ']') {
10780
+ inCharGroup = false;
10781
+ }
10782
+ else if (!inCharGroup && source[i] === '[') {
10783
+ inCharGroup = true;
10784
+ }
10785
+ }
10786
+ try {
10787
+ const regexTest = new RegExp(pattern);
10788
+ }
10789
+ catch {
10790
+ console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`);
10791
+ return regex.source;
10792
+ }
10793
+ return pattern;
10794
+ };
10795
+
10796
+ function parseRecordDef(def, refs) {
10797
+ if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
10798
+ return {
10799
+ type: 'object',
10800
+ required: def.keyType._def.values,
10801
+ properties: def.keyType._def.values.reduce((acc, key) => ({
10802
+ ...acc,
10803
+ [key]: parseDef(def.valueType._def, {
10804
+ ...refs,
10805
+ currentPath: [...refs.currentPath, 'properties', key],
10806
+ }) ?? {},
10807
+ }), {}),
10808
+ additionalProperties: false,
10809
+ };
10810
+ }
10811
+ const schema = {
10812
+ type: 'object',
10813
+ additionalProperties: parseDef(def.valueType._def, {
10814
+ ...refs,
10815
+ currentPath: [...refs.currentPath, 'additionalProperties'],
10816
+ }) ?? {},
10817
+ };
10818
+ if (refs.target === 'openApi3') {
10819
+ return schema;
10820
+ }
10821
+ if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
10822
+ const keyType = Object.entries(parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {});
10823
+ return {
10824
+ ...schema,
10825
+ propertyNames: keyType,
10826
+ };
10827
+ }
10828
+ else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
10829
+ return {
10830
+ ...schema,
10831
+ propertyNames: {
10832
+ enum: def.keyType._def.values,
10833
+ },
10834
+ };
10835
+ }
10836
+ return schema;
10837
+ }
10838
+
10839
+ function parseMapDef(def, refs) {
10840
+ if (refs.mapStrategy === 'record') {
10841
+ return parseRecordDef(def, refs);
10842
+ }
10843
+ const keys = parseDef(def.keyType._def, {
10844
+ ...refs,
10845
+ currentPath: [...refs.currentPath, 'items', 'items', '0'],
10846
+ }) || {};
10847
+ const values = parseDef(def.valueType._def, {
10848
+ ...refs,
10849
+ currentPath: [...refs.currentPath, 'items', 'items', '1'],
10850
+ }) || {};
10851
+ return {
10852
+ type: 'array',
10853
+ maxItems: 125,
10854
+ items: {
10855
+ type: 'array',
10856
+ items: [keys, values],
10857
+ minItems: 2,
10858
+ maxItems: 2,
10859
+ },
10860
+ };
10861
+ }
10862
+
10863
+ function parseNativeEnumDef(def) {
10864
+ const object = def.values;
10865
+ const actualKeys = Object.keys(def.values).filter((key) => {
10866
+ return typeof object[object[key]] !== 'number';
10867
+ });
10868
+ const actualValues = actualKeys.map((key) => object[key]);
10869
+ const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
10870
+ return {
10871
+ type: parsedTypes.length === 1 ?
10872
+ parsedTypes[0] === 'string' ?
10873
+ 'string'
10874
+ : 'number'
10875
+ : ['string', 'number'],
10876
+ enum: actualValues,
10877
+ };
10878
+ }
10879
+
10880
+ function parseNeverDef() {
10881
+ return {
10882
+ not: {},
10883
+ };
10884
+ }
10885
+
10886
+ function parseNullDef(refs) {
10887
+ return refs.target === 'openApi3' ?
10888
+ {
10889
+ enum: ['null'],
10890
+ nullable: true,
10891
+ }
10892
+ : {
10893
+ type: 'null',
10894
+ };
10895
+ }
10896
+
10897
+ const primitiveMappings = {
10898
+ ZodString: 'string',
10899
+ ZodNumber: 'number',
10900
+ ZodBigInt: 'integer',
10901
+ ZodBoolean: 'boolean',
10902
+ ZodNull: 'null',
10903
+ };
10904
+ function parseUnionDef(def, refs) {
10905
+ if (refs.target === 'openApi3')
10906
+ return asAnyOf(def, refs);
10907
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
10908
+ // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.
10909
+ if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
10910
+ // all types in union are primitive and lack checks, so might as well squash into {type: [...]}
10911
+ const types = options.reduce((types, x) => {
10912
+ const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43
10913
+ return type && !types.includes(type) ? [...types, type] : types;
10914
+ }, []);
10915
+ return {
10916
+ type: types.length > 1 ? types : types[0],
10917
+ };
10918
+ }
10919
+ else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) {
10920
+ // all options literals
10921
+ const types = options.reduce((acc, x) => {
10922
+ const type = typeof x._def.value;
10923
+ switch (type) {
10924
+ case 'string':
10925
+ case 'number':
10926
+ case 'boolean':
10927
+ return [...acc, type];
10928
+ case 'bigint':
10929
+ return [...acc, 'integer'];
10930
+ case 'object':
10931
+ if (x._def.value === null)
10932
+ return [...acc, 'null'];
10933
+ case 'symbol':
10934
+ case 'undefined':
10935
+ case 'function':
10936
+ default:
10937
+ return acc;
10938
+ }
10939
+ }, []);
10940
+ if (types.length === options.length) {
10941
+ // all the literals are primitive, as far as null can be considered primitive
10942
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
10943
+ return {
10944
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
10945
+ enum: options.reduce((acc, x) => {
10946
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
10947
+ }, []),
10948
+ };
10949
+ }
10950
+ }
10951
+ else if (options.every((x) => x._def.typeName === 'ZodEnum')) {
10952
+ return {
10953
+ type: 'string',
10954
+ enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []),
10955
+ };
10956
+ }
10957
+ return asAnyOf(def, refs);
10958
+ }
10959
+ const asAnyOf = (def, refs) => {
10960
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options)
10961
+ .map((x, i) => parseDef(x._def, {
10962
+ ...refs,
10963
+ currentPath: [...refs.currentPath, 'anyOf', `${i}`],
10964
+ }))
10965
+ .filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0)));
10966
+ return anyOf.length ? { anyOf } : undefined;
10967
+ };
10968
+
10969
+ function parseNullableDef(def, refs) {
10970
+ if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) &&
10971
+ (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
10972
+ if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') {
10973
+ return {
10974
+ type: primitiveMappings[def.innerType._def.typeName],
10975
+ nullable: true,
10976
+ };
10977
+ }
10978
+ return {
10979
+ type: [primitiveMappings[def.innerType._def.typeName], 'null'],
10980
+ };
10981
+ }
10982
+ if (refs.target === 'openApi3') {
10983
+ const base = parseDef(def.innerType._def, {
10984
+ ...refs,
10985
+ currentPath: [...refs.currentPath],
10986
+ });
10987
+ if (base && '$ref' in base)
10988
+ return { allOf: [base], nullable: true };
10989
+ return base && { ...base, nullable: true };
10990
+ }
10991
+ const base = parseDef(def.innerType._def, {
10992
+ ...refs,
10993
+ currentPath: [...refs.currentPath, 'anyOf', '0'],
10994
+ });
10995
+ return base && { anyOf: [base, { type: 'null' }] };
10996
+ }
10997
+
10998
+ function parseNumberDef(def, refs) {
10999
+ const res = {
11000
+ type: 'number',
11001
+ };
11002
+ if (!def.checks)
11003
+ return res;
11004
+ for (const check of def.checks) {
11005
+ switch (check.kind) {
11006
+ case 'int':
11007
+ res.type = 'integer';
11008
+ addErrorMessage(res, 'type', check.message, refs);
11009
+ break;
11010
+ case 'min':
11011
+ if (refs.target === 'jsonSchema7') {
11012
+ if (check.inclusive) {
11013
+ setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);
11014
+ }
11015
+ else {
11016
+ setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);
11017
+ }
11018
+ }
11019
+ else {
11020
+ if (!check.inclusive) {
11021
+ res.exclusiveMinimum = true;
11022
+ }
11023
+ setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);
11024
+ }
11025
+ break;
11026
+ case 'max':
11027
+ if (refs.target === 'jsonSchema7') {
11028
+ if (check.inclusive) {
11029
+ setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);
11030
+ }
11031
+ else {
11032
+ setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);
11033
+ }
11034
+ }
11035
+ else {
11036
+ if (!check.inclusive) {
11037
+ res.exclusiveMaximum = true;
11038
+ }
11039
+ setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);
11040
+ }
11041
+ break;
11042
+ case 'multipleOf':
11043
+ setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);
11044
+ break;
11045
+ }
11046
+ }
11047
+ return res;
11048
+ }
11049
+
11050
+ function decideAdditionalProperties(def, refs) {
11051
+ if (refs.removeAdditionalStrategy === 'strict') {
11052
+ return def.catchall._def.typeName === 'ZodNever' ?
11053
+ def.unknownKeys !== 'strict'
11054
+ : parseDef(def.catchall._def, {
11055
+ ...refs,
11056
+ currentPath: [...refs.currentPath, 'additionalProperties'],
11057
+ }) ?? true;
11058
+ }
11059
+ else {
11060
+ return def.catchall._def.typeName === 'ZodNever' ?
11061
+ def.unknownKeys === 'passthrough'
11062
+ : parseDef(def.catchall._def, {
11063
+ ...refs,
11064
+ currentPath: [...refs.currentPath, 'additionalProperties'],
11065
+ }) ?? true;
11066
+ }
11067
+ }
11068
+ function parseObjectDef(def, refs) {
11069
+ const result = {
11070
+ type: 'object',
11071
+ ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {
11072
+ if (propDef === undefined || propDef._def === undefined)
11073
+ return acc;
11074
+ const propertyPath = [...refs.currentPath, 'properties', propName];
11075
+ const parsedDef = parseDef(propDef._def, {
11076
+ ...refs,
11077
+ currentPath: propertyPath,
11078
+ propertyPath,
11079
+ });
11080
+ if (parsedDef === undefined)
11081
+ return acc;
11082
+ if (refs.openaiStrictMode &&
11083
+ propDef.isOptional() &&
11084
+ !propDef.isNullable() &&
11085
+ typeof propDef._def?.defaultValue === 'undefined') {
11086
+ throw new Error(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);
11087
+ }
11088
+ return {
11089
+ properties: {
11090
+ ...acc.properties,
11091
+ [propName]: parsedDef,
11092
+ },
11093
+ required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName],
11094
+ };
11095
+ }, { properties: {}, required: [] }),
11096
+ additionalProperties: decideAdditionalProperties(def, refs),
11097
+ };
11098
+ if (!result.required.length)
11099
+ delete result.required;
11100
+ return result;
11101
+ }
11102
+
11103
+ const parseOptionalDef = (def, refs) => {
11104
+ if (refs.propertyPath &&
11105
+ refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString()) {
11106
+ return parseDef(def.innerType._def, { ...refs, currentPath: refs.currentPath });
11107
+ }
11108
+ const innerSchema = parseDef(def.innerType._def, {
11109
+ ...refs,
11110
+ currentPath: [...refs.currentPath, 'anyOf', '1'],
11111
+ });
11112
+ return innerSchema ?
11113
+ {
11114
+ anyOf: [
11115
+ {
11116
+ not: {},
11117
+ },
11118
+ innerSchema,
11119
+ ],
11120
+ }
11121
+ : {};
11122
+ };
11123
+
11124
+ const parsePipelineDef = (def, refs) => {
11125
+ if (refs.pipeStrategy === 'input') {
11126
+ return parseDef(def.in._def, refs);
11127
+ }
11128
+ else if (refs.pipeStrategy === 'output') {
11129
+ return parseDef(def.out._def, refs);
11130
+ }
11131
+ const a = parseDef(def.in._def, {
11132
+ ...refs,
11133
+ currentPath: [...refs.currentPath, 'allOf', '0'],
11134
+ });
11135
+ const b = parseDef(def.out._def, {
11136
+ ...refs,
11137
+ currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'],
11138
+ });
11139
+ return {
11140
+ allOf: [a, b].filter((x) => x !== undefined),
11141
+ };
11142
+ };
11143
+
11144
+ function parsePromiseDef(def, refs) {
11145
+ return parseDef(def.type._def, refs);
11146
+ }
11147
+
11148
+ function parseSetDef(def, refs) {
11149
+ const items = parseDef(def.valueType._def, {
11150
+ ...refs,
11151
+ currentPath: [...refs.currentPath, 'items'],
11152
+ });
11153
+ const schema = {
11154
+ type: 'array',
11155
+ uniqueItems: true,
11156
+ items,
11157
+ };
11158
+ if (def.minSize) {
11159
+ setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs);
11160
+ }
11161
+ if (def.maxSize) {
11162
+ setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs);
11163
+ }
11164
+ return schema;
11165
+ }
11166
+
11167
+ function parseTupleDef(def, refs) {
11168
+ if (def.rest) {
11169
+ return {
11170
+ type: 'array',
11171
+ minItems: def.items.length,
11172
+ items: def.items
11173
+ .map((x, i) => parseDef(x._def, {
11174
+ ...refs,
11175
+ currentPath: [...refs.currentPath, 'items', `${i}`],
11176
+ }))
11177
+ .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),
11178
+ additionalItems: parseDef(def.rest._def, {
11179
+ ...refs,
11180
+ currentPath: [...refs.currentPath, 'additionalItems'],
11181
+ }),
11182
+ };
11183
+ }
11184
+ else {
11185
+ return {
11186
+ type: 'array',
11187
+ minItems: def.items.length,
11188
+ maxItems: def.items.length,
11189
+ items: def.items
11190
+ .map((x, i) => parseDef(x._def, {
11191
+ ...refs,
11192
+ currentPath: [...refs.currentPath, 'items', `${i}`],
11193
+ }))
11194
+ .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),
11195
+ };
11196
+ }
11197
+ }
11198
+
11199
+ function parseUndefinedDef() {
11200
+ return {
11201
+ not: {},
11202
+ };
11203
+ }
11204
+
11205
+ function parseUnknownDef() {
11206
+ return {};
11207
+ }
11208
+
11209
+ const parseReadonlyDef = (def, refs) => {
11210
+ return parseDef(def.innerType._def, refs);
11211
+ };
11212
+
11213
+ function parseDef(def, refs, forceResolution = false) {
11214
+ const seenItem = refs.seen.get(def);
11215
+ if (refs.override) {
11216
+ const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
11217
+ if (overrideResult !== ignoreOverride) {
11218
+ return overrideResult;
11219
+ }
11220
+ }
11221
+ if (seenItem && !forceResolution) {
11222
+ const seenSchema = get$ref(seenItem, refs);
11223
+ if (seenSchema !== undefined) {
11224
+ if ('$ref' in seenSchema) {
11225
+ refs.seenRefs.add(seenSchema.$ref);
11226
+ }
11227
+ return seenSchema;
11228
+ }
11229
+ }
11230
+ const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
11231
+ refs.seen.set(def, newItem);
11232
+ const jsonSchema = selectParser(def, def.typeName, refs, forceResolution);
11233
+ if (jsonSchema) {
11234
+ addMeta(def, refs, jsonSchema);
11235
+ }
11236
+ newItem.jsonSchema = jsonSchema;
11237
+ return jsonSchema;
11238
+ }
11239
+ const get$ref = (item, refs) => {
11240
+ switch (refs.$refStrategy) {
11241
+ case 'root':
11242
+ return { $ref: item.path.join('/') };
11243
+ // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e.
11244
+ // the top-level schema *must* be `{"type": "object", "properties": {...}}` but if we ever
11245
+ // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract
11246
+ // the schema to `#/definitions/` and reference that.
11247
+ //
11248
+ // e.g. if we need to reference a schema at
11249
+ // `["#","definitions","contactPerson","properties","person1","properties","name"]`
11250
+ // then we'll extract it out to `contactPerson_properties_person1_properties_name`
11251
+ case 'extract-to-root':
11252
+ const name = item.path.slice(refs.basePath.length + 1).join('_');
11253
+ // we don't need to extract the root schema in this case, as it's already
11254
+ // been added to the definitions
11255
+ if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') {
11256
+ refs.definitions[name] = item.def;
11257
+ }
11258
+ return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') };
11259
+ case 'relative':
11260
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
11261
+ case 'none':
11262
+ case 'seen': {
11263
+ if (item.path.length < refs.currentPath.length &&
11264
+ item.path.every((value, index) => refs.currentPath[index] === value)) {
11265
+ console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`);
11266
+ return {};
11267
+ }
11268
+ return refs.$refStrategy === 'seen' ? {} : undefined;
11269
+ }
11270
+ }
11271
+ };
11272
+ const getRelativePath = (pathA, pathB) => {
11273
+ let i = 0;
11274
+ for (; i < pathA.length && i < pathB.length; i++) {
11275
+ if (pathA[i] !== pathB[i])
11276
+ break;
11277
+ }
11278
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');
11279
+ };
11280
+ const selectParser = (def, typeName, refs, forceResolution) => {
11281
+ switch (typeName) {
11282
+ case ZodFirstPartyTypeKind.ZodString:
11283
+ return parseStringDef(def, refs);
11284
+ case ZodFirstPartyTypeKind.ZodNumber:
11285
+ return parseNumberDef(def, refs);
11286
+ case ZodFirstPartyTypeKind.ZodObject:
11287
+ return parseObjectDef(def, refs);
11288
+ case ZodFirstPartyTypeKind.ZodBigInt:
11289
+ return parseBigintDef(def, refs);
11290
+ case ZodFirstPartyTypeKind.ZodBoolean:
11291
+ return parseBooleanDef();
11292
+ case ZodFirstPartyTypeKind.ZodDate:
11293
+ return parseDateDef(def, refs);
11294
+ case ZodFirstPartyTypeKind.ZodUndefined:
11295
+ return parseUndefinedDef();
11296
+ case ZodFirstPartyTypeKind.ZodNull:
11297
+ return parseNullDef(refs);
11298
+ case ZodFirstPartyTypeKind.ZodArray:
11299
+ return parseArrayDef(def, refs);
11300
+ case ZodFirstPartyTypeKind.ZodUnion:
11301
+ case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
11302
+ return parseUnionDef(def, refs);
11303
+ case ZodFirstPartyTypeKind.ZodIntersection:
11304
+ return parseIntersectionDef(def, refs);
11305
+ case ZodFirstPartyTypeKind.ZodTuple:
11306
+ return parseTupleDef(def, refs);
11307
+ case ZodFirstPartyTypeKind.ZodRecord:
11308
+ return parseRecordDef(def, refs);
11309
+ case ZodFirstPartyTypeKind.ZodLiteral:
11310
+ return parseLiteralDef(def, refs);
11311
+ case ZodFirstPartyTypeKind.ZodEnum:
11312
+ return parseEnumDef(def);
11313
+ case ZodFirstPartyTypeKind.ZodNativeEnum:
11314
+ return parseNativeEnumDef(def);
11315
+ case ZodFirstPartyTypeKind.ZodNullable:
11316
+ return parseNullableDef(def, refs);
11317
+ case ZodFirstPartyTypeKind.ZodOptional:
11318
+ return parseOptionalDef(def, refs);
11319
+ case ZodFirstPartyTypeKind.ZodMap:
11320
+ return parseMapDef(def, refs);
11321
+ case ZodFirstPartyTypeKind.ZodSet:
11322
+ return parseSetDef(def, refs);
11323
+ case ZodFirstPartyTypeKind.ZodLazy:
11324
+ return parseDef(def.getter()._def, refs);
11325
+ case ZodFirstPartyTypeKind.ZodPromise:
11326
+ return parsePromiseDef(def, refs);
11327
+ case ZodFirstPartyTypeKind.ZodNaN:
11328
+ case ZodFirstPartyTypeKind.ZodNever:
11329
+ return parseNeverDef();
11330
+ case ZodFirstPartyTypeKind.ZodEffects:
11331
+ return parseEffectsDef(def, refs, forceResolution);
11332
+ case ZodFirstPartyTypeKind.ZodAny:
11333
+ return parseAnyDef();
11334
+ case ZodFirstPartyTypeKind.ZodUnknown:
11335
+ return parseUnknownDef();
11336
+ case ZodFirstPartyTypeKind.ZodDefault:
11337
+ return parseDefaultDef(def, refs);
11338
+ case ZodFirstPartyTypeKind.ZodBranded:
11339
+ return parseBrandedDef(def, refs);
11340
+ case ZodFirstPartyTypeKind.ZodReadonly:
11341
+ return parseReadonlyDef(def, refs);
11342
+ case ZodFirstPartyTypeKind.ZodCatch:
11343
+ return parseCatchDef(def, refs);
11344
+ case ZodFirstPartyTypeKind.ZodPipeline:
11345
+ return parsePipelineDef(def, refs);
11346
+ case ZodFirstPartyTypeKind.ZodFunction:
11347
+ case ZodFirstPartyTypeKind.ZodVoid:
11348
+ case ZodFirstPartyTypeKind.ZodSymbol:
11349
+ return undefined;
11350
+ default:
11351
+ return ((_) => undefined)();
11352
+ }
11353
+ };
11354
+ const addMeta = (def, refs, jsonSchema) => {
11355
+ if (def.description) {
11356
+ jsonSchema.description = def.description;
11357
+ if (refs.markdownDescription) {
11358
+ jsonSchema.markdownDescription = def.description;
11359
+ }
11360
+ }
11361
+ return jsonSchema;
11362
+ };
11363
+
11364
+ const zodToJsonSchema = (schema, options) => {
11365
+ const refs = getRefs(options);
11366
+ const name = typeof options === 'string' ? options
11367
+ : options?.nameStrategy === 'title' ? undefined
11368
+ : options?.name;
11369
+ const main = parseDef(schema._def, name === undefined ? refs : ({
11370
+ ...refs,
11371
+ currentPath: [...refs.basePath, refs.definitionPath, name],
11372
+ }), false) ?? {};
11373
+ const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ?
11374
+ options.name
11375
+ : undefined;
11376
+ if (title !== undefined) {
11377
+ main.title = title;
11378
+ }
11379
+ const definitions = (() => {
11380
+ if (isEmptyObj(refs.definitions)) {
11381
+ return undefined;
11382
+ }
11383
+ const definitions = {};
11384
+ const processedDefinitions = new Set();
11385
+ // the call to `parseDef()` here might itself add more entries to `.definitions`
11386
+ // so we need to continually evaluate definitions until we've resolved all of them
11387
+ //
11388
+ // we have a generous iteration limit here to avoid blowing up the stack if there
11389
+ // are any bugs that would otherwise result in us iterating indefinitely
11390
+ for (let i = 0; i < 500; i++) {
11391
+ const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key));
11392
+ if (newDefinitions.length === 0)
11393
+ break;
11394
+ for (const [key, schema] of newDefinitions) {
11395
+ definitions[key] =
11396
+ parseDef(zodDef(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {};
11397
+ processedDefinitions.add(key);
11398
+ }
11399
+ }
11400
+ return definitions;
11401
+ })();
11402
+ const combined = name === undefined ?
11403
+ definitions ?
11404
+ {
11405
+ ...main,
11406
+ [refs.definitionPath]: definitions,
11407
+ }
11408
+ : main
11409
+ : refs.nameStrategy === 'duplicate-ref' ?
11410
+ {
11411
+ ...main,
11412
+ ...(definitions || refs.seenRefs.size ?
11413
+ {
11414
+ [refs.definitionPath]: {
11415
+ ...definitions,
11416
+ // only actually duplicate the schema definition if it was ever referenced
11417
+ // otherwise the duplication is completely pointless
11418
+ ...(refs.seenRefs.size ? { [name]: main } : undefined),
11419
+ },
11420
+ }
11421
+ : undefined),
11422
+ }
11423
+ : {
11424
+ $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'),
11425
+ [refs.definitionPath]: {
11426
+ ...definitions,
11427
+ [name]: main,
11428
+ },
11429
+ };
11430
+ if (refs.target === 'jsonSchema7') {
11431
+ combined.$schema = 'http://json-schema.org/draft-07/schema#';
11432
+ }
11433
+ else if (refs.target === 'jsonSchema2019-09') {
11434
+ combined.$schema = 'https://json-schema.org/draft/2019-09/schema#';
11435
+ }
11436
+ return combined;
11437
+ };
11438
+
11439
+ function toStrictJsonSchema(schema) {
11440
+ if (schema.type !== 'object') {
11441
+ throw new Error(`Root schema must have type: 'object' but got type: ${schema.type ? `'${schema.type}'` : 'undefined'}`);
11442
+ }
11443
+ const schemaCopy = structuredClone(schema);
11444
+ return ensureStrictJsonSchema(schemaCopy, [], schemaCopy);
11445
+ }
11446
+ function isNullable(schema) {
11447
+ if (typeof schema === 'boolean') {
11448
+ return false;
11449
+ }
11450
+ if (schema.type === 'null') {
11451
+ return true;
11452
+ }
11453
+ for (const oneOfVariant of schema.oneOf ?? []) {
11454
+ if (isNullable(oneOfVariant)) {
11455
+ return true;
11456
+ }
11457
+ }
11458
+ for (const allOfVariant of schema.anyOf ?? []) {
11459
+ if (isNullable(allOfVariant)) {
11460
+ return true;
11461
+ }
11462
+ }
11463
+ return false;
11464
+ }
11465
+ /**
11466
+ * Mutates the given JSON schema to ensure it conforms to the `strict` standard
11467
+ * that the API expects.
11468
+ */
11469
+ function ensureStrictJsonSchema(jsonSchema, path, root) {
11470
+ if (typeof jsonSchema === 'boolean') {
11471
+ throw new TypeError(`Expected object schema but got boolean; path=${path.join('/')}`);
11472
+ }
11473
+ if (!isObject(jsonSchema)) {
11474
+ throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path.join('/')}`);
11475
+ }
11476
+ // Handle $defs (non-standard but sometimes used)
11477
+ const defs = jsonSchema.$defs;
11478
+ if (isObject(defs)) {
11479
+ for (const [defName, defSchema] of Object.entries(defs)) {
11480
+ ensureStrictJsonSchema(defSchema, [...path, '$defs', defName], root);
11481
+ }
11482
+ }
11483
+ // Handle definitions (draft-04 style, deprecated in draft-07 but still used)
11484
+ const definitions = jsonSchema.definitions;
11485
+ if (isObject(definitions)) {
11486
+ for (const [definitionName, definitionSchema] of Object.entries(definitions)) {
11487
+ ensureStrictJsonSchema(definitionSchema, [...path, 'definitions', definitionName], root);
11488
+ }
11489
+ }
11490
+ // Add additionalProperties: false to object types
11491
+ const typ = jsonSchema.type;
11492
+ if (typ === 'object' && !('additionalProperties' in jsonSchema)) {
11493
+ jsonSchema.additionalProperties = false;
11494
+ }
11495
+ const required = jsonSchema.required ?? [];
11496
+ // Handle object properties
11497
+ const properties = jsonSchema.properties;
11498
+ if (isObject(properties)) {
11499
+ for (const [key, value] of Object.entries(properties)) {
11500
+ if (!isNullable(value) && !required.includes(key)) {
11501
+ throw new Error(`Zod field at \`${[...path, 'properties', key].join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);
11502
+ }
11503
+ }
11504
+ jsonSchema.required = Object.keys(properties);
11505
+ jsonSchema.properties = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [
11506
+ key,
11507
+ ensureStrictJsonSchema(propSchema, [...path, 'properties', key], root),
11508
+ ]));
11509
+ }
11510
+ // Handle arrays
11511
+ const items = jsonSchema.items;
11512
+ if (isObject(items)) {
11513
+ jsonSchema.items = ensureStrictJsonSchema(items, [...path, 'items'], root);
11514
+ }
11515
+ // Handle unions (anyOf)
11516
+ const anyOf = jsonSchema.anyOf;
11517
+ if (Array.isArray(anyOf)) {
11518
+ jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path, 'anyOf', String(i)], root));
11519
+ }
11520
+ // Handle intersections (allOf)
11521
+ const allOf = jsonSchema.allOf;
11522
+ if (Array.isArray(allOf)) {
11523
+ if (allOf.length === 1) {
11524
+ const resolved = ensureStrictJsonSchema(allOf[0], [...path, 'allOf', '0'], root);
11525
+ Object.assign(jsonSchema, resolved);
11526
+ delete jsonSchema.allOf;
11527
+ }
11528
+ else {
11529
+ jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path, 'allOf', String(i)], root));
11530
+ }
11531
+ }
11532
+ // Strip `null` defaults as there's no meaningful distinction
11533
+ if (jsonSchema.default === null) {
11534
+ delete jsonSchema.default;
11535
+ }
11536
+ // Handle $ref with additional properties
11537
+ const ref = jsonSchema.$ref;
11538
+ if (ref && hasMoreThanNKeys(jsonSchema, 1)) {
11539
+ if (typeof ref !== 'string') {
11540
+ throw new TypeError(`Received non-string $ref - ${ref}; path=${path.join('/')}`);
11541
+ }
11542
+ const resolved = resolveRef(root, ref);
11543
+ if (typeof resolved === 'boolean') {
11544
+ throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object schema but got boolean`);
11545
+ }
11546
+ if (!isObject(resolved)) {
11547
+ throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object but got ${JSON.stringify(resolved)}`);
11548
+ }
11549
+ // Properties from the json schema take priority over the ones on the `$ref`
11550
+ Object.assign(jsonSchema, { ...resolved, ...jsonSchema });
11551
+ delete jsonSchema.$ref;
11552
+ // Since the schema expanded from `$ref` might not have `additionalProperties: false` applied,
11553
+ // we call `ensureStrictJsonSchema` again to fix the inlined schema and ensure it's valid.
11554
+ return ensureStrictJsonSchema(jsonSchema, path, root);
11555
+ }
11556
+ return jsonSchema;
11557
+ }
11558
+ function resolveRef(root, ref) {
11559
+ if (!ref.startsWith('#/')) {
11560
+ throw new Error(`Unexpected $ref format ${JSON.stringify(ref)}; Does not start with #/`);
11561
+ }
11562
+ const pathParts = ref.slice(2).split('/');
11563
+ let resolved = root;
11564
+ for (const key of pathParts) {
11565
+ if (!isObject(resolved)) {
11566
+ throw new Error(`encountered non-object entry while resolving ${ref} - ${JSON.stringify(resolved)}`);
11567
+ }
11568
+ const value = resolved[key];
11569
+ if (value === undefined) {
11570
+ throw new Error(`Key ${key} not found while resolving ${ref}`);
11571
+ }
11572
+ resolved = value;
11573
+ }
11574
+ return resolved;
11575
+ }
11576
+ function isObject(obj) {
11577
+ return typeof obj === 'object' && obj !== null && !Array.isArray(obj);
11578
+ }
11579
+ function hasMoreThanNKeys(obj, n) {
11580
+ let i = 0;
11581
+ for (const _ in obj) {
11582
+ i++;
11583
+ if (i > n) {
11584
+ return true;
11585
+ }
11586
+ }
11587
+ return false;
11588
+ }
11589
+
11590
+ function zodV3ToJsonSchema(schema, options) {
11591
+ return zodToJsonSchema(schema, {
11592
+ openaiStrictMode: true,
11593
+ name: options.name,
11594
+ nameStrategy: 'duplicate-ref',
11595
+ $refStrategy: 'extract-to-root',
11596
+ nullableStrategy: 'property',
11597
+ });
11598
+ }
11599
+ function zodV4ToJsonSchema(schema) {
11600
+ return toStrictJsonSchema(toJSONSchema(schema, {
11601
+ target: 'draft-7',
11602
+ }));
11603
+ }
11604
+ function isZodV4(zodObject) {
11605
+ return '_zod' in zodObject;
11606
+ }
11607
+ function zodTextFormat(zodObject, name, props) {
11608
+ return makeParseableTextFormat({
11609
+ type: 'json_schema',
11610
+ ...props,
11611
+ name,
11612
+ strict: true,
11613
+ schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }),
11614
+ }, (content) => zodObject.parse(JSON.parse(content)));
11615
+ }
11616
+
11617
+ // llm-openai-config.ts
11618
+ const DEFAULT_MODEL = 'gpt-4.1-mini';
11619
+ const GPT_5_4_HIGH_CONTEXT_THRESHOLD_TOKENS = 272_000;
11620
+ const GPT_5_4_HIGH_CONTEXT_INPUT_MULTIPLIER = 2;
11621
+ const GPT_5_4_HIGH_CONTEXT_OUTPUT_MULTIPLIER = 1.5;
11622
+ /** Token costs in USD per 1M tokens. Last updated Mar 2026. */
11623
+ const openAiModelCosts = {
11624
+ 'gpt-4o': {
11625
+ inputCost: 2.5 / 1_000_000,
11626
+ cacheHitCost: 1.25 / 1_000_000,
11627
+ outputCost: 10 / 1_000_000,
11628
+ },
11629
+ 'gpt-4o-mini': {
11630
+ inputCost: 0.15 / 1_000_000,
11631
+ cacheHitCost: 0.075 / 1_000_000,
11632
+ outputCost: 0.6 / 1_000_000,
11633
+ },
11634
+ 'o1-mini': {
11635
+ inputCost: 1.1 / 1_000_000,
11636
+ cacheHitCost: 0.55 / 1_000_000,
11637
+ outputCost: 4.4 / 1_000_000,
11638
+ },
11639
+ 'o1': {
11640
+ inputCost: 15 / 1_000_000,
11641
+ cacheHitCost: 7.5 / 1_000_000,
11642
+ outputCost: 60 / 1_000_000,
11643
+ },
11644
+ 'o3-mini': {
11645
+ inputCost: 1.1 / 1_000_000,
11646
+ cacheHitCost: 0.55 / 1_000_000,
11647
+ outputCost: 4.4 / 1_000_000,
11648
+ },
11649
+ 'o3': {
11650
+ inputCost: 2 / 1_000_000,
11651
+ cacheHitCost: 0.5 / 1_000_000,
11652
+ outputCost: 8 / 1_000_000,
11653
+ },
11654
+ 'gpt-4.1': {
11655
+ inputCost: 2 / 1_000_000,
11656
+ cacheHitCost: 0.5 / 1_000_000,
11657
+ outputCost: 8 / 1_000_000,
11658
+ },
11659
+ 'gpt-4.1-mini': {
11660
+ inputCost: 0.4 / 1_000_000,
11661
+ cacheHitCost: 0.1 / 1_000_000,
11662
+ outputCost: 1.6 / 1_000_000,
11663
+ },
11664
+ 'gpt-4.1-nano': {
11665
+ inputCost: 0.1 / 1_000_000,
11666
+ cacheHitCost: 0.025 / 1_000_000,
11667
+ outputCost: 0.4 / 1_000_000,
11668
+ },
11669
+ 'gpt-5': {
11670
+ inputCost: 1.25 / 1_000_000,
11671
+ cacheHitCost: 0.125 / 1_000_000,
11672
+ outputCost: 10 / 1_000_000,
11673
+ },
11674
+ 'gpt-5-mini': {
11675
+ inputCost: 0.25 / 1_000_000,
11676
+ cacheHitCost: 0.025 / 1_000_000,
11677
+ outputCost: 2 / 1_000_000,
11678
+ },
11679
+ 'gpt-5-nano': {
11680
+ inputCost: 0.05 / 1_000_000,
11681
+ cacheHitCost: 0.005 / 1_000_000,
11682
+ outputCost: 0.4 / 1_000_000,
11683
+ },
11684
+ 'gpt-5.1': {
11685
+ inputCost: 1.25 / 1_000_000,
11686
+ cacheHitCost: 0.125 / 1_000_000,
11687
+ outputCost: 10 / 1_000_000,
11688
+ },
11689
+ 'gpt-5.4': {
11690
+ inputCost: 2.5 / 1_000_000,
11691
+ cacheHitCost: 0.25 / 1_000_000,
11692
+ outputCost: 15 / 1_000_000,
11693
+ },
11694
+ 'gpt-5.4-pro': {
11695
+ inputCost: 30 / 1_000_000,
11696
+ outputCost: 180 / 1_000_000,
11697
+ },
11698
+ 'gpt-5.2': {
11699
+ inputCost: 1.75 / 1_000_000,
11700
+ cacheHitCost: 0.175 / 1_000_000,
11701
+ outputCost: 14 / 1_000_000,
11702
+ },
11703
+ 'gpt-5.2-pro': {
11704
+ inputCost: 21 / 1_000_000,
11705
+ outputCost: 168 / 1_000_000,
11706
+ },
11707
+ 'gpt-5.1-codex': {
11708
+ inputCost: 1.25 / 1_000_000,
11709
+ cacheHitCost: 0.125 / 1_000_000,
11710
+ outputCost: 10 / 1_000_000,
11711
+ },
11712
+ 'gpt-5.1-codex-max': {
11713
+ inputCost: 1.25 / 1_000_000,
11714
+ cacheHitCost: 0.125 / 1_000_000,
11715
+ outputCost: 10 / 1_000_000,
11716
+ },
11717
+ 'o4-mini': {
11718
+ inputCost: 1.1 / 1_000_000,
11719
+ cacheHitCost: 0.275 / 1_000_000,
11720
+ outputCost: 4.4 / 1_000_000,
11721
+ },
11722
+ };
11723
+ const deepseekModelCosts = {
11724
+ 'deepseek-chat': {
11725
+ inputCost: 0.27 / 1_000_000, // $0.27 per 1M tokens (Cache miss price)
11726
+ cacheHitCost: 0.07 / 1_000_000, // $0.07 per 1M tokens (Cache hit price)
11727
+ outputCost: 1.1 / 1_000_000, // $1.10 per 1M tokens
11728
+ },
11729
+ 'deepseek-reasoner': {
11730
+ inputCost: 0.55 / 1_000_000, // $0.55 per 1M tokens (Cache miss price)
11731
+ cacheHitCost: 0.14 / 1_000_000, // $0.14 per 1M tokens (Cache hit price)
11732
+ outputCost: 2.19 / 1_000_000, // $2.19 per 1M tokens
11733
+ },
11734
+ };
11735
+ function shouldUseGPT54HighContextPricing(model, inputTokens) {
11736
+ return (model === 'gpt-5.4' || model === 'gpt-5.4-pro') && inputTokens > GPT_5_4_HIGH_CONTEXT_THRESHOLD_TOKENS;
11737
+ }
11738
+ /** Image generation costs in USD per image. Based on OpenAI pricing as of Feb 2025. */
11739
+ const openAiImageCosts = {
11740
+ 'gpt-image-1': 0.0075, // $0.0075 per image for gpt-image-1
11741
+ 'gpt-image-1.5': 0.0075, // Assumes parity pricing with gpt-image-1 until OpenAI publishes updated rates
11742
+ };
11743
+ /**
11744
+ * Calculates the cost of generating images using OpenAI's Images API.
11745
+ *
11746
+ * @param model The image generation model name.
11747
+ * @param imageCount The number of images generated.
11748
+ * @returns The cost of generating the images in USD.
11749
+ */
11750
+ function calculateImageCost(model, imageCount) {
11751
+ if (typeof model !== 'string' || typeof imageCount !== 'number' || imageCount <= 0) {
11752
+ return 0;
11753
+ }
11754
+ const costPerImage = openAiImageCosts[model];
11755
+ if (!costPerImage)
11756
+ return 0;
11757
+ return imageCount * costPerImage;
11758
+ }
11759
+ /**
11760
+ * Calculates the cost of calling a language model in USD based on the provider and model, tokens, and given costs per 1M tokens.
11761
+ *
11762
+ * @param provider The provider of the language model. Supported providers are 'openai' and 'deepseek'.
11763
+ * @param model The name of the language model. Supported models are listed in the `openAiModelCosts` and `deepseekModelCosts` objects.
11764
+ * @param inputTokens The number of input tokens passed to the language model.
11765
+ * @param outputTokens The number of output tokens generated by the language model.
11766
+ * @param reasoningTokens The number of output tokens generated by the language model for reasoning.
11767
+ * @param cacheHitTokens The number of input tokens billed at cached-input rates.
11768
+ * @returns The cost of calling the language model in USD.
11769
+ */
11770
+ function calculateCost(provider, model, inputTokens, outputTokens, reasoningTokens, cacheHitTokens) {
11771
+ if (typeof provider !== 'string' ||
11772
+ typeof model !== 'string' ||
11773
+ typeof inputTokens !== 'number' ||
11774
+ typeof outputTokens !== 'number' ||
11775
+ (reasoningTokens !== undefined && typeof reasoningTokens !== 'number') ||
11776
+ (cacheHitTokens !== undefined && typeof cacheHitTokens !== 'number')) {
11777
+ return 0;
11778
+ }
11779
+ const modelCosts = provider === 'deepseek' ? deepseekModelCosts[model] : openAiModelCosts[model];
11780
+ if (!modelCosts)
11781
+ return 0;
11782
+ const boundedCacheHitTokens = Math.min(Math.max(cacheHitTokens || 0, 0), inputTokens);
11783
+ let inputCost = inputTokens * modelCosts.inputCost;
11784
+ if (typeof modelCosts.cacheHitCost === 'number' && boundedCacheHitTokens > 0) {
11785
+ inputCost = boundedCacheHitTokens * modelCosts.cacheHitCost + (inputTokens - boundedCacheHitTokens) * modelCosts.inputCost;
11786
+ }
11787
+ let outputCost = outputTokens * modelCosts.outputCost;
11788
+ let reasoningCost = (reasoningTokens || 0) * modelCosts.outputCost;
11789
+ if (provider === 'openai' && shouldUseGPT54HighContextPricing(model, inputTokens)) {
11790
+ inputCost *= GPT_5_4_HIGH_CONTEXT_INPUT_MULTIPLIER;
11791
+ outputCost *= GPT_5_4_HIGH_CONTEXT_OUTPUT_MULTIPLIER;
11792
+ reasoningCost *= GPT_5_4_HIGH_CONTEXT_OUTPUT_MULTIPLIER;
11793
+ }
11794
+ return inputCost + outputCost + reasoningCost;
11795
+ }
11796
+
11797
+ /**
11798
+ * Fix a broken JSON string by attempting to extract and parse valid JSON content. This function is very lenient and will attempt to fix many types of JSON errors, including unbalanced brackets, missing or extra commas, improperly escaped $ signs, unquoted strings, trailing commas, missing closing brackets or braces, etc.
11799
+ * @param {string} jsonStr - The broken JSON string to fix
11800
+ * @returns {JsonValue} - The parsed JSON value
11801
+ */
11802
+ function fixBrokenJson(jsonStr) {
11803
+ // Pre-process: Fix improperly escaped $ signs
11804
+ jsonStr = jsonStr.replace(/\\\$/g, '$');
11805
+ let index = 0;
11806
+ function parse() {
11807
+ const results = [];
11808
+ while (index < jsonStr.length) {
11809
+ skipWhitespace();
11810
+ const value = parseValue();
11811
+ if (value !== undefined) {
11812
+ results.push(value);
11813
+ }
11814
+ else {
11815
+ index++; // Skip invalid character
11816
+ }
11817
+ }
11818
+ return results.length === 1 ? results[0] : results;
11819
+ }
11820
+ function parseValue() {
11821
+ skipWhitespace();
11822
+ const char = getChar();
11823
+ if (!char)
11824
+ return undefined;
11825
+ if (char === '{')
11826
+ return parseObject();
11827
+ if (char === '[')
11828
+ return parseArray();
11829
+ if (char === '"' || char === "'")
11830
+ return parseString();
11831
+ if (char === 't' && jsonStr.slice(index, index + 4).toLowerCase() === 'true') {
11832
+ index += 4;
11833
+ return true;
11834
+ }
11835
+ if (char === 'f' && jsonStr.slice(index, index + 5).toLowerCase() === 'false') {
11836
+ index += 5;
11837
+ return false;
11838
+ }
11839
+ if (char === 'n' && jsonStr.slice(index, index + 4).toLowerCase() === 'null') {
11840
+ index += 4;
11841
+ return null;
11842
+ }
11843
+ if (/[a-zA-Z]/.test(char))
11844
+ return parseString(); // Unquoted string
11845
+ if (char === '-' || char === '.' || /\d/.test(char))
11846
+ return parseNumber();
11847
+ return undefined; // Unknown character
11848
+ }
11849
+ function parseObject() {
11850
+ const obj = {};
11851
+ index++; // Skip opening brace
11852
+ skipWhitespace();
11853
+ while (index < jsonStr.length && getChar() !== '}') {
11854
+ skipWhitespace();
11855
+ const key = parseString();
11856
+ if (key === undefined) {
11857
+ console.warn(`Expected key at position ${index}`);
11858
+ index++;
11859
+ continue;
11860
+ }
11861
+ skipWhitespace();
11862
+ if (getChar() === ':') {
11863
+ index++; // Skip colon
11864
+ }
11865
+ else {
11866
+ console.warn(`Missing colon after key "${key}" at position ${index}`);
11867
+ }
11868
+ skipWhitespace();
11869
+ const value = parseValue();
11870
+ if (value === undefined) {
11871
+ console.warn(`Expected value for key "${key}" at position ${index}`);
11872
+ index++;
11873
+ continue;
11874
+ }
11875
+ obj[key] = value;
11876
+ skipWhitespace();
11877
+ if (getChar() === ',') {
11878
+ index++; // Skip comma
11879
+ }
11880
+ else {
11881
+ break;
11882
+ }
11883
+ skipWhitespace();
11884
+ }
11885
+ if (getChar() === '}') {
11886
+ index++; // Skip closing brace
9059
11887
  }
9060
11888
  else {
9061
11889
  // Add a closing brace if it's missing
@@ -9360,6 +12188,8 @@ const isSupportedModel = (model) => {
9360
12188
  'gpt-5-mini',
9361
12189
  'gpt-5-nano',
9362
12190
  'gpt-5.1',
12191
+ 'gpt-5.4',
12192
+ 'gpt-5.4-pro',
9363
12193
  'gpt-5.2',
9364
12194
  'gpt-5.2-pro',
9365
12195
  'gpt-5.1-codex',
@@ -9386,6 +12216,8 @@ function supportsTemperature(model) {
9386
12216
  'gpt-5-mini',
9387
12217
  'gpt-5-nano',
9388
12218
  'gpt-5.1',
12219
+ 'gpt-5.4',
12220
+ 'gpt-5.4-pro',
9389
12221
  'gpt-5.2',
9390
12222
  'gpt-5.2-pro',
9391
12223
  'gpt-5.1-codex',
@@ -9413,6 +12245,8 @@ function isGPT5Model(model) {
9413
12245
  'gpt-5-mini',
9414
12246
  'gpt-5-nano',
9415
12247
  'gpt-5.1',
12248
+ 'gpt-5.4',
12249
+ 'gpt-5.4-pro',
9416
12250
  'gpt-5.2',
9417
12251
  'gpt-5.2-pro',
9418
12252
  'gpt-5.1-codex',
@@ -9420,6 +12254,38 @@ function isGPT5Model(model) {
9420
12254
  ];
9421
12255
  return gpt5Models.includes(model);
9422
12256
  }
12257
+ function supportsStructuredOutputs(model) {
12258
+ return normalizeModelName(model) !== 'gpt-5.4-pro';
12259
+ }
12260
+ function supportsDistillation(model) {
12261
+ return normalizeModelName(model) !== 'gpt-5.4-pro';
12262
+ }
12263
+ function isZodSchema(schema) {
12264
+ return typeof schema === 'object' && schema !== null && 'safeParse' in schema;
12265
+ }
12266
+ function buildJsonSchemaFormat(schema, schemaName, schemaDescription, schemaStrict) {
12267
+ if (isZodSchema(schema)) {
12268
+ const zodFormat = zodTextFormat(schema, schemaName, schemaDescription
12269
+ ? {
12270
+ description: schemaDescription,
12271
+ }
12272
+ : undefined);
12273
+ return {
12274
+ type: 'json_schema',
12275
+ name: zodFormat.name,
12276
+ schema: zodFormat.schema,
12277
+ ...(zodFormat.description ? { description: zodFormat.description } : {}),
12278
+ ...(schemaStrict !== undefined ? { strict: schemaStrict } : { strict: zodFormat.strict }),
12279
+ };
12280
+ }
12281
+ return {
12282
+ type: 'json_schema',
12283
+ name: schemaName,
12284
+ schema,
12285
+ ...(schemaDescription ? { description: schemaDescription } : {}),
12286
+ ...(schemaStrict !== undefined ? { strict: schemaStrict } : {}),
12287
+ };
12288
+ }
9423
12289
  /**
9424
12290
  * Makes a call to OpenAI's Responses API for more advanced use cases with built-in tools.
9425
12291
  *
@@ -9462,8 +12328,15 @@ const makeResponsesAPICall = async (input, options = {}) => {
9462
12328
  input,
9463
12329
  ...cleanOptions,
9464
12330
  };
12331
+ if (requestBody.text?.format?.type === 'json_schema' && !supportsStructuredOutputs(normalizedModel)) {
12332
+ throw new Error(`Model ${normalizedModel} does not support structured outputs`);
12333
+ }
12334
+ if (requestBody.store && !supportsDistillation(normalizedModel)) {
12335
+ throw new Error(`Model ${normalizedModel} does not support distillation`);
12336
+ }
9465
12337
  // Make the API call to the Responses endpoint
9466
12338
  const response = await openai.responses.create(requestBody);
12339
+ const cacheHitTokens = response.usage?.input_tokens_details?.cached_tokens || 0;
9467
12340
  // Extract tool calls from the output
9468
12341
  const toolCalls = response.output
9469
12342
  ?.filter((item) => item.type === 'function_call')
@@ -9503,7 +12376,8 @@ const makeResponsesAPICall = async (input, options = {}) => {
9503
12376
  reasoning_tokens: response.usage?.output_tokens_details?.reasoning_tokens || 0,
9504
12377
  provider: 'openai',
9505
12378
  model: normalizedModel,
9506
- cost: calculateCost('openai', normalizedModel, response.usage?.input_tokens || 0, response.usage?.output_tokens || 0, response.usage?.output_tokens_details?.reasoning_tokens || 0),
12379
+ cache_hit_tokens: cacheHitTokens,
12380
+ cost: calculateCost('openai', normalizedModel, response.usage?.input_tokens || 0, response.usage?.output_tokens || 0, response.usage?.output_tokens_details?.reasoning_tokens || 0, cacheHitTokens),
9507
12381
  },
9508
12382
  tool_calls: toolCalls,
9509
12383
  ...(codeInterpreterOutputs ? { code_interpreter_outputs: codeInterpreterOutputs } : {}),
@@ -9519,9 +12393,13 @@ const makeResponsesAPICall = async (input, options = {}) => {
9519
12393
  .join('') || '';
9520
12394
  // Determine the format for parsing the response
9521
12395
  let parsingFormat = 'text';
9522
- if (requestBody.text?.format?.type === 'json_object') {
12396
+ const requestedFormat = requestBody.text?.format;
12397
+ if (requestedFormat?.type === 'json_object') {
9523
12398
  parsingFormat = 'json';
9524
12399
  }
12400
+ else if (requestedFormat?.type === 'json_schema') {
12401
+ parsingFormat = requestedFormat;
12402
+ }
9525
12403
  // Handle regular responses
9526
12404
  const parsedResponse = await parseResponse(textContent, parsingFormat);
9527
12405
  if (parsedResponse === null) {
@@ -9535,7 +12413,8 @@ const makeResponsesAPICall = async (input, options = {}) => {
9535
12413
  reasoning_tokens: response.usage?.output_tokens_details?.reasoning_tokens || 0,
9536
12414
  provider: 'openai',
9537
12415
  model: normalizedModel,
9538
- cost: calculateCost('openai', normalizedModel, response.usage?.input_tokens || 0, response.usage?.output_tokens || 0, response.usage?.output_tokens_details?.reasoning_tokens || 0),
12416
+ cache_hit_tokens: cacheHitTokens,
12417
+ cost: calculateCost('openai', normalizedModel, response.usage?.input_tokens || 0, response.usage?.output_tokens || 0, response.usage?.output_tokens_details?.reasoning_tokens || 0, cacheHitTokens),
9539
12418
  },
9540
12419
  tool_calls: toolCalls,
9541
12420
  ...(codeInterpreterOutputs ? { code_interpreter_outputs: codeInterpreterOutputs } : {}),
@@ -9558,7 +12437,7 @@ const makeResponsesAPICall = async (input, options = {}) => {
9558
12437
  * });
9559
12438
  */
9560
12439
  async function makeLLMCall(input, options = {}) {
9561
- const { apiKey, model = DEFAULT_MODEL, responseFormat = 'text', tools, useCodeInterpreter = false, useWebSearch = false, imageBase64, imageDetail = 'high', context, } = options;
12440
+ const { apiKey, model = DEFAULT_MODEL, responseFormat = 'text', schema, schemaName = 'response', schemaDescription, schemaStrict, tools, useCodeInterpreter = false, useWebSearch = false, imageBase64, imageDetail = 'high', context, } = options;
9562
12441
  // Validate model
9563
12442
  const normalizedModel = normalizeModelName(model);
9564
12443
  if (!isSupportedModel(normalizedModel)) {
@@ -9636,9 +12515,17 @@ async function makeLLMCall(input, options = {}) {
9636
12515
  responsesOptions.temperature = 0.2;
9637
12516
  }
9638
12517
  // Configure response format
9639
- if (responseFormat === 'json') {
12518
+ if (schema) {
12519
+ responsesOptions.text = {
12520
+ format: buildJsonSchemaFormat(schema, schemaName, schemaDescription, schemaStrict),
12521
+ };
12522
+ }
12523
+ else if (responseFormat === 'json') {
9640
12524
  responsesOptions.text = { format: { type: 'json_object' } };
9641
12525
  }
12526
+ else if (typeof responseFormat === 'object' && responseFormat.type === 'json_schema') {
12527
+ responsesOptions.text = { format: responseFormat };
12528
+ }
9642
12529
  // Configure built-in tools
9643
12530
  if (useCodeInterpreter) {
9644
12531
  responsesOptions.tools = [{ type: 'code_interpreter', container: { type: 'auto' } }];
@@ -9667,6 +12554,8 @@ const MULTIMODAL_VISION_MODELS = new Set([
9667
12554
  'gpt-5-mini',
9668
12555
  'gpt-5-nano',
9669
12556
  'gpt-5.1',
12557
+ 'gpt-5.4',
12558
+ 'gpt-5.4-pro',
9670
12559
  'gpt-5.2',
9671
12560
  'gpt-5.2-pro',
9672
12561
  'gpt-5.1-codex',