@ai-sdk/provider-utils 4.0.0-beta.15 → 4.0.0-beta.16

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.mjs CHANGED
@@ -194,7 +194,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
194
194
  }
195
195
 
196
196
  // src/version.ts
197
- var VERSION = true ? "4.0.0-beta.15" : "0.0.0-test";
197
+ var VERSION = true ? "4.0.0-beta.16" : "0.0.0-test";
198
198
 
199
199
  // src/get-from-api.ts
200
200
  var getOriginalFetch = () => globalThis.fetch;
@@ -474,630 +474,799 @@ function secureJsonParse(text) {
474
474
  // src/validate-types.ts
475
475
  import { TypeValidationError as TypeValidationError2 } from "@ai-sdk/provider";
476
476
 
477
- // src/validator.ts
477
+ // src/schema.ts
478
478
  import { TypeValidationError } from "@ai-sdk/provider";
479
- var validatorSymbol = Symbol.for("vercel.ai.validator");
480
- function validator(validate) {
481
- return { [validatorSymbol]: true, validate };
482
- }
483
- function isValidator(value) {
484
- return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
485
- }
486
- function lazyValidator(createValidator) {
487
- let validator2;
488
- return () => {
489
- if (validator2 == null) {
490
- validator2 = createValidator();
479
+ import * as z4 from "zod/v4";
480
+
481
+ // src/to-json-schema/arktype-to-json-schema.ts
482
+ var arktypeToJsonSchema = (schema) => () => {
483
+ return schema.toJsonSchema();
484
+ };
485
+
486
+ // src/to-json-schema/effect-to-json-schema.ts
487
+ var effectToJsonSchema = (schema) => async () => {
488
+ try {
489
+ const { JSONSchema } = await import("effect");
490
+ return JSONSchema.make(schema);
491
+ } catch (e) {
492
+ throw new Error(`Failed to import module 'effect'`);
493
+ }
494
+ };
495
+
496
+ // src/to-json-schema/valibot-to-json-schema.ts
497
+ var valibotToJsonSchema = (schema) => {
498
+ return async () => {
499
+ try {
500
+ const { toJsonSchema } = await import("@valibot/to-json-schema");
501
+ return toJsonSchema(schema);
502
+ } catch (e) {
503
+ throw new Error(`Failed to import module '@valibot/to-json-schema'`);
491
504
  }
492
- return validator2;
493
505
  };
494
- }
495
- function asValidator(value) {
496
- return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
497
- }
498
- function standardSchemaValidator(standardSchema2) {
499
- return validator(async (value) => {
500
- const result = await standardSchema2["~standard"].validate(value);
501
- return result.issues == null ? { success: true, value: result.value } : {
502
- success: false,
503
- error: new TypeValidationError({
504
- value,
505
- cause: result.issues
506
- })
507
- };
508
- });
506
+ };
507
+
508
+ // src/to-json-schema/zod3-to-json-schema/options.ts
509
+ var ignoreOverride = Symbol(
510
+ "Let zodToJsonSchema decide on which parser to use"
511
+ );
512
+ var defaultOptions = {
513
+ name: void 0,
514
+ $refStrategy: "root",
515
+ basePath: ["#"],
516
+ effectStrategy: "input",
517
+ pipeStrategy: "all",
518
+ dateStrategy: "format:date-time",
519
+ mapStrategy: "entries",
520
+ removeAdditionalStrategy: "passthrough",
521
+ allowedAdditionalProperties: true,
522
+ rejectedAdditionalProperties: false,
523
+ definitionPath: "definitions",
524
+ strictUnions: false,
525
+ definitions: {},
526
+ errorMessages: false,
527
+ patternStrategy: "escape",
528
+ applyRegexFlags: false,
529
+ emailStrategy: "format:email",
530
+ base64Strategy: "contentEncoding:base64",
531
+ nameStrategy: "ref"
532
+ };
533
+ var getDefaultOptions = (options) => typeof options === "string" ? {
534
+ ...defaultOptions,
535
+ name: options
536
+ } : {
537
+ ...defaultOptions,
538
+ ...options
539
+ };
540
+
541
+ // src/to-json-schema/zod3-to-json-schema/select-parser.ts
542
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
543
+
544
+ // src/to-json-schema/zod3-to-json-schema/parsers/any.ts
545
+ function parseAnyDef() {
546
+ return {};
509
547
  }
510
548
 
511
- // src/validate-types.ts
512
- async function validateTypes({
513
- value,
514
- schema
515
- }) {
516
- const result = await safeValidateTypes({ value, schema });
517
- if (!result.success) {
518
- throw TypeValidationError2.wrap({ value, cause: result.error });
549
+ // src/to-json-schema/zod3-to-json-schema/parsers/array.ts
550
+ import { ZodFirstPartyTypeKind } from "zod/v3";
551
+ function parseArrayDef(def, refs) {
552
+ var _a, _b, _c;
553
+ const res = {
554
+ type: "array"
555
+ };
556
+ if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
557
+ res.items = parseDef(def.type._def, {
558
+ ...refs,
559
+ currentPath: [...refs.currentPath, "items"]
560
+ });
519
561
  }
520
- return result.value;
521
- }
522
- async function safeValidateTypes({
523
- value,
524
- schema
525
- }) {
526
- const validator2 = asValidator(schema);
527
- try {
528
- if (validator2.validate == null) {
529
- return { success: true, value, rawValue: value };
530
- }
531
- const result = await validator2.validate(value);
532
- if (result.success) {
533
- return { success: true, value: result.value, rawValue: value };
534
- }
535
- return {
536
- success: false,
537
- error: TypeValidationError2.wrap({ value, cause: result.error }),
538
- rawValue: value
539
- };
540
- } catch (error) {
541
- return {
542
- success: false,
543
- error: TypeValidationError2.wrap({ value, cause: error }),
544
- rawValue: value
545
- };
562
+ if (def.minLength) {
563
+ res.minItems = def.minLength.value;
564
+ }
565
+ if (def.maxLength) {
566
+ res.maxItems = def.maxLength.value;
567
+ }
568
+ if (def.exactLength) {
569
+ res.minItems = def.exactLength.value;
570
+ res.maxItems = def.exactLength.value;
546
571
  }
572
+ return res;
547
573
  }
548
574
 
549
- // src/parse-json.ts
550
- async function parseJSON({
551
- text,
552
- schema
553
- }) {
554
- try {
555
- const value = secureJsonParse(text);
556
- if (schema == null) {
557
- return value;
558
- }
559
- return validateTypes({ value, schema });
560
- } catch (error) {
561
- if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {
562
- throw error;
575
+ // src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts
576
+ function parseBigintDef(def) {
577
+ const res = {
578
+ type: "integer",
579
+ format: "int64"
580
+ };
581
+ if (!def.checks) return res;
582
+ for (const check of def.checks) {
583
+ switch (check.kind) {
584
+ case "min":
585
+ if (check.inclusive) {
586
+ res.minimum = check.value;
587
+ } else {
588
+ res.exclusiveMinimum = check.value;
589
+ }
590
+ break;
591
+ case "max":
592
+ if (check.inclusive) {
593
+ res.maximum = check.value;
594
+ } else {
595
+ res.exclusiveMaximum = check.value;
596
+ }
597
+ break;
598
+ case "multipleOf":
599
+ res.multipleOf = check.value;
600
+ break;
563
601
  }
564
- throw new JSONParseError({ text, cause: error });
565
602
  }
603
+ return res;
566
604
  }
567
- async function safeParseJSON({
568
- text,
569
- schema
570
- }) {
571
- try {
572
- const value = secureJsonParse(text);
573
- if (schema == null) {
574
- return { success: true, value, rawValue: value };
575
- }
576
- return await safeValidateTypes({ value, schema });
577
- } catch (error) {
605
+
606
+ // src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts
607
+ function parseBooleanDef() {
608
+ return { type: "boolean" };
609
+ }
610
+
611
+ // src/to-json-schema/zod3-to-json-schema/parsers/branded.ts
612
+ function parseBrandedDef(_def, refs) {
613
+ return parseDef(_def.type._def, refs);
614
+ }
615
+
616
+ // src/to-json-schema/zod3-to-json-schema/parsers/catch.ts
617
+ var parseCatchDef = (def, refs) => {
618
+ return parseDef(def.innerType._def, refs);
619
+ };
620
+
621
+ // src/to-json-schema/zod3-to-json-schema/parsers/date.ts
622
+ function parseDateDef(def, refs, overrideDateStrategy) {
623
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
624
+ if (Array.isArray(strategy)) {
578
625
  return {
579
- success: false,
580
- error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
581
- rawValue: void 0
626
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
582
627
  };
583
628
  }
629
+ switch (strategy) {
630
+ case "string":
631
+ case "format:date-time":
632
+ return {
633
+ type: "string",
634
+ format: "date-time"
635
+ };
636
+ case "format:date":
637
+ return {
638
+ type: "string",
639
+ format: "date"
640
+ };
641
+ case "integer":
642
+ return integerDateParser(def);
643
+ }
584
644
  }
585
- function isParsableJson(input) {
586
- try {
587
- secureJsonParse(input);
588
- return true;
589
- } catch (e) {
590
- return false;
645
+ var integerDateParser = (def) => {
646
+ const res = {
647
+ type: "integer",
648
+ format: "unix-time"
649
+ };
650
+ for (const check of def.checks) {
651
+ switch (check.kind) {
652
+ case "min":
653
+ res.minimum = check.value;
654
+ break;
655
+ case "max":
656
+ res.maximum = check.value;
657
+ break;
658
+ }
591
659
  }
660
+ return res;
661
+ };
662
+
663
+ // src/to-json-schema/zod3-to-json-schema/parsers/default.ts
664
+ function parseDefaultDef(_def, refs) {
665
+ return {
666
+ ...parseDef(_def.innerType._def, refs),
667
+ default: _def.defaultValue()
668
+ };
592
669
  }
593
670
 
594
- // src/parse-json-event-stream.ts
595
- import {
596
- EventSourceParserStream
597
- } from "eventsource-parser/stream";
598
- function parseJsonEventStream({
599
- stream,
600
- schema
601
- }) {
602
- return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
603
- new TransformStream({
604
- async transform({ data }, controller) {
605
- if (data === "[DONE]") {
606
- return;
607
- }
608
- controller.enqueue(await safeParseJSON({ text: data, schema }));
609
- }
610
- })
611
- );
671
+ // src/to-json-schema/zod3-to-json-schema/parsers/effects.ts
672
+ function parseEffectsDef(_def, refs) {
673
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
612
674
  }
613
675
 
614
- // src/parse-provider-options.ts
615
- import { InvalidArgumentError as InvalidArgumentError2 } from "@ai-sdk/provider";
616
- async function parseProviderOptions({
617
- provider,
618
- providerOptions,
619
- schema
620
- }) {
621
- if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
622
- return void 0;
623
- }
624
- const parsedProviderOptions = await safeValidateTypes({
625
- value: providerOptions[provider],
626
- schema
627
- });
628
- if (!parsedProviderOptions.success) {
629
- throw new InvalidArgumentError2({
630
- argument: "providerOptions",
631
- message: `invalid ${provider} provider options`,
632
- cause: parsedProviderOptions.error
633
- });
634
- }
635
- return parsedProviderOptions.value;
676
+ // src/to-json-schema/zod3-to-json-schema/parsers/enum.ts
677
+ function parseEnumDef(def) {
678
+ return {
679
+ type: "string",
680
+ enum: Array.from(def.values)
681
+ };
636
682
  }
637
683
 
638
- // src/post-to-api.ts
639
- import { APICallError as APICallError3 } from "@ai-sdk/provider";
640
- var getOriginalFetch2 = () => globalThis.fetch;
641
- var postJsonToApi = async ({
642
- url,
643
- headers,
644
- body,
645
- failedResponseHandler,
646
- successfulResponseHandler,
647
- abortSignal,
648
- fetch
649
- }) => postToApi({
650
- url,
651
- headers: {
652
- "Content-Type": "application/json",
653
- ...headers
654
- },
655
- body: {
656
- content: JSON.stringify(body),
657
- values: body
658
- },
659
- failedResponseHandler,
660
- successfulResponseHandler,
661
- abortSignal,
662
- fetch
663
- });
664
- var postFormDataToApi = async ({
665
- url,
666
- headers,
667
- formData,
668
- failedResponseHandler,
669
- successfulResponseHandler,
670
- abortSignal,
671
- fetch
672
- }) => postToApi({
673
- url,
674
- headers,
675
- body: {
676
- content: formData,
677
- values: Object.fromEntries(formData.entries())
678
- },
679
- failedResponseHandler,
680
- successfulResponseHandler,
681
- abortSignal,
682
- fetch
683
- });
684
- var postToApi = async ({
685
- url,
686
- headers = {},
687
- body,
688
- successfulResponseHandler,
689
- failedResponseHandler,
690
- abortSignal,
691
- fetch = getOriginalFetch2()
692
- }) => {
693
- try {
694
- const response = await fetch(url, {
695
- method: "POST",
696
- headers: withUserAgentSuffix(
697
- headers,
698
- `ai-sdk/provider-utils/${VERSION}`,
699
- getRuntimeEnvironmentUserAgent()
700
- ),
701
- body: body.content,
702
- signal: abortSignal
703
- });
704
- const responseHeaders = extractResponseHeaders(response);
705
- if (!response.ok) {
706
- let errorInformation;
707
- try {
708
- errorInformation = await failedResponseHandler({
709
- response,
710
- url,
711
- requestBodyValues: body.values
712
- });
713
- } catch (error) {
714
- if (isAbortError(error) || APICallError3.isInstance(error)) {
715
- throw error;
716
- }
717
- throw new APICallError3({
718
- message: "Failed to process error response",
719
- cause: error,
720
- statusCode: response.status,
721
- url,
722
- responseHeaders,
723
- requestBodyValues: body.values
724
- });
725
- }
726
- throw errorInformation.value;
727
- }
728
- try {
729
- return await successfulResponseHandler({
730
- response,
731
- url,
732
- requestBodyValues: body.values
733
- });
734
- } catch (error) {
735
- if (error instanceof Error) {
736
- if (isAbortError(error) || APICallError3.isInstance(error)) {
737
- throw error;
738
- }
684
+ // src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts
685
+ var isJsonSchema7AllOfType = (type) => {
686
+ if ("type" in type && type.type === "string") return false;
687
+ return "allOf" in type;
688
+ };
689
+ function parseIntersectionDef(def, refs) {
690
+ const allOf = [
691
+ parseDef(def.left._def, {
692
+ ...refs,
693
+ currentPath: [...refs.currentPath, "allOf", "0"]
694
+ }),
695
+ parseDef(def.right._def, {
696
+ ...refs,
697
+ currentPath: [...refs.currentPath, "allOf", "1"]
698
+ })
699
+ ].filter((x) => !!x);
700
+ const mergedAllOf = [];
701
+ allOf.forEach((schema) => {
702
+ if (isJsonSchema7AllOfType(schema)) {
703
+ mergedAllOf.push(...schema.allOf);
704
+ } else {
705
+ let nestedSchema = schema;
706
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
707
+ const { additionalProperties, ...rest } = schema;
708
+ nestedSchema = rest;
739
709
  }
740
- throw new APICallError3({
741
- message: "Failed to process successful response",
742
- cause: error,
743
- statusCode: response.status,
744
- url,
745
- responseHeaders,
746
- requestBodyValues: body.values
747
- });
710
+ mergedAllOf.push(nestedSchema);
748
711
  }
749
- } catch (error) {
750
- throw handleFetchError({ error, url, requestBodyValues: body.values });
751
- }
752
- };
753
-
754
- // src/types/tool.ts
755
- function tool(tool2) {
756
- return tool2;
757
- }
758
- function dynamicTool(tool2) {
759
- return { ...tool2, type: "dynamic" };
760
- }
761
-
762
- // src/provider-defined-tool-factory.ts
763
- function createProviderDefinedToolFactory({
764
- id,
765
- name,
766
- inputSchema
767
- }) {
768
- return ({
769
- execute,
770
- outputSchema,
771
- needsApproval,
772
- toModelOutput,
773
- onInputStart,
774
- onInputDelta,
775
- onInputAvailable,
776
- ...args
777
- }) => tool({
778
- type: "provider-defined",
779
- id,
780
- name,
781
- args,
782
- inputSchema,
783
- outputSchema,
784
- execute,
785
- needsApproval,
786
- toModelOutput,
787
- onInputStart,
788
- onInputDelta,
789
- onInputAvailable
790
- });
791
- }
792
- function createProviderDefinedToolFactoryWithOutputSchema({
793
- id,
794
- name,
795
- inputSchema,
796
- outputSchema
797
- }) {
798
- return ({
799
- execute,
800
- needsApproval,
801
- toModelOutput,
802
- onInputStart,
803
- onInputDelta,
804
- onInputAvailable,
805
- ...args
806
- }) => tool({
807
- type: "provider-defined",
808
- id,
809
- name,
810
- args,
811
- inputSchema,
812
- outputSchema,
813
- execute,
814
- needsApproval,
815
- toModelOutput,
816
- onInputStart,
817
- onInputDelta,
818
- onInputAvailable
819
712
  });
713
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
820
714
  }
821
715
 
822
- // src/resolve.ts
823
- async function resolve(value) {
824
- if (typeof value === "function") {
825
- value = value();
826
- }
827
- return Promise.resolve(value);
828
- }
829
-
830
- // src/response-handler.ts
831
- import { APICallError as APICallError4, EmptyResponseBodyError } from "@ai-sdk/provider";
832
- var createJsonErrorResponseHandler = ({
833
- errorSchema,
834
- errorToMessage,
835
- isRetryable
836
- }) => async ({ response, url, requestBodyValues }) => {
837
- const responseBody = await response.text();
838
- const responseHeaders = extractResponseHeaders(response);
839
- if (responseBody.trim() === "") {
840
- return {
841
- responseHeaders,
842
- value: new APICallError4({
843
- message: response.statusText,
844
- url,
845
- requestBodyValues,
846
- statusCode: response.status,
847
- responseHeaders,
848
- responseBody,
849
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
850
- })
851
- };
852
- }
853
- try {
854
- const parsedError = await parseJSON({
855
- text: responseBody,
856
- schema: errorSchema
857
- });
858
- return {
859
- responseHeaders,
860
- value: new APICallError4({
861
- message: errorToMessage(parsedError),
862
- url,
863
- requestBodyValues,
864
- statusCode: response.status,
865
- responseHeaders,
866
- responseBody,
867
- data: parsedError,
868
- isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
869
- })
870
- };
871
- } catch (parseError) {
872
- return {
873
- responseHeaders,
874
- value: new APICallError4({
875
- message: response.statusText,
876
- url,
877
- requestBodyValues,
878
- statusCode: response.status,
879
- responseHeaders,
880
- responseBody,
881
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
882
- })
883
- };
884
- }
885
- };
886
- var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
887
- const responseHeaders = extractResponseHeaders(response);
888
- if (response.body == null) {
889
- throw new EmptyResponseBodyError({});
716
+ // src/to-json-schema/zod3-to-json-schema/parsers/literal.ts
717
+ function parseLiteralDef(def) {
718
+ const parsedType = typeof def.value;
719
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
720
+ return {
721
+ type: Array.isArray(def.value) ? "array" : "object"
722
+ };
890
723
  }
891
724
  return {
892
- responseHeaders,
893
- value: parseJsonEventStream({
894
- stream: response.body,
895
- schema: chunkSchema
896
- })
725
+ type: parsedType === "bigint" ? "integer" : parsedType,
726
+ const: def.value
897
727
  };
728
+ }
729
+
730
+ // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
731
+ import {
732
+ ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
733
+ } from "zod/v3";
734
+
735
+ // src/to-json-schema/zod3-to-json-schema/parsers/string.ts
736
+ var emojiRegex = void 0;
737
+ var zodPatterns = {
738
+ /**
739
+ * `c` was changed to `[cC]` to replicate /i flag
740
+ */
741
+ cuid: /^[cC][^\s-]{8,}$/,
742
+ cuid2: /^[0-9a-z]+$/,
743
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
744
+ /**
745
+ * `a-z` was added to replicate /i flag
746
+ */
747
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
748
+ /**
749
+ * Constructed a valid Unicode RegExp
750
+ *
751
+ * Lazily instantiate since this type of regex isn't supported
752
+ * in all envs (e.g. React Native).
753
+ *
754
+ * See:
755
+ * https://github.com/colinhacks/zod/issues/2433
756
+ * Fix in Zod:
757
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
758
+ */
759
+ emoji: () => {
760
+ if (emojiRegex === void 0) {
761
+ emojiRegex = RegExp(
762
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
763
+ "u"
764
+ );
765
+ }
766
+ return emojiRegex;
767
+ },
768
+ /**
769
+ * Unused
770
+ */
771
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
772
+ /**
773
+ * Unused
774
+ */
775
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
776
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
777
+ /**
778
+ * Unused
779
+ */
780
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
781
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
782
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
783
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
784
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
785
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
898
786
  };
899
- var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
900
- const responseHeaders = extractResponseHeaders(response);
901
- if (response.body == null) {
902
- throw new EmptyResponseBodyError({});
903
- }
904
- let buffer = "";
905
- return {
906
- responseHeaders,
907
- value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(
908
- new TransformStream({
909
- async transform(chunkText, controller) {
910
- if (chunkText.endsWith("\n")) {
911
- controller.enqueue(
912
- await safeParseJSON({
913
- text: buffer + chunkText,
914
- schema: chunkSchema
915
- })
916
- );
917
- buffer = "";
918
- } else {
919
- buffer += chunkText;
787
+ function parseStringDef(def, refs) {
788
+ const res = {
789
+ type: "string"
790
+ };
791
+ if (def.checks) {
792
+ for (const check of def.checks) {
793
+ switch (check.kind) {
794
+ case "min":
795
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
796
+ break;
797
+ case "max":
798
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
799
+ break;
800
+ case "email":
801
+ switch (refs.emailStrategy) {
802
+ case "format:email":
803
+ addFormat(res, "email", check.message, refs);
804
+ break;
805
+ case "format:idn-email":
806
+ addFormat(res, "idn-email", check.message, refs);
807
+ break;
808
+ case "pattern:zod":
809
+ addPattern(res, zodPatterns.email, check.message, refs);
810
+ break;
920
811
  }
812
+ break;
813
+ case "url":
814
+ addFormat(res, "uri", check.message, refs);
815
+ break;
816
+ case "uuid":
817
+ addFormat(res, "uuid", check.message, refs);
818
+ break;
819
+ case "regex":
820
+ addPattern(res, check.regex, check.message, refs);
821
+ break;
822
+ case "cuid":
823
+ addPattern(res, zodPatterns.cuid, check.message, refs);
824
+ break;
825
+ case "cuid2":
826
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
827
+ break;
828
+ case "startsWith":
829
+ addPattern(
830
+ res,
831
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
832
+ check.message,
833
+ refs
834
+ );
835
+ break;
836
+ case "endsWith":
837
+ addPattern(
838
+ res,
839
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
840
+ check.message,
841
+ refs
842
+ );
843
+ break;
844
+ case "datetime":
845
+ addFormat(res, "date-time", check.message, refs);
846
+ break;
847
+ case "date":
848
+ addFormat(res, "date", check.message, refs);
849
+ break;
850
+ case "time":
851
+ addFormat(res, "time", check.message, refs);
852
+ break;
853
+ case "duration":
854
+ addFormat(res, "duration", check.message, refs);
855
+ break;
856
+ case "length":
857
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
858
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
859
+ break;
860
+ case "includes": {
861
+ addPattern(
862
+ res,
863
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
864
+ check.message,
865
+ refs
866
+ );
867
+ break;
921
868
  }
922
- })
923
- )
924
- };
925
- };
926
- var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
927
- const responseBody = await response.text();
928
- const parsedResult = await safeParseJSON({
929
- text: responseBody,
930
- schema: responseSchema
931
- });
932
- const responseHeaders = extractResponseHeaders(response);
933
- if (!parsedResult.success) {
934
- throw new APICallError4({
935
- message: "Invalid JSON response",
936
- cause: parsedResult.error,
937
- statusCode: response.status,
938
- responseHeaders,
939
- responseBody,
940
- url,
941
- requestBodyValues
942
- });
869
+ case "ip": {
870
+ if (check.version !== "v6") {
871
+ addFormat(res, "ipv4", check.message, refs);
872
+ }
873
+ if (check.version !== "v4") {
874
+ addFormat(res, "ipv6", check.message, refs);
875
+ }
876
+ break;
877
+ }
878
+ case "base64url":
879
+ addPattern(res, zodPatterns.base64url, check.message, refs);
880
+ break;
881
+ case "jwt":
882
+ addPattern(res, zodPatterns.jwt, check.message, refs);
883
+ break;
884
+ case "cidr": {
885
+ if (check.version !== "v6") {
886
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
887
+ }
888
+ if (check.version !== "v4") {
889
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
890
+ }
891
+ break;
892
+ }
893
+ case "emoji":
894
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
895
+ break;
896
+ case "ulid": {
897
+ addPattern(res, zodPatterns.ulid, check.message, refs);
898
+ break;
899
+ }
900
+ case "base64": {
901
+ switch (refs.base64Strategy) {
902
+ case "format:binary": {
903
+ addFormat(res, "binary", check.message, refs);
904
+ break;
905
+ }
906
+ case "contentEncoding:base64": {
907
+ res.contentEncoding = "base64";
908
+ break;
909
+ }
910
+ case "pattern:zod": {
911
+ addPattern(res, zodPatterns.base64, check.message, refs);
912
+ break;
913
+ }
914
+ }
915
+ break;
916
+ }
917
+ case "nanoid": {
918
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
919
+ }
920
+ case "toLowerCase":
921
+ case "toUpperCase":
922
+ case "trim":
923
+ break;
924
+ default:
925
+ /* @__PURE__ */ ((_) => {
926
+ })(check);
927
+ }
928
+ }
943
929
  }
944
- return {
945
- responseHeaders,
946
- value: parsedResult.value,
947
- rawValue: parsedResult.rawValue
948
- };
949
- };
950
- var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
951
- const responseHeaders = extractResponseHeaders(response);
952
- if (!response.body) {
953
- throw new APICallError4({
954
- message: "Response body is empty",
955
- url,
956
- requestBodyValues,
957
- statusCode: response.status,
958
- responseHeaders,
959
- responseBody: void 0
930
+ return res;
931
+ }
932
+ function escapeLiteralCheckValue(literal, refs) {
933
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
934
+ }
935
+ var ALPHA_NUMERIC = new Set(
936
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
937
+ );
938
+ function escapeNonAlphaNumeric(source) {
939
+ let result = "";
940
+ for (let i = 0; i < source.length; i++) {
941
+ if (!ALPHA_NUMERIC.has(source[i])) {
942
+ result += "\\";
943
+ }
944
+ result += source[i];
945
+ }
946
+ return result;
947
+ }
948
+ function addFormat(schema, value, message, refs) {
949
+ var _a;
950
+ if (schema.format || ((_a = schema.anyOf) == null ? void 0 : _a.some((x) => x.format))) {
951
+ if (!schema.anyOf) {
952
+ schema.anyOf = [];
953
+ }
954
+ if (schema.format) {
955
+ schema.anyOf.push({
956
+ format: schema.format
957
+ });
958
+ delete schema.format;
959
+ }
960
+ schema.anyOf.push({
961
+ format: value,
962
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
960
963
  });
964
+ } else {
965
+ schema.format = value;
961
966
  }
962
- try {
963
- const buffer = await response.arrayBuffer();
964
- return {
965
- responseHeaders,
966
- value: new Uint8Array(buffer)
967
- };
968
- } catch (error) {
969
- throw new APICallError4({
970
- message: "Failed to read response as array buffer",
971
- url,
972
- requestBodyValues,
973
- statusCode: response.status,
974
- responseHeaders,
975
- responseBody: void 0,
976
- cause: error
967
+ }
968
+ function addPattern(schema, regex, message, refs) {
969
+ var _a;
970
+ if (schema.pattern || ((_a = schema.allOf) == null ? void 0 : _a.some((x) => x.pattern))) {
971
+ if (!schema.allOf) {
972
+ schema.allOf = [];
973
+ }
974
+ if (schema.pattern) {
975
+ schema.allOf.push({
976
+ pattern: schema.pattern
977
+ });
978
+ delete schema.pattern;
979
+ }
980
+ schema.allOf.push({
981
+ pattern: stringifyRegExpWithFlags(regex, refs),
982
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
977
983
  });
984
+ } else {
985
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
978
986
  }
979
- };
980
- var createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {
981
- const responseHeaders = extractResponseHeaders(response);
982
- const responseBody = await response.text();
983
- return {
984
- responseHeaders,
985
- value: new APICallError4({
986
- message: response.statusText,
987
- url,
988
- requestBodyValues,
989
- statusCode: response.status,
990
- responseHeaders,
991
- responseBody
992
- })
987
+ }
988
+ function stringifyRegExpWithFlags(regex, refs) {
989
+ var _a;
990
+ if (!refs.applyRegexFlags || !regex.flags) {
991
+ return regex.source;
992
+ }
993
+ const flags = {
994
+ i: regex.flags.includes("i"),
995
+ // Case-insensitive
996
+ m: regex.flags.includes("m"),
997
+ // `^` and `$` matches adjacent to newline characters
998
+ s: regex.flags.includes("s")
999
+ // `.` matches newlines
993
1000
  };
994
- };
995
-
996
- // src/schema.ts
997
- import { TypeValidationError as TypeValidationError4 } from "@ai-sdk/provider";
998
- import * as z4 from "zod/v4";
999
-
1000
- // src/to-json-schema/arktype-to-json-schema.ts
1001
- var arktypeToJsonSchema = async (schema) => {
1002
- return schema.toJsonSchema();
1003
- };
1004
-
1005
- // src/to-json-schema/effect-to-json-schema.ts
1006
- var effectToJsonSchema = async (schema) => {
1001
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
1002
+ let pattern = "";
1003
+ let isEscaped = false;
1004
+ let inCharGroup = false;
1005
+ let inCharRange = false;
1006
+ for (let i = 0; i < source.length; i++) {
1007
+ if (isEscaped) {
1008
+ pattern += source[i];
1009
+ isEscaped = false;
1010
+ continue;
1011
+ }
1012
+ if (flags.i) {
1013
+ if (inCharGroup) {
1014
+ if (source[i].match(/[a-z]/)) {
1015
+ if (inCharRange) {
1016
+ pattern += source[i];
1017
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1018
+ inCharRange = false;
1019
+ } else if (source[i + 1] === "-" && ((_a = source[i + 2]) == null ? void 0 : _a.match(/[a-z]/))) {
1020
+ pattern += source[i];
1021
+ inCharRange = true;
1022
+ } else {
1023
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
1024
+ }
1025
+ continue;
1026
+ }
1027
+ } else if (source[i].match(/[a-z]/)) {
1028
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1029
+ continue;
1030
+ }
1031
+ }
1032
+ if (flags.m) {
1033
+ if (source[i] === "^") {
1034
+ pattern += `(^|(?<=[\r
1035
+ ]))`;
1036
+ continue;
1037
+ } else if (source[i] === "$") {
1038
+ pattern += `($|(?=[\r
1039
+ ]))`;
1040
+ continue;
1041
+ }
1042
+ }
1043
+ if (flags.s && source[i] === ".") {
1044
+ pattern += inCharGroup ? `${source[i]}\r
1045
+ ` : `[${source[i]}\r
1046
+ ]`;
1047
+ continue;
1048
+ }
1049
+ pattern += source[i];
1050
+ if (source[i] === "\\") {
1051
+ isEscaped = true;
1052
+ } else if (inCharGroup && source[i] === "]") {
1053
+ inCharGroup = false;
1054
+ } else if (!inCharGroup && source[i] === "[") {
1055
+ inCharGroup = true;
1056
+ }
1057
+ }
1007
1058
  try {
1008
- const { JSONSchema } = await import("effect");
1009
- return JSONSchema.make(schema);
1059
+ new RegExp(pattern);
1010
1060
  } catch (e) {
1011
- throw new Error(`Failed to import module 'effect'`);
1061
+ console.warn(
1062
+ `Could not convert regex pattern at ${refs.currentPath.join(
1063
+ "/"
1064
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
1065
+ );
1066
+ return regex.source;
1012
1067
  }
1013
- };
1068
+ return pattern;
1069
+ }
1014
1070
 
1015
- // src/to-json-schema/valibot-to-json-schema.ts
1016
- var valibotToJsonSchema = async (schema) => {
1017
- try {
1018
- const { toJsonSchema } = await import("@valibot/to-json-schema");
1019
- return toJsonSchema(schema);
1020
- } catch (e) {
1021
- throw new Error(`Failed to import module '@valibot/to-json-schema'`);
1071
+ // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
1072
+ function parseRecordDef(def, refs) {
1073
+ var _a, _b, _c, _d, _e, _f;
1074
+ const schema = {
1075
+ type: "object",
1076
+ additionalProperties: (_a = parseDef(def.valueType._def, {
1077
+ ...refs,
1078
+ currentPath: [...refs.currentPath, "additionalProperties"]
1079
+ })) != null ? _a : refs.allowedAdditionalProperties
1080
+ };
1081
+ if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1082
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1083
+ return {
1084
+ ...schema,
1085
+ propertyNames: keyType
1086
+ };
1087
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1088
+ return {
1089
+ ...schema,
1090
+ propertyNames: {
1091
+ enum: def.keyType._def.values
1092
+ }
1093
+ };
1094
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1095
+ const { type, ...keyType } = parseBrandedDef(
1096
+ def.keyType._def,
1097
+ refs
1098
+ );
1099
+ return {
1100
+ ...schema,
1101
+ propertyNames: keyType
1102
+ };
1022
1103
  }
1023
- };
1104
+ return schema;
1105
+ }
1024
1106
 
1025
- // src/to-json-schema/zod3-to-json-schema/options.ts
1026
- var ignoreOverride = Symbol(
1027
- "Let zodToJsonSchema decide on which parser to use"
1028
- );
1029
- var defaultOptions = {
1030
- name: void 0,
1031
- $refStrategy: "root",
1032
- basePath: ["#"],
1033
- effectStrategy: "input",
1034
- pipeStrategy: "all",
1035
- dateStrategy: "format:date-time",
1036
- mapStrategy: "entries",
1037
- removeAdditionalStrategy: "passthrough",
1038
- allowedAdditionalProperties: true,
1039
- rejectedAdditionalProperties: false,
1040
- definitionPath: "definitions",
1041
- strictUnions: false,
1042
- definitions: {},
1043
- errorMessages: false,
1044
- patternStrategy: "escape",
1045
- applyRegexFlags: false,
1046
- emailStrategy: "format:email",
1047
- base64Strategy: "contentEncoding:base64",
1048
- nameStrategy: "ref"
1049
- };
1050
- var getDefaultOptions = (options) => typeof options === "string" ? {
1051
- ...defaultOptions,
1052
- name: options
1053
- } : {
1054
- ...defaultOptions,
1055
- ...options
1056
- };
1107
+ // src/to-json-schema/zod3-to-json-schema/parsers/map.ts
1108
+ function parseMapDef(def, refs) {
1109
+ if (refs.mapStrategy === "record") {
1110
+ return parseRecordDef(def, refs);
1111
+ }
1112
+ const keys = parseDef(def.keyType._def, {
1113
+ ...refs,
1114
+ currentPath: [...refs.currentPath, "items", "items", "0"]
1115
+ }) || parseAnyDef();
1116
+ const values = parseDef(def.valueType._def, {
1117
+ ...refs,
1118
+ currentPath: [...refs.currentPath, "items", "items", "1"]
1119
+ }) || parseAnyDef();
1120
+ return {
1121
+ type: "array",
1122
+ maxItems: 125,
1123
+ items: {
1124
+ type: "array",
1125
+ items: [keys, values],
1126
+ minItems: 2,
1127
+ maxItems: 2
1128
+ }
1129
+ };
1130
+ }
1057
1131
 
1058
- // src/to-json-schema/zod3-to-json-schema/select-parser.ts
1059
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
1132
+ // src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts
1133
+ function parseNativeEnumDef(def) {
1134
+ const object = def.values;
1135
+ const actualKeys = Object.keys(def.values).filter((key) => {
1136
+ return typeof object[object[key]] !== "number";
1137
+ });
1138
+ const actualValues = actualKeys.map((key) => object[key]);
1139
+ const parsedTypes = Array.from(
1140
+ new Set(actualValues.map((values) => typeof values))
1141
+ );
1142
+ return {
1143
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1144
+ enum: actualValues
1145
+ };
1146
+ }
1060
1147
 
1061
- // src/to-json-schema/zod3-to-json-schema/parsers/any.ts
1062
- function parseAnyDef() {
1063
- return {};
1148
+ // src/to-json-schema/zod3-to-json-schema/parsers/never.ts
1149
+ function parseNeverDef() {
1150
+ return { not: parseAnyDef() };
1064
1151
  }
1065
1152
 
1066
- // src/to-json-schema/zod3-to-json-schema/parsers/array.ts
1067
- import { ZodFirstPartyTypeKind } from "zod/v3";
1068
- function parseArrayDef(def, refs) {
1069
- var _a, _b, _c;
1070
- const res = {
1071
- type: "array"
1153
+ // src/to-json-schema/zod3-to-json-schema/parsers/null.ts
1154
+ function parseNullDef() {
1155
+ return {
1156
+ type: "null"
1072
1157
  };
1073
- if (((_a = def.type) == null ? void 0 : _a._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
1074
- res.items = parseDef(def.type._def, {
1075
- ...refs,
1076
- currentPath: [...refs.currentPath, "items"]
1077
- });
1078
- }
1079
- if (def.minLength) {
1080
- res.minItems = def.minLength.value;
1081
- }
1082
- if (def.maxLength) {
1083
- res.maxItems = def.maxLength.value;
1158
+ }
1159
+
1160
+ // src/to-json-schema/zod3-to-json-schema/parsers/union.ts
1161
+ var primitiveMappings = {
1162
+ ZodString: "string",
1163
+ ZodNumber: "number",
1164
+ ZodBigInt: "integer",
1165
+ ZodBoolean: "boolean",
1166
+ ZodNull: "null"
1167
+ };
1168
+ function parseUnionDef(def, refs) {
1169
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1170
+ if (options.every(
1171
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1172
+ )) {
1173
+ const types = options.reduce((types2, x) => {
1174
+ const type = primitiveMappings[x._def.typeName];
1175
+ return type && !types2.includes(type) ? [...types2, type] : types2;
1176
+ }, []);
1177
+ return {
1178
+ type: types.length > 1 ? types : types[0]
1179
+ };
1180
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1181
+ const types = options.reduce(
1182
+ (acc, x) => {
1183
+ const type = typeof x._def.value;
1184
+ switch (type) {
1185
+ case "string":
1186
+ case "number":
1187
+ case "boolean":
1188
+ return [...acc, type];
1189
+ case "bigint":
1190
+ return [...acc, "integer"];
1191
+ case "object":
1192
+ if (x._def.value === null) return [...acc, "null"];
1193
+ case "symbol":
1194
+ case "undefined":
1195
+ case "function":
1196
+ default:
1197
+ return acc;
1198
+ }
1199
+ },
1200
+ []
1201
+ );
1202
+ if (types.length === options.length) {
1203
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1204
+ return {
1205
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1206
+ enum: options.reduce(
1207
+ (acc, x) => {
1208
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1209
+ },
1210
+ []
1211
+ )
1212
+ };
1213
+ }
1214
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1215
+ return {
1216
+ type: "string",
1217
+ enum: options.reduce(
1218
+ (acc, x) => [
1219
+ ...acc,
1220
+ ...x._def.values.filter((x2) => !acc.includes(x2))
1221
+ ],
1222
+ []
1223
+ )
1224
+ };
1084
1225
  }
1085
- if (def.exactLength) {
1086
- res.minItems = def.exactLength.value;
1087
- res.maxItems = def.exactLength.value;
1226
+ return asAnyOf(def, refs);
1227
+ }
1228
+ var asAnyOf = (def, refs) => {
1229
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1230
+ (x, i) => parseDef(x._def, {
1231
+ ...refs,
1232
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
1233
+ })
1234
+ ).filter(
1235
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1236
+ );
1237
+ return anyOf.length ? { anyOf } : void 0;
1238
+ };
1239
+
1240
+ // src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts
1241
+ function parseNullableDef(def, refs) {
1242
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1243
+ def.innerType._def.typeName
1244
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1245
+ return {
1246
+ type: [
1247
+ primitiveMappings[def.innerType._def.typeName],
1248
+ "null"
1249
+ ]
1250
+ };
1088
1251
  }
1089
- return res;
1252
+ const base = parseDef(def.innerType._def, {
1253
+ ...refs,
1254
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1255
+ });
1256
+ return base && { anyOf: [base, { type: "null" }] };
1090
1257
  }
1091
1258
 
1092
- // src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts
1093
- function parseBigintDef(def) {
1259
+ // src/to-json-schema/zod3-to-json-schema/parsers/number.ts
1260
+ function parseNumberDef(def) {
1094
1261
  const res = {
1095
- type: "integer",
1096
- format: "int64"
1262
+ type: "number"
1097
1263
  };
1098
1264
  if (!def.checks) return res;
1099
1265
  for (const check of def.checks) {
1100
1266
  switch (check.kind) {
1267
+ case "int":
1268
+ res.type = "integer";
1269
+ break;
1101
1270
  case "min":
1102
1271
  if (check.inclusive) {
1103
1272
  res.minimum = check.value;
@@ -1117,1219 +1286,1017 @@ function parseBigintDef(def) {
1117
1286
  break;
1118
1287
  }
1119
1288
  }
1120
- return res;
1121
- }
1122
-
1123
- // src/to-json-schema/zod3-to-json-schema/parsers/boolean.ts
1124
- function parseBooleanDef() {
1125
- return { type: "boolean" };
1126
- }
1127
-
1128
- // src/to-json-schema/zod3-to-json-schema/parsers/branded.ts
1129
- function parseBrandedDef(_def, refs) {
1130
- return parseDef(_def.type._def, refs);
1131
- }
1289
+ return res;
1290
+ }
1291
+
1292
+ // src/to-json-schema/zod3-to-json-schema/parsers/object.ts
1293
+ function parseObjectDef(def, refs) {
1294
+ const result = {
1295
+ type: "object",
1296
+ properties: {}
1297
+ };
1298
+ const required = [];
1299
+ const shape = def.shape();
1300
+ for (const propName in shape) {
1301
+ let propDef = shape[propName];
1302
+ if (propDef === void 0 || propDef._def === void 0) {
1303
+ continue;
1304
+ }
1305
+ const propOptional = safeIsOptional(propDef);
1306
+ const parsedDef = parseDef(propDef._def, {
1307
+ ...refs,
1308
+ currentPath: [...refs.currentPath, "properties", propName],
1309
+ propertyPath: [...refs.currentPath, "properties", propName]
1310
+ });
1311
+ if (parsedDef === void 0) {
1312
+ continue;
1313
+ }
1314
+ result.properties[propName] = parsedDef;
1315
+ if (!propOptional) {
1316
+ required.push(propName);
1317
+ }
1318
+ }
1319
+ if (required.length) {
1320
+ result.required = required;
1321
+ }
1322
+ const additionalProperties = decideAdditionalProperties(def, refs);
1323
+ if (additionalProperties !== void 0) {
1324
+ result.additionalProperties = additionalProperties;
1325
+ }
1326
+ return result;
1327
+ }
1328
+ function decideAdditionalProperties(def, refs) {
1329
+ if (def.catchall._def.typeName !== "ZodNever") {
1330
+ return parseDef(def.catchall._def, {
1331
+ ...refs,
1332
+ currentPath: [...refs.currentPath, "additionalProperties"]
1333
+ });
1334
+ }
1335
+ switch (def.unknownKeys) {
1336
+ case "passthrough":
1337
+ return refs.allowedAdditionalProperties;
1338
+ case "strict":
1339
+ return refs.rejectedAdditionalProperties;
1340
+ case "strip":
1341
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1342
+ }
1343
+ }
1344
+ function safeIsOptional(schema) {
1345
+ try {
1346
+ return schema.isOptional();
1347
+ } catch (e) {
1348
+ return true;
1349
+ }
1350
+ }
1351
+
1352
+ // src/to-json-schema/zod3-to-json-schema/parsers/optional.ts
1353
+ var parseOptionalDef = (def, refs) => {
1354
+ var _a;
1355
+ if (refs.currentPath.toString() === ((_a = refs.propertyPath) == null ? void 0 : _a.toString())) {
1356
+ return parseDef(def.innerType._def, refs);
1357
+ }
1358
+ const innerSchema = parseDef(def.innerType._def, {
1359
+ ...refs,
1360
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1361
+ });
1362
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1363
+ };
1364
+
1365
+ // src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts
1366
+ var parsePipelineDef = (def, refs) => {
1367
+ if (refs.pipeStrategy === "input") {
1368
+ return parseDef(def.in._def, refs);
1369
+ } else if (refs.pipeStrategy === "output") {
1370
+ return parseDef(def.out._def, refs);
1371
+ }
1372
+ const a = parseDef(def.in._def, {
1373
+ ...refs,
1374
+ currentPath: [...refs.currentPath, "allOf", "0"]
1375
+ });
1376
+ const b = parseDef(def.out._def, {
1377
+ ...refs,
1378
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1379
+ });
1380
+ return {
1381
+ allOf: [a, b].filter((x) => x !== void 0)
1382
+ };
1383
+ };
1384
+
1385
+ // src/to-json-schema/zod3-to-json-schema/parsers/promise.ts
1386
+ function parsePromiseDef(def, refs) {
1387
+ return parseDef(def.type._def, refs);
1388
+ }
1389
+
1390
+ // src/to-json-schema/zod3-to-json-schema/parsers/set.ts
1391
+ function parseSetDef(def, refs) {
1392
+ const items = parseDef(def.valueType._def, {
1393
+ ...refs,
1394
+ currentPath: [...refs.currentPath, "items"]
1395
+ });
1396
+ const schema = {
1397
+ type: "array",
1398
+ uniqueItems: true,
1399
+ items
1400
+ };
1401
+ if (def.minSize) {
1402
+ schema.minItems = def.minSize.value;
1403
+ }
1404
+ if (def.maxSize) {
1405
+ schema.maxItems = def.maxSize.value;
1406
+ }
1407
+ return schema;
1408
+ }
1409
+
1410
+ // src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts
1411
+ function parseTupleDef(def, refs) {
1412
+ if (def.rest) {
1413
+ return {
1414
+ type: "array",
1415
+ minItems: def.items.length,
1416
+ items: def.items.map(
1417
+ (x, i) => parseDef(x._def, {
1418
+ ...refs,
1419
+ currentPath: [...refs.currentPath, "items", `${i}`]
1420
+ })
1421
+ ).reduce(
1422
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1423
+ []
1424
+ ),
1425
+ additionalItems: parseDef(def.rest._def, {
1426
+ ...refs,
1427
+ currentPath: [...refs.currentPath, "additionalItems"]
1428
+ })
1429
+ };
1430
+ } else {
1431
+ return {
1432
+ type: "array",
1433
+ minItems: def.items.length,
1434
+ maxItems: def.items.length,
1435
+ items: def.items.map(
1436
+ (x, i) => parseDef(x._def, {
1437
+ ...refs,
1438
+ currentPath: [...refs.currentPath, "items", `${i}`]
1439
+ })
1440
+ ).reduce(
1441
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1442
+ []
1443
+ )
1444
+ };
1445
+ }
1446
+ }
1447
+
1448
+ // src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts
1449
+ function parseUndefinedDef() {
1450
+ return {
1451
+ not: parseAnyDef()
1452
+ };
1453
+ }
1454
+
1455
+ // src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts
1456
+ function parseUnknownDef() {
1457
+ return parseAnyDef();
1458
+ }
1459
+
1460
+ // src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts
1461
+ var parseReadonlyDef = (def, refs) => {
1462
+ return parseDef(def.innerType._def, refs);
1463
+ };
1464
+
1465
+ // src/to-json-schema/zod3-to-json-schema/select-parser.ts
1466
+ var selectParser = (def, typeName, refs) => {
1467
+ switch (typeName) {
1468
+ case ZodFirstPartyTypeKind3.ZodString:
1469
+ return parseStringDef(def, refs);
1470
+ case ZodFirstPartyTypeKind3.ZodNumber:
1471
+ return parseNumberDef(def);
1472
+ case ZodFirstPartyTypeKind3.ZodObject:
1473
+ return parseObjectDef(def, refs);
1474
+ case ZodFirstPartyTypeKind3.ZodBigInt:
1475
+ return parseBigintDef(def);
1476
+ case ZodFirstPartyTypeKind3.ZodBoolean:
1477
+ return parseBooleanDef();
1478
+ case ZodFirstPartyTypeKind3.ZodDate:
1479
+ return parseDateDef(def, refs);
1480
+ case ZodFirstPartyTypeKind3.ZodUndefined:
1481
+ return parseUndefinedDef();
1482
+ case ZodFirstPartyTypeKind3.ZodNull:
1483
+ return parseNullDef();
1484
+ case ZodFirstPartyTypeKind3.ZodArray:
1485
+ return parseArrayDef(def, refs);
1486
+ case ZodFirstPartyTypeKind3.ZodUnion:
1487
+ case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1488
+ return parseUnionDef(def, refs);
1489
+ case ZodFirstPartyTypeKind3.ZodIntersection:
1490
+ return parseIntersectionDef(def, refs);
1491
+ case ZodFirstPartyTypeKind3.ZodTuple:
1492
+ return parseTupleDef(def, refs);
1493
+ case ZodFirstPartyTypeKind3.ZodRecord:
1494
+ return parseRecordDef(def, refs);
1495
+ case ZodFirstPartyTypeKind3.ZodLiteral:
1496
+ return parseLiteralDef(def);
1497
+ case ZodFirstPartyTypeKind3.ZodEnum:
1498
+ return parseEnumDef(def);
1499
+ case ZodFirstPartyTypeKind3.ZodNativeEnum:
1500
+ return parseNativeEnumDef(def);
1501
+ case ZodFirstPartyTypeKind3.ZodNullable:
1502
+ return parseNullableDef(def, refs);
1503
+ case ZodFirstPartyTypeKind3.ZodOptional:
1504
+ return parseOptionalDef(def, refs);
1505
+ case ZodFirstPartyTypeKind3.ZodMap:
1506
+ return parseMapDef(def, refs);
1507
+ case ZodFirstPartyTypeKind3.ZodSet:
1508
+ return parseSetDef(def, refs);
1509
+ case ZodFirstPartyTypeKind3.ZodLazy:
1510
+ return () => def.getter()._def;
1511
+ case ZodFirstPartyTypeKind3.ZodPromise:
1512
+ return parsePromiseDef(def, refs);
1513
+ case ZodFirstPartyTypeKind3.ZodNaN:
1514
+ case ZodFirstPartyTypeKind3.ZodNever:
1515
+ return parseNeverDef();
1516
+ case ZodFirstPartyTypeKind3.ZodEffects:
1517
+ return parseEffectsDef(def, refs);
1518
+ case ZodFirstPartyTypeKind3.ZodAny:
1519
+ return parseAnyDef();
1520
+ case ZodFirstPartyTypeKind3.ZodUnknown:
1521
+ return parseUnknownDef();
1522
+ case ZodFirstPartyTypeKind3.ZodDefault:
1523
+ return parseDefaultDef(def, refs);
1524
+ case ZodFirstPartyTypeKind3.ZodBranded:
1525
+ return parseBrandedDef(def, refs);
1526
+ case ZodFirstPartyTypeKind3.ZodReadonly:
1527
+ return parseReadonlyDef(def, refs);
1528
+ case ZodFirstPartyTypeKind3.ZodCatch:
1529
+ return parseCatchDef(def, refs);
1530
+ case ZodFirstPartyTypeKind3.ZodPipeline:
1531
+ return parsePipelineDef(def, refs);
1532
+ case ZodFirstPartyTypeKind3.ZodFunction:
1533
+ case ZodFirstPartyTypeKind3.ZodVoid:
1534
+ case ZodFirstPartyTypeKind3.ZodSymbol:
1535
+ return void 0;
1536
+ default:
1537
+ return /* @__PURE__ */ ((_) => void 0)(typeName);
1538
+ }
1539
+ };
1132
1540
 
1133
- // src/to-json-schema/zod3-to-json-schema/parsers/catch.ts
1134
- var parseCatchDef = (def, refs) => {
1135
- return parseDef(def.innerType._def, refs);
1541
+ // src/to-json-schema/zod3-to-json-schema/get-relative-path.ts
1542
+ var getRelativePath = (pathA, pathB) => {
1543
+ let i = 0;
1544
+ for (; i < pathA.length && i < pathB.length; i++) {
1545
+ if (pathA[i] !== pathB[i]) break;
1546
+ }
1547
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1136
1548
  };
1137
1549
 
1138
- // src/to-json-schema/zod3-to-json-schema/parsers/date.ts
1139
- function parseDateDef(def, refs, overrideDateStrategy) {
1140
- const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
1141
- if (Array.isArray(strategy)) {
1142
- return {
1143
- anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
1144
- };
1550
+ // src/to-json-schema/zod3-to-json-schema/parse-def.ts
1551
+ function parseDef(def, refs, forceResolution = false) {
1552
+ var _a;
1553
+ const seenItem = refs.seen.get(def);
1554
+ if (refs.override) {
1555
+ const overrideResult = (_a = refs.override) == null ? void 0 : _a.call(
1556
+ refs,
1557
+ def,
1558
+ refs,
1559
+ seenItem,
1560
+ forceResolution
1561
+ );
1562
+ if (overrideResult !== ignoreOverride) {
1563
+ return overrideResult;
1564
+ }
1145
1565
  }
1146
- switch (strategy) {
1147
- case "string":
1148
- case "format:date-time":
1149
- return {
1150
- type: "string",
1151
- format: "date-time"
1152
- };
1153
- case "format:date":
1154
- return {
1155
- type: "string",
1156
- format: "date"
1157
- };
1158
- case "integer":
1159
- return integerDateParser(def);
1566
+ if (seenItem && !forceResolution) {
1567
+ const seenSchema = get$ref(seenItem, refs);
1568
+ if (seenSchema !== void 0) {
1569
+ return seenSchema;
1570
+ }
1160
1571
  }
1572
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1573
+ refs.seen.set(def, newItem);
1574
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1575
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1576
+ if (jsonSchema2) {
1577
+ addMeta(def, refs, jsonSchema2);
1578
+ }
1579
+ if (refs.postProcess) {
1580
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1581
+ newItem.jsonSchema = jsonSchema2;
1582
+ return postProcessResult;
1583
+ }
1584
+ newItem.jsonSchema = jsonSchema2;
1585
+ return jsonSchema2;
1161
1586
  }
1162
- var integerDateParser = (def) => {
1163
- const res = {
1164
- type: "integer",
1165
- format: "unix-time"
1166
- };
1167
- for (const check of def.checks) {
1168
- switch (check.kind) {
1169
- case "min":
1170
- res.minimum = check.value;
1171
- break;
1172
- case "max":
1173
- res.maximum = check.value;
1174
- break;
1587
+ var get$ref = (item, refs) => {
1588
+ switch (refs.$refStrategy) {
1589
+ case "root":
1590
+ return { $ref: item.path.join("/") };
1591
+ case "relative":
1592
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1593
+ case "none":
1594
+ case "seen": {
1595
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1596
+ console.warn(
1597
+ `Recursive reference detected at ${refs.currentPath.join(
1598
+ "/"
1599
+ )}! Defaulting to any`
1600
+ );
1601
+ return parseAnyDef();
1602
+ }
1603
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1175
1604
  }
1176
1605
  }
1177
- return res;
1178
1606
  };
1179
-
1180
- // src/to-json-schema/zod3-to-json-schema/parsers/default.ts
1181
- function parseDefaultDef(_def, refs) {
1182
- return {
1183
- ...parseDef(_def.innerType._def, refs),
1184
- default: _def.defaultValue()
1185
- };
1186
- }
1187
-
1188
- // src/to-json-schema/zod3-to-json-schema/parsers/effects.ts
1189
- function parseEffectsDef(_def, refs) {
1190
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
1191
- }
1192
-
1193
- // src/to-json-schema/zod3-to-json-schema/parsers/enum.ts
1194
- function parseEnumDef(def) {
1195
- return {
1196
- type: "string",
1197
- enum: Array.from(def.values)
1198
- };
1199
- }
1200
-
1201
- // src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts
1202
- var isJsonSchema7AllOfType = (type) => {
1203
- if ("type" in type && type.type === "string") return false;
1204
- return "allOf" in type;
1607
+ var addMeta = (def, refs, jsonSchema2) => {
1608
+ if (def.description) {
1609
+ jsonSchema2.description = def.description;
1610
+ }
1611
+ return jsonSchema2;
1205
1612
  };
1206
- function parseIntersectionDef(def, refs) {
1207
- const allOf = [
1208
- parseDef(def.left._def, {
1209
- ...refs,
1210
- currentPath: [...refs.currentPath, "allOf", "0"]
1211
- }),
1212
- parseDef(def.right._def, {
1213
- ...refs,
1214
- currentPath: [...refs.currentPath, "allOf", "1"]
1215
- })
1216
- ].filter((x) => !!x);
1217
- const mergedAllOf = [];
1218
- allOf.forEach((schema) => {
1219
- if (isJsonSchema7AllOfType(schema)) {
1220
- mergedAllOf.push(...schema.allOf);
1221
- } else {
1222
- let nestedSchema = schema;
1223
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
1224
- const { additionalProperties, ...rest } = schema;
1225
- nestedSchema = rest;
1226
- }
1227
- mergedAllOf.push(nestedSchema);
1228
- }
1229
- });
1230
- return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
1231
- }
1232
1613
 
1233
- // src/to-json-schema/zod3-to-json-schema/parsers/literal.ts
1234
- function parseLiteralDef(def) {
1235
- const parsedType = typeof def.value;
1236
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1237
- return {
1238
- type: Array.isArray(def.value) ? "array" : "object"
1239
- };
1240
- }
1614
+ // src/to-json-schema/zod3-to-json-schema/refs.ts
1615
+ var getRefs = (options) => {
1616
+ const _options = getDefaultOptions(options);
1617
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1241
1618
  return {
1242
- type: parsedType === "bigint" ? "integer" : parsedType,
1243
- const: def.value
1619
+ ..._options,
1620
+ currentPath,
1621
+ propertyPath: void 0,
1622
+ seen: new Map(
1623
+ Object.entries(_options.definitions).map(([name, def]) => [
1624
+ def._def,
1625
+ {
1626
+ def: def._def,
1627
+ path: [..._options.basePath, _options.definitionPath, name],
1628
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1629
+ jsonSchema: void 0
1630
+ }
1631
+ ])
1632
+ )
1244
1633
  };
1245
- }
1246
-
1247
- // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
1248
- import {
1249
- ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2
1250
- } from "zod/v3";
1634
+ };
1251
1635
 
1252
- // src/to-json-schema/zod3-to-json-schema/parsers/string.ts
1253
- var emojiRegex = void 0;
1254
- var zodPatterns = {
1255
- /**
1256
- * `c` was changed to `[cC]` to replicate /i flag
1257
- */
1258
- cuid: /^[cC][^\s-]{8,}$/,
1259
- cuid2: /^[0-9a-z]+$/,
1260
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1261
- /**
1262
- * `a-z` was added to replicate /i flag
1263
- */
1264
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1265
- /**
1266
- * Constructed a valid Unicode RegExp
1267
- *
1268
- * Lazily instantiate since this type of regex isn't supported
1269
- * in all envs (e.g. React Native).
1270
- *
1271
- * See:
1272
- * https://github.com/colinhacks/zod/issues/2433
1273
- * Fix in Zod:
1274
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1275
- */
1276
- emoji: () => {
1277
- if (emojiRegex === void 0) {
1278
- emojiRegex = RegExp(
1279
- "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
1280
- "u"
1281
- );
1636
+ // src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts
1637
+ var zod3ToJsonSchema = (schema, options) => {
1638
+ var _a;
1639
+ const refs = getRefs(options);
1640
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1641
+ (acc, [name2, schema2]) => {
1642
+ var _a2;
1643
+ return {
1644
+ ...acc,
1645
+ [name2]: (_a2 = parseDef(
1646
+ schema2._def,
1647
+ {
1648
+ ...refs,
1649
+ currentPath: [...refs.basePath, refs.definitionPath, name2]
1650
+ },
1651
+ true
1652
+ )) != null ? _a2 : parseAnyDef()
1653
+ };
1654
+ },
1655
+ {}
1656
+ ) : void 0;
1657
+ const name = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1658
+ const main = (_a = parseDef(
1659
+ schema._def,
1660
+ name === void 0 ? refs : {
1661
+ ...refs,
1662
+ currentPath: [...refs.basePath, refs.definitionPath, name]
1663
+ },
1664
+ false
1665
+ )) != null ? _a : parseAnyDef();
1666
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1667
+ if (title !== void 0) {
1668
+ main.title = title;
1669
+ }
1670
+ const combined = name === void 0 ? definitions ? {
1671
+ ...main,
1672
+ [refs.definitionPath]: definitions
1673
+ } : main : {
1674
+ $ref: [
1675
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1676
+ refs.definitionPath,
1677
+ name
1678
+ ].join("/"),
1679
+ [refs.definitionPath]: {
1680
+ ...definitions,
1681
+ [name]: main
1282
1682
  }
1283
- return emojiRegex;
1284
- },
1285
- /**
1286
- * Unused
1287
- */
1288
- uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
1289
- /**
1290
- * Unused
1291
- */
1292
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
1293
- ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
1294
- /**
1295
- * Unused
1296
- */
1297
- ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
1298
- ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
1299
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1300
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1301
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
1302
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1683
+ };
1684
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1685
+ return combined;
1303
1686
  };
1304
- function parseStringDef(def, refs) {
1305
- const res = {
1306
- type: "string"
1687
+
1688
+ // src/schema.ts
1689
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1690
+ function lazySchema(createSchema) {
1691
+ let schema;
1692
+ return () => {
1693
+ if (schema == null) {
1694
+ schema = createSchema();
1695
+ }
1696
+ return schema;
1307
1697
  };
1308
- if (def.checks) {
1309
- for (const check of def.checks) {
1310
- switch (check.kind) {
1311
- case "min":
1312
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1313
- break;
1314
- case "max":
1315
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1316
- break;
1317
- case "email":
1318
- switch (refs.emailStrategy) {
1319
- case "format:email":
1320
- addFormat(res, "email", check.message, refs);
1321
- break;
1322
- case "format:idn-email":
1323
- addFormat(res, "idn-email", check.message, refs);
1324
- break;
1325
- case "pattern:zod":
1326
- addPattern(res, zodPatterns.email, check.message, refs);
1327
- break;
1328
- }
1329
- break;
1330
- case "url":
1331
- addFormat(res, "uri", check.message, refs);
1332
- break;
1333
- case "uuid":
1334
- addFormat(res, "uuid", check.message, refs);
1335
- break;
1336
- case "regex":
1337
- addPattern(res, check.regex, check.message, refs);
1338
- break;
1339
- case "cuid":
1340
- addPattern(res, zodPatterns.cuid, check.message, refs);
1341
- break;
1342
- case "cuid2":
1343
- addPattern(res, zodPatterns.cuid2, check.message, refs);
1344
- break;
1345
- case "startsWith":
1346
- addPattern(
1347
- res,
1348
- RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
1349
- check.message,
1350
- refs
1351
- );
1352
- break;
1353
- case "endsWith":
1354
- addPattern(
1355
- res,
1356
- RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
1357
- check.message,
1358
- refs
1359
- );
1360
- break;
1361
- case "datetime":
1362
- addFormat(res, "date-time", check.message, refs);
1363
- break;
1364
- case "date":
1365
- addFormat(res, "date", check.message, refs);
1366
- break;
1367
- case "time":
1368
- addFormat(res, "time", check.message, refs);
1369
- break;
1370
- case "duration":
1371
- addFormat(res, "duration", check.message, refs);
1372
- break;
1373
- case "length":
1374
- res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
1375
- res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
1376
- break;
1377
- case "includes": {
1378
- addPattern(
1379
- res,
1380
- RegExp(escapeLiteralCheckValue(check.value, refs)),
1381
- check.message,
1382
- refs
1383
- );
1384
- break;
1385
- }
1386
- case "ip": {
1387
- if (check.version !== "v6") {
1388
- addFormat(res, "ipv4", check.message, refs);
1389
- }
1390
- if (check.version !== "v4") {
1391
- addFormat(res, "ipv6", check.message, refs);
1392
- }
1393
- break;
1394
- }
1395
- case "base64url":
1396
- addPattern(res, zodPatterns.base64url, check.message, refs);
1397
- break;
1398
- case "jwt":
1399
- addPattern(res, zodPatterns.jwt, check.message, refs);
1400
- break;
1401
- case "cidr": {
1402
- if (check.version !== "v6") {
1403
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
1404
- }
1405
- if (check.version !== "v4") {
1406
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
1407
- }
1408
- break;
1409
- }
1410
- case "emoji":
1411
- addPattern(res, zodPatterns.emoji(), check.message, refs);
1412
- break;
1413
- case "ulid": {
1414
- addPattern(res, zodPatterns.ulid, check.message, refs);
1415
- break;
1416
- }
1417
- case "base64": {
1418
- switch (refs.base64Strategy) {
1419
- case "format:binary": {
1420
- addFormat(res, "binary", check.message, refs);
1421
- break;
1422
- }
1423
- case "contentEncoding:base64": {
1424
- res.contentEncoding = "base64";
1425
- break;
1426
- }
1427
- case "pattern:zod": {
1428
- addPattern(res, zodPatterns.base64, check.message, refs);
1429
- break;
1430
- }
1431
- }
1432
- break;
1433
- }
1434
- case "nanoid": {
1435
- addPattern(res, zodPatterns.nanoid, check.message, refs);
1436
- }
1437
- case "toLowerCase":
1438
- case "toUpperCase":
1439
- case "trim":
1440
- break;
1441
- default:
1442
- /* @__PURE__ */ ((_) => {
1443
- })(check);
1698
+ }
1699
+ function jsonSchema(jsonSchema2, {
1700
+ validate
1701
+ } = {}) {
1702
+ return {
1703
+ [schemaSymbol]: true,
1704
+ _type: void 0,
1705
+ // should never be used directly
1706
+ get jsonSchema() {
1707
+ if (typeof jsonSchema2 === "function") {
1708
+ jsonSchema2 = jsonSchema2();
1444
1709
  }
1445
- }
1446
- }
1447
- return res;
1710
+ return jsonSchema2;
1711
+ },
1712
+ validate
1713
+ };
1448
1714
  }
1449
- function escapeLiteralCheckValue(literal, refs) {
1450
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
1715
+ function isSchema(value) {
1716
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1451
1717
  }
1452
- var ALPHA_NUMERIC = new Set(
1453
- "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
1454
- );
1455
- function escapeNonAlphaNumeric(source) {
1456
- let result = "";
1457
- for (let i = 0; i < source.length; i++) {
1458
- if (!ALPHA_NUMERIC.has(source[i])) {
1459
- result += "\\";
1460
- }
1461
- result += source[i];
1462
- }
1463
- return result;
1718
+ function asSchema(schema) {
1719
+ return schema == null ? jsonSchema({
1720
+ properties: {},
1721
+ additionalProperties: false
1722
+ }) : isSchema(schema) ? schema : "~standard" in schema ? standardSchema(schema) : schema();
1464
1723
  }
1465
- function addFormat(schema, value, message, refs) {
1466
- var _a;
1467
- if (schema.format || ((_a = schema.anyOf) == null ? void 0 : _a.some((x) => x.format))) {
1468
- if (!schema.anyOf) {
1469
- schema.anyOf = [];
1724
+ function standardSchema(standardSchema2) {
1725
+ const vendor = standardSchema2["~standard"].vendor;
1726
+ switch (vendor) {
1727
+ case "zod": {
1728
+ return zodSchema(
1729
+ standardSchema2
1730
+ );
1731
+ }
1732
+ case "arktype": {
1733
+ return standardSchemaWithJsonSchemaResolver(
1734
+ standardSchema2,
1735
+ arktypeToJsonSchema
1736
+ );
1737
+ }
1738
+ case "effect": {
1739
+ return standardSchemaWithJsonSchemaResolver(
1740
+ standardSchema2,
1741
+ effectToJsonSchema
1742
+ );
1470
1743
  }
1471
- if (schema.format) {
1472
- schema.anyOf.push({
1473
- format: schema.format
1744
+ case "valibot": {
1745
+ return standardSchemaWithJsonSchemaResolver(
1746
+ standardSchema2,
1747
+ valibotToJsonSchema
1748
+ );
1749
+ }
1750
+ default: {
1751
+ return standardSchemaWithJsonSchemaResolver(standardSchema2, () => () => {
1752
+ throw new Error(`Unsupported standard schema vendor: ${vendor}`);
1474
1753
  });
1475
- delete schema.format;
1476
1754
  }
1477
- schema.anyOf.push({
1478
- format: value,
1479
- ...message && refs.errorMessages && { errorMessage: { format: message } }
1480
- });
1481
- } else {
1482
- schema.format = value;
1483
1755
  }
1484
1756
  }
1485
- function addPattern(schema, regex, message, refs) {
1486
- var _a;
1487
- if (schema.pattern || ((_a = schema.allOf) == null ? void 0 : _a.some((x) => x.pattern))) {
1488
- if (!schema.allOf) {
1489
- schema.allOf = [];
1490
- }
1491
- if (schema.pattern) {
1492
- schema.allOf.push({
1493
- pattern: schema.pattern
1494
- });
1495
- delete schema.pattern;
1757
+ function standardSchemaWithJsonSchemaResolver(standardSchema2, jsonSchemaResolver) {
1758
+ return jsonSchema(jsonSchemaResolver(standardSchema2), {
1759
+ validate: async (value) => {
1760
+ const result = await standardSchema2["~standard"].validate(value);
1761
+ return "value" in result ? { success: true, value: result.value } : {
1762
+ success: false,
1763
+ error: new TypeValidationError({
1764
+ value,
1765
+ cause: result.issues
1766
+ })
1767
+ };
1496
1768
  }
1497
- schema.allOf.push({
1498
- pattern: stringifyRegExpWithFlags(regex, refs),
1499
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
1500
- });
1501
- } else {
1502
- schema.pattern = stringifyRegExpWithFlags(regex, refs);
1503
- }
1769
+ });
1504
1770
  }
1505
- function stringifyRegExpWithFlags(regex, refs) {
1771
+ function zod3Schema(zodSchema2, options) {
1506
1772
  var _a;
1507
- if (!refs.applyRegexFlags || !regex.flags) {
1508
- return regex.source;
1509
- }
1510
- const flags = {
1511
- i: regex.flags.includes("i"),
1512
- // Case-insensitive
1513
- m: regex.flags.includes("m"),
1514
- // `^` and `$` matches adjacent to newline characters
1515
- s: regex.flags.includes("s")
1516
- // `.` matches newlines
1517
- };
1518
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
1519
- let pattern = "";
1520
- let isEscaped = false;
1521
- let inCharGroup = false;
1522
- let inCharRange = false;
1523
- for (let i = 0; i < source.length; i++) {
1524
- if (isEscaped) {
1525
- pattern += source[i];
1526
- isEscaped = false;
1527
- continue;
1528
- }
1529
- if (flags.i) {
1530
- if (inCharGroup) {
1531
- if (source[i].match(/[a-z]/)) {
1532
- if (inCharRange) {
1533
- pattern += source[i];
1534
- pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
1535
- inCharRange = false;
1536
- } else if (source[i + 1] === "-" && ((_a = source[i + 2]) == null ? void 0 : _a.match(/[a-z]/))) {
1537
- pattern += source[i];
1538
- inCharRange = true;
1539
- } else {
1540
- pattern += `${source[i]}${source[i].toUpperCase()}`;
1541
- }
1542
- continue;
1543
- }
1544
- } else if (source[i].match(/[a-z]/)) {
1545
- pattern += `[${source[i]}${source[i].toUpperCase()}]`;
1546
- continue;
1773
+ const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
1774
+ return jsonSchema(
1775
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1776
+ () => zod3ToJsonSchema(zodSchema2, {
1777
+ $refStrategy: useReferences ? "root" : "none"
1778
+ }),
1779
+ {
1780
+ validate: async (value) => {
1781
+ const result = await zodSchema2.safeParseAsync(value);
1782
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1547
1783
  }
1548
1784
  }
1549
- if (flags.m) {
1550
- if (source[i] === "^") {
1551
- pattern += `(^|(?<=[\r
1552
- ]))`;
1553
- continue;
1554
- } else if (source[i] === "$") {
1555
- pattern += `($|(?=[\r
1556
- ]))`;
1557
- continue;
1785
+ );
1786
+ }
1787
+ function zod4Schema(zodSchema2, options) {
1788
+ var _a;
1789
+ const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
1790
+ return jsonSchema(
1791
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1792
+ () => z4.toJSONSchema(zodSchema2, {
1793
+ target: "draft-7",
1794
+ io: "output",
1795
+ reused: useReferences ? "ref" : "inline"
1796
+ }),
1797
+ {
1798
+ validate: async (value) => {
1799
+ const result = await z4.safeParseAsync(zodSchema2, value);
1800
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1558
1801
  }
1559
1802
  }
1560
- if (flags.s && source[i] === ".") {
1561
- pattern += inCharGroup ? `${source[i]}\r
1562
- ` : `[${source[i]}\r
1563
- ]`;
1564
- continue;
1565
- }
1566
- pattern += source[i];
1567
- if (source[i] === "\\") {
1568
- isEscaped = true;
1569
- } else if (inCharGroup && source[i] === "]") {
1570
- inCharGroup = false;
1571
- } else if (!inCharGroup && source[i] === "[") {
1572
- inCharGroup = true;
1573
- }
1574
- }
1575
- try {
1576
- new RegExp(pattern);
1577
- } catch (e) {
1578
- console.warn(
1579
- `Could not convert regex pattern at ${refs.currentPath.join(
1580
- "/"
1581
- )} to a flag-independent form! Falling back to the flag-ignorant source`
1582
- );
1583
- return regex.source;
1584
- }
1585
- return pattern;
1803
+ );
1586
1804
  }
1587
-
1588
- // src/to-json-schema/zod3-to-json-schema/parsers/record.ts
1589
- function parseRecordDef(def, refs) {
1590
- var _a, _b, _c, _d, _e, _f;
1591
- const schema = {
1592
- type: "object",
1593
- additionalProperties: (_a = parseDef(def.valueType._def, {
1594
- ...refs,
1595
- currentPath: [...refs.currentPath, "additionalProperties"]
1596
- })) != null ? _a : refs.allowedAdditionalProperties
1597
- };
1598
- if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind2.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
1599
- const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1600
- return {
1601
- ...schema,
1602
- propertyNames: keyType
1603
- };
1604
- } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind2.ZodEnum) {
1605
- return {
1606
- ...schema,
1607
- propertyNames: {
1608
- enum: def.keyType._def.values
1609
- }
1610
- };
1611
- } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
1612
- const { type, ...keyType } = parseBrandedDef(
1613
- def.keyType._def,
1614
- refs
1615
- );
1616
- return {
1617
- ...schema,
1618
- propertyNames: keyType
1619
- };
1620
- }
1621
- return schema;
1805
+ function isZod4Schema(zodSchema2) {
1806
+ return "_zod" in zodSchema2;
1622
1807
  }
1623
-
1624
- // src/to-json-schema/zod3-to-json-schema/parsers/map.ts
1625
- function parseMapDef(def, refs) {
1626
- if (refs.mapStrategy === "record") {
1627
- return parseRecordDef(def, refs);
1808
+ function zodSchema(zodSchema2, options) {
1809
+ if (isZod4Schema(zodSchema2)) {
1810
+ return zod4Schema(zodSchema2, options);
1811
+ } else {
1812
+ return zod3Schema(zodSchema2, options);
1628
1813
  }
1629
- const keys = parseDef(def.keyType._def, {
1630
- ...refs,
1631
- currentPath: [...refs.currentPath, "items", "items", "0"]
1632
- }) || parseAnyDef();
1633
- const values = parseDef(def.valueType._def, {
1634
- ...refs,
1635
- currentPath: [...refs.currentPath, "items", "items", "1"]
1636
- }) || parseAnyDef();
1637
- return {
1638
- type: "array",
1639
- maxItems: 125,
1640
- items: {
1641
- type: "array",
1642
- items: [keys, values],
1643
- minItems: 2,
1644
- maxItems: 2
1645
- }
1646
- };
1647
1814
  }
1648
1815
 
1649
- // src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts
1650
- function parseNativeEnumDef(def) {
1651
- const object = def.values;
1652
- const actualKeys = Object.keys(def.values).filter((key) => {
1653
- return typeof object[object[key]] !== "number";
1654
- });
1655
- const actualValues = actualKeys.map((key) => object[key]);
1656
- const parsedTypes = Array.from(
1657
- new Set(actualValues.map((values) => typeof values))
1658
- );
1659
- return {
1660
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
1661
- enum: actualValues
1662
- };
1816
+ // src/validate-types.ts
1817
+ async function validateTypes({
1818
+ value,
1819
+ schema
1820
+ }) {
1821
+ const result = await safeValidateTypes({ value, schema });
1822
+ if (!result.success) {
1823
+ throw TypeValidationError2.wrap({ value, cause: result.error });
1824
+ }
1825
+ return result.value;
1663
1826
  }
1664
-
1665
- // src/to-json-schema/zod3-to-json-schema/parsers/never.ts
1666
- function parseNeverDef() {
1667
- return { not: parseAnyDef() };
1827
+ async function safeValidateTypes({
1828
+ value,
1829
+ schema
1830
+ }) {
1831
+ const actualSchema = asSchema(schema);
1832
+ try {
1833
+ if (actualSchema.validate == null) {
1834
+ return { success: true, value, rawValue: value };
1835
+ }
1836
+ const result = await actualSchema.validate(value);
1837
+ if (result.success) {
1838
+ return { success: true, value: result.value, rawValue: value };
1839
+ }
1840
+ return {
1841
+ success: false,
1842
+ error: TypeValidationError2.wrap({ value, cause: result.error }),
1843
+ rawValue: value
1844
+ };
1845
+ } catch (error) {
1846
+ return {
1847
+ success: false,
1848
+ error: TypeValidationError2.wrap({ value, cause: error }),
1849
+ rawValue: value
1850
+ };
1851
+ }
1668
1852
  }
1669
1853
 
1670
- // src/to-json-schema/zod3-to-json-schema/parsers/null.ts
1671
- function parseNullDef() {
1672
- return {
1673
- type: "null"
1674
- };
1854
+ // src/parse-json.ts
1855
+ async function parseJSON({
1856
+ text,
1857
+ schema
1858
+ }) {
1859
+ try {
1860
+ const value = secureJsonParse(text);
1861
+ if (schema == null) {
1862
+ return value;
1863
+ }
1864
+ return validateTypes({ value, schema });
1865
+ } catch (error) {
1866
+ if (JSONParseError.isInstance(error) || TypeValidationError3.isInstance(error)) {
1867
+ throw error;
1868
+ }
1869
+ throw new JSONParseError({ text, cause: error });
1870
+ }
1675
1871
  }
1676
-
1677
- // src/to-json-schema/zod3-to-json-schema/parsers/union.ts
1678
- var primitiveMappings = {
1679
- ZodString: "string",
1680
- ZodNumber: "number",
1681
- ZodBigInt: "integer",
1682
- ZodBoolean: "boolean",
1683
- ZodNull: "null"
1684
- };
1685
- function parseUnionDef(def, refs) {
1686
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
1687
- if (options.every(
1688
- (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
1689
- )) {
1690
- const types = options.reduce((types2, x) => {
1691
- const type = primitiveMappings[x._def.typeName];
1692
- return type && !types2.includes(type) ? [...types2, type] : types2;
1693
- }, []);
1694
- return {
1695
- type: types.length > 1 ? types : types[0]
1696
- };
1697
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
1698
- const types = options.reduce(
1699
- (acc, x) => {
1700
- const type = typeof x._def.value;
1701
- switch (type) {
1702
- case "string":
1703
- case "number":
1704
- case "boolean":
1705
- return [...acc, type];
1706
- case "bigint":
1707
- return [...acc, "integer"];
1708
- case "object":
1709
- if (x._def.value === null) return [...acc, "null"];
1710
- case "symbol":
1711
- case "undefined":
1712
- case "function":
1713
- default:
1714
- return acc;
1715
- }
1716
- },
1717
- []
1718
- );
1719
- if (types.length === options.length) {
1720
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
1721
- return {
1722
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
1723
- enum: options.reduce(
1724
- (acc, x) => {
1725
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
1726
- },
1727
- []
1728
- )
1729
- };
1872
+ async function safeParseJSON({
1873
+ text,
1874
+ schema
1875
+ }) {
1876
+ try {
1877
+ const value = secureJsonParse(text);
1878
+ if (schema == null) {
1879
+ return { success: true, value, rawValue: value };
1730
1880
  }
1731
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
1881
+ return await safeValidateTypes({ value, schema });
1882
+ } catch (error) {
1732
1883
  return {
1733
- type: "string",
1734
- enum: options.reduce(
1735
- (acc, x) => [
1736
- ...acc,
1737
- ...x._def.values.filter((x2) => !acc.includes(x2))
1738
- ],
1739
- []
1740
- )
1884
+ success: false,
1885
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
1886
+ rawValue: void 0
1741
1887
  };
1742
1888
  }
1743
- return asAnyOf(def, refs);
1744
1889
  }
1745
- var asAnyOf = (def, refs) => {
1746
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
1747
- (x, i) => parseDef(x._def, {
1748
- ...refs,
1749
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
1890
+ function isParsableJson(input) {
1891
+ try {
1892
+ secureJsonParse(input);
1893
+ return true;
1894
+ } catch (e) {
1895
+ return false;
1896
+ }
1897
+ }
1898
+
1899
+ // src/parse-json-event-stream.ts
1900
+ import {
1901
+ EventSourceParserStream
1902
+ } from "eventsource-parser/stream";
1903
+ function parseJsonEventStream({
1904
+ stream,
1905
+ schema
1906
+ }) {
1907
+ return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
1908
+ new TransformStream({
1909
+ async transform({ data }, controller) {
1910
+ if (data === "[DONE]") {
1911
+ return;
1912
+ }
1913
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
1914
+ }
1750
1915
  })
1751
- ).filter(
1752
- (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
1753
1916
  );
1754
- return anyOf.length ? { anyOf } : void 0;
1755
- };
1917
+ }
1756
1918
 
1757
- // src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts
1758
- function parseNullableDef(def, refs) {
1759
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1760
- def.innerType._def.typeName
1761
- ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
1762
- return {
1763
- type: [
1764
- primitiveMappings[def.innerType._def.typeName],
1765
- "null"
1766
- ]
1767
- };
1919
+ // src/parse-provider-options.ts
1920
+ import { InvalidArgumentError as InvalidArgumentError2 } from "@ai-sdk/provider";
1921
+ async function parseProviderOptions({
1922
+ provider,
1923
+ providerOptions,
1924
+ schema
1925
+ }) {
1926
+ if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
1927
+ return void 0;
1768
1928
  }
1769
- const base = parseDef(def.innerType._def, {
1770
- ...refs,
1771
- currentPath: [...refs.currentPath, "anyOf", "0"]
1929
+ const parsedProviderOptions = await safeValidateTypes({
1930
+ value: providerOptions[provider],
1931
+ schema
1772
1932
  });
1773
- return base && { anyOf: [base, { type: "null" }] };
1933
+ if (!parsedProviderOptions.success) {
1934
+ throw new InvalidArgumentError2({
1935
+ argument: "providerOptions",
1936
+ message: `invalid ${provider} provider options`,
1937
+ cause: parsedProviderOptions.error
1938
+ });
1939
+ }
1940
+ return parsedProviderOptions.value;
1774
1941
  }
1775
1942
 
1776
- // src/to-json-schema/zod3-to-json-schema/parsers/number.ts
1777
- function parseNumberDef(def) {
1778
- const res = {
1779
- type: "number"
1780
- };
1781
- if (!def.checks) return res;
1782
- for (const check of def.checks) {
1783
- switch (check.kind) {
1784
- case "int":
1785
- res.type = "integer";
1786
- break;
1787
- case "min":
1788
- if (check.inclusive) {
1789
- res.minimum = check.value;
1790
- } else {
1791
- res.exclusiveMinimum = check.value;
1943
+ // src/post-to-api.ts
1944
+ import { APICallError as APICallError3 } from "@ai-sdk/provider";
1945
+ var getOriginalFetch2 = () => globalThis.fetch;
1946
+ var postJsonToApi = async ({
1947
+ url,
1948
+ headers,
1949
+ body,
1950
+ failedResponseHandler,
1951
+ successfulResponseHandler,
1952
+ abortSignal,
1953
+ fetch
1954
+ }) => postToApi({
1955
+ url,
1956
+ headers: {
1957
+ "Content-Type": "application/json",
1958
+ ...headers
1959
+ },
1960
+ body: {
1961
+ content: JSON.stringify(body),
1962
+ values: body
1963
+ },
1964
+ failedResponseHandler,
1965
+ successfulResponseHandler,
1966
+ abortSignal,
1967
+ fetch
1968
+ });
1969
+ var postFormDataToApi = async ({
1970
+ url,
1971
+ headers,
1972
+ formData,
1973
+ failedResponseHandler,
1974
+ successfulResponseHandler,
1975
+ abortSignal,
1976
+ fetch
1977
+ }) => postToApi({
1978
+ url,
1979
+ headers,
1980
+ body: {
1981
+ content: formData,
1982
+ values: Object.fromEntries(formData.entries())
1983
+ },
1984
+ failedResponseHandler,
1985
+ successfulResponseHandler,
1986
+ abortSignal,
1987
+ fetch
1988
+ });
1989
+ var postToApi = async ({
1990
+ url,
1991
+ headers = {},
1992
+ body,
1993
+ successfulResponseHandler,
1994
+ failedResponseHandler,
1995
+ abortSignal,
1996
+ fetch = getOriginalFetch2()
1997
+ }) => {
1998
+ try {
1999
+ const response = await fetch(url, {
2000
+ method: "POST",
2001
+ headers: withUserAgentSuffix(
2002
+ headers,
2003
+ `ai-sdk/provider-utils/${VERSION}`,
2004
+ getRuntimeEnvironmentUserAgent()
2005
+ ),
2006
+ body: body.content,
2007
+ signal: abortSignal
2008
+ });
2009
+ const responseHeaders = extractResponseHeaders(response);
2010
+ if (!response.ok) {
2011
+ let errorInformation;
2012
+ try {
2013
+ errorInformation = await failedResponseHandler({
2014
+ response,
2015
+ url,
2016
+ requestBodyValues: body.values
2017
+ });
2018
+ } catch (error) {
2019
+ if (isAbortError(error) || APICallError3.isInstance(error)) {
2020
+ throw error;
1792
2021
  }
1793
- break;
1794
- case "max":
1795
- if (check.inclusive) {
1796
- res.maximum = check.value;
1797
- } else {
1798
- res.exclusiveMaximum = check.value;
2022
+ throw new APICallError3({
2023
+ message: "Failed to process error response",
2024
+ cause: error,
2025
+ statusCode: response.status,
2026
+ url,
2027
+ responseHeaders,
2028
+ requestBodyValues: body.values
2029
+ });
2030
+ }
2031
+ throw errorInformation.value;
2032
+ }
2033
+ try {
2034
+ return await successfulResponseHandler({
2035
+ response,
2036
+ url,
2037
+ requestBodyValues: body.values
2038
+ });
2039
+ } catch (error) {
2040
+ if (error instanceof Error) {
2041
+ if (isAbortError(error) || APICallError3.isInstance(error)) {
2042
+ throw error;
1799
2043
  }
1800
- break;
1801
- case "multipleOf":
1802
- res.multipleOf = check.value;
1803
- break;
2044
+ }
2045
+ throw new APICallError3({
2046
+ message: "Failed to process successful response",
2047
+ cause: error,
2048
+ statusCode: response.status,
2049
+ url,
2050
+ responseHeaders,
2051
+ requestBodyValues: body.values
2052
+ });
1804
2053
  }
2054
+ } catch (error) {
2055
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
1805
2056
  }
1806
- return res;
1807
- }
2057
+ };
1808
2058
 
1809
- // src/to-json-schema/zod3-to-json-schema/parsers/object.ts
1810
- function parseObjectDef(def, refs) {
1811
- const result = {
1812
- type: "object",
1813
- properties: {}
1814
- };
1815
- const required = [];
1816
- const shape = def.shape();
1817
- for (const propName in shape) {
1818
- let propDef = shape[propName];
1819
- if (propDef === void 0 || propDef._def === void 0) {
1820
- continue;
1821
- }
1822
- const propOptional = safeIsOptional(propDef);
1823
- const parsedDef = parseDef(propDef._def, {
1824
- ...refs,
1825
- currentPath: [...refs.currentPath, "properties", propName],
1826
- propertyPath: [...refs.currentPath, "properties", propName]
1827
- });
1828
- if (parsedDef === void 0) {
1829
- continue;
1830
- }
1831
- result.properties[propName] = parsedDef;
1832
- if (!propOptional) {
1833
- required.push(propName);
1834
- }
1835
- }
1836
- if (required.length) {
1837
- result.required = required;
1838
- }
1839
- const additionalProperties = decideAdditionalProperties(def, refs);
1840
- if (additionalProperties !== void 0) {
1841
- result.additionalProperties = additionalProperties;
1842
- }
1843
- return result;
1844
- }
1845
- function decideAdditionalProperties(def, refs) {
1846
- if (def.catchall._def.typeName !== "ZodNever") {
1847
- return parseDef(def.catchall._def, {
1848
- ...refs,
1849
- currentPath: [...refs.currentPath, "additionalProperties"]
1850
- });
1851
- }
1852
- switch (def.unknownKeys) {
1853
- case "passthrough":
1854
- return refs.allowedAdditionalProperties;
1855
- case "strict":
1856
- return refs.rejectedAdditionalProperties;
1857
- case "strip":
1858
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1859
- }
2059
+ // src/types/tool.ts
2060
+ function tool(tool2) {
2061
+ return tool2;
1860
2062
  }
1861
- function safeIsOptional(schema) {
1862
- try {
1863
- return schema.isOptional();
1864
- } catch (e) {
1865
- return true;
1866
- }
2063
+ function dynamicTool(tool2) {
2064
+ return { ...tool2, type: "dynamic" };
1867
2065
  }
1868
2066
 
1869
- // src/to-json-schema/zod3-to-json-schema/parsers/optional.ts
1870
- var parseOptionalDef = (def, refs) => {
1871
- var _a;
1872
- if (refs.currentPath.toString() === ((_a = refs.propertyPath) == null ? void 0 : _a.toString())) {
1873
- return parseDef(def.innerType._def, refs);
1874
- }
1875
- const innerSchema = parseDef(def.innerType._def, {
1876
- ...refs,
1877
- currentPath: [...refs.currentPath, "anyOf", "1"]
1878
- });
1879
- return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1880
- };
1881
-
1882
- // src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts
1883
- var parsePipelineDef = (def, refs) => {
1884
- if (refs.pipeStrategy === "input") {
1885
- return parseDef(def.in._def, refs);
1886
- } else if (refs.pipeStrategy === "output") {
1887
- return parseDef(def.out._def, refs);
1888
- }
1889
- const a = parseDef(def.in._def, {
1890
- ...refs,
1891
- currentPath: [...refs.currentPath, "allOf", "0"]
2067
+ // src/provider-defined-tool-factory.ts
2068
+ function createProviderDefinedToolFactory({
2069
+ id,
2070
+ name,
2071
+ inputSchema
2072
+ }) {
2073
+ return ({
2074
+ execute,
2075
+ outputSchema,
2076
+ needsApproval,
2077
+ toModelOutput,
2078
+ onInputStart,
2079
+ onInputDelta,
2080
+ onInputAvailable,
2081
+ ...args
2082
+ }) => tool({
2083
+ type: "provider-defined",
2084
+ id,
2085
+ name,
2086
+ args,
2087
+ inputSchema,
2088
+ outputSchema,
2089
+ execute,
2090
+ needsApproval,
2091
+ toModelOutput,
2092
+ onInputStart,
2093
+ onInputDelta,
2094
+ onInputAvailable
1892
2095
  });
1893
- const b = parseDef(def.out._def, {
1894
- ...refs,
1895
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
2096
+ }
2097
+ function createProviderDefinedToolFactoryWithOutputSchema({
2098
+ id,
2099
+ name,
2100
+ inputSchema,
2101
+ outputSchema
2102
+ }) {
2103
+ return ({
2104
+ execute,
2105
+ needsApproval,
2106
+ toModelOutput,
2107
+ onInputStart,
2108
+ onInputDelta,
2109
+ onInputAvailable,
2110
+ ...args
2111
+ }) => tool({
2112
+ type: "provider-defined",
2113
+ id,
2114
+ name,
2115
+ args,
2116
+ inputSchema,
2117
+ outputSchema,
2118
+ execute,
2119
+ needsApproval,
2120
+ toModelOutput,
2121
+ onInputStart,
2122
+ onInputDelta,
2123
+ onInputAvailable
1896
2124
  });
1897
- return {
1898
- allOf: [a, b].filter((x) => x !== void 0)
1899
- };
1900
- };
1901
-
1902
- // src/to-json-schema/zod3-to-json-schema/parsers/promise.ts
1903
- function parsePromiseDef(def, refs) {
1904
- return parseDef(def.type._def, refs);
1905
2125
  }
1906
2126
 
1907
- // src/to-json-schema/zod3-to-json-schema/parsers/set.ts
1908
- function parseSetDef(def, refs) {
1909
- const items = parseDef(def.valueType._def, {
1910
- ...refs,
1911
- currentPath: [...refs.currentPath, "items"]
1912
- });
1913
- const schema = {
1914
- type: "array",
1915
- uniqueItems: true,
1916
- items
1917
- };
1918
- if (def.minSize) {
1919
- schema.minItems = def.minSize.value;
2127
+ // src/resolve.ts
2128
+ async function resolve(value) {
2129
+ if (typeof value === "function") {
2130
+ value = value();
1920
2131
  }
1921
- if (def.maxSize) {
1922
- schema.maxItems = def.maxSize.value;
2132
+ return Promise.resolve(value);
2133
+ }
2134
+
2135
+ // src/response-handler.ts
2136
+ import { APICallError as APICallError4, EmptyResponseBodyError } from "@ai-sdk/provider";
2137
+ var createJsonErrorResponseHandler = ({
2138
+ errorSchema,
2139
+ errorToMessage,
2140
+ isRetryable
2141
+ }) => async ({ response, url, requestBodyValues }) => {
2142
+ const responseBody = await response.text();
2143
+ const responseHeaders = extractResponseHeaders(response);
2144
+ if (responseBody.trim() === "") {
2145
+ return {
2146
+ responseHeaders,
2147
+ value: new APICallError4({
2148
+ message: response.statusText,
2149
+ url,
2150
+ requestBodyValues,
2151
+ statusCode: response.status,
2152
+ responseHeaders,
2153
+ responseBody,
2154
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2155
+ })
2156
+ };
1923
2157
  }
1924
- return schema;
1925
- }
1926
-
1927
- // src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts
1928
- function parseTupleDef(def, refs) {
1929
- if (def.rest) {
2158
+ try {
2159
+ const parsedError = await parseJSON({
2160
+ text: responseBody,
2161
+ schema: errorSchema
2162
+ });
1930
2163
  return {
1931
- type: "array",
1932
- minItems: def.items.length,
1933
- items: def.items.map(
1934
- (x, i) => parseDef(x._def, {
1935
- ...refs,
1936
- currentPath: [...refs.currentPath, "items", `${i}`]
1937
- })
1938
- ).reduce(
1939
- (acc, x) => x === void 0 ? acc : [...acc, x],
1940
- []
1941
- ),
1942
- additionalItems: parseDef(def.rest._def, {
1943
- ...refs,
1944
- currentPath: [...refs.currentPath, "additionalItems"]
2164
+ responseHeaders,
2165
+ value: new APICallError4({
2166
+ message: errorToMessage(parsedError),
2167
+ url,
2168
+ requestBodyValues,
2169
+ statusCode: response.status,
2170
+ responseHeaders,
2171
+ responseBody,
2172
+ data: parsedError,
2173
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
1945
2174
  })
1946
2175
  };
1947
- } else {
2176
+ } catch (parseError) {
1948
2177
  return {
1949
- type: "array",
1950
- minItems: def.items.length,
1951
- maxItems: def.items.length,
1952
- items: def.items.map(
1953
- (x, i) => parseDef(x._def, {
1954
- ...refs,
1955
- currentPath: [...refs.currentPath, "items", `${i}`]
1956
- })
1957
- ).reduce(
1958
- (acc, x) => x === void 0 ? acc : [...acc, x],
1959
- []
1960
- )
2178
+ responseHeaders,
2179
+ value: new APICallError4({
2180
+ message: response.statusText,
2181
+ url,
2182
+ requestBodyValues,
2183
+ statusCode: response.status,
2184
+ responseHeaders,
2185
+ responseBody,
2186
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
2187
+ })
1961
2188
  };
1962
2189
  }
1963
- }
1964
-
1965
- // src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts
1966
- function parseUndefinedDef() {
1967
- return {
1968
- not: parseAnyDef()
1969
- };
1970
- }
1971
-
1972
- // src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts
1973
- function parseUnknownDef() {
1974
- return parseAnyDef();
1975
- }
1976
-
1977
- // src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts
1978
- var parseReadonlyDef = (def, refs) => {
1979
- return parseDef(def.innerType._def, refs);
1980
- };
1981
-
1982
- // src/to-json-schema/zod3-to-json-schema/select-parser.ts
1983
- var selectParser = (def, typeName, refs) => {
1984
- switch (typeName) {
1985
- case ZodFirstPartyTypeKind3.ZodString:
1986
- return parseStringDef(def, refs);
1987
- case ZodFirstPartyTypeKind3.ZodNumber:
1988
- return parseNumberDef(def);
1989
- case ZodFirstPartyTypeKind3.ZodObject:
1990
- return parseObjectDef(def, refs);
1991
- case ZodFirstPartyTypeKind3.ZodBigInt:
1992
- return parseBigintDef(def);
1993
- case ZodFirstPartyTypeKind3.ZodBoolean:
1994
- return parseBooleanDef();
1995
- case ZodFirstPartyTypeKind3.ZodDate:
1996
- return parseDateDef(def, refs);
1997
- case ZodFirstPartyTypeKind3.ZodUndefined:
1998
- return parseUndefinedDef();
1999
- case ZodFirstPartyTypeKind3.ZodNull:
2000
- return parseNullDef();
2001
- case ZodFirstPartyTypeKind3.ZodArray:
2002
- return parseArrayDef(def, refs);
2003
- case ZodFirstPartyTypeKind3.ZodUnion:
2004
- case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
2005
- return parseUnionDef(def, refs);
2006
- case ZodFirstPartyTypeKind3.ZodIntersection:
2007
- return parseIntersectionDef(def, refs);
2008
- case ZodFirstPartyTypeKind3.ZodTuple:
2009
- return parseTupleDef(def, refs);
2010
- case ZodFirstPartyTypeKind3.ZodRecord:
2011
- return parseRecordDef(def, refs);
2012
- case ZodFirstPartyTypeKind3.ZodLiteral:
2013
- return parseLiteralDef(def);
2014
- case ZodFirstPartyTypeKind3.ZodEnum:
2015
- return parseEnumDef(def);
2016
- case ZodFirstPartyTypeKind3.ZodNativeEnum:
2017
- return parseNativeEnumDef(def);
2018
- case ZodFirstPartyTypeKind3.ZodNullable:
2019
- return parseNullableDef(def, refs);
2020
- case ZodFirstPartyTypeKind3.ZodOptional:
2021
- return parseOptionalDef(def, refs);
2022
- case ZodFirstPartyTypeKind3.ZodMap:
2023
- return parseMapDef(def, refs);
2024
- case ZodFirstPartyTypeKind3.ZodSet:
2025
- return parseSetDef(def, refs);
2026
- case ZodFirstPartyTypeKind3.ZodLazy:
2027
- return () => def.getter()._def;
2028
- case ZodFirstPartyTypeKind3.ZodPromise:
2029
- return parsePromiseDef(def, refs);
2030
- case ZodFirstPartyTypeKind3.ZodNaN:
2031
- case ZodFirstPartyTypeKind3.ZodNever:
2032
- return parseNeverDef();
2033
- case ZodFirstPartyTypeKind3.ZodEffects:
2034
- return parseEffectsDef(def, refs);
2035
- case ZodFirstPartyTypeKind3.ZodAny:
2036
- return parseAnyDef();
2037
- case ZodFirstPartyTypeKind3.ZodUnknown:
2038
- return parseUnknownDef();
2039
- case ZodFirstPartyTypeKind3.ZodDefault:
2040
- return parseDefaultDef(def, refs);
2041
- case ZodFirstPartyTypeKind3.ZodBranded:
2042
- return parseBrandedDef(def, refs);
2043
- case ZodFirstPartyTypeKind3.ZodReadonly:
2044
- return parseReadonlyDef(def, refs);
2045
- case ZodFirstPartyTypeKind3.ZodCatch:
2046
- return parseCatchDef(def, refs);
2047
- case ZodFirstPartyTypeKind3.ZodPipeline:
2048
- return parsePipelineDef(def, refs);
2049
- case ZodFirstPartyTypeKind3.ZodFunction:
2050
- case ZodFirstPartyTypeKind3.ZodVoid:
2051
- case ZodFirstPartyTypeKind3.ZodSymbol:
2052
- return void 0;
2053
- default:
2054
- return /* @__PURE__ */ ((_) => void 0)(typeName);
2055
- }
2056
- };
2057
-
2058
- // src/to-json-schema/zod3-to-json-schema/get-relative-path.ts
2059
- var getRelativePath = (pathA, pathB) => {
2060
- let i = 0;
2061
- for (; i < pathA.length && i < pathB.length; i++) {
2062
- if (pathA[i] !== pathB[i]) break;
2063
- }
2064
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
2065
2190
  };
2066
-
2067
- // src/to-json-schema/zod3-to-json-schema/parse-def.ts
2068
- function parseDef(def, refs, forceResolution = false) {
2069
- var _a;
2070
- const seenItem = refs.seen.get(def);
2071
- if (refs.override) {
2072
- const overrideResult = (_a = refs.override) == null ? void 0 : _a.call(
2073
- refs,
2074
- def,
2075
- refs,
2076
- seenItem,
2077
- forceResolution
2078
- );
2079
- if (overrideResult !== ignoreOverride) {
2080
- return overrideResult;
2081
- }
2082
- }
2083
- if (seenItem && !forceResolution) {
2084
- const seenSchema = get$ref(seenItem, refs);
2085
- if (seenSchema !== void 0) {
2086
- return seenSchema;
2087
- }
2088
- }
2089
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
2090
- refs.seen.set(def, newItem);
2091
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
2092
- const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
2093
- if (jsonSchema2) {
2094
- addMeta(def, refs, jsonSchema2);
2095
- }
2096
- if (refs.postProcess) {
2097
- const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
2098
- newItem.jsonSchema = jsonSchema2;
2099
- return postProcessResult;
2100
- }
2101
- newItem.jsonSchema = jsonSchema2;
2102
- return jsonSchema2;
2103
- }
2104
- var get$ref = (item, refs) => {
2105
- switch (refs.$refStrategy) {
2106
- case "root":
2107
- return { $ref: item.path.join("/") };
2108
- case "relative":
2109
- return { $ref: getRelativePath(refs.currentPath, item.path) };
2110
- case "none":
2111
- case "seen": {
2112
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
2113
- console.warn(
2114
- `Recursive reference detected at ${refs.currentPath.join(
2115
- "/"
2116
- )}! Defaulting to any`
2117
- );
2118
- return parseAnyDef();
2119
- }
2120
- return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
2121
- }
2191
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
2192
+ const responseHeaders = extractResponseHeaders(response);
2193
+ if (response.body == null) {
2194
+ throw new EmptyResponseBodyError({});
2122
2195
  }
2196
+ return {
2197
+ responseHeaders,
2198
+ value: parseJsonEventStream({
2199
+ stream: response.body,
2200
+ schema: chunkSchema
2201
+ })
2202
+ };
2123
2203
  };
2124
- var addMeta = (def, refs, jsonSchema2) => {
2125
- if (def.description) {
2126
- jsonSchema2.description = def.description;
2204
+ var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
2205
+ const responseHeaders = extractResponseHeaders(response);
2206
+ if (response.body == null) {
2207
+ throw new EmptyResponseBodyError({});
2127
2208
  }
2128
- return jsonSchema2;
2129
- };
2130
-
2131
- // src/to-json-schema/zod3-to-json-schema/refs.ts
2132
- var getRefs = (options) => {
2133
- const _options = getDefaultOptions(options);
2134
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
2135
- return {
2136
- ..._options,
2137
- currentPath,
2138
- propertyPath: void 0,
2139
- seen: new Map(
2140
- Object.entries(_options.definitions).map(([name, def]) => [
2141
- def._def,
2142
- {
2143
- def: def._def,
2144
- path: [..._options.basePath, _options.definitionPath, name],
2145
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
2146
- jsonSchema: void 0
2209
+ let buffer = "";
2210
+ return {
2211
+ responseHeaders,
2212
+ value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(
2213
+ new TransformStream({
2214
+ async transform(chunkText, controller) {
2215
+ if (chunkText.endsWith("\n")) {
2216
+ controller.enqueue(
2217
+ await safeParseJSON({
2218
+ text: buffer + chunkText,
2219
+ schema: chunkSchema
2220
+ })
2221
+ );
2222
+ buffer = "";
2223
+ } else {
2224
+ buffer += chunkText;
2225
+ }
2147
2226
  }
2148
- ])
2227
+ })
2149
2228
  )
2150
2229
  };
2151
2230
  };
2152
-
2153
- // src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts
2154
- var zod3ToJsonSchema = (schema, options) => {
2155
- var _a;
2156
- const refs = getRefs(options);
2157
- let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
2158
- (acc, [name2, schema2]) => {
2159
- var _a2;
2160
- return {
2161
- ...acc,
2162
- [name2]: (_a2 = parseDef(
2163
- schema2._def,
2164
- {
2165
- ...refs,
2166
- currentPath: [...refs.basePath, refs.definitionPath, name2]
2167
- },
2168
- true
2169
- )) != null ? _a2 : parseAnyDef()
2170
- };
2171
- },
2172
- {}
2173
- ) : void 0;
2174
- const name = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
2175
- const main = (_a = parseDef(
2176
- schema._def,
2177
- name === void 0 ? refs : {
2178
- ...refs,
2179
- currentPath: [...refs.basePath, refs.definitionPath, name]
2180
- },
2181
- false
2182
- )) != null ? _a : parseAnyDef();
2183
- const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
2184
- if (title !== void 0) {
2185
- main.title = title;
2231
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
2232
+ const responseBody = await response.text();
2233
+ const parsedResult = await safeParseJSON({
2234
+ text: responseBody,
2235
+ schema: responseSchema
2236
+ });
2237
+ const responseHeaders = extractResponseHeaders(response);
2238
+ if (!parsedResult.success) {
2239
+ throw new APICallError4({
2240
+ message: "Invalid JSON response",
2241
+ cause: parsedResult.error,
2242
+ statusCode: response.status,
2243
+ responseHeaders,
2244
+ responseBody,
2245
+ url,
2246
+ requestBodyValues
2247
+ });
2186
2248
  }
2187
- const combined = name === void 0 ? definitions ? {
2188
- ...main,
2189
- [refs.definitionPath]: definitions
2190
- } : main : {
2191
- $ref: [
2192
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
2193
- refs.definitionPath,
2194
- name
2195
- ].join("/"),
2196
- [refs.definitionPath]: {
2197
- ...definitions,
2198
- [name]: main
2199
- }
2200
- };
2201
- combined.$schema = "http://json-schema.org/draft-07/schema#";
2202
- return combined;
2203
- };
2204
-
2205
- // src/schema.ts
2206
- var schemaSymbol = Symbol.for("vercel.ai.schema");
2207
- function lazySchema(createSchema) {
2208
- let schema;
2209
- return () => {
2210
- if (schema == null) {
2211
- schema = createSchema();
2212
- }
2213
- return schema;
2214
- };
2215
- }
2216
- function jsonSchema(jsonSchema2, {
2217
- validate
2218
- } = {}) {
2219
2249
  return {
2220
- [schemaSymbol]: true,
2221
- _type: void 0,
2222
- // should never be used directly
2223
- [validatorSymbol]: true,
2224
- get jsonSchema() {
2225
- if (typeof jsonSchema2 === "function") {
2226
- jsonSchema2 = jsonSchema2();
2227
- }
2228
- return jsonSchema2;
2229
- },
2230
- validate
2250
+ responseHeaders,
2251
+ value: parsedResult.value,
2252
+ rawValue: parsedResult.rawValue
2231
2253
  };
2232
- }
2233
- function isSchema(value) {
2234
- return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
2235
- }
2236
- function asSchema(schema) {
2237
- return schema == null ? jsonSchema({
2238
- properties: {},
2239
- additionalProperties: false
2240
- }) : isSchema(schema) ? schema : "~standard" in schema ? standardSchema(schema) : schema();
2241
- }
2242
- function standardSchema(standardSchema2) {
2243
- const vendor = standardSchema2["~standard"].vendor;
2244
- switch (vendor) {
2245
- case "zod": {
2246
- return zodSchema(
2247
- standardSchema2
2248
- );
2249
- }
2250
- case "arktype": {
2251
- return standardSchemaWithJsonSchemaResolver(
2252
- standardSchema2,
2253
- arktypeToJsonSchema
2254
- );
2255
- }
2256
- case "effect": {
2257
- return standardSchemaWithJsonSchemaResolver(
2258
- standardSchema2,
2259
- effectToJsonSchema
2260
- );
2261
- }
2262
- case "valibot": {
2263
- return standardSchemaWithJsonSchemaResolver(
2264
- standardSchema2,
2265
- valibotToJsonSchema
2266
- );
2267
- }
2268
- default: {
2269
- return standardSchemaWithJsonSchemaResolver(standardSchema2, () => {
2270
- throw new Error(`Unsupported standard schema vendor: ${vendor}`);
2271
- });
2272
- }
2254
+ };
2255
+ var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
2256
+ const responseHeaders = extractResponseHeaders(response);
2257
+ if (!response.body) {
2258
+ throw new APICallError4({
2259
+ message: "Response body is empty",
2260
+ url,
2261
+ requestBodyValues,
2262
+ statusCode: response.status,
2263
+ responseHeaders,
2264
+ responseBody: void 0
2265
+ });
2273
2266
  }
2274
- }
2275
- function standardSchemaWithJsonSchemaResolver(standardSchema2, jsonSchemaResolver) {
2276
- return jsonSchema(jsonSchemaResolver(standardSchema2), {
2277
- validate: async (value) => {
2278
- const result = await standardSchema2["~standard"].validate(value);
2279
- return "value" in result ? { success: true, value: result.value } : {
2280
- success: false,
2281
- error: new TypeValidationError4({
2282
- value,
2283
- cause: result.issues
2284
- })
2285
- };
2286
- }
2287
- });
2288
- }
2289
- function zod3Schema(zodSchema2, options) {
2290
- var _a;
2291
- const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
2292
- return jsonSchema(
2293
- // defer json schema creation to avoid unnecessary computation when only validation is needed
2294
- () => zod3ToJsonSchema(zodSchema2, {
2295
- $refStrategy: useReferences ? "root" : "none"
2296
- }),
2297
- {
2298
- validate: async (value) => {
2299
- const result = await zodSchema2.safeParseAsync(value);
2300
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2301
- }
2302
- }
2303
- );
2304
- }
2305
- function zod4Schema(zodSchema2, options) {
2306
- var _a;
2307
- const useReferences = (_a = options == null ? void 0 : options.useReferences) != null ? _a : false;
2308
- return jsonSchema(
2309
- // defer json schema creation to avoid unnecessary computation when only validation is needed
2310
- () => z4.toJSONSchema(zodSchema2, {
2311
- target: "draft-7",
2312
- io: "output",
2313
- reused: useReferences ? "ref" : "inline"
2314
- }),
2315
- {
2316
- validate: async (value) => {
2317
- const result = await z4.safeParseAsync(zodSchema2, value);
2318
- return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
2319
- }
2320
- }
2321
- );
2322
- }
2323
- function isZod4Schema(zodSchema2) {
2324
- return "_zod" in zodSchema2;
2325
- }
2326
- function zodSchema(zodSchema2, options) {
2327
- if (isZod4Schema(zodSchema2)) {
2328
- return zod4Schema(zodSchema2, options);
2329
- } else {
2330
- return zod3Schema(zodSchema2, options);
2267
+ try {
2268
+ const buffer = await response.arrayBuffer();
2269
+ return {
2270
+ responseHeaders,
2271
+ value: new Uint8Array(buffer)
2272
+ };
2273
+ } catch (error) {
2274
+ throw new APICallError4({
2275
+ message: "Failed to read response as array buffer",
2276
+ url,
2277
+ requestBodyValues,
2278
+ statusCode: response.status,
2279
+ responseHeaders,
2280
+ responseBody: void 0,
2281
+ cause: error
2282
+ });
2331
2283
  }
2332
- }
2284
+ };
2285
+ var createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {
2286
+ const responseHeaders = extractResponseHeaders(response);
2287
+ const responseBody = await response.text();
2288
+ return {
2289
+ responseHeaders,
2290
+ value: new APICallError4({
2291
+ message: response.statusText,
2292
+ url,
2293
+ requestBodyValues,
2294
+ statusCode: response.status,
2295
+ responseHeaders,
2296
+ responseBody
2297
+ })
2298
+ };
2299
+ };
2333
2300
 
2334
2301
  // src/uint8-utils.ts
2335
2302
  var { btoa, atob } = globalThis;
@@ -2387,7 +2354,6 @@ export {
2387
2354
  EventSourceParserStream2 as EventSourceParserStream,
2388
2355
  VERSION,
2389
2356
  asSchema,
2390
- asValidator,
2391
2357
  combineHeaders,
2392
2358
  convertAsyncIteratorToReadableStream,
2393
2359
  convertBase64ToUint8Array,
@@ -2414,10 +2380,8 @@ export {
2414
2380
  isAbortError,
2415
2381
  isParsableJson,
2416
2382
  isUrlSupported,
2417
- isValidator,
2418
2383
  jsonSchema,
2419
2384
  lazySchema,
2420
- lazyValidator,
2421
2385
  loadApiKey,
2422
2386
  loadOptionalSetting,
2423
2387
  loadSetting,
@@ -2432,10 +2396,8 @@ export {
2432
2396
  resolve,
2433
2397
  safeParseJSON,
2434
2398
  safeValidateTypes,
2435
- standardSchemaValidator,
2436
2399
  tool,
2437
2400
  validateTypes,
2438
- validator,
2439
2401
  withUserAgentSuffix,
2440
2402
  withoutTrailingSlash,
2441
2403
  zodSchema