integrate-sdk 0.7.24 → 0.7.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/adapters/auto-routes.d.ts +51 -0
  2. package/dist/adapters/auto-routes.d.ts.map +1 -0
  3. package/dist/adapters/auto-routes.js +2 -2
  4. package/dist/adapters/base-handler.d.ts +182 -0
  5. package/dist/adapters/base-handler.d.ts.map +1 -0
  6. package/dist/adapters/base-handler.js +1 -1
  7. package/dist/adapters/index.d.ts +12 -0
  8. package/dist/adapters/index.d.ts.map +1 -0
  9. package/dist/adapters/index.js +2048 -0
  10. package/dist/adapters/nextjs-oauth-redirect.d.ts +41 -0
  11. package/dist/adapters/nextjs-oauth-redirect.d.ts.map +1 -0
  12. package/dist/adapters/nextjs-oauth-redirect.js +2 -2
  13. package/dist/adapters/nextjs.d.ts +358 -0
  14. package/dist/adapters/nextjs.d.ts.map +1 -0
  15. package/dist/adapters/nextjs.js +3 -3
  16. package/dist/adapters/node.d.ts +48 -0
  17. package/dist/adapters/node.d.ts.map +1 -0
  18. package/dist/adapters/node.js +2 -2
  19. package/dist/adapters/solid-start.d.ts +8 -0
  20. package/dist/adapters/solid-start.d.ts.map +1 -0
  21. package/dist/adapters/solid-start.js +12 -12
  22. package/dist/adapters/svelte-kit.d.ts +83 -0
  23. package/dist/adapters/svelte-kit.d.ts.map +1 -0
  24. package/dist/adapters/svelte-kit.js +13 -13
  25. package/dist/adapters/tanstack-start.d.ts +53 -0
  26. package/dist/adapters/tanstack-start.d.ts.map +1 -0
  27. package/dist/adapters/tanstack-start.js +1 -1
  28. package/dist/index.js +0 -4202
  29. package/dist/server.d.ts +12 -0
  30. package/dist/server.d.ts.map +1 -1
  31. package/dist/server.js +4708 -0
  32. package/dist/src/adapters/index.d.ts +12 -0
  33. package/dist/src/adapters/index.d.ts.map +1 -0
  34. package/dist/src/index.d.ts +0 -2
  35. package/dist/src/index.d.ts.map +1 -1
  36. package/package.json +3 -63
  37. package/server.ts +12 -0
package/dist/server.js CHANGED
@@ -2441,15 +2441,4723 @@ function toSvelteKitHandler(clientOrHandlerOrOptions, _redirectOptions) {
2441
2441
  }
2442
2442
  };
2443
2443
  }
