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