2444
+ // node_modules/zod/v3/external.js
2445
+ var exports_external = {};
2446
+ __export(exports_external, {
2447
+ void: () => voidType,
2448
+ util: () => util,
2449
+ unknown: () => unknownType,
2450
+ union: () => unionType,
2451
+ undefined: () => undefinedType,
2452
+ tuple: () => tupleType,
2453
+ transformer: () => effectsType,
2454
+ symbol: () => symbolType,
2455
+ string: () => stringType,
2456
+ strictObject: () => strictObjectType,
2457
+ setErrorMap: () => setErrorMap,
2458
+ set: () => setType,
2459
+ record: () => recordType,
2460
+ quotelessJson: () => quotelessJson,
2461
+ promise: () => promiseType,
2462
+ preprocess: () => preprocessType,
2463
+ pipeline: () => pipelineType,
2464
+ ostring: () => ostring,
2465
+ optional: () => optionalType,
2466
+ onumber: () => onumber,
2467
+ oboolean: () => oboolean,
2468
+ objectUtil: () => objectUtil,
2469
+ object: () => objectType,
2470
+ number: () => numberType,
2471
+ nullable: () => nullableType,
2472
+ null: () => nullType,
2473
+ never: () => neverType,
2474
+ nativeEnum: () => nativeEnumType,
2475
+ nan: () => nanType,
2476
+ map: () => mapType,
2477
+ makeIssue: () => makeIssue,
2478
+ literal: () => literalType,
2479
+ lazy: () => lazyType,
2480
+ late: () => late,
2481
+ isValid: () => isValid,
2482
+ isDirty: () => isDirty,
2483
+ isAsync: () => isAsync,
2484
+ isAborted: () => isAborted,
2485
+ intersection: () => intersectionType,
2486
+ instanceof: () => instanceOfType,
2487
+ getParsedType: () => getParsedType,
2488
+ getErrorMap: () => getErrorMap,
2489
+ function: () => functionType,
2490
+ enum: () => enumType,
2491
+ effect: () => effectsType,
2492
+ discriminatedUnion: () => discriminatedUnionType,
2493
+ defaultErrorMap: () => en_default,
2494
+ datetimeRegex: () => datetimeRegex,
2495
+ date: () => dateType,
2496
+ custom: () => custom,
2497
+ coerce: () => coerce,
2498
+ boolean: () => booleanType,
2499
+ bigint: () => bigIntType,
2500
+ array: () => arrayType,
2501
+ any: () => anyType,
2502
+ addIssueToContext: () => addIssueToContext,
2503
+ ZodVoid: () => ZodVoid,
2504
+ ZodUnknown: () => ZodUnknown,
2505
+ ZodUnion: () => ZodUnion,
2506
+ ZodUndefined: () => ZodUndefined,
2507
+ ZodType: () => ZodType,
2508
+ ZodTuple: () => ZodTuple,
2509
+ ZodTransformer: () => ZodEffects,
2510
+ ZodSymbol: () => ZodSymbol,
2511
+ ZodString: () => ZodString,
2512
+ ZodSet: () => ZodSet,
2513
+ ZodSchema: () => ZodType,
2514
+ ZodRecord: () => ZodRecord,
2515
+ ZodReadonly: () => ZodReadonly,
2516
+ ZodPromise: () => ZodPromise,
2517
+ ZodPipeline: () => ZodPipeline,
2518
+ ZodParsedType: () => ZodParsedType,
2519
+ ZodOptional: () => ZodOptional,
2520
+ ZodObject: () => ZodObject,
2521
+ ZodNumber: () => ZodNumber,
2522
+ ZodNullable: () => ZodNullable,
2523
+ ZodNull: () => ZodNull,
2524
+ ZodNever: () => ZodNever,
2525
+ ZodNativeEnum: () => ZodNativeEnum,
2526
+ ZodNaN: () => ZodNaN,
2527
+ ZodMap: () => ZodMap,
2528
+ ZodLiteral: () => ZodLiteral,
2529
+ ZodLazy: () => ZodLazy,
2530
+ ZodIssueCode: () => ZodIssueCode,
2531
+ ZodIntersection: () => ZodIntersection,
2532
+ ZodFunction: () => ZodFunction,
2533
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
2534
+ ZodError: () => ZodError,
2535
+ ZodEnum: () => ZodEnum,
2536
+ ZodEffects: () => ZodEffects,
2537
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
2538
+ ZodDefault: () => ZodDefault,
2539
+ ZodDate: () => ZodDate,
2540
+ ZodCatch: () => ZodCatch,
2541
+ ZodBranded: () => ZodBranded,
2542
+ ZodBoolean: () => ZodBoolean,
2543
+ ZodBigInt: () => ZodBigInt,
2544
+ ZodArray: () => ZodArray,
2545
+ ZodAny: () => ZodAny,
2546
+ Schema: () => ZodType,
2547
+ ParseStatus: () => ParseStatus,
2548
+ OK: () => OK,
2549
+ NEVER: () => NEVER,
2550
+ INVALID: () => INVALID,
2551
+ EMPTY_PATH: () => EMPTY_PATH,
2552
+ DIRTY: () => DIRTY,
2553
+ BRAND: () => BRAND
2554
+ });
2555
+
2556
+ // node_modules/zod/v3/helpers/util.js
2557
+ var util;
2558
+ (function(util2) {
2559
+ util2.assertEqual = (_) => {};
2560
+ function assertIs(_arg) {}
2561
+ util2.assertIs = assertIs;
2562
+ function assertNever(_x) {
2563
+ throw new Error;
2564
+ }
2565
+ util2.assertNever = assertNever;
2566
+ util2.arrayToEnum = (items) => {
2567
+ const obj = {};
2568
+ for (const item of items) {
2569
+ obj[item] = item;
2570
+ }
2571
+ return obj;
2572
+ };
2573
+ util2.getValidEnumValues = (obj) => {
2574
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
2575
+ const filtered = {};
2576
+ for (const k of validKeys) {
2577
+ filtered[k] = obj[k];
2578
+ }
2579
+ return util2.objectValues(filtered);
2580
+ };
2581
+ util2.objectValues = (obj) => {
2582
+ return util2.objectKeys(obj).map(function(e) {
2583
+ return obj[e];
2584
+ });
2585
+ };
2586
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
2587
+ const keys = [];
2588
+ for (const key in object) {
2589
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
2590
+ keys.push(key);
2591
+ }
2592
+ }
2593
+ return keys;
2594
+ };
2595
+ util2.find = (arr, checker) => {
2596
+ for (const item of arr) {
2597
+ if (checker(item))
2598
+ return item;
2599
+ }
2600
+ return;
2601
+ };
2602
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
2603
+ function joinValues(array, separator = " | ") {
2604
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
2605
+ }
2606
+ util2.joinValues = joinValues;
2607
+ util2.jsonStringifyReplacer = (_, value) => {
2608
+ if (typeof value === "bigint") {
2609
+ return value.toString();
2610
+ }
2611
+ return value;
2612
+ };
2613
+ })(util || (util = {}));
2614
+ var objectUtil;
2615
+ (function(objectUtil2) {
2616
+ objectUtil2.mergeShapes = (first, second) => {
2617
+ return {
2618
+ ...first,
2619
+ ...second
2620
+ };
2621
+ };
2622
+ })(objectUtil || (objectUtil = {}));
2623
+ var ZodParsedType = util.arrayToEnum([
2624
+ "string",
2625
+ "nan",
2626
+ "number",
2627
+ "integer",
2628
+ "float",
2629
+ "boolean",
2630
+ "date",
2631
+ "bigint",
2632
+ "symbol",
2633
+ "function",
2634
+ "undefined",
2635
+ "null",
2636
+ "array",
2637
+ "object",
2638
+ "unknown",
2639
+ "promise",
2640
+ "void",
2641
+ "never",
2642
+ "map",
2643
+ "set"
2644
+ ]);
2645
+ var getParsedType = (data) => {
2646
+ const t = typeof data;
2647
+ switch (t) {
2648
+ case "undefined":
2649
+ return ZodParsedType.undefined;
2650
+ case "string":
2651
+ return ZodParsedType.string;
2652
+ case "number":
2653
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
2654
+ case "boolean":
2655
+ return ZodParsedType.boolean;
2656
+ case "function":
2657
+ return ZodParsedType.function;
2658
+ case "bigint":
2659
+ return ZodParsedType.bigint;
2660
+ case "symbol":
2661
+ return ZodParsedType.symbol;
2662
+ case "object":
2663
+ if (Array.isArray(data)) {
2664
+ return ZodParsedType.array;
2665
+ }
2666
+ if (data === null) {
2667
+ return ZodParsedType.null;
2668
+ }
2669
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
2670
+ return ZodParsedType.promise;
2671
+ }
2672
+ if (typeof Map !== "undefined" && data instanceof Map) {
2673
+ return ZodParsedType.map;
2674
+ }
2675
+ if (typeof Set !== "undefined" && data instanceof Set) {
2676
+ return ZodParsedType.set;
2677
+ }
2678
+ if (typeof Date !== "undefined" && data instanceof Date) {
2679
+ return ZodParsedType.date;
2680
+ }
2681
+ return ZodParsedType.object;
2682
+ default:
2683
+ return ZodParsedType.unknown;
2684
+ }
2685
+ };
2686
+
2687
+ // node_modules/zod/v3/ZodError.js
2688
+ var ZodIssueCode = util.arrayToEnum([
2689
+ "invalid_type",
2690
+ "invalid_literal",
2691
+ "custom",
2692
+ "invalid_union",
2693
+ "invalid_union_discriminator",
2694
+ "invalid_enum_value",
2695
+ "unrecognized_keys",
2696
+ "invalid_arguments",
2697
+ "invalid_return_type",
2698
+ "invalid_date",
2699
+ "invalid_string",
2700
+ "too_small",
2701
+ "too_big",
2702
+ "invalid_intersection_types",
2703
+ "not_multiple_of",
2704
+ "not_finite"
2705
+ ]);
2706
+ var quotelessJson = (obj) => {
2707
+ const json = JSON.stringify(obj, null, 2);
2708
+ return json.replace(/"([^"]+)":/g, "$1:");
2709
+ };
2710
+
2711
+ class ZodError extends Error {
2712
+ get errors() {
2713
+ return this.issues;
2714
+ }
2715
+ constructor(issues) {
2716
+ super();
2717
+ this.issues = [];
2718
+ this.addIssue = (sub) => {
2719
+ this.issues = [...this.issues, sub];
2720
+ };
2721
+ this.addIssues = (subs = []) => {
2722
+ this.issues = [...this.issues, ...subs];
2723
+ };
2724
+ const actualProto = new.target.prototype;
2725
+ if (Object.setPrototypeOf) {
2726
+ Object.setPrototypeOf(this, actualProto);
2727
+ } else {
2728
+ this.__proto__ = actualProto;
2729
+ }
2730
+ this.name = "ZodError";
2731
+ this.issues = issues;
2732
+ }
2733
+ format(_mapper) {
2734
+ const mapper = _mapper || function(issue) {
2735
+ return issue.message;
2736
+ };
2737
+ const fieldErrors = { _errors: [] };
2738
+ const processError = (error) => {
2739
+ for (const issue of error.issues) {
2740
+ if (issue.code === "invalid_union") {
2741
+ issue.unionErrors.map(processError);
2742
+ } else if (issue.code === "invalid_return_type") {
2743
+ processError(issue.returnTypeError);
2744
+ } else if (issue.code === "invalid_arguments") {
2745
+ processError(issue.argumentsError);
2746
+ } else if (issue.path.length === 0) {
2747
+ fieldErrors._errors.push(mapper(issue));
2748
+ } else {
2749
+ let curr = fieldErrors;
2750
+ let i = 0;
2751
+ while (i < issue.path.length) {
2752
+ const el = issue.path[i];
2753
+ const terminal = i === issue.path.length - 1;
2754
+ if (!terminal) {
2755
+ curr[el] = curr[el] || { _errors: [] };
2756
+ } else {
2757
+ curr[el] = curr[el] || { _errors: [] };
2758
+ curr[el]._errors.push(mapper(issue));
2759
+ }
2760
+ curr = curr[el];
2761
+ i++;
2762
+ }
2763
+ }
2764
+ }
2765
+ };
2766
+ processError(this);
2767
+ return fieldErrors;
2768
+ }
2769
+ static assert(value) {
2770
+ if (!(value instanceof ZodError)) {
2771
+ throw new Error(`Not a ZodError: ${value}`);
2772
+ }
2773
+ }
2774
+ toString() {
2775
+ return this.message;
2776
+ }
2777
+ get message() {
2778
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
2779
+ }
2780
+ get isEmpty() {
2781
+ return this.issues.length === 0;
2782
+ }
2783
+ flatten(mapper = (issue) => issue.message) {
2784
+ const fieldErrors = {};
2785
+ const formErrors = [];
2786
+ for (const sub of this.issues) {
2787
+ if (sub.path.length > 0) {
2788
+ const firstEl = sub.path[0];
2789
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
2790
+ fieldErrors[firstEl].push(mapper(sub));
2791
+ } else {
2792
+ formErrors.push(mapper(sub));
2793
+ }
2794
+ }
2795
+ return { formErrors, fieldErrors };
2796
+ }
2797
+ get formErrors() {
2798
+ return this.flatten();
2799
+ }
2800
+ }
2801
+ ZodError.create = (issues) => {
2802
+ const error = new ZodError(issues);
2803
+ return error;
2804
+ };
2805
+
2806
+ // node_modules/zod/v3/locales/en.js
2807
+ var errorMap = (issue, _ctx) => {
2808
+ let message;
2809
+ switch (issue.code) {
2810
+ case ZodIssueCode.invalid_type:
2811
+ if (issue.received === ZodParsedType.undefined) {
2812
+ message = "Required";
2813
+ } else {
2814
+ message = `Expected ${issue.expected}, received ${issue.received}`;
2815
+ }
2816
+ break;
2817
+ case ZodIssueCode.invalid_literal:
2818
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
2819
+ break;
2820
+ case ZodIssueCode.unrecognized_keys:
2821
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
2822
+ break;
2823
+ case ZodIssueCode.invalid_union:
2824
+ message = `Invalid input`;
2825
+ break;
2826
+ case ZodIssueCode.invalid_union_discriminator:
2827
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
2828
+ break;
2829
+ case ZodIssueCode.invalid_enum_value:
2830
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
2831
+ break;
2832
+ case ZodIssueCode.invalid_arguments:
2833
+ message = `Invalid function arguments`;
2834
+ break;
2835
+ case ZodIssueCode.invalid_return_type:
2836
+ message = `Invalid function return type`;
2837
+ break;
2838
+ case ZodIssueCode.invalid_date:
2839
+ message = `Invalid date`;
2840
+ break;
2841
+ case ZodIssueCode.invalid_string:
2842
+ if (typeof issue.validation === "object") {
2843
+ if ("includes" in issue.validation) {
2844
+ message = `Invalid input: must include "${issue.validation.includes}"`;
2845
+ if (typeof issue.validation.position === "number") {
2846
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
2847
+ }
2848
+ } else if ("startsWith" in issue.validation) {
2849
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
2850
+ } else if ("endsWith" in issue.validation) {
2851
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
2852
+ } else {
2853
+ util.assertNever(issue.validation);
2854
+ }
2855
+ } else if (issue.validation !== "regex") {
2856
+ message = `Invalid ${issue.validation}`;
2857
+ } else {
2858
+ message = "Invalid";
2859
+ }
2860
+ break;
2861
+ case ZodIssueCode.too_small:
2862
+ if (issue.type === "array")
2863
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
2864
+ else if (issue.type === "string")
2865
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
2866
+ else if (issue.type === "number")
2867
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
2868
+ else if (issue.type === "bigint")
2869
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
2870
+ else if (issue.type === "date")
2871
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
2872
+ else
2873
+ message = "Invalid input";
2874
+ break;
2875
+ case ZodIssueCode.too_big:
2876
+ if (issue.type === "array")
2877
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
2878
+ else if (issue.type === "string")
2879
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
2880
+ else if (issue.type === "number")
2881
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
2882
+ else if (issue.type === "bigint")
2883
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
2884
+ else if (issue.type === "date")
2885
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
2886
+ else
2887
+ message = "Invalid input";
2888
+ break;
2889
+ case ZodIssueCode.custom:
2890
+ message = `Invalid input`;
2891
+ break;
2892
+ case ZodIssueCode.invalid_intersection_types:
2893
+ message = `Intersection results could not be merged`;
2894
+ break;
2895
+ case ZodIssueCode.not_multiple_of:
2896
+ message = `Number must be a multiple of ${issue.multipleOf}`;
2897
+ break;
2898
+ case ZodIssueCode.not_finite:
2899
+ message = "Number must be finite";
2900
+ break;
2901
+ default:
2902
+ message = _ctx.defaultError;
2903
+ util.assertNever(issue);
2904
+ }
2905
+ return { message };
2906
+ };
2907
+ var en_default = errorMap;
2908
+
2909
+ // node_modules/zod/v3/errors.js
2910
+ var overrideErrorMap = en_default;
2911
+ function setErrorMap(map) {
2912
+ overrideErrorMap = map;
2913
+ }
2914
+ function getErrorMap() {
2915
+ return overrideErrorMap;
2916
+ }
2917
+ // node_modules/zod/v3/helpers/parseUtil.js
2918
+ var makeIssue = (params) => {
2919
+ const { data, path, errorMaps, issueData } = params;
2920
+ const fullPath = [...path, ...issueData.path || []];
2921
+ const fullIssue = {
2922
+ ...issueData,
2923
+ path: fullPath
2924
+ };
2925
+ if (issueData.message !== undefined) {
2926
+ return {
2927
+ ...issueData,
2928
+ path: fullPath,
2929
+ message: issueData.message
2930
+ };
2931
+ }
2932
+ let errorMessage = "";
2933
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
2934
+ for (const map of maps) {
2935
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
2936
+ }
2937
+ return {
2938
+ ...issueData,
2939
+ path: fullPath,
2940
+ message: errorMessage
2941
+ };
2942
+ };
2943
+ var EMPTY_PATH = [];
2944
+ function addIssueToContext(ctx, issueData) {
2945
+ const overrideMap = getErrorMap();
2946
+ const issue = makeIssue({
2947
+ issueData,
2948
+ data: ctx.data,
2949
+ path: ctx.path,
2950
+ errorMaps: [
2951
+ ctx.common.contextualErrorMap,
2952
+ ctx.schemaErrorMap,
2953
+ overrideMap,
2954
+ overrideMap === en_default ? undefined : en_default
2955
+ ].filter((x) => !!x)
2956
+ });
2957
+ ctx.common.issues.push(issue);
2958
+ }
2959
+
2960
+ class ParseStatus {
2961
+ constructor() {
2962
+ this.value = "valid";
2963
+ }
2964
+ dirty() {
2965
+ if (this.value === "valid")
2966
+ this.value = "dirty";
2967
+ }
2968
+ abort() {
2969
+ if (this.value !== "aborted")
2970
+ this.value = "aborted";
2971
+ }
2972
+ static mergeArray(status, results) {
2973
+ const arrayValue = [];
2974
+ for (const s of results) {
2975
+ if (s.status === "aborted")
2976
+ return INVALID;
2977
+ if (s.status === "dirty")
2978
+ status.dirty();
2979
+ arrayValue.push(s.value);
2980
+ }
2981
+ return { status: status.value, value: arrayValue };
2982
+ }
2983
+ static async mergeObjectAsync(status, pairs) {
2984
+ const syncPairs = [];
2985
+ for (const pair of pairs) {
2986
+ const key = await pair.key;
2987
+ const value = await pair.value;
2988
+ syncPairs.push({
2989
+ key,
2990
+ value
2991
+ });
2992
+ }
2993
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2994
+ }
2995
+ static mergeObjectSync(status, pairs) {
2996
+ const finalObject = {};
2997
+ for (const pair of pairs) {
2998
+ const { key, value } = pair;
2999
+ if (key.status === "aborted")
3000
+ return INVALID;
3001
+ if (value.status === "aborted")
3002
+ return INVALID;
3003
+ if (key.status === "dirty")
3004
+ status.dirty();
3005
+ if (value.status === "dirty")
3006
+ status.dirty();
3007
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
3008
+ finalObject[key.value] = value.value;
3009
+ }
3010
+ }
3011
+ return { status: status.value, value: finalObject };
3012
+ }
3013
+ }
3014
+ var INVALID = Object.freeze({
3015
+ status: "aborted"
3016
+ });
3017
+ var DIRTY = (value) => ({ status: "dirty", value });
3018
+ var OK = (value) => ({ status: "valid", value });
3019
+ var isAborted = (x) => x.status === "aborted";
3020
+ var isDirty = (x) => x.status === "dirty";
3021
+ var isValid = (x) => x.status === "valid";
3022
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
3023
+ // node_modules/zod/v3/helpers/errorUtil.js
3024
+ var errorUtil;
3025
+ (function(errorUtil2) {
3026
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
3027
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
3028
+ })(errorUtil || (errorUtil = {}));
3029
+
3030
+ // node_modules/zod/v3/types.js
3031
+ class ParseInputLazyPath {
3032
+ constructor(parent, value, path, key) {
3033
+ this._cachedPath = [];
3034
+ this.parent = parent;
3035
+ this.data = value;
3036
+ this._path = path;
3037
+ this._key = key;
3038
+ }
3039
+ get path() {
3040
+ if (!this._cachedPath.length) {
3041
+ if (Array.isArray(this._key)) {
3042
+ this._cachedPath.push(...this._path, ...this._key);
3043
+ } else {
3044
+ this._cachedPath.push(...this._path, this._key);
3045
+ }
3046
+ }
3047
+ return this._cachedPath;
3048
+ }
3049
+ }
3050
+ var handleResult = (ctx, result) => {
3051
+ if (isValid(result)) {
3052
+ return { success: true, data: result.value };
3053
+ } else {
3054
+ if (!ctx.common.issues.length) {
3055
+ throw new Error("Validation failed but no issues detected.");
3056
+ }
3057
+ return {
3058
+ success: false,
3059
+ get error() {
3060
+ if (this._error)
3061
+ return this._error;
3062
+ const error = new ZodError(ctx.common.issues);
3063
+ this._error = error;
3064
+ return this._error;
3065
+ }
3066
+ };
3067
+ }
3068
+ };
3069
+ function processCreateParams(params) {
3070
+ if (!params)
3071
+ return {};
3072
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
3073
+ if (errorMap2 && (invalid_type_error || required_error)) {
3074
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
3075
+ }
3076
+ if (errorMap2)
3077
+ return { errorMap: errorMap2, description };
3078
+ const customMap = (iss, ctx) => {
3079
+ const { message } = params;
3080
+ if (iss.code === "invalid_enum_value") {
3081
+ return { message: message ?? ctx.defaultError };
3082
+ }
3083
+ if (typeof ctx.data === "undefined") {
3084
+ return { message: message ?? required_error ?? ctx.defaultError };
3085
+ }
3086
+ if (iss.code !== "invalid_type")
3087
+ return { message: ctx.defaultError };
3088
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
3089
+ };
3090
+ return { errorMap: customMap, description };
3091
+ }
3092
+
3093
+ class ZodType {
3094
+ get description() {
3095
+ return this._def.description;
3096
+ }
3097
+ _getType(input) {
3098
+ return getParsedType(input.data);
3099
+ }
3100
+ _getOrReturnCtx(input, ctx) {
3101
+ return ctx || {
3102
+ common: input.parent.common,
3103
+ data: input.data,
3104
+ parsedType: getParsedType(input.data),
3105
+ schemaErrorMap: this._def.errorMap,
3106
+ path: input.path,
3107
+ parent: input.parent
3108
+ };
3109
+ }
3110
+ _processInputParams(input) {
3111
+ return {
3112
+ status: new ParseStatus,
3113
+ ctx: {
3114
+ common: input.parent.common,
3115
+ data: input.data,
3116
+ parsedType: getParsedType(input.data),
3117
+ schemaErrorMap: this._def.errorMap,
3118
+ path: input.path,
3119
+ parent: input.parent
3120
+ }
3121
+ };
3122
+ }
3123
+ _parseSync(input) {
3124
+ const result = this._parse(input);
3125
+ if (isAsync(result)) {
3126
+ throw new Error("Synchronous parse encountered promise.");
3127
+ }
3128
+ return result;
3129
+ }
3130
+ _parseAsync(input) {
3131
+ const result = this._parse(input);
3132
+ return Promise.resolve(result);
3133
+ }
3134
+ parse(data, params) {
3135
+ const result = this.safeParse(data, params);
3136
+ if (result.success)
3137
+ return result.data;
3138
+ throw result.error;
3139
+ }
3140
+ safeParse(data, params) {
3141
+ const ctx = {
3142
+ common: {
3143
+ issues: [],
3144
+ async: params?.async ?? false,
3145
+ contextualErrorMap: params?.errorMap
3146
+ },
3147
+ path: params?.path || [],
3148
+ schemaErrorMap: this._def.errorMap,
3149
+ parent: null,
3150
+ data,
3151
+ parsedType: getParsedType(data)
3152
+ };
3153
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
3154
+ return handleResult(ctx, result);
3155
+ }
3156
+ "~validate"(data) {
3157
+ const ctx = {
3158
+ common: {
3159
+ issues: [],
3160
+ async: !!this["~standard"].async
3161
+ },
3162
+ path: [],
3163
+ schemaErrorMap: this._def.errorMap,
3164
+ parent: null,
3165
+ data,
3166
+ parsedType: getParsedType(data)
3167
+ };
3168
+ if (!this["~standard"].async) {
3169
+ try {
3170
+ const result = this._parseSync({ data, path: [], parent: ctx });
3171
+ return isValid(result) ? {
3172
+ value: result.value
3173
+ } : {
3174
+ issues: ctx.common.issues
3175
+ };
3176
+ } catch (err) {
3177
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
3178
+ this["~standard"].async = true;
3179
+ }
3180
+ ctx.common = {
3181
+ issues: [],
3182
+ async: true
3183
+ };
3184
+ }
3185
+ }
3186
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
3187
+ value: result.value
3188
+ } : {
3189
+ issues: ctx.common.issues
3190
+ });
3191
+ }
3192
+ async parseAsync(data, params) {
3193
+ const result = await this.safeParseAsync(data, params);
3194
+ if (result.success)
3195
+ return result.data;
3196
+ throw result.error;
3197
+ }
3198
+ async safeParseAsync(data, params) {
3199
+ const ctx = {
3200
+ common: {
3201
+ issues: [],
3202
+ contextualErrorMap: params?.errorMap,
3203
+ async: true
3204
+ },
3205
+ path: params?.path || [],
3206
+ schemaErrorMap: this._def.errorMap,
3207
+ parent: null,
3208
+ data,
3209
+ parsedType: getParsedType(data)
3210
+ };
3211
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
3212
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
3213
+ return handleResult(ctx, result);
3214
+ }
3215
+ refine(check, message) {
3216
+ const getIssueProperties = (val) => {
3217
+ if (typeof message === "string" || typeof message === "undefined") {
3218
+ return { message };
3219
+ } else if (typeof message === "function") {
3220
+ return message(val);
3221
+ } else {
3222
+ return message;
3223
+ }
3224
+ };
3225
+ return this._refinement((val, ctx) => {
3226
+ const result = check(val);
3227
+ const setError = () => ctx.addIssue({
3228
+ code: ZodIssueCode.custom,
3229
+ ...getIssueProperties(val)
3230
+ });
3231
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
3232
+ return result.then((data) => {
3233
+ if (!data) {
3234
+ setError();
3235
+ return false;
3236
+ } else {
3237
+ return true;
3238
+ }
3239
+ });
3240
+ }
3241
+ if (!result) {
3242
+ setError();
3243
+ return false;
3244
+ } else {
3245
+ return true;
3246
+ }
3247
+ });
3248
+ }
3249
+ refinement(check, refinementData) {
3250
+ return this._refinement((val, ctx) => {
3251
+ if (!check(val)) {
3252
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
3253
+ return false;
3254
+ } else {
3255
+ return true;
3256
+ }
3257
+ });
3258
+ }
3259
+ _refinement(refinement) {
3260
+ return new ZodEffects({
3261
+ schema: this,
3262
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3263
+ effect: { type: "refinement", refinement }
3264
+ });
3265
+ }
3266
+ superRefine(refinement) {
3267
+ return this._refinement(refinement);
3268
+ }
3269
+ constructor(def) {
3270
+ this.spa = this.safeParseAsync;
3271
+ this._def = def;
3272
+ this.parse = this.parse.bind(this);
3273
+ this.safeParse = this.safeParse.bind(this);
3274
+ this.parseAsync = this.parseAsync.bind(this);
3275
+ this.safeParseAsync = this.safeParseAsync.bind(this);
3276
+ this.spa = this.spa.bind(this);
3277
+ this.refine = this.refine.bind(this);
3278
+ this.refinement = this.refinement.bind(this);
3279
+ this.superRefine = this.superRefine.bind(this);
3280
+ this.optional = this.optional.bind(this);
3281
+ this.nullable = this.nullable.bind(this);
3282
+ this.nullish = this.nullish.bind(this);
3283
+ this.array = this.array.bind(this);
3284
+ this.promise = this.promise.bind(this);
3285
+ this.or = this.or.bind(this);
3286
+ this.and = this.and.bind(this);
3287
+ this.transform = this.transform.bind(this);
3288
+ this.brand = this.brand.bind(this);
3289
+ this.default = this.default.bind(this);
3290
+ this.catch = this.catch.bind(this);
3291
+ this.describe = this.describe.bind(this);
3292
+ this.pipe = this.pipe.bind(this);
3293
+ this.readonly = this.readonly.bind(this);
3294
+ this.isNullable = this.isNullable.bind(this);
3295
+ this.isOptional = this.isOptional.bind(this);
3296
+ this["~standard"] = {
3297
+ version: 1,
3298
+ vendor: "zod",
3299
+ validate: (data) => this["~validate"](data)
3300
+ };
3301
+ }
3302
+ optional() {
3303
+ return ZodOptional.create(this, this._def);
3304
+ }
3305
+ nullable() {
3306
+ return ZodNullable.create(this, this._def);
3307
+ }
3308
+ nullish() {
3309
+ return this.nullable().optional();
3310
+ }
3311
+ array() {
3312
+ return ZodArray.create(this);
3313
+ }
3314
+ promise() {
3315
+ return ZodPromise.create(this, this._def);
3316
+ }
3317
+ or(option) {
3318
+ return ZodUnion.create([this, option], this._def);
3319
+ }
3320
+ and(incoming) {
3321
+ return ZodIntersection.create(this, incoming, this._def);
3322
+ }
3323
+ transform(transform) {
3324
+ return new ZodEffects({
3325
+ ...processCreateParams(this._def),
3326
+ schema: this,
3327
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3328
+ effect: { type: "transform", transform }
3329
+ });
3330
+ }
3331
+ default(def) {
3332
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
3333
+ return new ZodDefault({
3334
+ ...processCreateParams(this._def),
3335
+ innerType: this,
3336
+ defaultValue: defaultValueFunc,
3337
+ typeName: ZodFirstPartyTypeKind.ZodDefault
3338
+ });
3339
+ }
3340
+ brand() {
3341
+ return new ZodBranded({
3342
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
3343
+ type: this,
3344
+ ...processCreateParams(this._def)
3345
+ });
3346
+ }
3347
+ catch(def) {
3348
+ const catchValueFunc = typeof def === "function" ? def : () => def;
3349
+ return new ZodCatch({
3350
+ ...processCreateParams(this._def),
3351
+ innerType: this,
3352
+ catchValue: catchValueFunc,
3353
+ typeName: ZodFirstPartyTypeKind.ZodCatch
3354
+ });
3355
+ }
3356
+ describe(description) {
3357
+ const This = this.constructor;
3358
+ return new This({
3359
+ ...this._def,
3360
+ description
3361
+ });
3362
+ }
3363
+ pipe(target) {
3364
+ return ZodPipeline.create(this, target);
3365
+ }
3366
+ readonly() {
3367
+ return ZodReadonly.create(this);
3368
+ }
3369
+ isOptional() {
3370
+ return this.safeParse(undefined).success;
3371
+ }
3372
+ isNullable() {
3373
+ return this.safeParse(null).success;
3374
+ }
3375
+ }
3376
+ var cuidRegex = /^c[^\s-]{8,}$/i;
3377
+ var cuid2Regex = /^[0-9a-z]+$/;
3378
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
3379
+ var uuidRegex = /^[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}$/i;
3380
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
3381
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
3382
+ var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
3383
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
3384
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
3385
+ var emojiRegex;
3386
+ var ipv4Regex = /^(?:(?: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])$/;
3387
+ var ipv4CidrRegex = /^(?:(?: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])$/;
3388
+ var ipv6Regex = /^(([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]))$/;
3389
+ var ipv6CidrRegex = /^(([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])$/;
3390
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
3391
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
3392
+ var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
3393
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
3394
+ function timeRegexSource(args) {
3395
+ let secondsRegexSource = `[0-5]\\d`;
3396
+ if (args.precision) {
3397
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
3398
+ } else if (args.precision == null) {
3399
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
3400
+ }
3401
+ const secondsQuantifier = args.precision ? "+" : "?";
3402
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
3403
+ }
3404
+ function timeRegex(args) {
3405
+ return new RegExp(`^${timeRegexSource(args)}$`);
3406
+ }
3407
+ function datetimeRegex(args) {
3408
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
3409
+ const opts = [];
3410
+ opts.push(args.local ? `Z?` : `Z`);
3411
+ if (args.offset)
3412
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
3413
+ regex = `${regex}(${opts.join("|")})`;
3414
+ return new RegExp(`^${regex}$`);
3415
+ }
3416
+ function isValidIP(ip, version) {
3417
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
3418
+ return true;
3419
+ }
3420
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
3421
+ return true;
3422
+ }
3423
+ return false;
3424
+ }
3425
+ function isValidJWT(jwt, alg) {
3426
+ if (!jwtRegex.test(jwt))
3427
+ return false;
3428
+ try {
3429
+ const [header] = jwt.split(".");
3430
+ if (!header)
3431
+ return false;
3432
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
3433
+ const decoded = JSON.parse(atob(base64));
3434
+ if (typeof decoded !== "object" || decoded === null)
3435
+ return false;
3436
+ if ("typ" in decoded && decoded?.typ !== "JWT")
3437
+ return false;
3438
+ if (!decoded.alg)
3439
+ return false;
3440
+ if (alg && decoded.alg !== alg)
3441
+ return false;
3442
+ return true;
3443
+ } catch {
3444
+ return false;
3445
+ }
3446
+ }
3447
+ function isValidCidr(ip, version) {
3448
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
3449
+ return true;
3450
+ }
3451
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
3452
+ return true;
3453
+ }
3454
+ return false;
3455
+ }
3456
+
3457
+ class ZodString extends ZodType {
3458
+ _parse(input) {
3459
+ if (this._def.coerce) {
3460
+ input.data = String(input.data);
3461
+ }
3462
+ const parsedType = this._getType(input);
3463
+ if (parsedType !== ZodParsedType.string) {
3464
+ const ctx2 = this._getOrReturnCtx(input);
3465
+ addIssueToContext(ctx2, {
3466
+ code: ZodIssueCode.invalid_type,
3467
+ expected: ZodParsedType.string,
3468
+ received: ctx2.parsedType
3469
+ });
3470
+ return INVALID;
3471
+ }
3472
+ const status = new ParseStatus;
3473
+ let ctx = undefined;
3474
+ for (const check of this._def.checks) {
3475
+ if (check.kind === "min") {
3476
+ if (input.data.length < check.value) {
3477
+ ctx = this._getOrReturnCtx(input, ctx);
3478
+ addIssueToContext(ctx, {
3479
+ code: ZodIssueCode.too_small,
3480
+ minimum: check.value,
3481
+ type: "string",
3482
+ inclusive: true,
3483
+ exact: false,
3484
+ message: check.message
3485
+ });
3486
+ status.dirty();
3487
+ }
3488
+ } else if (check.kind === "max") {
3489
+ if (input.data.length > check.value) {
3490
+ ctx = this._getOrReturnCtx(input, ctx);
3491
+ addIssueToContext(ctx, {
3492
+ code: ZodIssueCode.too_big,
3493
+ maximum: check.value,
3494
+ type: "string",
3495
+ inclusive: true,
3496
+ exact: false,
3497
+ message: check.message
3498
+ });
3499
+ status.dirty();
3500
+ }
3501
+ } else if (check.kind === "length") {
3502
+ const tooBig = input.data.length > check.value;
3503
+ const tooSmall = input.data.length < check.value;
3504
+ if (tooBig || tooSmall) {
3505
+ ctx = this._getOrReturnCtx(input, ctx);
3506
+ if (tooBig) {
3507
+ addIssueToContext(ctx, {
3508
+ code: ZodIssueCode.too_big,
3509
+ maximum: check.value,
3510
+ type: "string",
3511
+ inclusive: true,
3512
+ exact: true,
3513
+ message: check.message
3514
+ });
3515
+ } else if (tooSmall) {
3516
+ addIssueToContext(ctx, {
3517
+ code: ZodIssueCode.too_small,
3518
+ minimum: check.value,
3519
+ type: "string",
3520
+ inclusive: true,
3521
+ exact: true,
3522
+ message: check.message
3523
+ });
3524
+ }
3525
+ status.dirty();
3526
+ }
3527
+ } else if (check.kind === "email") {
3528
+ if (!emailRegex.test(input.data)) {
3529
+ ctx = this._getOrReturnCtx(input, ctx);
3530
+ addIssueToContext(ctx, {
3531
+ validation: "email",
3532
+ code: ZodIssueCode.invalid_string,
3533
+ message: check.message
3534
+ });
3535
+ status.dirty();
3536
+ }
3537
+ } else if (check.kind === "emoji") {
3538
+ if (!emojiRegex) {
3539
+ emojiRegex = new RegExp(_emojiRegex, "u");
3540
+ }
3541
+ if (!emojiRegex.test(input.data)) {
3542
+ ctx = this._getOrReturnCtx(input, ctx);
3543
+ addIssueToContext(ctx, {
3544
+ validation: "emoji",
3545
+ code: ZodIssueCode.invalid_string,
3546
+ message: check.message
3547
+ });
3548
+ status.dirty();
3549
+ }
3550
+ } else if (check.kind === "uuid") {
3551
+ if (!uuidRegex.test(input.data)) {
3552
+ ctx = this._getOrReturnCtx(input, ctx);
3553
+ addIssueToContext(ctx, {
3554
+ validation: "uuid",
3555
+ code: ZodIssueCode.invalid_string,
3556
+ message: check.message
3557
+ });
3558
+ status.dirty();
3559
+ }
3560
+ } else if (check.kind === "nanoid") {
3561
+ if (!nanoidRegex.test(input.data)) {
3562
+ ctx = this._getOrReturnCtx(input, ctx);
3563
+ addIssueToContext(ctx, {
3564
+ validation: "nanoid",
3565
+ code: ZodIssueCode.invalid_string,
3566
+ message: check.message
3567
+ });
3568
+ status.dirty();
3569
+ }
3570
+ } else if (check.kind === "cuid") {
3571
+ if (!cuidRegex.test(input.data)) {
3572
+ ctx = this._getOrReturnCtx(input, ctx);
3573
+ addIssueToContext(ctx, {
3574
+ validation: "cuid",
3575
+ code: ZodIssueCode.invalid_string,
3576
+ message: check.message
3577
+ });
3578
+ status.dirty();
3579
+ }
3580
+ } else if (check.kind === "cuid2") {
3581
+ if (!cuid2Regex.test(input.data)) {
3582
+ ctx = this._getOrReturnCtx(input, ctx);
3583
+ addIssueToContext(ctx, {
3584
+ validation: "cuid2",
3585
+ code: ZodIssueCode.invalid_string,
3586
+ message: check.message
3587
+ });
3588
+ status.dirty();
3589
+ }
3590
+ } else if (check.kind === "ulid") {
3591
+ if (!ulidRegex.test(input.data)) {
3592
+ ctx = this._getOrReturnCtx(input, ctx);
3593
+ addIssueToContext(ctx, {
3594
+ validation: "ulid",
3595
+ code: ZodIssueCode.invalid_string,
3596
+ message: check.message
3597
+ });
3598
+ status.dirty();
3599
+ }
3600
+ } else if (check.kind === "url") {
3601
+ try {
3602
+ new URL(input.data);
3603
+ } catch {
3604
+ ctx = this._getOrReturnCtx(input, ctx);
3605
+ addIssueToContext(ctx, {
3606
+ validation: "url",
3607
+ code: ZodIssueCode.invalid_string,
3608
+ message: check.message
3609
+ });
3610
+ status.dirty();
3611
+ }
3612
+ } else if (check.kind === "regex") {
3613
+ check.regex.lastIndex = 0;
3614
+ const testResult = check.regex.test(input.data);
3615
+ if (!testResult) {
3616
+ ctx = this._getOrReturnCtx(input, ctx);
3617
+ addIssueToContext(ctx, {
3618
+ validation: "regex",
3619
+ code: ZodIssueCode.invalid_string,
3620
+ message: check.message
3621
+ });
3622
+ status.dirty();
3623
+ }
3624
+ } else if (check.kind === "trim") {
3625
+ input.data = input.data.trim();
3626
+ } else if (check.kind === "includes") {
3627
+ if (!input.data.includes(check.value, check.position)) {
3628
+ ctx = this._getOrReturnCtx(input, ctx);
3629
+ addIssueToContext(ctx, {
3630
+ code: ZodIssueCode.invalid_string,
3631
+ validation: { includes: check.value, position: check.position },
3632
+ message: check.message
3633
+ });
3634
+ status.dirty();
3635
+ }
3636
+ } else if (check.kind === "toLowerCase") {
3637
+ input.data = input.data.toLowerCase();
3638
+ } else if (check.kind === "toUpperCase") {
3639
+ input.data = input.data.toUpperCase();
3640
+ } else if (check.kind === "startsWith") {
3641
+ if (!input.data.startsWith(check.value)) {
3642
+ ctx = this._getOrReturnCtx(input, ctx);
3643
+ addIssueToContext(ctx, {
3644
+ code: ZodIssueCode.invalid_string,
3645
+ validation: { startsWith: check.value },
3646
+ message: check.message
3647
+ });
3648
+ status.dirty();
3649
+ }
3650
+ } else if (check.kind === "endsWith") {
3651
+ if (!input.data.endsWith(check.value)) {
3652
+ ctx = this._getOrReturnCtx(input, ctx);
3653
+ addIssueToContext(ctx, {
3654
+ code: ZodIssueCode.invalid_string,
3655
+ validation: { endsWith: check.value },
3656
+ message: check.message
3657
+ });
3658
+ status.dirty();
3659
+ }
3660
+ } else if (check.kind === "datetime") {
3661
+ const regex = datetimeRegex(check);
3662
+ if (!regex.test(input.data)) {
3663
+ ctx = this._getOrReturnCtx(input, ctx);
3664
+ addIssueToContext(ctx, {
3665
+ code: ZodIssueCode.invalid_string,
3666
+ validation: "datetime",
3667
+ message: check.message
3668
+ });
3669
+ status.dirty();
3670
+ }
3671
+ } else if (check.kind === "date") {
3672
+ const regex = dateRegex;
3673
+ if (!regex.test(input.data)) {
3674
+ ctx = this._getOrReturnCtx(input, ctx);
3675
+ addIssueToContext(ctx, {
3676
+ code: ZodIssueCode.invalid_string,
3677
+ validation: "date",
3678
+ message: check.message
3679
+ });
3680
+ status.dirty();
3681
+ }
3682
+ } else if (check.kind === "time") {
3683
+ const regex = timeRegex(check);
3684
+ if (!regex.test(input.data)) {
3685
+ ctx = this._getOrReturnCtx(input, ctx);
3686
+ addIssueToContext(ctx, {
3687
+ code: ZodIssueCode.invalid_string,
3688
+ validation: "time",
3689
+ message: check.message
3690
+ });
3691
+ status.dirty();
3692
+ }
3693
+ } else if (check.kind === "duration") {
3694
+ if (!durationRegex.test(input.data)) {
3695
+ ctx = this._getOrReturnCtx(input, ctx);
3696
+ addIssueToContext(ctx, {
3697
+ validation: "duration",
3698
+ code: ZodIssueCode.invalid_string,
3699
+ message: check.message
3700
+ });
3701
+ status.dirty();
3702
+ }
3703
+ } else if (check.kind === "ip") {
3704
+ if (!isValidIP(input.data, check.version)) {
3705
+ ctx = this._getOrReturnCtx(input, ctx);
3706
+ addIssueToContext(ctx, {
3707
+ validation: "ip",
3708
+ code: ZodIssueCode.invalid_string,
3709
+ message: check.message
3710
+ });
3711
+ status.dirty();
3712
+ }
3713
+ } else if (check.kind === "jwt") {
3714
+ if (!isValidJWT(input.data, check.alg)) {
3715
+ ctx = this._getOrReturnCtx(input, ctx);
3716
+ addIssueToContext(ctx, {
3717
+ validation: "jwt",
3718
+ code: ZodIssueCode.invalid_string,
3719
+ message: check.message
3720
+ });
3721
+ status.dirty();
3722
+ }
3723
+ } else if (check.kind === "cidr") {
3724
+ if (!isValidCidr(input.data, check.version)) {
3725
+ ctx = this._getOrReturnCtx(input, ctx);
3726
+ addIssueToContext(ctx, {
3727
+ validation: "cidr",
3728
+ code: ZodIssueCode.invalid_string,
3729
+ message: check.message
3730
+ });
3731
+ status.dirty();
3732
+ }
3733
+ } else if (check.kind === "base64") {
3734
+ if (!base64Regex.test(input.data)) {
3735
+ ctx = this._getOrReturnCtx(input, ctx);
3736
+ addIssueToContext(ctx, {
3737
+ validation: "base64",
3738
+ code: ZodIssueCode.invalid_string,
3739
+ message: check.message
3740
+ });
3741
+ status.dirty();
3742
+ }
3743
+ } else if (check.kind === "base64url") {
3744
+ if (!base64urlRegex.test(input.data)) {
3745
+ ctx = this._getOrReturnCtx(input, ctx);
3746
+ addIssueToContext(ctx, {
3747
+ validation: "base64url",
3748
+ code: ZodIssueCode.invalid_string,
3749
+ message: check.message
3750
+ });
3751
+ status.dirty();
3752
+ }
3753
+ } else {
3754
+ util.assertNever(check);
3755
+ }
3756
+ }
3757
+ return { status: status.value, value: input.data };
3758
+ }
3759
+ _regex(regex, validation, message) {
3760
+ return this.refinement((data) => regex.test(data), {
3761
+ validation,
3762
+ code: ZodIssueCode.invalid_string,
3763
+ ...errorUtil.errToObj(message)
3764
+ });
3765
+ }
3766
+ _addCheck(check) {
3767
+ return new ZodString({
3768
+ ...this._def,
3769
+ checks: [...this._def.checks, check]
3770
+ });
3771
+ }
3772
+ email(message) {
3773
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
3774
+ }
3775
+ url(message) {
3776
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
3777
+ }
3778
+ emoji(message) {
3779
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
3780
+ }
3781
+ uuid(message) {
3782
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
3783
+ }
3784
+ nanoid(message) {
3785
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
3786
+ }
3787
+ cuid(message) {
3788
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
3789
+ }
3790
+ cuid2(message) {
3791
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
3792
+ }
3793
+ ulid(message) {
3794
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
3795
+ }
3796
+ base64(message) {
3797
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
3798
+ }
3799
+ base64url(message) {
3800
+ return this._addCheck({
3801
+ kind: "base64url",
3802
+ ...errorUtil.errToObj(message)
3803
+ });
3804
+ }
3805
+ jwt(options) {
3806
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
3807
+ }
3808
+ ip(options) {
3809
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
3810
+ }
3811
+ cidr(options) {
3812
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
3813
+ }
3814
+ datetime(options) {
3815
+ if (typeof options === "string") {
3816
+ return this._addCheck({
3817
+ kind: "datetime",
3818
+ precision: null,
3819
+ offset: false,
3820
+ local: false,
3821
+ message: options
3822
+ });
3823
+ }
3824
+ return this._addCheck({
3825
+ kind: "datetime",
3826
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
3827
+ offset: options?.offset ?? false,
3828
+ local: options?.local ?? false,
3829
+ ...errorUtil.errToObj(options?.message)
3830
+ });
3831
+ }
3832
+ date(message) {
3833
+ return this._addCheck({ kind: "date", message });
3834
+ }
3835
+ time(options) {
3836
+ if (typeof options === "string") {
3837
+ return this._addCheck({
3838
+ kind: "time",
3839
+ precision: null,
3840
+ message: options
3841
+ });
3842
+ }
3843
+ return this._addCheck({
3844
+ kind: "time",
3845
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
3846
+ ...errorUtil.errToObj(options?.message)
3847
+ });
3848
+ }
3849
+ duration(message) {
3850
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
3851
+ }
3852
+ regex(regex, message) {
3853
+ return this._addCheck({
3854
+ kind: "regex",
3855
+ regex,
3856
+ ...errorUtil.errToObj(message)
3857
+ });
3858
+ }
3859
+ includes(value, options) {
3860
+ return this._addCheck({
3861
+ kind: "includes",
3862
+ value,
3863
+ position: options?.position,
3864
+ ...errorUtil.errToObj(options?.message)
3865
+ });
3866
+ }
3867
+ startsWith(value, message) {
3868
+ return this._addCheck({
3869
+ kind: "startsWith",
3870
+ value,
3871
+ ...errorUtil.errToObj(message)
3872
+ });
3873
+ }
3874
+ endsWith(value, message) {
3875
+ return this._addCheck({
3876
+ kind: "endsWith",
3877
+ value,
3878
+ ...errorUtil.errToObj(message)
3879
+ });
3880
+ }
3881
+ min(minLength, message) {
3882
+ return this._addCheck({
3883
+ kind: "min",
3884
+ value: minLength,
3885
+ ...errorUtil.errToObj(message)
3886
+ });
3887
+ }
3888
+ max(maxLength, message) {
3889
+ return this._addCheck({
3890
+ kind: "max",
3891
+ value: maxLength,
3892
+ ...errorUtil.errToObj(message)
3893
+ });
3894
+ }
3895
+ length(len, message) {
3896
+ return this._addCheck({
3897
+ kind: "length",
3898
+ value: len,
3899
+ ...errorUtil.errToObj(message)
3900
+ });
3901
+ }
3902
+ nonempty(message) {
3903
+ return this.min(1, errorUtil.errToObj(message));
3904
+ }
3905
+ trim() {
3906
+ return new ZodString({
3907
+ ...this._def,
3908
+ checks: [...this._def.checks, { kind: "trim" }]
3909
+ });
3910
+ }
3911
+ toLowerCase() {
3912
+ return new ZodString({
3913
+ ...this._def,
3914
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
3915
+ });
3916
+ }
3917
+ toUpperCase() {
3918
+ return new ZodString({
3919
+ ...this._def,
3920
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
3921
+ });
3922
+ }
3923
+ get isDatetime() {
3924
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
3925
+ }
3926
+ get isDate() {
3927
+ return !!this._def.checks.find((ch) => ch.kind === "date");
3928
+ }
3929
+ get isTime() {
3930
+ return !!this._def.checks.find((ch) => ch.kind === "time");
3931
+ }
3932
+ get isDuration() {
3933
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
3934
+ }
3935
+ get isEmail() {
3936
+ return !!this._def.checks.find((ch) => ch.kind === "email");
3937
+ }
3938
+ get isURL() {
3939
+ return !!this._def.checks.find((ch) => ch.kind === "url");
3940
+ }
3941
+ get isEmoji() {
3942
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
3943
+ }
3944
+ get isUUID() {
3945
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
3946
+ }
3947
+ get isNANOID() {
3948
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
3949
+ }
3950
+ get isCUID() {
3951
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
3952
+ }
3953
+ get isCUID2() {
3954
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
3955
+ }
3956
+ get isULID() {
3957
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
3958
+ }
3959
+ get isIP() {
3960
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
3961
+ }
3962
+ get isCIDR() {
3963
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
3964
+ }
3965
+ get isBase64() {
3966
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
3967
+ }
3968
+ get isBase64url() {
3969
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
3970
+ }
3971
+ get minLength() {
3972
+ let min = null;
3973
+ for (const ch of this._def.checks) {
3974
+ if (ch.kind === "min") {
3975
+ if (min === null || ch.value > min)
3976
+ min = ch.value;
3977
+ }
3978
+ }
3979
+ return min;
3980
+ }
3981
+ get maxLength() {
3982
+ let max = null;
3983
+ for (const ch of this._def.checks) {
3984
+ if (ch.kind === "max") {
3985
+ if (max === null || ch.value < max)
3986
+ max = ch.value;
3987
+ }
3988
+ }
3989
+ return max;
3990
+ }
3991
+ }
3992
+ ZodString.create = (params) => {
3993
+ return new ZodString({
3994
+ checks: [],
3995
+ typeName: ZodFirstPartyTypeKind.ZodString,
3996
+ coerce: params?.coerce ?? false,
3997
+ ...processCreateParams(params)
3998
+ });
3999
+ };
4000
+ function floatSafeRemainder(val, step) {
4001
+ const valDecCount = (val.toString().split(".")[1] || "").length;
4002
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
4003
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
4004
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
4005
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
4006
+ return valInt % stepInt / 10 ** decCount;
4007
+ }
4008
+
4009
+ class ZodNumber extends ZodType {
4010
+ constructor() {
4011
+ super(...arguments);
4012
+ this.min = this.gte;
4013
+ this.max = this.lte;
4014
+ this.step = this.multipleOf;
4015
+ }
4016
+ _parse(input) {
4017
+ if (this._def.coerce) {
4018
+ input.data = Number(input.data);
4019
+ }
4020
+ const parsedType = this._getType(input);
4021
+ if (parsedType !== ZodParsedType.number) {
4022
+ const ctx2 = this._getOrReturnCtx(input);
4023
+ addIssueToContext(ctx2, {
4024
+ code: ZodIssueCode.invalid_type,
4025
+ expected: ZodParsedType.number,
4026
+ received: ctx2.parsedType
4027
+ });
4028
+ return INVALID;
4029
+ }
4030
+ let ctx = undefined;
4031
+ const status = new ParseStatus;
4032
+ for (const check of this._def.checks) {
4033
+ if (check.kind === "int") {
4034
+ if (!util.isInteger(input.data)) {
4035
+ ctx = this._getOrReturnCtx(input, ctx);
4036
+ addIssueToContext(ctx, {
4037
+ code: ZodIssueCode.invalid_type,
4038
+ expected: "integer",
4039
+ received: "float",
4040
+ message: check.message
4041
+ });
4042
+ status.dirty();
4043
+ }
4044
+ } else if (check.kind === "min") {
4045
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
4046
+ if (tooSmall) {
4047
+ ctx = this._getOrReturnCtx(input, ctx);
4048
+ addIssueToContext(ctx, {
4049
+ code: ZodIssueCode.too_small,
4050
+ minimum: check.value,
4051
+ type: "number",
4052
+ inclusive: check.inclusive,
4053
+ exact: false,
4054
+ message: check.message
4055
+ });
4056
+ status.dirty();
4057
+ }
4058
+ } else if (check.kind === "max") {
4059
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
4060
+ if (tooBig) {
4061
+ ctx = this._getOrReturnCtx(input, ctx);
4062
+ addIssueToContext(ctx, {
4063
+ code: ZodIssueCode.too_big,
4064
+ maximum: check.value,
4065
+ type: "number",
4066
+ inclusive: check.inclusive,
4067
+ exact: false,
4068
+ message: check.message
4069
+ });
4070
+ status.dirty();
4071
+ }
4072
+ } else if (check.kind === "multipleOf") {
4073
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
4074
+ ctx = this._getOrReturnCtx(input, ctx);
4075
+ addIssueToContext(ctx, {
4076
+ code: ZodIssueCode.not_multiple_of,
4077
+ multipleOf: check.value,
4078
+ message: check.message
4079
+ });
4080
+ status.dirty();
4081
+ }
4082
+ } else if (check.kind === "finite") {
4083
+ if (!Number.isFinite(input.data)) {
4084
+ ctx = this._getOrReturnCtx(input, ctx);
4085
+ addIssueToContext(ctx, {
4086
+ code: ZodIssueCode.not_finite,
4087
+ message: check.message
4088
+ });
4089
+ status.dirty();
4090
+ }
4091
+ } else {
4092
+ util.assertNever(check);
4093
+ }
4094
+ }
4095
+ return { status: status.value, value: input.data };
4096
+ }
4097
+ gte(value, message) {
4098
+ return this.setLimit("min", value, true, errorUtil.toString(message));
4099
+ }
4100
+ gt(value, message) {
4101
+ return this.setLimit("min", value, false, errorUtil.toString(message));
4102
+ }
4103
+ lte(value, message) {
4104
+ return this.setLimit("max", value, true, errorUtil.toString(message));
4105
+ }
4106
+ lt(value, message) {
4107
+ return this.setLimit("max", value, false, errorUtil.toString(message));
4108
+ }
4109
+ setLimit(kind, value, inclusive, message) {
4110
+ return new ZodNumber({
4111
+ ...this._def,
4112
+ checks: [
4113
+ ...this._def.checks,
4114
+ {
4115
+ kind,
4116
+ value,
4117
+ inclusive,
4118
+ message: errorUtil.toString(message)
4119
+ }
4120
+ ]
4121
+ });
4122
+ }
4123
+ _addCheck(check) {
4124
+ return new ZodNumber({
4125
+ ...this._def,
4126
+ checks: [...this._def.checks, check]
4127
+ });
4128
+ }
4129
+ int(message) {
4130
+ return this._addCheck({
4131
+ kind: "int",
4132
+ message: errorUtil.toString(message)
4133
+ });
4134
+ }
4135
+ positive(message) {
4136
+ return this._addCheck({
4137
+ kind: "min",
4138
+ value: 0,
4139
+ inclusive: false,
4140
+ message: errorUtil.toString(message)
4141
+ });
4142
+ }
4143
+ negative(message) {
4144
+ return this._addCheck({
4145
+ kind: "max",
4146
+ value: 0,
4147
+ inclusive: false,
4148
+ message: errorUtil.toString(message)
4149
+ });
4150
+ }
4151
+ nonpositive(message) {
4152
+ return this._addCheck({
4153
+ kind: "max",
4154
+ value: 0,
4155
+ inclusive: true,
4156
+ message: errorUtil.toString(message)
4157
+ });
4158
+ }
4159
+ nonnegative(message) {
4160
+ return this._addCheck({
4161
+ kind: "min",
4162
+ value: 0,
4163
+ inclusive: true,
4164
+ message: errorUtil.toString(message)
4165
+ });
4166
+ }
4167
+ multipleOf(value, message) {
4168
+ return this._addCheck({
4169
+ kind: "multipleOf",
4170
+ value,
4171
+ message: errorUtil.toString(message)
4172
+ });
4173
+ }
4174
+ finite(message) {
4175
+ return this._addCheck({
4176
+ kind: "finite",
4177
+ message: errorUtil.toString(message)
4178
+ });
4179
+ }
4180
+ safe(message) {
4181
+ return this._addCheck({
4182
+ kind: "min",
4183
+ inclusive: true,
4184
+ value: Number.MIN_SAFE_INTEGER,
4185
+ message: errorUtil.toString(message)
4186
+ })._addCheck({
4187
+ kind: "max",
4188
+ inclusive: true,
4189
+ value: Number.MAX_SAFE_INTEGER,
4190
+ message: errorUtil.toString(message)
4191
+ });
4192
+ }
4193
+ get minValue() {
4194
+ let min = null;
4195
+ for (const ch of this._def.checks) {
4196
+ if (ch.kind === "min") {
4197
+ if (min === null || ch.value > min)
4198
+ min = ch.value;
4199
+ }
4200
+ }
4201
+ return min;
4202
+ }
4203
+ get maxValue() {
4204
+ let max = null;
4205
+ for (const ch of this._def.checks) {
4206
+ if (ch.kind === "max") {
4207
+ if (max === null || ch.value < max)
4208
+ max = ch.value;
4209
+ }
4210
+ }
4211
+ return max;
4212
+ }
4213
+ get isInt() {
4214
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
4215
+ }
4216
+ get isFinite() {
4217
+ let max = null;
4218
+ let min = null;
4219
+ for (const ch of this._def.checks) {
4220
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
4221
+ return true;
4222
+ } else if (ch.kind === "min") {
4223
+ if (min === null || ch.value > min)
4224
+ min = ch.value;
4225
+ } else if (ch.kind === "max") {
4226
+ if (max === null || ch.value < max)
4227
+ max = ch.value;
4228
+ }
4229
+ }
4230
+ return Number.isFinite(min) && Number.isFinite(max);
4231
+ }
4232
+ }
4233
+ ZodNumber.create = (params) => {
4234
+ return new ZodNumber({
4235
+ checks: [],
4236
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
4237
+ coerce: params?.coerce || false,
4238
+ ...processCreateParams(params)
4239
+ });
4240
+ };
4241
+
4242
+ class ZodBigInt extends ZodType {
4243
+ constructor() {
4244
+ super(...arguments);
4245
+ this.min = this.gte;
4246
+ this.max = this.lte;
4247
+ }
4248
+ _parse(input) {
4249
+ if (this._def.coerce) {
4250
+ try {
4251
+ input.data = BigInt(input.data);
4252
+ } catch {
4253
+ return this._getInvalidInput(input);
4254
+ }
4255
+ }
4256
+ const parsedType = this._getType(input);
4257
+ if (parsedType !== ZodParsedType.bigint) {
4258
+ return this._getInvalidInput(input);
4259
+ }
4260
+ let ctx = undefined;
4261
+ const status = new ParseStatus;
4262
+ for (const check of this._def.checks) {
4263
+ if (check.kind === "min") {
4264
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
4265
+ if (tooSmall) {
4266
+ ctx = this._getOrReturnCtx(input, ctx);
4267
+ addIssueToContext(ctx, {
4268
+ code: ZodIssueCode.too_small,
4269
+ type: "bigint",
4270
+ minimum: check.value,
4271
+ inclusive: check.inclusive,
4272
+ message: check.message
4273
+ });
4274
+ status.dirty();
4275
+ }
4276
+ } else if (check.kind === "max") {
4277
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
4278
+ if (tooBig) {
4279
+ ctx = this._getOrReturnCtx(input, ctx);
4280
+ addIssueToContext(ctx, {
4281
+ code: ZodIssueCode.too_big,
4282
+ type: "bigint",
4283
+ maximum: check.value,
4284
+ inclusive: check.inclusive,
4285
+ message: check.message
4286
+ });
4287
+ status.dirty();
4288
+ }
4289
+ } else if (check.kind === "multipleOf") {
4290
+ if (input.data % check.value !== BigInt(0)) {
4291
+ ctx = this._getOrReturnCtx(input, ctx);
4292
+ addIssueToContext(ctx, {
4293
+ code: ZodIssueCode.not_multiple_of,
4294
+ multipleOf: check.value,
4295
+ message: check.message
4296
+ });
4297
+ status.dirty();
4298
+ }
4299
+ } else {
4300
+ util.assertNever(check);
4301
+ }
4302
+ }
4303
+ return { status: status.value, value: input.data };
4304
+ }
4305
+ _getInvalidInput(input) {
4306
+ const ctx = this._getOrReturnCtx(input);
4307
+ addIssueToContext(ctx, {
4308
+ code: ZodIssueCode.invalid_type,
4309
+ expected: ZodParsedType.bigint,
4310
+ received: ctx.parsedType
4311
+ });
4312
+ return INVALID;
4313
+ }
4314
+ gte(value, message) {
4315
+ return this.setLimit("min", value, true, errorUtil.toString(message));
4316
+ }
4317
+ gt(value, message) {
4318
+ return this.setLimit("min", value, false, errorUtil.toString(message));
4319
+ }
4320
+ lte(value, message) {
4321
+ return this.setLimit("max", value, true, errorUtil.toString(message));
4322
+ }
4323
+ lt(value, message) {
4324
+ return this.setLimit("max", value, false, errorUtil.toString(message));
4325
+ }
4326
+ setLimit(kind, value, inclusive, message) {
4327
+ return new ZodBigInt({
4328
+ ...this._def,
4329
+ checks: [
4330
+ ...this._def.checks,
4331
+ {
4332
+ kind,
4333
+ value,
4334
+ inclusive,
4335
+ message: errorUtil.toString(message)
4336
+ }
4337
+ ]
4338
+ });
4339
+ }
4340
+ _addCheck(check) {
4341
+ return new ZodBigInt({
4342
+ ...this._def,
4343
+ checks: [...this._def.checks, check]
4344
+ });
4345
+ }
4346
+ positive(message) {
4347
+ return this._addCheck({
4348
+ kind: "min",
4349
+ value: BigInt(0),
4350
+ inclusive: false,
4351
+ message: errorUtil.toString(message)
4352
+ });
4353
+ }
4354
+ negative(message) {
4355
+ return this._addCheck({
4356
+ kind: "max",
4357
+ value: BigInt(0),
4358
+ inclusive: false,
4359
+ message: errorUtil.toString(message)
4360
+ });
4361
+ }
4362
+ nonpositive(message) {
4363
+ return this._addCheck({
4364
+ kind: "max",
4365
+ value: BigInt(0),
4366
+ inclusive: true,
4367
+ message: errorUtil.toString(message)
4368
+ });
4369
+ }
4370
+ nonnegative(message) {
4371
+ return this._addCheck({
4372
+ kind: "min",
4373
+ value: BigInt(0),
4374
+ inclusive: true,
4375
+ message: errorUtil.toString(message)
4376
+ });
4377
+ }
4378
+ multipleOf(value, message) {
4379
+ return this._addCheck({
4380
+ kind: "multipleOf",
4381
+ value,
4382
+ message: errorUtil.toString(message)
4383
+ });
4384
+ }
4385
+ get minValue() {
4386
+ let min = null;
4387
+ for (const ch of this._def.checks) {
4388
+ if (ch.kind === "min") {
4389
+ if (min === null || ch.value > min)
4390
+ min = ch.value;
4391
+ }
4392
+ }
4393
+ return min;
4394
+ }
4395
+ get maxValue() {
4396
+ let max = null;
4397
+ for (const ch of this._def.checks) {
4398
+ if (ch.kind === "max") {
4399
+ if (max === null || ch.value < max)
4400
+ max = ch.value;
4401
+ }
4402
+ }
4403
+ return max;
4404
+ }
4405
+ }
4406
+ ZodBigInt.create = (params) => {
4407
+ return new ZodBigInt({
4408
+ checks: [],
4409
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
4410
+ coerce: params?.coerce ?? false,
4411
+ ...processCreateParams(params)
4412
+ });
4413
+ };
4414
+
4415
+ class ZodBoolean extends ZodType {
4416
+ _parse(input) {
4417
+ if (this._def.coerce) {
4418
+ input.data = Boolean(input.data);
4419
+ }
4420
+ const parsedType = this._getType(input);
4421
+ if (parsedType !== ZodParsedType.boolean) {
4422
+ const ctx = this._getOrReturnCtx(input);
4423
+ addIssueToContext(ctx, {
4424
+ code: ZodIssueCode.invalid_type,
4425
+ expected: ZodParsedType.boolean,
4426
+ received: ctx.parsedType
4427
+ });
4428
+ return INVALID;
4429
+ }
4430
+ return OK(input.data);
4431
+ }
4432
+ }
4433
+ ZodBoolean.create = (params) => {
4434
+ return new ZodBoolean({
4435
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
4436
+ coerce: params?.coerce || false,
4437
+ ...processCreateParams(params)
4438
+ });
4439
+ };
4440
+
4441
+ class ZodDate extends ZodType {
4442
+ _parse(input) {
4443
+ if (this._def.coerce) {
4444
+ input.data = new Date(input.data);
4445
+ }
4446
+ const parsedType = this._getType(input);
4447
+ if (parsedType !== ZodParsedType.date) {
4448
+ const ctx2 = this._getOrReturnCtx(input);
4449
+ addIssueToContext(ctx2, {
4450
+ code: ZodIssueCode.invalid_type,
4451
+ expected: ZodParsedType.date,
4452
+ received: ctx2.parsedType
4453
+ });
4454
+ return INVALID;
4455
+ }
4456
+ if (Number.isNaN(input.data.getTime())) {
4457
+ const ctx2 = this._getOrReturnCtx(input);
4458
+ addIssueToContext(ctx2, {
4459
+ code: ZodIssueCode.invalid_date
4460
+ });
4461
+ return INVALID;
4462
+ }
4463
+ const status = new ParseStatus;
4464
+ let ctx = undefined;
4465
+ for (const check of this._def.checks) {
4466
+ if (check.kind === "min") {
4467
+ if (input.data.getTime() < check.value) {
4468
+ ctx = this._getOrReturnCtx(input, ctx);
4469
+ addIssueToContext(ctx, {
4470
+ code: ZodIssueCode.too_small,
4471
+ message: check.message,
4472
+ inclusive: true,
4473
+ exact: false,
4474
+ minimum: check.value,
4475
+ type: "date"
4476
+ });
4477
+ status.dirty();
4478
+ }
4479
+ } else if (check.kind === "max") {
4480
+ if (input.data.getTime() > check.value) {
4481
+ ctx = this._getOrReturnCtx(input, ctx);
4482
+ addIssueToContext(ctx, {
4483
+ code: ZodIssueCode.too_big,
4484
+ message: check.message,
4485
+ inclusive: true,
4486
+ exact: false,
4487
+ maximum: check.value,
4488
+ type: "date"
4489
+ });
4490
+ status.dirty();
4491
+ }
4492
+ } else {
4493
+ util.assertNever(check);
4494
+ }
4495
+ }
4496
+ return {
4497
+ status: status.value,
4498
+ value: new Date(input.data.getTime())
4499
+ };
4500
+ }
4501
+ _addCheck(check) {
4502
+ return new ZodDate({
4503
+ ...this._def,
4504
+ checks: [...this._def.checks, check]
4505
+ });
4506
+ }
4507
+ min(minDate, message) {
4508
+ return this._addCheck({
4509
+ kind: "min",
4510
+ value: minDate.getTime(),
4511
+ message: errorUtil.toString(message)
4512
+ });
4513
+ }
4514
+ max(maxDate, message) {
4515
+ return this._addCheck({
4516
+ kind: "max",
4517
+ value: maxDate.getTime(),
4518
+ message: errorUtil.toString(message)
4519
+ });
4520
+ }
4521
+ get minDate() {
4522
+ let min = null;
4523
+ for (const ch of this._def.checks) {
4524
+ if (ch.kind === "min") {
4525
+ if (min === null || ch.value > min)
4526
+ min = ch.value;
4527
+ }
4528
+ }
4529
+ return min != null ? new Date(min) : null;
4530
+ }
4531
+ get maxDate() {
4532
+ let max = null;
4533
+ for (const ch of this._def.checks) {
4534
+ if (ch.kind === "max") {
4535
+ if (max === null || ch.value < max)
4536
+ max = ch.value;
4537
+ }
4538
+ }
4539
+ return max != null ? new Date(max) : null;
4540
+ }
4541
+ }
4542
+ ZodDate.create = (params) => {
4543
+ return new ZodDate({
4544
+ checks: [],
4545
+ coerce: params?.coerce || false,
4546
+ typeName: ZodFirstPartyTypeKind.ZodDate,
4547
+ ...processCreateParams(params)
4548
+ });
4549
+ };
4550
+
4551
+ class ZodSymbol extends ZodType {
4552
+ _parse(input) {
4553
+ const parsedType = this._getType(input);
4554
+ if (parsedType !== ZodParsedType.symbol) {
4555
+ const ctx = this._getOrReturnCtx(input);
4556
+ addIssueToContext(ctx, {
4557
+ code: ZodIssueCode.invalid_type,
4558
+ expected: ZodParsedType.symbol,
4559
+ received: ctx.parsedType
4560
+ });
4561
+ return INVALID;
4562
+ }
4563
+ return OK(input.data);
4564
+ }
4565
+ }
4566
+ ZodSymbol.create = (params) => {
4567
+ return new ZodSymbol({
4568
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
4569
+ ...processCreateParams(params)
4570
+ });
4571
+ };
4572
+
4573
+ class ZodUndefined extends ZodType {
4574
+ _parse(input) {
4575
+ const parsedType = this._getType(input);
4576
+ if (parsedType !== ZodParsedType.undefined) {
4577
+ const ctx = this._getOrReturnCtx(input);
4578
+ addIssueToContext(ctx, {
4579
+ code: ZodIssueCode.invalid_type,
4580
+ expected: ZodParsedType.undefined,
4581
+ received: ctx.parsedType
4582
+ });
4583
+ return INVALID;
4584
+ }
4585
+ return OK(input.data);
4586
+ }
4587
+ }
4588
+ ZodUndefined.create = (params) => {
4589
+ return new ZodUndefined({
4590
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
4591
+ ...processCreateParams(params)
4592
+ });
4593
+ };
4594
+
4595
+ class ZodNull extends ZodType {
4596
+ _parse(input) {
4597
+ const parsedType = this._getType(input);
4598
+ if (parsedType !== ZodParsedType.null) {
4599
+ const ctx = this._getOrReturnCtx(input);
4600
+ addIssueToContext(ctx, {
4601
+ code: ZodIssueCode.invalid_type,
4602
+ expected: ZodParsedType.null,
4603
+ received: ctx.parsedType
4604
+ });
4605
+ return INVALID;
4606
+ }
4607
+ return OK(input.data);
4608
+ }
4609
+ }
4610
+ ZodNull.create = (params) => {
4611
+ return new ZodNull({
4612
+ typeName: ZodFirstPartyTypeKind.ZodNull,
4613
+ ...processCreateParams(params)
4614
+ });
4615
+ };
4616
+
4617
+ class ZodAny extends ZodType {
4618
+ constructor() {
4619
+ super(...arguments);
4620
+ this._any = true;
4621
+ }
4622
+ _parse(input) {
4623
+ return OK(input.data);
4624
+ }
4625
+ }
4626
+ ZodAny.create = (params) => {
4627
+ return new ZodAny({
4628
+ typeName: ZodFirstPartyTypeKind.ZodAny,
4629
+ ...processCreateParams(params)
4630
+ });
4631
+ };
4632
+
4633
+ class ZodUnknown extends ZodType {
4634
+ constructor() {
4635
+ super(...arguments);
4636
+ this._unknown = true;
4637
+ }
4638
+ _parse(input) {
4639
+ return OK(input.data);
4640
+ }
4641
+ }
4642
+ ZodUnknown.create = (params) => {
4643
+ return new ZodUnknown({
4644
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
4645
+ ...processCreateParams(params)
4646
+ });
4647
+ };
4648
+
4649
+ class ZodNever extends ZodType {
4650
+ _parse(input) {
4651
+ const ctx = this._getOrReturnCtx(input);
4652
+ addIssueToContext(ctx, {
4653
+ code: ZodIssueCode.invalid_type,
4654
+ expected: ZodParsedType.never,
4655
+ received: ctx.parsedType
4656
+ });
4657
+ return INVALID;
4658
+ }
4659
+ }
4660
+ ZodNever.create = (params) => {
4661
+ return new ZodNever({
4662
+ typeName: ZodFirstPartyTypeKind.ZodNever,
4663
+ ...processCreateParams(params)
4664
+ });
4665
+ };
4666
+
4667
+ class ZodVoid extends ZodType {
4668
+ _parse(input) {
4669
+ const parsedType = this._getType(input);
4670
+ if (parsedType !== ZodParsedType.undefined) {
4671
+ const ctx = this._getOrReturnCtx(input);
4672
+ addIssueToContext(ctx, {
4673
+ code: ZodIssueCode.invalid_type,
4674
+ expected: ZodParsedType.void,
4675
+ received: ctx.parsedType
4676
+ });
4677
+ return INVALID;
4678
+ }
4679
+ return OK(input.data);
4680
+ }
4681
+ }
4682
+ ZodVoid.create = (params) => {
4683
+ return new ZodVoid({
4684
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
4685
+ ...processCreateParams(params)
4686
+ });
4687
+ };
4688
+
4689
+ class ZodArray extends ZodType {
4690
+ _parse(input) {
4691
+ const { ctx, status } = this._processInputParams(input);
4692
+ const def = this._def;
4693
+ if (ctx.parsedType !== ZodParsedType.array) {
4694
+ addIssueToContext(ctx, {
4695
+ code: ZodIssueCode.invalid_type,
4696
+ expected: ZodParsedType.array,
4697
+ received: ctx.parsedType
4698
+ });
4699
+ return INVALID;
4700
+ }
4701
+ if (def.exactLength !== null) {
4702
+ const tooBig = ctx.data.length > def.exactLength.value;
4703
+ const tooSmall = ctx.data.length < def.exactLength.value;
4704
+ if (tooBig || tooSmall) {
4705
+ addIssueToContext(ctx, {
4706
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
4707
+ minimum: tooSmall ? def.exactLength.value : undefined,
4708
+ maximum: tooBig ? def.exactLength.value : undefined,
4709
+ type: "array",
4710
+ inclusive: true,
4711
+ exact: true,
4712
+ message: def.exactLength.message
4713
+ });
4714
+ status.dirty();
4715
+ }
4716
+ }
4717
+ if (def.minLength !== null) {
4718
+ if (ctx.data.length < def.minLength.value) {
4719
+ addIssueToContext(ctx, {
4720
+ code: ZodIssueCode.too_small,
4721
+ minimum: def.minLength.value,
4722
+ type: "array",
4723
+ inclusive: true,
4724
+ exact: false,
4725
+ message: def.minLength.message
4726
+ });
4727
+ status.dirty();
4728
+ }
4729
+ }
4730
+ if (def.maxLength !== null) {
4731
+ if (ctx.data.length > def.maxLength.value) {
4732
+ addIssueToContext(ctx, {
4733
+ code: ZodIssueCode.too_big,
4734
+ maximum: def.maxLength.value,
4735
+ type: "array",
4736
+ inclusive: true,
4737
+ exact: false,
4738
+ message: def.maxLength.message
4739
+ });
4740
+ status.dirty();
4741
+ }
4742
+ }
4743
+ if (ctx.common.async) {
4744
+ return Promise.all([...ctx.data].map((item, i) => {
4745
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
4746
+ })).then((result2) => {
4747
+ return ParseStatus.mergeArray(status, result2);
4748
+ });
4749
+ }
4750
+ const result = [...ctx.data].map((item, i) => {
4751
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
4752
+ });
4753
+ return ParseStatus.mergeArray(status, result);
4754
+ }
4755
+ get element() {
4756
+ return this._def.type;
4757
+ }
4758
+ min(minLength, message) {
4759
+ return new ZodArray({
4760
+ ...this._def,
4761
+ minLength: { value: minLength, message: errorUtil.toString(message) }
4762
+ });
4763
+ }
4764
+ max(maxLength, message) {
4765
+ return new ZodArray({
4766
+ ...this._def,
4767
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
4768
+ });
4769
+ }
4770
+ length(len, message) {
4771
+ return new ZodArray({
4772
+ ...this._def,
4773
+ exactLength: { value: len, message: errorUtil.toString(message) }
4774
+ });
4775
+ }
4776
+ nonempty(message) {
4777
+ return this.min(1, message);
4778
+ }
4779
+ }
4780
+ ZodArray.create = (schema, params) => {
4781
+ return new ZodArray({
4782
+ type: schema,
4783
+ minLength: null,
4784
+ maxLength: null,
4785
+ exactLength: null,
4786
+ typeName: ZodFirstPartyTypeKind.ZodArray,
4787
+ ...processCreateParams(params)
4788
+ });
4789
+ };
4790
+ function deepPartialify(schema) {
4791
+ if (schema instanceof ZodObject) {
4792
+ const newShape = {};
4793
+ for (const key in schema.shape) {
4794
+ const fieldSchema = schema.shape[key];
4795
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
4796
+ }
4797
+ return new ZodObject({
4798
+ ...schema._def,
4799
+ shape: () => newShape
4800
+ });
4801
+ } else if (schema instanceof ZodArray) {
4802
+ return new ZodArray({
4803
+ ...schema._def,
4804
+ type: deepPartialify(schema.element)
4805
+ });
4806
+ } else if (schema instanceof ZodOptional) {
4807
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
4808
+ } else if (schema instanceof ZodNullable) {
4809
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
4810
+ } else if (schema instanceof ZodTuple) {
4811
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
4812
+ } else {
4813
+ return schema;
4814
+ }
4815
+ }
4816
+
4817
+ class ZodObject extends ZodType {
4818
+ constructor() {
4819
+ super(...arguments);
4820
+ this._cached = null;
4821
+ this.nonstrict = this.passthrough;
4822
+ this.augment = this.extend;
4823
+ }
4824
+ _getCached() {
4825
+ if (this._cached !== null)
4826
+ return this._cached;
4827
+ const shape = this._def.shape();
4828
+ const keys = util.objectKeys(shape);
4829
+ this._cached = { shape, keys };
4830
+ return this._cached;
4831
+ }
4832
+ _parse(input) {
4833
+ const parsedType = this._getType(input);
4834
+ if (parsedType !== ZodParsedType.object) {
4835
+ const ctx2 = this._getOrReturnCtx(input);
4836
+ addIssueToContext(ctx2, {
4837
+ code: ZodIssueCode.invalid_type,
4838
+ expected: ZodParsedType.object,
4839
+ received: ctx2.parsedType
4840
+ });
4841
+ return INVALID;
4842
+ }
4843
+ const { status, ctx } = this._processInputParams(input);
4844
+ const { shape, keys: shapeKeys } = this._getCached();
4845
+ const extraKeys = [];
4846
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
4847
+ for (const key in ctx.data) {
4848
+ if (!shapeKeys.includes(key)) {
4849
+ extraKeys.push(key);
4850
+ }
4851
+ }
4852
+ }
4853
+ const pairs = [];
4854
+ for (const key of shapeKeys) {
4855
+ const keyValidator = shape[key];
4856
+ const value = ctx.data[key];
4857
+ pairs.push({
4858
+ key: { status: "valid", value: key },
4859
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
4860
+ alwaysSet: key in ctx.data
4861
+ });
4862
+ }
4863
+ if (this._def.catchall instanceof ZodNever) {
4864
+ const unknownKeys = this._def.unknownKeys;
4865
+ if (unknownKeys === "passthrough") {
4866
+ for (const key of extraKeys) {
4867
+ pairs.push({
4868
+ key: { status: "valid", value: key },
4869
+ value: { status: "valid", value: ctx.data[key] }
4870
+ });
4871
+ }
4872
+ } else if (unknownKeys === "strict") {
4873
+ if (extraKeys.length > 0) {
4874
+ addIssueToContext(ctx, {
4875
+ code: ZodIssueCode.unrecognized_keys,
4876
+ keys: extraKeys
4877
+ });
4878
+ status.dirty();
4879
+ }
4880
+ } else if (unknownKeys === "strip") {} else {
4881
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
4882
+ }
4883
+ } else {
4884
+ const catchall = this._def.catchall;
4885
+ for (const key of extraKeys) {
4886
+ const value = ctx.data[key];
4887
+ pairs.push({
4888
+ key: { status: "valid", value: key },
4889
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
4890
+ alwaysSet: key in ctx.data
4891
+ });
4892
+ }
4893
+ }
4894
+ if (ctx.common.async) {
4895
+ return Promise.resolve().then(async () => {
4896
+ const syncPairs = [];
4897
+ for (const pair of pairs) {
4898
+ const key = await pair.key;
4899
+ const value = await pair.value;
4900
+ syncPairs.push({
4901
+ key,
4902
+ value,
4903
+ alwaysSet: pair.alwaysSet
4904
+ });
4905
+ }
4906
+ return syncPairs;
4907
+ }).then((syncPairs) => {
4908
+ return ParseStatus.mergeObjectSync(status, syncPairs);
4909
+ });
4910
+ } else {
4911
+ return ParseStatus.mergeObjectSync(status, pairs);
4912
+ }
4913
+ }
4914
+ get shape() {
4915
+ return this._def.shape();
4916
+ }
4917
+ strict(message) {
4918
+ errorUtil.errToObj;
4919
+ return new ZodObject({
4920
+ ...this._def,
4921
+ unknownKeys: "strict",
4922
+ ...message !== undefined ? {
4923
+ errorMap: (issue, ctx) => {
4924
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
4925
+ if (issue.code === "unrecognized_keys")
4926
+ return {
4927
+ message: errorUtil.errToObj(message).message ?? defaultError
4928
+ };
4929
+ return {
4930
+ message: defaultError
4931
+ };
4932
+ }
4933
+ } : {}
4934
+ });
4935
+ }
4936
+ strip() {
4937
+ return new ZodObject({
4938
+ ...this._def,
4939
+ unknownKeys: "strip"
4940
+ });
4941
+ }
4942
+ passthrough() {
4943
+ return new ZodObject({
4944
+ ...this._def,
4945
+ unknownKeys: "passthrough"
4946
+ });
4947
+ }
4948
+ extend(augmentation) {
4949
+ return new ZodObject({
4950
+ ...this._def,
4951
+ shape: () => ({
4952
+ ...this._def.shape(),
4953
+ ...augmentation
4954
+ })
4955
+ });
4956
+ }
4957
+ merge(merging) {
4958
+ const merged = new ZodObject({
4959
+ unknownKeys: merging._def.unknownKeys,
4960
+ catchall: merging._def.catchall,
4961
+ shape: () => ({
4962
+ ...this._def.shape(),
4963
+ ...merging._def.shape()
4964
+ }),
4965
+ typeName: ZodFirstPartyTypeKind.ZodObject
4966
+ });
4967
+ return merged;
4968
+ }
4969
+ setKey(key, schema) {
4970
+ return this.augment({ [key]: schema });
4971
+ }
4972
+ catchall(index) {
4973
+ return new ZodObject({
4974
+ ...this._def,
4975
+ catchall: index
4976
+ });
4977
+ }
4978
+ pick(mask) {
4979
+ const shape = {};
4980
+ for (const key of util.objectKeys(mask)) {
4981
+ if (mask[key] && this.shape[key]) {
4982
+ shape[key] = this.shape[key];
4983
+ }
4984
+ }
4985
+ return new ZodObject({
4986
+ ...this._def,
4987
+ shape: () => shape
4988
+ });
4989
+ }
4990
+ omit(mask) {
4991
+ const shape = {};
4992
+ for (const key of util.objectKeys(this.shape)) {
4993
+ if (!mask[key]) {
4994
+ shape[key] = this.shape[key];
4995
+ }
4996
+ }
4997
+ return new ZodObject({
4998
+ ...this._def,
4999
+ shape: () => shape
5000
+ });
5001
+ }
5002
+ deepPartial() {
5003
+ return deepPartialify(this);
5004
+ }
5005
+ partial(mask) {
5006
+ const newShape = {};
5007
+ for (const key of util.objectKeys(this.shape)) {
5008
+ const fieldSchema = this.shape[key];
5009
+ if (mask && !mask[key]) {
5010
+ newShape[key] = fieldSchema;
5011
+ } else {
5012
+ newShape[key] = fieldSchema.optional();
5013
+ }
5014
+ }
5015
+ return new ZodObject({
5016
+ ...this._def,
5017
+ shape: () => newShape
5018
+ });
5019
+ }
5020
+ required(mask) {
5021
+ const newShape = {};
5022
+ for (const key of util.objectKeys(this.shape)) {
5023
+ if (mask && !mask[key]) {
5024
+ newShape[key] = this.shape[key];
5025
+ } else {
5026
+ const fieldSchema = this.shape[key];
5027
+ let newField = fieldSchema;
5028
+ while (newField instanceof ZodOptional) {
5029
+ newField = newField._def.innerType;
5030
+ }
5031
+ newShape[key] = newField;
5032
+ }
5033
+ }
5034
+ return new ZodObject({
5035
+ ...this._def,
5036
+ shape: () => newShape
5037
+ });
5038
+ }
5039
+ keyof() {
5040
+ return createZodEnum(util.objectKeys(this.shape));
5041
+ }
5042
+ }
5043
+ ZodObject.create = (shape, params) => {
5044
+ return new ZodObject({
5045
+ shape: () => shape,
5046
+ unknownKeys: "strip",
5047
+ catchall: ZodNever.create(),
5048
+ typeName: ZodFirstPartyTypeKind.ZodObject,
5049
+ ...processCreateParams(params)
5050
+ });
5051
+ };
5052
+ ZodObject.strictCreate = (shape, params) => {
5053
+ return new ZodObject({
5054
+ shape: () => shape,
5055
+ unknownKeys: "strict",
5056
+ catchall: ZodNever.create(),
5057
+ typeName: ZodFirstPartyTypeKind.ZodObject,
5058
+ ...processCreateParams(params)
5059
+ });
5060
+ };
5061
+ ZodObject.lazycreate = (shape, params) => {
5062
+ return new ZodObject({
5063
+ shape,
5064
+ unknownKeys: "strip",
5065
+ catchall: ZodNever.create(),
5066
+ typeName: ZodFirstPartyTypeKind.ZodObject,
5067
+ ...processCreateParams(params)
5068
+ });
5069
+ };
5070
+
5071
+ class ZodUnion extends ZodType {
5072
+ _parse(input) {
5073
+ const { ctx } = this._processInputParams(input);
5074
+ const options = this._def.options;
5075
+ function handleResults(results) {
5076
+ for (const result of results) {
5077
+ if (result.result.status === "valid") {
5078
+ return result.result;
5079
+ }
5080
+ }
5081
+ for (const result of results) {
5082
+ if (result.result.status === "dirty") {
5083
+ ctx.common.issues.push(...result.ctx.common.issues);
5084
+ return result.result;
5085
+ }
5086
+ }
5087
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
5088
+ addIssueToContext(ctx, {
5089
+ code: ZodIssueCode.invalid_union,
5090
+ unionErrors
5091
+ });
5092
+ return INVALID;
5093
+ }
5094
+ if (ctx.common.async) {
5095
+ return Promise.all(options.map(async (option) => {
5096
+ const childCtx = {
5097
+ ...ctx,
5098
+ common: {
5099
+ ...ctx.common,
5100
+ issues: []
5101
+ },
5102
+ parent: null
5103
+ };
5104
+ return {
5105
+ result: await option._parseAsync({
5106
+ data: ctx.data,
5107
+ path: ctx.path,
5108
+ parent: childCtx
5109
+ }),
5110
+ ctx: childCtx
5111
+ };
5112
+ })).then(handleResults);
5113
+ } else {
5114
+ let dirty = undefined;
5115
+ const issues = [];
5116
+ for (const option of options) {
5117
+ const childCtx = {
5118
+ ...ctx,
5119
+ common: {
5120
+ ...ctx.common,
5121
+ issues: []
5122
+ },
5123
+ parent: null
5124
+ };
5125
+ const result = option._parseSync({
5126
+ data: ctx.data,
5127
+ path: ctx.path,
5128
+ parent: childCtx
5129
+ });
5130
+ if (result.status === "valid") {
5131
+ return result;
5132
+ } else if (result.status === "dirty" && !dirty) {
5133
+ dirty = { result, ctx: childCtx };
5134
+ }
5135
+ if (childCtx.common.issues.length) {
5136
+ issues.push(childCtx.common.issues);
5137
+ }
5138
+ }
5139
+ if (dirty) {
5140
+ ctx.common.issues.push(...dirty.ctx.common.issues);
5141
+ return dirty.result;
5142
+ }
5143
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
5144
+ addIssueToContext(ctx, {
5145
+ code: ZodIssueCode.invalid_union,
5146
+ unionErrors
5147
+ });
5148
+ return INVALID;
5149
+ }
5150
+ }
5151
+ get options() {
5152
+ return this._def.options;
5153
+ }
5154
+ }
5155
+ ZodUnion.create = (types, params) => {
5156
+ return new ZodUnion({
5157
+ options: types,
5158
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
5159
+ ...processCreateParams(params)
5160
+ });
5161
+ };
5162
+ var getDiscriminator = (type) => {
5163
+ if (type instanceof ZodLazy) {
5164
+ return getDiscriminator(type.schema);
5165
+ } else if (type instanceof ZodEffects) {
5166
+ return getDiscriminator(type.innerType());
5167
+ } else if (type instanceof ZodLiteral) {
5168
+ return [type.value];
5169
+ } else if (type instanceof ZodEnum) {
5170
+ return type.options;
5171
+ } else if (type instanceof ZodNativeEnum) {
5172
+ return util.objectValues(type.enum);
5173
+ } else if (type instanceof ZodDefault) {
5174
+ return getDiscriminator(type._def.innerType);
5175
+ } else if (type instanceof ZodUndefined) {
5176
+ return [undefined];
5177
+ } else if (type instanceof ZodNull) {
5178
+ return [null];
5179
+ } else if (type instanceof ZodOptional) {
5180
+ return [undefined, ...getDiscriminator(type.unwrap())];
5181
+ } else if (type instanceof ZodNullable) {
5182
+ return [null, ...getDiscriminator(type.unwrap())];
5183
+ } else if (type instanceof ZodBranded) {
5184
+ return getDiscriminator(type.unwrap());
5185
+ } else if (type instanceof ZodReadonly) {
5186
+ return getDiscriminator(type.unwrap());
5187
+ } else if (type instanceof ZodCatch) {
5188
+ return getDiscriminator(type._def.innerType);
5189
+ } else {
5190
+ return [];
5191
+ }
5192
+ };
5193
+
5194
+ class ZodDiscriminatedUnion extends ZodType {
5195
+ _parse(input) {
5196
+ const { ctx } = this._processInputParams(input);
5197
+ if (ctx.parsedType !== ZodParsedType.object) {
5198
+ addIssueToContext(ctx, {
5199
+ code: ZodIssueCode.invalid_type,
5200
+ expected: ZodParsedType.object,
5201
+ received: ctx.parsedType
5202
+ });
5203
+ return INVALID;
5204
+ }
5205
+ const discriminator = this.discriminator;
5206
+ const discriminatorValue = ctx.data[discriminator];
5207
+ const option = this.optionsMap.get(discriminatorValue);
5208
+ if (!option) {
5209
+ addIssueToContext(ctx, {
5210
+ code: ZodIssueCode.invalid_union_discriminator,
5211
+ options: Array.from(this.optionsMap.keys()),
5212
+ path: [discriminator]
5213
+ });
5214
+ return INVALID;
5215
+ }
5216
+ if (ctx.common.async) {
5217
+ return option._parseAsync({
5218
+ data: ctx.data,
5219
+ path: ctx.path,
5220
+ parent: ctx
5221
+ });
5222
+ } else {
5223
+ return option._parseSync({
5224
+ data: ctx.data,
5225
+ path: ctx.path,
5226
+ parent: ctx
5227
+ });
5228
+ }
5229
+ }
5230
+ get discriminator() {
5231
+ return this._def.discriminator;
5232
+ }
5233
+ get options() {
5234
+ return this._def.options;
5235
+ }
5236
+ get optionsMap() {
5237
+ return this._def.optionsMap;
5238
+ }
5239
+ static create(discriminator, options, params) {
5240
+ const optionsMap = new Map;
5241
+ for (const type of options) {
5242
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
5243
+ if (!discriminatorValues.length) {
5244
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
5245
+ }
5246
+ for (const value of discriminatorValues) {
5247
+ if (optionsMap.has(value)) {
5248
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
5249
+ }
5250
+ optionsMap.set(value, type);
5251
+ }
5252
+ }
5253
+ return new ZodDiscriminatedUnion({
5254
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
5255
+ discriminator,
5256
+ options,
5257
+ optionsMap,
5258
+ ...processCreateParams(params)
5259
+ });
5260
+ }
5261
+ }
5262
+ function mergeValues(a, b) {
5263
+ const aType = getParsedType(a);
5264
+ const bType = getParsedType(b);
5265
+ if (a === b) {
5266
+ return { valid: true, data: a };
5267
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
5268
+ const bKeys = util.objectKeys(b);
5269
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
5270
+ const newObj = { ...a, ...b };
5271
+ for (const key of sharedKeys) {
5272
+ const sharedValue = mergeValues(a[key], b[key]);
5273
+ if (!sharedValue.valid) {
5274
+ return { valid: false };
5275
+ }
5276
+ newObj[key] = sharedValue.data;
5277
+ }
5278
+ return { valid: true, data: newObj };
5279
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
5280
+ if (a.length !== b.length) {
5281
+ return { valid: false };
5282
+ }
5283
+ const newArray = [];
5284
+ for (let index = 0;index < a.length; index++) {
5285
+ const itemA = a[index];
5286
+ const itemB = b[index];
5287
+ const sharedValue = mergeValues(itemA, itemB);
5288
+ if (!sharedValue.valid) {
5289
+ return { valid: false };
5290
+ }
5291
+ newArray.push(sharedValue.data);
5292
+ }
5293
+ return { valid: true, data: newArray };
5294
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
5295
+ return { valid: true, data: a };
5296
+ } else {
5297
+ return { valid: false };
5298
+ }
5299
+ }
5300
+
5301
+ class ZodIntersection extends ZodType {
5302
+ _parse(input) {
5303
+ const { status, ctx } = this._processInputParams(input);
5304
+ const handleParsed = (parsedLeft, parsedRight) => {
5305
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
5306
+ return INVALID;
5307
+ }
5308
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
5309
+ if (!merged.valid) {
5310
+ addIssueToContext(ctx, {
5311
+ code: ZodIssueCode.invalid_intersection_types
5312
+ });
5313
+ return INVALID;
5314
+ }
5315
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
5316
+ status.dirty();
5317
+ }
5318
+ return { status: status.value, value: merged.data };
5319
+ };
5320
+ if (ctx.common.async) {
5321
+ return Promise.all([
5322
+ this._def.left._parseAsync({
5323
+ data: ctx.data,
5324
+ path: ctx.path,
5325
+ parent: ctx
5326
+ }),
5327
+ this._def.right._parseAsync({
5328
+ data: ctx.data,
5329
+ path: ctx.path,
5330
+ parent: ctx
5331
+ })
5332
+ ]).then(([left, right]) => handleParsed(left, right));
5333
+ } else {
5334
+ return handleParsed(this._def.left._parseSync({
5335
+ data: ctx.data,
5336
+ path: ctx.path,
5337
+ parent: ctx
5338
+ }), this._def.right._parseSync({
5339
+ data: ctx.data,
5340
+ path: ctx.path,
5341
+ parent: ctx
5342
+ }));
5343
+ }
5344
+ }
5345
+ }
5346
+ ZodIntersection.create = (left, right, params) => {
5347
+ return new ZodIntersection({
5348
+ left,
5349
+ right,
5350
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
5351
+ ...processCreateParams(params)
5352
+ });
5353
+ };
5354
+
5355
+ class ZodTuple extends ZodType {
5356
+ _parse(input) {
5357
+ const { status, ctx } = this._processInputParams(input);
5358
+ if (ctx.parsedType !== ZodParsedType.array) {
5359
+ addIssueToContext(ctx, {
5360
+ code: ZodIssueCode.invalid_type,
5361
+ expected: ZodParsedType.array,
5362
+ received: ctx.parsedType
5363
+ });
5364
+ return INVALID;
5365
+ }
5366
+ if (ctx.data.length < this._def.items.length) {
5367
+ addIssueToContext(ctx, {
5368
+ code: ZodIssueCode.too_small,
5369
+ minimum: this._def.items.length,
5370
+ inclusive: true,
5371
+ exact: false,
5372
+ type: "array"
5373
+ });
5374
+ return INVALID;
5375
+ }
5376
+ const rest = this._def.rest;
5377
+ if (!rest && ctx.data.length > this._def.items.length) {
5378
+ addIssueToContext(ctx, {
5379
+ code: ZodIssueCode.too_big,
5380
+ maximum: this._def.items.length,
5381
+ inclusive: true,
5382
+ exact: false,
5383
+ type: "array"
5384
+ });
5385
+ status.dirty();
5386
+ }
5387
+ const items = [...ctx.data].map((item, itemIndex) => {
5388
+ const schema = this._def.items[itemIndex] || this._def.rest;
5389
+ if (!schema)
5390
+ return null;
5391
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
5392
+ }).filter((x) => !!x);
5393
+ if (ctx.common.async) {
5394
+ return Promise.all(items).then((results) => {
5395
+ return ParseStatus.mergeArray(status, results);
5396
+ });
5397
+ } else {
5398
+ return ParseStatus.mergeArray(status, items);
5399
+ }
5400
+ }
5401
+ get items() {
5402
+ return this._def.items;
5403
+ }
5404
+ rest(rest) {
5405
+ return new ZodTuple({
5406
+ ...this._def,
5407
+ rest
5408
+ });
5409
+ }
5410
+ }
5411
+ ZodTuple.create = (schemas, params) => {
5412
+ if (!Array.isArray(schemas)) {
5413
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
5414
+ }
5415
+ return new ZodTuple({
5416
+ items: schemas,
5417
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
5418
+ rest: null,
5419
+ ...processCreateParams(params)
5420
+ });
5421
+ };
5422
+
5423
+ class ZodRecord extends ZodType {
5424
+ get keySchema() {
5425
+ return this._def.keyType;
5426
+ }
5427
+ get valueSchema() {
5428
+ return this._def.valueType;
5429
+ }
5430
+ _parse(input) {
5431
+ const { status, ctx } = this._processInputParams(input);
5432
+ if (ctx.parsedType !== ZodParsedType.object) {
5433
+ addIssueToContext(ctx, {
5434
+ code: ZodIssueCode.invalid_type,
5435
+ expected: ZodParsedType.object,
5436
+ received: ctx.parsedType
5437
+ });
5438
+ return INVALID;
5439
+ }
5440
+ const pairs = [];
5441
+ const keyType = this._def.keyType;
5442
+ const valueType = this._def.valueType;
5443
+ for (const key in ctx.data) {
5444
+ pairs.push({
5445
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
5446
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
5447
+ alwaysSet: key in ctx.data
5448
+ });
5449
+ }
5450
+ if (ctx.common.async) {
5451
+ return ParseStatus.mergeObjectAsync(status, pairs);
5452
+ } else {
5453
+ return ParseStatus.mergeObjectSync(status, pairs);
5454
+ }
5455
+ }
5456
+ get element() {
5457
+ return this._def.valueType;
5458
+ }
5459
+ static create(first, second, third) {
5460
+ if (second instanceof ZodType) {
5461
+ return new ZodRecord({
5462
+ keyType: first,
5463
+ valueType: second,
5464
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
5465
+ ...processCreateParams(third)
5466
+ });
5467
+ }
5468
+ return new ZodRecord({
5469
+ keyType: ZodString.create(),
5470
+ valueType: first,
5471
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
5472
+ ...processCreateParams(second)
5473
+ });
5474
+ }
5475
+ }
5476
+
5477
+ class ZodMap extends ZodType {
5478
+ get keySchema() {
5479
+ return this._def.keyType;
5480
+ }
5481
+ get valueSchema() {
5482
+ return this._def.valueType;
5483
+ }
5484
+ _parse(input) {
5485
+ const { status, ctx } = this._processInputParams(input);
5486
+ if (ctx.parsedType !== ZodParsedType.map) {
5487
+ addIssueToContext(ctx, {
5488
+ code: ZodIssueCode.invalid_type,
5489
+ expected: ZodParsedType.map,
5490
+ received: ctx.parsedType
5491
+ });
5492
+ return INVALID;
5493
+ }
5494
+ const keyType = this._def.keyType;
5495
+ const valueType = this._def.valueType;
5496
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
5497
+ return {
5498
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
5499
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
5500
+ };
5501
+ });
5502
+ if (ctx.common.async) {
5503
+ const finalMap = new Map;
5504
+ return Promise.resolve().then(async () => {
5505
+ for (const pair of pairs) {
5506
+ const key = await pair.key;
5507
+ const value = await pair.value;
5508
+ if (key.status === "aborted" || value.status === "aborted") {
5509
+ return INVALID;
5510
+ }
5511
+ if (key.status === "dirty" || value.status === "dirty") {
5512
+ status.dirty();
5513
+ }
5514
+ finalMap.set(key.value, value.value);
5515
+ }
5516
+ return { status: status.value, value: finalMap };
5517
+ });
5518
+ } else {
5519
+ const finalMap = new Map;
5520
+ for (const pair of pairs) {
5521
+ const key = pair.key;
5522
+ const value = pair.value;
5523
+ if (key.status === "aborted" || value.status === "aborted") {
5524
+ return INVALID;
5525
+ }
5526
+ if (key.status === "dirty" || value.status === "dirty") {
5527
+ status.dirty();
5528
+ }
5529
+ finalMap.set(key.value, value.value);
5530
+ }
5531
+ return { status: status.value, value: finalMap };
5532
+ }
5533
+ }
5534
+ }
5535
+ ZodMap.create = (keyType, valueType, params) => {
5536
+ return new ZodMap({
5537
+ valueType,
5538
+ keyType,
5539
+ typeName: ZodFirstPartyTypeKind.ZodMap,
5540
+ ...processCreateParams(params)
5541
+ });
5542
+ };
5543
+
5544
+ class ZodSet extends ZodType {
5545
+ _parse(input) {
5546
+ const { status, ctx } = this._processInputParams(input);
5547
+ if (ctx.parsedType !== ZodParsedType.set) {
5548
+ addIssueToContext(ctx, {
5549
+ code: ZodIssueCode.invalid_type,
5550
+ expected: ZodParsedType.set,
5551
+ received: ctx.parsedType
5552
+ });
5553
+ return INVALID;
5554
+ }
5555
+ const def = this._def;
5556
+ if (def.minSize !== null) {
5557
+ if (ctx.data.size < def.minSize.value) {
5558
+ addIssueToContext(ctx, {
5559
+ code: ZodIssueCode.too_small,
5560
+ minimum: def.minSize.value,
5561
+ type: "set",
5562
+ inclusive: true,
5563
+ exact: false,
5564
+ message: def.minSize.message
5565
+ });
5566
+ status.dirty();
5567
+ }
5568
+ }
5569
+ if (def.maxSize !== null) {
5570
+ if (ctx.data.size > def.maxSize.value) {
5571
+ addIssueToContext(ctx, {
5572
+ code: ZodIssueCode.too_big,
5573
+ maximum: def.maxSize.value,
5574
+ type: "set",
5575
+ inclusive: true,
5576
+ exact: false,
5577
+ message: def.maxSize.message
5578
+ });
5579
+ status.dirty();
5580
+ }
5581
+ }
5582
+ const valueType = this._def.valueType;
5583
+ function finalizeSet(elements2) {
5584
+ const parsedSet = new Set;
5585
+ for (const element of elements2) {
5586
+ if (element.status === "aborted")
5587
+ return INVALID;
5588
+ if (element.status === "dirty")
5589
+ status.dirty();
5590
+ parsedSet.add(element.value);
5591
+ }
5592
+ return { status: status.value, value: parsedSet };
5593
+ }
5594
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
5595
+ if (ctx.common.async) {
5596
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
5597
+ } else {
5598
+ return finalizeSet(elements);
5599
+ }
5600
+ }
5601
+ min(minSize, message) {
5602
+ return new ZodSet({
5603
+ ...this._def,
5604
+ minSize: { value: minSize, message: errorUtil.toString(message) }
5605
+ });
5606
+ }
5607
+ max(maxSize, message) {
5608
+ return new ZodSet({
5609
+ ...this._def,
5610
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
5611
+ });
5612
+ }
5613
+ size(size, message) {
5614
+ return this.min(size, message).max(size, message);
5615
+ }
5616
+ nonempty(message) {
5617
+ return this.min(1, message);
5618
+ }
5619
+ }
5620
+ ZodSet.create = (valueType, params) => {
5621
+ return new ZodSet({
5622
+ valueType,
5623
+ minSize: null,
5624
+ maxSize: null,
5625
+ typeName: ZodFirstPartyTypeKind.ZodSet,
5626
+ ...processCreateParams(params)
5627
+ });
5628
+ };
5629
+
5630
+ class ZodFunction extends ZodType {
5631
+ constructor() {
5632
+ super(...arguments);
5633
+ this.validate = this.implement;
5634
+ }
5635
+ _parse(input) {
5636
+ const { ctx } = this._processInputParams(input);
5637
+ if (ctx.parsedType !== ZodParsedType.function) {
5638
+ addIssueToContext(ctx, {
5639
+ code: ZodIssueCode.invalid_type,
5640
+ expected: ZodParsedType.function,
5641
+ received: ctx.parsedType
5642
+ });
5643
+ return INVALID;
5644
+ }
5645
+ function makeArgsIssue(args, error) {
5646
+ return makeIssue({
5647
+ data: args,
5648
+ path: ctx.path,
5649
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
5650
+ issueData: {
5651
+ code: ZodIssueCode.invalid_arguments,
5652
+ argumentsError: error
5653
+ }
5654
+ });
5655
+ }
5656
+ function makeReturnsIssue(returns, error) {
5657
+ return makeIssue({
5658
+ data: returns,
5659
+ path: ctx.path,
5660
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
5661
+ issueData: {
5662
+ code: ZodIssueCode.invalid_return_type,
5663
+ returnTypeError: error
5664
+ }
5665
+ });
5666
+ }
5667
+ const params = { errorMap: ctx.common.contextualErrorMap };
5668
+ const fn = ctx.data;
5669
+ if (this._def.returns instanceof ZodPromise) {
5670
+ const me = this;
5671
+ return OK(async function(...args) {
5672
+ const error = new ZodError([]);
5673
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
5674
+ error.addIssue(makeArgsIssue(args, e));
5675
+ throw error;
5676
+ });
5677
+ const result = await Reflect.apply(fn, this, parsedArgs);
5678
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
5679
+ error.addIssue(makeReturnsIssue(result, e));
5680
+ throw error;
5681
+ });
5682
+ return parsedReturns;
5683
+ });
5684
+ } else {
5685
+ const me = this;
5686
+ return OK(function(...args) {
5687
+ const parsedArgs = me._def.args.safeParse(args, params);
5688
+ if (!parsedArgs.success) {
5689
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
5690
+ }
5691
+ const result = Reflect.apply(fn, this, parsedArgs.data);
5692
+ const parsedReturns = me._def.returns.safeParse(result, params);
5693
+ if (!parsedReturns.success) {
5694
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
5695
+ }
5696
+ return parsedReturns.data;
5697
+ });
5698
+ }
5699
+ }
5700
+ parameters() {
5701
+ return this._def.args;
5702
+ }
5703
+ returnType() {
5704
+ return this._def.returns;
5705
+ }
5706
+ args(...items) {
5707
+ return new ZodFunction({
5708
+ ...this._def,
5709
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
5710
+ });
5711
+ }
5712
+ returns(returnType) {
5713
+ return new ZodFunction({
5714
+ ...this._def,
5715
+ returns: returnType
5716
+ });
5717
+ }
5718
+ implement(func) {
5719
+ const validatedFunc = this.parse(func);
5720
+ return validatedFunc;
5721
+ }
5722
+ strictImplement(func) {
5723
+ const validatedFunc = this.parse(func);
5724
+ return validatedFunc;
5725
+ }
5726
+ static create(args, returns, params) {
5727
+ return new ZodFunction({
5728
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
5729
+ returns: returns || ZodUnknown.create(),
5730
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
5731
+ ...processCreateParams(params)
5732
+ });
5733
+ }
5734
+ }
5735
+
5736
+ class ZodLazy extends ZodType {
5737
+ get schema() {
5738
+ return this._def.getter();
5739
+ }
5740
+ _parse(input) {
5741
+ const { ctx } = this._processInputParams(input);
5742
+ const lazySchema = this._def.getter();
5743
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
5744
+ }
5745
+ }
5746
+ ZodLazy.create = (getter, params) => {
5747
+ return new ZodLazy({
5748
+ getter,
5749
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
5750
+ ...processCreateParams(params)
5751
+ });
5752
+ };
5753
+
5754
+ class ZodLiteral extends ZodType {
5755
+ _parse(input) {
5756
+ if (input.data !== this._def.value) {
5757
+ const ctx = this._getOrReturnCtx(input);
5758
+ addIssueToContext(ctx, {
5759
+ received: ctx.data,
5760
+ code: ZodIssueCode.invalid_literal,
5761
+ expected: this._def.value
5762
+ });
5763
+ return INVALID;
5764
+ }
5765
+ return { status: "valid", value: input.data };
5766
+ }
5767
+ get value() {
5768
+ return this._def.value;
5769
+ }
5770
+ }
5771
+ ZodLiteral.create = (value, params) => {
5772
+ return new ZodLiteral({
5773
+ value,
5774
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
5775
+ ...processCreateParams(params)
5776
+ });
5777
+ };
5778
+ function createZodEnum(values, params) {
5779
+ return new ZodEnum({
5780
+ values,
5781
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
5782
+ ...processCreateParams(params)
5783
+ });
5784
+ }
5785
+
5786
+ class ZodEnum extends ZodType {
5787
+ _parse(input) {
5788
+ if (typeof input.data !== "string") {
5789
+ const ctx = this._getOrReturnCtx(input);
5790
+ const expectedValues = this._def.values;
5791
+ addIssueToContext(ctx, {
5792
+ expected: util.joinValues(expectedValues),
5793
+ received: ctx.parsedType,
5794
+ code: ZodIssueCode.invalid_type
5795
+ });
5796
+ return INVALID;
5797
+ }
5798
+ if (!this._cache) {
5799
+ this._cache = new Set(this._def.values);
5800
+ }
5801
+ if (!this._cache.has(input.data)) {
5802
+ const ctx = this._getOrReturnCtx(input);
5803
+ const expectedValues = this._def.values;
5804
+ addIssueToContext(ctx, {
5805
+ received: ctx.data,
5806
+ code: ZodIssueCode.invalid_enum_value,
5807
+ options: expectedValues
5808
+ });
5809
+ return INVALID;
5810
+ }
5811
+ return OK(input.data);
5812
+ }
5813
+ get options() {
5814
+ return this._def.values;
5815
+ }
5816
+ get enum() {
5817
+ const enumValues = {};
5818
+ for (const val of this._def.values) {
5819
+ enumValues[val] = val;
5820
+ }
5821
+ return enumValues;
5822
+ }
5823
+ get Values() {
5824
+ const enumValues = {};
5825
+ for (const val of this._def.values) {
5826
+ enumValues[val] = val;
5827
+ }
5828
+ return enumValues;
5829
+ }
5830
+ get Enum() {
5831
+ const enumValues = {};
5832
+ for (const val of this._def.values) {
5833
+ enumValues[val] = val;
5834
+ }
5835
+ return enumValues;
5836
+ }
5837
+ extract(values, newDef = this._def) {
5838
+ return ZodEnum.create(values, {
5839
+ ...this._def,
5840
+ ...newDef
5841
+ });
5842
+ }
5843
+ exclude(values, newDef = this._def) {
5844
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
5845
+ ...this._def,
5846
+ ...newDef
5847
+ });
5848
+ }
5849
+ }
5850
+ ZodEnum.create = createZodEnum;
5851
+
5852
+ class ZodNativeEnum extends ZodType {
5853
+ _parse(input) {
5854
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
5855
+ const ctx = this._getOrReturnCtx(input);
5856
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
5857
+ const expectedValues = util.objectValues(nativeEnumValues);
5858
+ addIssueToContext(ctx, {
5859
+ expected: util.joinValues(expectedValues),
5860
+ received: ctx.parsedType,
5861
+ code: ZodIssueCode.invalid_type
5862
+ });
5863
+ return INVALID;
5864
+ }
5865
+ if (!this._cache) {
5866
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
5867
+ }
5868
+ if (!this._cache.has(input.data)) {
5869
+ const expectedValues = util.objectValues(nativeEnumValues);
5870
+ addIssueToContext(ctx, {
5871
+ received: ctx.data,
5872
+ code: ZodIssueCode.invalid_enum_value,
5873
+ options: expectedValues
5874
+ });
5875
+ return INVALID;
5876
+ }
5877
+ return OK(input.data);
5878
+ }
5879
+ get enum() {
5880
+ return this._def.values;
5881
+ }
5882
+ }
5883
+ ZodNativeEnum.create = (values, params) => {
5884
+ return new ZodNativeEnum({
5885
+ values,
5886
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
5887
+ ...processCreateParams(params)
5888
+ });
5889
+ };
5890
+
5891
+ class ZodPromise extends ZodType {
5892
+ unwrap() {
5893
+ return this._def.type;
5894
+ }
5895
+ _parse(input) {
5896
+ const { ctx } = this._processInputParams(input);
5897
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
5898
+ addIssueToContext(ctx, {
5899
+ code: ZodIssueCode.invalid_type,
5900
+ expected: ZodParsedType.promise,
5901
+ received: ctx.parsedType
5902
+ });
5903
+ return INVALID;
5904
+ }
5905
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
5906
+ return OK(promisified.then((data) => {
5907
+ return this._def.type.parseAsync(data, {
5908
+ path: ctx.path,
5909
+ errorMap: ctx.common.contextualErrorMap
5910
+ });
5911
+ }));
5912
+ }
5913
+ }
5914
+ ZodPromise.create = (schema, params) => {
5915
+ return new ZodPromise({
5916
+ type: schema,
5917
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
5918
+ ...processCreateParams(params)
5919
+ });
5920
+ };
5921
+
5922
+ class ZodEffects extends ZodType {
5923
+ innerType() {
5924
+ return this._def.schema;
5925
+ }
5926
+ sourceType() {
5927
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
5928
+ }
5929
+ _parse(input) {
5930
+ const { status, ctx } = this._processInputParams(input);
5931
+ const effect = this._def.effect || null;
5932
+ const checkCtx = {
5933
+ addIssue: (arg) => {
5934
+ addIssueToContext(ctx, arg);
5935
+ if (arg.fatal) {
5936
+ status.abort();
5937
+ } else {
5938
+ status.dirty();
5939
+ }
5940
+ },
5941
+ get path() {
5942
+ return ctx.path;
5943
+ }
5944
+ };
5945
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
5946
+ if (effect.type === "preprocess") {
5947
+ const processed = effect.transform(ctx.data, checkCtx);
5948
+ if (ctx.common.async) {
5949
+ return Promise.resolve(processed).then(async (processed2) => {
5950
+ if (status.value === "aborted")
5951
+ return INVALID;
5952
+ const result = await this._def.schema._parseAsync({
5953
+ data: processed2,
5954
+ path: ctx.path,
5955
+ parent: ctx
5956
+ });
5957
+ if (result.status === "aborted")
5958
+ return INVALID;
5959
+ if (result.status === "dirty")
5960
+ return DIRTY(result.value);
5961
+ if (status.value === "dirty")
5962
+ return DIRTY(result.value);
5963
+ return result;
5964
+ });
5965
+ } else {
5966
+ if (status.value === "aborted")
5967
+ return INVALID;
5968
+ const result = this._def.schema._parseSync({
5969
+ data: processed,
5970
+ path: ctx.path,
5971
+ parent: ctx
5972
+ });
5973
+ if (result.status === "aborted")
5974
+ return INVALID;
5975
+ if (result.status === "dirty")
5976
+ return DIRTY(result.value);
5977
+ if (status.value === "dirty")
5978
+ return DIRTY(result.value);
5979
+ return result;
5980
+ }
5981
+ }
5982
+ if (effect.type === "refinement") {
5983
+ const executeRefinement = (acc) => {
5984
+ const result = effect.refinement(acc, checkCtx);
5985
+ if (ctx.common.async) {
5986
+ return Promise.resolve(result);
5987
+ }
5988
+ if (result instanceof Promise) {
5989
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
5990
+ }
5991
+ return acc;
5992
+ };
5993
+ if (ctx.common.async === false) {
5994
+ const inner = this._def.schema._parseSync({
5995
+ data: ctx.data,
5996
+ path: ctx.path,
5997
+ parent: ctx
5998
+ });
5999
+ if (inner.status === "aborted")
6000
+ return INVALID;
6001
+ if (inner.status === "dirty")
6002
+ status.dirty();
6003
+ executeRefinement(inner.value);
6004
+ return { status: status.value, value: inner.value };
6005
+ } else {
6006
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
6007
+ if (inner.status === "aborted")
6008
+ return INVALID;
6009
+ if (inner.status === "dirty")
6010
+ status.dirty();
6011
+ return executeRefinement(inner.value).then(() => {
6012
+ return { status: status.value, value: inner.value };
6013
+ });
6014
+ });
6015
+ }
6016
+ }
6017
+ if (effect.type === "transform") {
6018
+ if (ctx.common.async === false) {
6019
+ const base = this._def.schema._parseSync({
6020
+ data: ctx.data,
6021
+ path: ctx.path,
6022
+ parent: ctx
6023
+ });
6024
+ if (!isValid(base))
6025
+ return INVALID;
6026
+ const result = effect.transform(base.value, checkCtx);
6027
+ if (result instanceof Promise) {
6028
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
6029
+ }
6030
+ return { status: status.value, value: result };
6031
+ } else {
6032
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
6033
+ if (!isValid(base))
6034
+ return INVALID;
6035
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
6036
+ status: status.value,
6037
+ value: result
6038
+ }));
6039
+ });
6040
+ }
6041
+ }
6042
+ util.assertNever(effect);
6043
+ }
6044
+ }
6045
+ ZodEffects.create = (schema, effect, params) => {
6046
+ return new ZodEffects({
6047
+ schema,
6048
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
6049
+ effect,
6050
+ ...processCreateParams(params)
6051
+ });
6052
+ };
6053
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
6054
+ return new ZodEffects({
6055
+ schema,
6056
+ effect: { type: "preprocess", transform: preprocess },
6057
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
6058
+ ...processCreateParams(params)
6059
+ });
6060
+ };
6061
+ class ZodOptional extends ZodType {
6062
+ _parse(input) {
6063
+ const parsedType = this._getType(input);
6064
+ if (parsedType === ZodParsedType.undefined) {
6065
+ return OK(undefined);
6066
+ }
6067
+ return this._def.innerType._parse(input);
6068
+ }
6069
+ unwrap() {
6070
+ return this._def.innerType;
6071
+ }
6072
+ }
6073
+ ZodOptional.create = (type, params) => {
6074
+ return new ZodOptional({
6075
+ innerType: type,
6076
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
6077
+ ...processCreateParams(params)
6078
+ });
6079
+ };
6080
+
6081
+ class ZodNullable extends ZodType {
6082
+ _parse(input) {
6083
+ const parsedType = this._getType(input);
6084
+ if (parsedType === ZodParsedType.null) {
6085
+ return OK(null);
6086
+ }
6087
+ return this._def.innerType._parse(input);
6088
+ }
6089
+ unwrap() {
6090
+ return this._def.innerType;
6091
+ }
6092
+ }
6093
+ ZodNullable.create = (type, params) => {
6094
+ return new ZodNullable({
6095
+ innerType: type,
6096
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
6097
+ ...processCreateParams(params)
6098
+ });
6099
+ };
6100
+
6101
+ class ZodDefault extends ZodType {
6102
+ _parse(input) {
6103
+ const { ctx } = this._processInputParams(input);
6104
+ let data = ctx.data;
6105
+ if (ctx.parsedType === ZodParsedType.undefined) {
6106
+ data = this._def.defaultValue();
6107
+ }
6108
+ return this._def.innerType._parse({
6109
+ data,
6110
+ path: ctx.path,
6111
+ parent: ctx
6112
+ });
6113
+ }
6114
+ removeDefault() {
6115
+ return this._def.innerType;
6116
+ }
6117
+ }
6118
+ ZodDefault.create = (type, params) => {
6119
+ return new ZodDefault({
6120
+ innerType: type,
6121
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
6122
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
6123
+ ...processCreateParams(params)
6124
+ });
6125
+ };
6126
+
6127
+ class ZodCatch extends ZodType {
6128
+ _parse(input) {
6129
+ const { ctx } = this._processInputParams(input);
6130
+ const newCtx = {
6131
+ ...ctx,
6132
+ common: {
6133
+ ...ctx.common,
6134
+ issues: []
6135
+ }
6136
+ };
6137
+ const result = this._def.innerType._parse({
6138
+ data: newCtx.data,
6139
+ path: newCtx.path,
6140
+ parent: {
6141
+ ...newCtx
6142
+ }
6143
+ });
6144
+ if (isAsync(result)) {
6145
+ return result.then((result2) => {
6146
+ return {
6147
+ status: "valid",
6148
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
6149
+ get error() {
6150
+ return new ZodError(newCtx.common.issues);
6151
+ },
6152
+ input: newCtx.data
6153
+ })
6154
+ };
6155
+ });
6156
+ } else {
6157
+ return {
6158
+ status: "valid",
6159
+ value: result.status === "valid" ? result.value : this._def.catchValue({
6160
+ get error() {
6161
+ return new ZodError(newCtx.common.issues);
6162
+ },
6163
+ input: newCtx.data
6164
+ })
6165
+ };
6166
+ }
6167
+ }
6168
+ removeCatch() {
6169
+ return this._def.innerType;
6170
+ }
6171
+ }
6172
+ ZodCatch.create = (type, params) => {
6173
+ return new ZodCatch({
6174
+ innerType: type,
6175
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
6176
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
6177
+ ...processCreateParams(params)
6178
+ });
6179
+ };
6180
+
6181
+ class ZodNaN extends ZodType {
6182
+ _parse(input) {
6183
+ const parsedType = this._getType(input);
6184
+ if (parsedType !== ZodParsedType.nan) {
6185
+ const ctx = this._getOrReturnCtx(input);
6186
+ addIssueToContext(ctx, {
6187
+ code: ZodIssueCode.invalid_type,
6188
+ expected: ZodParsedType.nan,
6189
+ received: ctx.parsedType
6190
+ });
6191
+ return INVALID;
6192
+ }
6193
+ return { status: "valid", value: input.data };
6194
+ }
6195
+ }
6196
+ ZodNaN.create = (params) => {
6197
+ return new ZodNaN({
6198
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
6199
+ ...processCreateParams(params)
6200
+ });
6201
+ };
6202
+ var BRAND = Symbol("zod_brand");
6203
+
6204
+ class ZodBranded extends ZodType {
6205
+ _parse(input) {
6206
+ const { ctx } = this._processInputParams(input);
6207
+ const data = ctx.data;
6208
+ return this._def.type._parse({
6209
+ data,
6210
+ path: ctx.path,
6211
+ parent: ctx
6212
+ });
6213
+ }
6214
+ unwrap() {
6215
+ return this._def.type;
6216
+ }
6217
+ }
6218
+
6219
+ class ZodPipeline extends ZodType {
6220
+ _parse(input) {
6221
+ const { status, ctx } = this._processInputParams(input);
6222
+ if (ctx.common.async) {
6223
+ const handleAsync = async () => {
6224
+ const inResult = await this._def.in._parseAsync({
6225
+ data: ctx.data,
6226
+ path: ctx.path,
6227
+ parent: ctx
6228
+ });
6229
+ if (inResult.status === "aborted")
6230
+ return INVALID;
6231
+ if (inResult.status === "dirty") {
6232
+ status.dirty();
6233
+ return DIRTY(inResult.value);
6234
+ } else {
6235
+ return this._def.out._parseAsync({
6236
+ data: inResult.value,
6237
+ path: ctx.path,
6238
+ parent: ctx
6239
+ });
6240
+ }
6241
+ };
6242
+ return handleAsync();
6243
+ } else {
6244
+ const inResult = this._def.in._parseSync({
6245
+ data: ctx.data,
6246
+ path: ctx.path,
6247
+ parent: ctx
6248
+ });
6249
+ if (inResult.status === "aborted")
6250
+ return INVALID;
6251
+ if (inResult.status === "dirty") {
6252
+ status.dirty();
6253
+ return {
6254
+ status: "dirty",
6255
+ value: inResult.value
6256
+ };
6257
+ } else {
6258
+ return this._def.out._parseSync({
6259
+ data: inResult.value,
6260
+ path: ctx.path,
6261
+ parent: ctx
6262
+ });
6263
+ }
6264
+ }
6265
+ }
6266
+ static create(a, b) {
6267
+ return new ZodPipeline({
6268
+ in: a,
6269
+ out: b,
6270
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
6271
+ });
6272
+ }
6273
+ }
6274
+
6275
+ class ZodReadonly extends ZodType {
6276
+ _parse(input) {
6277
+ const result = this._def.innerType._parse(input);
6278
+ const freeze = (data) => {
6279
+ if (isValid(data)) {
6280
+ data.value = Object.freeze(data.value);
6281
+ }
6282
+ return data;
6283
+ };
6284
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
6285
+ }
6286
+ unwrap() {
6287
+ return this._def.innerType;
6288
+ }
6289
+ }
6290
+ ZodReadonly.create = (type, params) => {
6291
+ return new ZodReadonly({
6292
+ innerType: type,
6293
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
6294
+ ...processCreateParams(params)
6295
+ });
6296
+ };
6297
+ function cleanParams(params, data) {
6298
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
6299
+ const p2 = typeof p === "string" ? { message: p } : p;
6300
+ return p2;
6301
+ }
6302
+ function custom(check, _params = {}, fatal) {
6303
+ if (check)
6304
+ return ZodAny.create().superRefine((data, ctx) => {
6305
+ const r = check(data);
6306
+ if (r instanceof Promise) {
6307
+ return r.then((r2) => {
6308
+ if (!r2) {
6309
+ const params = cleanParams(_params, data);
6310
+ const _fatal = params.fatal ?? fatal ?? true;
6311
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
6312
+ }
6313
+ });
6314
+ }
6315
+ if (!r) {
6316
+ const params = cleanParams(_params, data);
6317
+ const _fatal = params.fatal ?? fatal ?? true;
6318
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
6319
+ }
6320
+ return;
6321
+ });
6322
+ return ZodAny.create();
6323
+ }
6324
+ var late = {
6325
+ object: ZodObject.lazycreate
6326
+ };
6327
+ var ZodFirstPartyTypeKind;
6328
+ (function(ZodFirstPartyTypeKind2) {
6329
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
6330
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
6331
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
6332
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
6333
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
6334
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
6335
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
6336
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
6337
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
6338
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
6339
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
6340
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
6341
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
6342
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
6343
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
6344
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
6345
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
6346
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
6347
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
6348
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
6349
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
6350
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
6351
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
6352
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
6353
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
6354
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
6355
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
6356
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
6357
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
6358
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
6359
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
6360
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
6361
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
6362
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
6363
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
6364
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
6365
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
6366
+ var instanceOfType = (cls, params = {
6367
+ message: `Input not instance of ${cls.name}`
6368
+ }) => custom((data) => data instanceof cls, params);
6369
+ var stringType = ZodString.create;
6370
+ var numberType = ZodNumber.create;
6371
+ var nanType = ZodNaN.create;
6372
+ var bigIntType = ZodBigInt.create;
6373
+ var booleanType = ZodBoolean.create;
6374
+ var dateType = ZodDate.create;
6375
+ var symbolType = ZodSymbol.create;
6376
+ var undefinedType = ZodUndefined.create;
6377
+ var nullType = ZodNull.create;
6378
+ var anyType = ZodAny.create;
6379
+ var unknownType = ZodUnknown.create;
6380
+ var neverType = ZodNever.create;
6381
+ var voidType = ZodVoid.create;
6382
+ var arrayType = ZodArray.create;
6383
+ var objectType = ZodObject.create;
6384
+ var strictObjectType = ZodObject.strictCreate;
6385
+ var unionType = ZodUnion.create;
6386
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
6387
+ var intersectionType = ZodIntersection.create;
6388
+ var tupleType = ZodTuple.create;
6389
+ var recordType = ZodRecord.create;
6390
+ var mapType = ZodMap.create;
6391
+ var setType = ZodSet.create;
6392
+ var functionType = ZodFunction.create;
6393
+ var lazyType = ZodLazy.create;
6394
+ var literalType = ZodLiteral.create;
6395
+ var enumType = ZodEnum.create;
6396
+ var nativeEnumType = ZodNativeEnum.create;
6397
+ var promiseType = ZodPromise.create;
6398
+ var effectsType = ZodEffects.create;
6399
+ var optionalType = ZodOptional.create;
6400
+ var nullableType = ZodNullable.create;
6401
+ var preprocessType = ZodEffects.createWithPreprocess;
6402
+ var pipelineType = ZodPipeline.create;
6403
+ var ostring = () => stringType().optional();
6404
+ var onumber = () => numberType().optional();
6405
+ var oboolean = () => booleanType().optional();
6406
+ var coerce = {
6407
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
6408
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
6409
+ boolean: (arg) => ZodBoolean.create({
6410
+ ...arg,
6411
+ coerce: true
6412
+ }),
6413
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
6414
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
6415
+ };
6416
+ var NEVER = INVALID;
6417
+ // src/utils/request-tokens.ts
6418
+ async function getProviderTokens(manualTokens) {
6419
+ if (manualTokens) {
6420
+ return manualTokens;
6421
+ }
6422
+ let tokensString = null;
6423
+ if (!tokensString) {
6424
+ try {
6425
+ const nextHeaders = await import("next/headers").catch(() => null);
6426
+ if (nextHeaders && typeof nextHeaders.headers === "function") {
6427
+ const headersList = nextHeaders.headers();
6428
+ tokensString = headersList.get("x-integrate-tokens");
6429
+ }
6430
+ } catch {}
6431
+ }
6432
+ if (!tokensString) {
6433
+ try {
6434
+ const getNuxtHeaders = new Function(`
6435
+ try {
6436
+ if (typeof useRequestHeaders === 'function') {
6437
+ return useRequestHeaders();
6438
+ }
6439
+ } catch {}
6440
+ return null;
6441
+ `);
6442
+ const headers = getNuxtHeaders();
6443
+ if (headers && typeof headers === "object") {
6444
+ tokensString = headers["x-integrate-tokens"];
6445
+ }
6446
+ } catch {}
6447
+ }
6448
+ if (!tokensString) {
6449
+ if (typeof process !== "undefined" && process.env) {
6450
+ tokensString = process.env.PROVIDER_TOKENS;
6451
+ }
6452
+ }
6453
+ if (tokensString) {
6454
+ try {
6455
+ const parsed = JSON.parse(tokensString);
6456
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
6457
+ return parsed;
6458
+ }
6459
+ } catch (error) {
6460
+ throw new Error(`Failed to parse provider tokens: ${error instanceof Error ? error.message : "Invalid JSON"}`);
6461
+ }
6462
+ }
6463
+ throw new Error("Provider tokens not found. Please pass tokens manually via options.providerTokens or set the x-integrate-tokens header in your request.");
6464
+ }
6465
+ async function tryGetProviderTokens(manualTokens) {
6466
+ try {
6467
+ return await getProviderTokens(manualTokens);
6468
+ } catch {
6469
+ return null;
6470
+ }
6471
+ }
6472
+
6473
+ // src/ai/utils.ts
6474
+ function getProviderForTool(client, toolName) {
6475
+ return client.getProviderForTool?.(toolName);
6476
+ }
6477
+ function jsonSchemaPropertyToZod(propSchema) {
6478
+ if (!propSchema || typeof propSchema !== "object") {
6479
+ return exports_external.any();
6480
+ }
6481
+ const type = propSchema.type;
6482
+ switch (type) {
6483
+ case "string":
6484
+ let stringSchema = exports_external.string();
6485
+ if (propSchema.description) {
6486
+ stringSchema = stringSchema.describe(propSchema.description);
6487
+ }
6488
+ if (propSchema.minLength !== undefined) {
6489
+ stringSchema = stringSchema.min(propSchema.minLength);
6490
+ }
6491
+ if (propSchema.maxLength !== undefined) {
6492
+ stringSchema = stringSchema.max(propSchema.maxLength);
6493
+ }
6494
+ if (propSchema.pattern) {
6495
+ stringSchema = stringSchema.regex(new RegExp(propSchema.pattern));
6496
+ }
6497
+ if (propSchema.enum) {
6498
+ return exports_external.enum(propSchema.enum);
6499
+ }
6500
+ return stringSchema;
6501
+ case "number":
6502
+ case "integer":
6503
+ let numberSchema = type === "integer" ? exports_external.number().int() : exports_external.number();
6504
+ if (propSchema.description) {
6505
+ numberSchema = numberSchema.describe(propSchema.description);
6506
+ }
6507
+ if (propSchema.minimum !== undefined) {
6508
+ numberSchema = numberSchema.min(propSchema.minimum);
6509
+ }
6510
+ if (propSchema.maximum !== undefined) {
6511
+ numberSchema = numberSchema.max(propSchema.maximum);
6512
+ }
6513
+ return numberSchema;
6514
+ case "boolean":
6515
+ let boolSchema = exports_external.boolean();
6516
+ if (propSchema.description) {
6517
+ boolSchema = boolSchema.describe(propSchema.description);
6518
+ }
6519
+ return boolSchema;
6520
+ case "array":
6521
+ let arraySchema = exports_external.array(propSchema.items ? jsonSchemaPropertyToZod(propSchema.items) : exports_external.any());
6522
+ if (propSchema.description) {
6523
+ arraySchema = arraySchema.describe(propSchema.description);
6524
+ }
6525
+ if (propSchema.minItems !== undefined) {
6526
+ arraySchema = arraySchema.min(propSchema.minItems);
6527
+ }
6528
+ if (propSchema.maxItems !== undefined) {
6529
+ arraySchema = arraySchema.max(propSchema.maxItems);
6530
+ }
6531
+ return arraySchema;
6532
+ case "object":
6533
+ if (propSchema.properties && typeof propSchema.properties === "object") {
6534
+ const shape = {};
6535
+ for (const [key, value] of Object.entries(propSchema.properties)) {
6536
+ shape[key] = jsonSchemaPropertyToZod(value);
6537
+ }
6538
+ let objSchema = exports_external.object(shape);
6539
+ if (propSchema.description) {
6540
+ objSchema = objSchema.describe(propSchema.description);
6541
+ }
6542
+ return objSchema;
6543
+ }
6544
+ return exports_external.record(exports_external.any());
6545
+ case "null":
6546
+ return exports_external.null();
6547
+ default:
6548
+ return exports_external.any();
6549
+ }
6550
+ }
6551
+ function jsonSchemaToZod(schema) {
6552
+ if (!schema || typeof schema !== "object") {
6553
+ return exports_external.object({});
6554
+ }
6555
+ if (schema.type === "None" || schema.type === null || schema.type === undefined) {
6556
+ if (schema.properties && typeof schema.properties === "object") {
6557
+ const shape = {};
6558
+ const required = schema.required || [];
6559
+ for (const [key, value] of Object.entries(schema.properties)) {
6560
+ let propSchema = jsonSchemaPropertyToZod(value);
6561
+ if (!required.includes(key)) {
6562
+ propSchema = propSchema.optional();
6563
+ }
6564
+ shape[key] = propSchema;
6565
+ }
6566
+ return exports_external.object(shape);
6567
+ }
6568
+ return exports_external.object({});
6569
+ }
6570
+ if (schema.type !== "object") {
6571
+ return exports_external.object({});
6572
+ }
6573
+ if (schema.properties && typeof schema.properties === "object") {
6574
+ const shape = {};
6575
+ const required = schema.required || [];
6576
+ for (const [key, value] of Object.entries(schema.properties)) {
6577
+ let propSchema = jsonSchemaPropertyToZod(value);
6578
+ if (!required.includes(key)) {
6579
+ propSchema = propSchema.optional();
6580
+ }
6581
+ shape[key] = propSchema;
6582
+ }
6583
+ return exports_external.object(shape);
6584
+ }
6585
+ return exports_external.object({});
6586
+ }
6587
+ async function executeToolWithToken(client, toolName, args, options) {
6588
+ if (options?.providerTokens) {
6589
+ const provider = getProviderForTool(client, toolName);
6590
+ if (provider && options.providerTokens[provider]) {
6591
+ const oauthManager = client.oauthManager;
6592
+ if (oauthManager && typeof oauthManager.setProviderToken === "function") {
6593
+ const existingToken = oauthManager.getProviderToken(provider);
6594
+ try {
6595
+ oauthManager.setProviderToken(provider, {
6596
+ accessToken: options.providerTokens[provider],
6597
+ tokenType: "Bearer"
6598
+ });
6599
+ const result2 = await client._callToolByName(toolName, args);
6600
+ return result2;
6601
+ } finally {
6602
+ if (existingToken) {
6603
+ oauthManager.setProviderToken(provider, existingToken);
6604
+ } else if (typeof oauthManager.removeProviderToken === "function") {
6605
+ oauthManager.removeProviderToken(provider);
6606
+ }
6607
+ }
6608
+ }
6609
+ }
6610
+ }
6611
+ const result = await client._callToolByName(toolName, args);
6612
+ return result;
6613
+ }
6614
+ async function ensureClientConnected(client) {
6615
+ if (!client.isConnected()) {
6616
+ await client.connect();
6617
+ }
6618
+ }
6619
+
6620
+ // src/ai/vercel-ai.ts
6621
+ function convertMCPToolToVercelAI(mcpTool, client, options) {
6622
+ return {
6623
+ description: mcpTool.description || `Execute ${mcpTool.name}`,
6624
+ inputSchema: jsonSchemaToZod(mcpTool.inputSchema),
6625
+ execute: async (args) => {
6626
+ return await executeToolWithToken(client, mcpTool.name, args, options);
6627
+ }
6628
+ };
6629
+ }
6630
+ function convertMCPToolsToVercelAI(client, options) {
6631
+ const mcpTools = client.getEnabledTools();
6632
+ const vercelTools = {};
6633
+ for (const mcpTool of mcpTools) {
6634
+ vercelTools[mcpTool.name] = convertMCPToolToVercelAI(mcpTool, client, options);
6635
+ }
6636
+ return vercelTools;
6637
+ }
6638
+ async function getVercelAITools(client, options) {
6639
+ await ensureClientConnected(client);
6640
+ let providerTokens = options?.providerTokens;
6641
+ if (!providerTokens) {
6642
+ try {
6643
+ providerTokens = await getProviderTokens();
6644
+ } catch {}
6645
+ }
6646
+ const finalOptions = providerTokens ? { ...options, providerTokens } : options;
6647
+ return convertMCPToolsToVercelAI(client, finalOptions);
6648
+ }
6649
+ // src/ai/openai.ts
6650
+ function convertMCPToolToOpenAI(mcpTool, _client, options) {
6651
+ const inputParams = mcpTool.inputSchema;
6652
+ return {
6653
+ type: "function",
6654
+ name: mcpTool.name,
6655
+ description: mcpTool.description || `Execute ${mcpTool.name}`,
6656
+ parameters: inputParams || {
6657
+ type: "object",
6658
+ properties: {},
6659
+ required: []
6660
+ },
6661
+ strict: options?.strict ?? false
6662
+ };
6663
+ }
6664
+ function convertMCPToolsToOpenAI(client, options) {
6665
+ const mcpTools = client.getEnabledTools();
6666
+ return mcpTools.map((mcpTool) => convertMCPToolToOpenAI(mcpTool, client, options));
6667
+ }
6668
+ async function executeOpenAIToolCall(client, toolCall, options) {
6669
+ const args = JSON.parse(toolCall.arguments);
6670
+ const result = await executeToolWithToken(client, toolCall.name, args, options);
6671
+ return JSON.stringify(result);
6672
+ }
6673
+ async function getOpenAITools(client, options) {
6674
+ await ensureClientConnected(client);
6675
+ let providerTokens = options?.providerTokens;
6676
+ if (!providerTokens) {
6677
+ try {
6678
+ providerTokens = await getProviderTokens();
6679
+ } catch {}
6680
+ }
6681
+ const finalOptions = providerTokens ? { ...options, providerTokens } : options;
6682
+ return convertMCPToolsToOpenAI(client, finalOptions);
6683
+ }
6684
+ // src/ai/openai-agents.ts
6685
+ function convertMCPToolToOpenAIAgents(mcpTool, client, options) {
6686
+ return {
6687
+ name: mcpTool.name,
6688
+ description: mcpTool.description || `Execute ${mcpTool.name}`,
6689
+ parameters: jsonSchemaToZod(mcpTool.inputSchema),
6690
+ execute: async (args) => {
6691
+ return await executeToolWithToken(client, mcpTool.name, args, options);
6692
+ }
6693
+ };
6694
+ }
6695
+ function convertMCPToolsToOpenAIAgents(client, options) {
6696
+ const mcpTools = client.getEnabledTools();
6697
+ return mcpTools.map((mcpTool) => convertMCPToolToOpenAIAgents(mcpTool, client, options));
6698
+ }
6699
+ async function getOpenAIAgentsTools(client, options) {
6700
+ await ensureClientConnected(client);
6701
+ let providerTokens = options?.providerTokens;
6702
+ if (!providerTokens) {
6703
+ try {
6704
+ providerTokens = await getProviderTokens();
6705
+ } catch {}
6706
+ }
6707
+ const finalOptions = providerTokens ? { ...options, providerTokens } : options;
6708
+ return convertMCPToolsToOpenAIAgents(client, finalOptions);
6709
+ }
6710
+ // src/ai/anthropic.ts
6711
+ function convertMCPToolToAnthropic(mcpTool, _client, _options) {
6712
+ return {
6713
+ name: mcpTool.name,
6714
+ description: mcpTool.description || `Execute ${mcpTool.name}`,
6715
+ input_schema: mcpTool.inputSchema || {
6716
+ type: "object",
6717
+ properties: {},
6718
+ required: []
6719
+ }
6720
+ };
6721
+ }
6722
+ function convertMCPToolsToAnthropic(client, options) {
6723
+ const mcpTools = client.getEnabledTools();
6724
+ return mcpTools.map((mcpTool) => convertMCPToolToAnthropic(mcpTool, client, options));
6725
+ }
6726
+ async function executeAnthropicToolCall(client, toolUse, options) {
6727
+ const result = await executeToolWithToken(client, toolUse.name, toolUse.input, options);
6728
+ return JSON.stringify(result);
6729
+ }
6730
+ async function handleAnthropicToolCalls(client, messageContent, options) {
6731
+ const toolResults = [];
6732
+ const toolUseBlocks = messageContent.filter((block) => block.type === "tool_use" && ("id" in block) && ("name" in block) && ("input" in block));
6733
+ for (const toolUse of toolUseBlocks) {
6734
+ try {
6735
+ const result = await executeAnthropicToolCall(client, toolUse, options);
6736
+ toolResults.push({
6737
+ type: "tool_result",
6738
+ tool_use_id: toolUse.id,
6739
+ content: result
6740
+ });
6741
+ } catch (error) {
6742
+ toolResults.push({
6743
+ type: "tool_result",
6744
+ tool_use_id: toolUse.id,
6745
+ content: JSON.stringify({
6746
+ error: error instanceof Error ? error.message : "Unknown error"
6747
+ })
6748
+ });
6749
+ }
6750
+ }
6751
+ return toolResults;
6752
+ }
6753
+ async function getAnthropicTools(client, options) {
6754
+ await ensureClientConnected(client);
6755
+ let providerTokens = options?.providerTokens;
6756
+ if (!providerTokens) {
6757
+ try {
6758
+ providerTokens = await getProviderTokens();
6759
+ } catch {}
6760
+ }
6761
+ const finalOptions = providerTokens ? { ...options, providerTokens } : options;
6762
+ return convertMCPToolsToAnthropic(client, finalOptions);
6763
+ }
6764
+ // src/ai/google.ts
6765
+ function convertMCPToolToGoogle(mcpTool, _client, _options) {
6766
+ return {
6767
+ name: mcpTool.name,
6768
+ description: mcpTool.description || `Execute ${mcpTool.name}`,
6769
+ parameters: {
6770
+ type: "object",
6771
+ description: mcpTool.description || "",
6772
+ properties: mcpTool.inputSchema?.properties || {},
6773
+ required: mcpTool.inputSchema?.required || []
6774
+ }
6775
+ };
6776
+ }
6777
+ function convertMCPToolsToGoogle(client, options) {
6778
+ const mcpTools = client.getEnabledTools();
6779
+ return mcpTools.map((mcpTool) => convertMCPToolToGoogle(mcpTool, client, options));
6780
+ }
6781
+ async function executeGoogleFunctionCall(client, functionCall, options) {
6782
+ const result = await executeToolWithToken(client, functionCall.name, functionCall.args, options);
6783
+ return JSON.stringify(result);
6784
+ }
6785
+ async function getGoogleTools(client, options) {
6786
+ await ensureClientConnected(client);
6787
+ let providerTokens = options?.providerTokens;
6788
+ if (!providerTokens) {
6789
+ try {
6790
+ providerTokens = await getProviderTokens();
6791
+ } catch {}
6792
+ }
6793
+ const finalOptions = providerTokens ? { ...options, providerTokens } : options;
6794
+ return convertMCPToolsToGoogle(client, finalOptions);
6795
+ }
6796
+ // src/ai/cloudflare.ts
6797
+ function convertMCPToolToCloudflare(mcpTool, _client, _options) {
6798
+ return {
6799
+ type: "function",
6800
+ function: {
6801
+ name: mcpTool.name,
6802
+ description: mcpTool.description || `Execute ${mcpTool.name}`,
6803
+ parameters: {
6804
+ type: "object",
6805
+ properties: mcpTool.inputSchema?.properties || {},
6806
+ required: mcpTool.inputSchema?.required || []
6807
+ }
6808
+ }
6809
+ };
6810
+ }
6811
+ function convertMCPToolsToCloudflare(client, options) {
6812
+ const mcpTools = client.getEnabledTools();
6813
+ const tools = {};
6814
+ for (const mcpTool of mcpTools) {
6815
+ tools[mcpTool.name] = convertMCPToolToCloudflare(mcpTool, client, options);
6816
+ }
6817
+ return tools;
6818
+ }
6819
+ async function executeCloudflareToolCall(client, toolCall, options) {
6820
+ const args = typeof toolCall.arguments === "string" ? JSON.parse(toolCall.arguments) : toolCall.arguments;
6821
+ const result = await executeToolWithToken(client, toolCall.name, args, options);
6822
+ return JSON.stringify(result);
6823
+ }
6824
+ async function getCloudflareTools(client, options) {
6825
+ await ensureClientConnected(client);
6826
+ let providerTokens = options?.providerTokens;
6827
+ if (!providerTokens) {
6828
+ try {
6829
+ providerTokens = await getProviderTokens();
6830
+ } catch {}
6831
+ }
6832
+ const finalOptions = providerTokens ? { ...options, providerTokens } : options;
6833
+ return convertMCPToolsToCloudflare(client, finalOptions);
6834
+ }
6835
+ // src/ai/langchain.ts
6836
+ function convertMCPToolToLangChain(mcpTool, client, options) {
6837
+ return {
6838
+ name: mcpTool.name,
6839
+ description: mcpTool.description || `Execute ${mcpTool.name}`,
6840
+ schema: jsonSchemaToZod(mcpTool.inputSchema),
6841
+ func: async (...args) => {
6842
+ const input = args[0];
6843
+ const result = await executeToolWithToken(client, mcpTool.name, input, options);
6844
+ return JSON.stringify(result);
6845
+ }
6846
+ };
6847
+ }
6848
+ function convertMCPToolsToLangChain(client, options) {
6849
+ const mcpTools = client.getEnabledTools();
6850
+ return mcpTools.map((mcpTool) => convertMCPToolToLangChain(mcpTool, client, options));
6851
+ }
6852
+ async function getLangChainTools(client, options) {
6853
+ await ensureClientConnected(client);
6854
+ let providerTokens = options?.providerTokens;
6855
+ if (!providerTokens) {
6856
+ try {
6857
+ providerTokens = await getProviderTokens();
6858
+ } catch {}
6859
+ }
6860
+ const finalOptions = providerTokens ? { ...options, providerTokens } : options;
6861
+ return convertMCPToolsToLangChain(client, finalOptions);
6862
+ }
6863
+ // src/ai/llamaindex.ts
6864
+ function convertMCPToolToLlamaIndex(mcpTool, client, options) {
6865
+ return {
6866
+ name: mcpTool.name,
6867
+ description: mcpTool.description || `Execute ${mcpTool.name}`,
6868
+ parameters: jsonSchemaToZod(mcpTool.inputSchema),
6869
+ execute: async (input) => {
6870
+ const result = await executeToolWithToken(client, mcpTool.name, input, options);
6871
+ return JSON.stringify(result);
6872
+ }
6873
+ };
6874
+ }
6875
+ function convertMCPToolsToLlamaIndex(client, options) {
6876
+ const mcpTools = client.getEnabledTools();
6877
+ return mcpTools.map((mcpTool) => convertMCPToolToLlamaIndex(mcpTool, client, options));
6878
+ }
6879
+ async function getLlamaIndexTools(client, options) {
6880
+ await ensureClientConnected(client);
6881
+ let providerTokens = options?.providerTokens;
6882
+ if (!providerTokens) {
6883
+ try {
6884
+ providerTokens = await getProviderTokens();
6885
+ } catch {}
6886
+ }
6887
+ const finalOptions = providerTokens ? { ...options, providerTokens } : options;
6888
+ return convertMCPToolsToLlamaIndex(client, finalOptions);
6889
+ }
6890
+ // src/ai/mastra.ts
6891
+ function convertMCPToolToMastra(mcpTool, client, options) {
6892
+ return {
6893
+ id: mcpTool.name,
6894
+ description: mcpTool.description || `Execute ${mcpTool.name}`,
6895
+ inputSchema: jsonSchemaToZod(mcpTool.inputSchema),
6896
+ execute: async ({ context }) => {
6897
+ const result = await executeToolWithToken(client, mcpTool.name, context, options);
6898
+ return result;
6899
+ }
6900
+ };
6901
+ }
6902
+ function convertMCPToolsToMastra(client, options) {
6903
+ const mcpTools = client.getEnabledTools();
6904
+ const tools = {};
6905
+ for (const mcpTool of mcpTools) {
6906
+ tools[mcpTool.name] = convertMCPToolToMastra(mcpTool, client, options);
6907
+ }
6908
+ return tools;
6909
+ }
6910
+ async function getMastraTools(client, options) {
6911
+ await ensureClientConnected(client);
6912
+ let providerTokens = options?.providerTokens;
6913
+ if (!providerTokens) {
6914
+ try {
6915
+ providerTokens = await getProviderTokens();
6916
+ } catch {}
6917
+ }
6918
+ const finalOptions = providerTokens ? { ...options, providerTokens } : options;
6919
+ return convertMCPToolsToMastra(client, finalOptions);
6920
+ }
6921
+ // src/ai/index.ts
6922
+ async function getAITools(client, provider, options) {
6923
+ switch (provider) {
6924
+ case "vercel-ai":
6925
+ return await getVercelAITools(client, options);
6926
+ case "openai":
6927
+ return await getOpenAITools(client, options);
6928
+ case "openai-agents":
6929
+ return await getOpenAIAgentsTools(client, options);
6930
+ case "anthropic":
6931
+ return await getAnthropicTools(client, options);
6932
+ case "google":
6933
+ return await getGoogleTools(client, options);
6934
+ case "cloudflare":
6935
+ return await getCloudflareTools(client, options);
6936
+ case "langchain":
6937
+ return await getLangChainTools(client, options);
6938
+ case "llamaindex":
6939
+ return await getLlamaIndexTools(client, options);
6940
+ case "mastra":
6941
+ return await getMastraTools(client, options);
6942
+ default:
6943
+ throw new Error(`Unsupported AI provider: ${provider}`);
6944
+ }
6945
+ }
6946
+ // src/adapters/node.ts
6947
+ function fromNodeHeaders(nodeHeaders) {
6948
+ const webHeaders = new Headers;
6949
+ for (const [key, value] of Object.entries(nodeHeaders)) {
6950
+ if (value !== undefined) {
6951
+ if (Array.isArray(value)) {
6952
+ value.forEach((v) => webHeaders.append(key, v));
6953
+ } else {
6954
+ webHeaders.set(key, value);
6955
+ }
6956
+ }
6957
+ }
6958
+ return webHeaders;
6959
+ }
6960
+ async function toWebRequest(req) {
6961
+ const protocol = req.socket.encrypted ? "https" : "http";
6962
+ const host = req.headers.host || "localhost";
6963
+ const url = `${protocol}://${host}${req.url}`;
6964
+ const headers = fromNodeHeaders(req.headers);
6965
+ let body;
6966
+ if (req.method && ["POST", "PUT", "PATCH"].includes(req.method)) {
6967
+ body = await new Promise((resolve, reject) => {
6968
+ let data = "";
6969
+ req.on("data", (chunk) => data += chunk);
6970
+ req.on("end", () => resolve(data));
6971
+ req.on("error", reject);
6972
+ });
6973
+ }
6974
+ return new Request(url, {
6975
+ method: req.method,
6976
+ headers,
6977
+ body: body || undefined
6978
+ });
6979
+ }
6980
+ async function sendWebResponse(webRes, nodeRes) {
6981
+ nodeRes.statusCode = webRes.status;
6982
+ webRes.headers.forEach((value, key) => {
6983
+ nodeRes.setHeader(key, value);
6984
+ });
6985
+ const body = await webRes.text();
6986
+ nodeRes.end(body);
6987
+ }
6988
+ function toNodeHandler(config) {
6989
+ const oauthHandler = new OAuthHandler(config);
6990
+ return async (req, res) => {
6991
+ try {
6992
+ const webReq = await toWebRequest(req);
6993
+ const url = new URL(webReq.url);
6994
+ const segments = url.pathname.split("/").filter(Boolean);
6995
+ const action = segments[segments.length - 1];
6996
+ let webRes;
6997
+ if (req.method === "POST") {
6998
+ if (action === "authorize") {
6999
+ const body = await webReq.json();
7000
+ const result = await oauthHandler.handleAuthorize(body);
7001
+ webRes = new Response(JSON.stringify(result), {
7002
+ status: 200,
7003
+ headers: { "Content-Type": "application/json" }
7004
+ });
7005
+ } else if (action === "callback") {
7006
+ const body = await webReq.json();
7007
+ const result = await oauthHandler.handleCallback(body);
7008
+ webRes = new Response(JSON.stringify(result), {
7009
+ status: 200,
7010
+ headers: { "Content-Type": "application/json" }
7011
+ });
7012
+ } else if (action === "disconnect") {
7013
+ const authHeader = webReq.headers.get("authorization");
7014
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
7015
+ webRes = new Response(JSON.stringify({ error: "Missing or invalid Authorization header" }), {
7016
+ status: 400,
7017
+ headers: { "Content-Type": "application/json" }
7018
+ });
7019
+ } else {
7020
+ const accessToken = authHeader.substring(7);
7021
+ const body = await webReq.json();
7022
+ const { provider } = body;
7023
+ if (!provider) {
7024
+ webRes = new Response(JSON.stringify({ error: "Missing provider in request body" }), {
7025
+ status: 400,
7026
+ headers: { "Content-Type": "application/json" }
7027
+ });
7028
+ } else {
7029
+ const result = await oauthHandler.handleDisconnect({ provider }, accessToken);
7030
+ webRes = new Response(JSON.stringify(result), {
7031
+ status: 200,
7032
+ headers: { "Content-Type": "application/json" }
7033
+ });
7034
+ }
7035
+ }
7036
+ } else {
7037
+ webRes = new Response(JSON.stringify({ error: `Unknown action: ${action}` }), {
7038
+ status: 404,
7039
+ headers: { "Content-Type": "application/json" }
7040
+ });
7041
+ }
7042
+ } else if (req.method === "GET" && action === "status") {
7043
+ const provider = url.searchParams.get("provider");
7044
+ const authHeader = webReq.headers.get("authorization");
7045
+ if (!provider) {
7046
+ webRes = new Response(JSON.stringify({ error: "Missing provider query parameter" }), {
7047
+ status: 400,
7048
+ headers: { "Content-Type": "application/json" }
7049
+ });
7050
+ } else if (!authHeader || !authHeader.startsWith("Bearer ")) {
7051
+ webRes = new Response(JSON.stringify({ error: "Missing or invalid Authorization header" }), {
7052
+ status: 400,
7053
+ headers: { "Content-Type": "application/json" }
7054
+ });
7055
+ } else {
7056
+ const accessToken = authHeader.substring(7);
7057
+ const result = await oauthHandler.handleStatus(provider, accessToken);
7058
+ webRes = new Response(JSON.stringify(result), {
7059
+ status: 200,
7060
+ headers: { "Content-Type": "application/json" }
7061
+ });
7062
+ }
7063
+ } else {
7064
+ webRes = new Response(JSON.stringify({ error: `Unknown action: ${action}` }), {
7065
+ status: 404,
7066
+ headers: { "Content-Type": "application/json" }
7067
+ });
7068
+ }
7069
+ await sendWebResponse(webRes, res);
7070
+ } catch (error) {
7071
+ console.error("[OAuth Handler] Error:", error);
7072
+ const errorRes = new Response(JSON.stringify({ error: error.message || "Internal server error" }), {
7073
+ status: 500,
7074
+ headers: { "Content-Type": "application/json" }
7075
+ });
7076
+ await sendWebResponse(errorRes, res);
7077
+ }
7078
+ };
7079
+ }
7080
+ // src/adapters/svelte-kit.ts
7081
+ async function svelteKitHandler({
7082
+ authConfig,
7083
+ event,
7084
+ resolve,
7085
+ basePath = "/api/integrate"
7086
+ }) {
7087
+ const { url } = event;
7088
+ const baseUrl = new URL(basePath, url.origin);
7089
+ if (!url.pathname.startsWith(baseUrl.pathname)) {
7090
+ return resolve(event);
7091
+ }
7092
+ return authConfig(event.request);
7093
+ }
7094
+ // src/adapters/tanstack-start.ts
7095
+ function toTanStackStartHandler(handler) {
7096
+ const baseHandler = async ({ request }) => {
7097
+ return handler(request);
7098
+ };
7099
+ return {
7100
+ GET: baseHandler,
7101
+ POST: baseHandler
7102
+ };
7103
+ }
7104
+ var createTanStackOAuthHandler = toTanStackStartHandler;
2444
7105
  export {
7106
+ tryGetProviderTokens,
7107
+ toTanStackStartHandler,
2445
7108
  toSvelteKitHandler,
2446
7109
  toSolidStartHandler,
7110
+ toNodeHandler,
2447
7111
  toNextJsHandler,
7112
+ svelteKitHandler,
7113
+ jsonSchemaToZod,
7114
+ jsonSchemaPropertyToZod,
7115
+ handleAnthropicToolCalls,
2448
7116
  gmailIntegration,
2449
7117
  githubIntegration,
7118
+ getVercelAITools,
7119
+ getProviderTokens,
7120
+ getProviderForTool,
7121
+ getOpenAITools,
7122
+ getOpenAIAgentsTools,
7123
+ getMastraTools,
7124
+ getLlamaIndexTools,
7125
+ getLangChainTools,
7126
+ getGoogleTools,
7127
+ getCloudflareTools,
7128
+ getAnthropicTools,
7129
+ getAITools,
2450
7130
  genericOAuthIntegration,
7131
+ fromNodeHeaders,
7132
+ executeToolWithToken,
7133
+ executeOpenAIToolCall,
7134
+ executeGoogleFunctionCall,
7135
+ executeCloudflareToolCall,
7136
+ executeAnthropicToolCall,
7137
+ ensureClientConnected,
7138
+ createTanStackOAuthHandler,
2451
7139
  createSimpleIntegration,
7140
+ createNextOAuthHandler,
2452
7141
  createMCPServer,
7142
+ convertMCPToolsToVercelAI,
7143
+ convertMCPToolsToOpenAIAgents,
7144
+ convertMCPToolsToOpenAI,
7145
+ convertMCPToolsToMastra,
7146
+ convertMCPToolsToLlamaIndex,
7147
+ convertMCPToolsToLangChain,
7148
+ convertMCPToolsToGoogle,
7149
+ convertMCPToolsToCloudflare,
7150
+ convertMCPToolsToAnthropic,
7151
+ convertMCPToolToVercelAI,
7152
+ convertMCPToolToOpenAIAgents,
7153
+ convertMCPToolToOpenAI,
7154
+ convertMCPToolToMastra,
7155
+ convertMCPToolToLlamaIndex,
7156
+ convertMCPToolToLangChain,
7157
+ convertMCPToolToGoogle,
7158
+ convertMCPToolToCloudflare,
7159
+ convertMCPToolToAnthropic,
2453
7160
  POST,
7161
+ OAuthHandler,
2454
7162
  GET
2455
7163
  };