@elizaos/plugin-twitter 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,7 @@
1
+ import {
2
+ __export
3
+ } from "./chunk-PZ5AY32C.js";
4
+
1
5
  // src/index.ts
2
6
  import {
3
7
  ChannelType as ChannelType6,
@@ -80,7 +84,7 @@ var Platform = class _Platform {
80
84
  */
81
85
  static async importPlatform() {
82
86
  if (PLATFORM_NODE) {
83
- const { platform } = await import("./node-WSVEVHDY.js");
87
+ const { platform } = await import("./node-L7ZVN5QV.js");
84
88
  return platform;
85
89
  }
86
90
  return genericPlatform;
@@ -561,10 +565,7 @@ function generateRandomIP() {
561
565
  // src/client/auth.ts
562
566
  function withTransform(fetchFn, transform) {
563
567
  return async (input, init) => {
564
- const fetchArgs = await transform?.request?.(input, init) ?? [
565
- input,
566
- init
567
- ];
568
+ const fetchArgs = await transform?.request?.(input, init) ?? [input, init];
568
569
  const res = await fetchFn(...fetchArgs);
569
570
  return await transform?.response?.(res) ?? res;
570
571
  };
@@ -8539,236 +8540,4342 @@ import {
8539
8540
  createUniqueUuid as createUniqueUuid5,
8540
8541
  logger as logger7
8541
8542
  } from "@elizaos/core";
8542
- var convertToCoreTweet = (tweet) => ({
8543
- id: tweet.id,
8544
- text: tweet.text,
8545
- conversationId: tweet.conversationId,
8546
- timestamp: tweet.timestamp,
8547
- userId: tweet.userId,
8548
- username: tweet.username,
8549
- name: tweet.name,
8550
- inReplyToStatusId: tweet.inReplyToStatusId,
8551
- permanentUrl: tweet.permanentUrl,
8552
- photos: tweet.photos,
8553
- hashtags: tweet.hashtags,
8554
- mentions: tweet.mentions.map((mention) => mention.username),
8555
- urls: tweet.urls,
8556
- videos: tweet.videos,
8557
- thread: tweet.thread
8543
+
8544
+ // src/environment.ts
8545
+ import { parseBooleanFromText } from "@elizaos/core";
8546
+
8547
+ // node_modules/zod/dist/esm/v3/external.js
8548
+ var external_exports = {};
8549
+ __export(external_exports, {
8550
+ BRAND: () => BRAND,
8551
+ DIRTY: () => DIRTY,
8552
+ EMPTY_PATH: () => EMPTY_PATH,
8553
+ INVALID: () => INVALID,
8554
+ NEVER: () => NEVER,
8555
+ OK: () => OK,
8556
+ ParseStatus: () => ParseStatus,
8557
+ Schema: () => ZodType,
8558
+ ZodAny: () => ZodAny,
8559
+ ZodArray: () => ZodArray,
8560
+ ZodBigInt: () => ZodBigInt,
8561
+ ZodBoolean: () => ZodBoolean,
8562
+ ZodBranded: () => ZodBranded,
8563
+ ZodCatch: () => ZodCatch,
8564
+ ZodDate: () => ZodDate,
8565
+ ZodDefault: () => ZodDefault,
8566
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
8567
+ ZodEffects: () => ZodEffects,
8568
+ ZodEnum: () => ZodEnum,
8569
+ ZodError: () => ZodError,
8570
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
8571
+ ZodFunction: () => ZodFunction,
8572
+ ZodIntersection: () => ZodIntersection,
8573
+ ZodIssueCode: () => ZodIssueCode,
8574
+ ZodLazy: () => ZodLazy,
8575
+ ZodLiteral: () => ZodLiteral,
8576
+ ZodMap: () => ZodMap,
8577
+ ZodNaN: () => ZodNaN,
8578
+ ZodNativeEnum: () => ZodNativeEnum,
8579
+ ZodNever: () => ZodNever,
8580
+ ZodNull: () => ZodNull,
8581
+ ZodNullable: () => ZodNullable,
8582
+ ZodNumber: () => ZodNumber,
8583
+ ZodObject: () => ZodObject,
8584
+ ZodOptional: () => ZodOptional,
8585
+ ZodParsedType: () => ZodParsedType,
8586
+ ZodPipeline: () => ZodPipeline,
8587
+ ZodPromise: () => ZodPromise,
8588
+ ZodReadonly: () => ZodReadonly,
8589
+ ZodRecord: () => ZodRecord,
8590
+ ZodSchema: () => ZodType,
8591
+ ZodSet: () => ZodSet,
8592
+ ZodString: () => ZodString,
8593
+ ZodSymbol: () => ZodSymbol,
8594
+ ZodTransformer: () => ZodEffects,
8595
+ ZodTuple: () => ZodTuple,
8596
+ ZodType: () => ZodType,
8597
+ ZodUndefined: () => ZodUndefined,
8598
+ ZodUnion: () => ZodUnion,
8599
+ ZodUnknown: () => ZodUnknown,
8600
+ ZodVoid: () => ZodVoid,
8601
+ addIssueToContext: () => addIssueToContext,
8602
+ any: () => anyType,
8603
+ array: () => arrayType,
8604
+ bigint: () => bigIntType,
8605
+ boolean: () => booleanType,
8606
+ coerce: () => coerce,
8607
+ custom: () => custom,
8608
+ date: () => dateType,
8609
+ datetimeRegex: () => datetimeRegex,
8610
+ defaultErrorMap: () => en_default,
8611
+ discriminatedUnion: () => discriminatedUnionType,
8612
+ effect: () => effectsType,
8613
+ enum: () => enumType,
8614
+ function: () => functionType,
8615
+ getErrorMap: () => getErrorMap,
8616
+ getParsedType: () => getParsedType,
8617
+ instanceof: () => instanceOfType,
8618
+ intersection: () => intersectionType,
8619
+ isAborted: () => isAborted,
8620
+ isAsync: () => isAsync,
8621
+ isDirty: () => isDirty,
8622
+ isValid: () => isValid,
8623
+ late: () => late,
8624
+ lazy: () => lazyType,
8625
+ literal: () => literalType,
8626
+ makeIssue: () => makeIssue,
8627
+ map: () => mapType,
8628
+ nan: () => nanType,
8629
+ nativeEnum: () => nativeEnumType,
8630
+ never: () => neverType,
8631
+ null: () => nullType,
8632
+ nullable: () => nullableType,
8633
+ number: () => numberType,
8634
+ object: () => objectType,
8635
+ objectUtil: () => objectUtil,
8636
+ oboolean: () => oboolean,
8637
+ onumber: () => onumber,
8638
+ optional: () => optionalType,
8639
+ ostring: () => ostring,
8640
+ pipeline: () => pipelineType,
8641
+ preprocess: () => preprocessType,
8642
+ promise: () => promiseType,
8643
+ quotelessJson: () => quotelessJson,
8644
+ record: () => recordType,
8645
+ set: () => setType,
8646
+ setErrorMap: () => setErrorMap,
8647
+ strictObject: () => strictObjectType,
8648
+ string: () => stringType,
8649
+ symbol: () => symbolType,
8650
+ transformer: () => effectsType,
8651
+ tuple: () => tupleType,
8652
+ undefined: () => undefinedType,
8653
+ union: () => unionType,
8654
+ unknown: () => unknownType,
8655
+ util: () => util,
8656
+ void: () => voidType
8558
8657
  });
8559
- var convertToCoreTweets = (tweets) => tweets.map(convertToCoreTweet);
8560
- var TwitterInteractionClient = class {
8561
- /**
8562
- * Constructor for setting up a new instance with the provided client, runtime, and state.
8563
- * @param {ClientBase} client - The client being used for communication.
8564
- * @param {IAgentRuntime} runtime - The runtime environment for the agent.
8565
- * @param {any} state - The initial state of the agent.
8566
- */
8567
- constructor(client, runtime, state) {
8568
- this.client = client;
8569
- this.runtime = runtime;
8570
- this.state = state;
8571
- this.isDryRun = this.state?.TWITTER_DRY_RUN || this.runtime.getSetting("TWITTER_DRY_RUN");
8658
+
8659
+ // node_modules/zod/dist/esm/v3/helpers/util.js
8660
+ var util;
8661
+ (function(util2) {
8662
+ util2.assertEqual = (_) => {
8663
+ };
8664
+ function assertIs(_arg) {
8572
8665
  }
8573
- /**
8574
- * Asynchronously starts the process of handling Twitter interactions on a loop.
8575
- * Uses an interval based on the 'TWITTER_POLL_INTERVAL' setting, or defaults to 2 minutes if not set.
8576
- */
8577
- async start() {
8578
- const handleTwitterInteractionsLoop = () => {
8579
- const interactionInterval = (this.state?.TWITTER_POLL_INTERVAL || this.runtime.getSetting(
8580
- "TWITTER_POLL_INTERVAL"
8581
- ) || 120) * 1e3;
8582
- this.handleTwitterInteractions();
8583
- setTimeout(handleTwitterInteractionsLoop, interactionInterval);
8584
- };
8585
- handleTwitterInteractionsLoop();
8666
+ util2.assertIs = assertIs;
8667
+ function assertNever(_x) {
8668
+ throw new Error();
8586
8669
  }
8587
- /**
8588
- * Asynchronously handles Twitter interactions by checking for mentions, processing tweets, and updating the last checked tweet ID.
8589
- */
8590
- async handleTwitterInteractions() {
8591
- logger7.log("Checking Twitter interactions");
8592
- const twitterUsername = this.client.profile?.username;
8593
- try {
8594
- const cursorKey = `twitter/${twitterUsername}/mention_cursor`;
8595
- const cachedCursor = await this.runtime.getCache(cursorKey);
8596
- const searchResult = await this.client.fetchSearchTweets(
8597
- `@${twitterUsername}`,
8598
- 20,
8599
- 1 /* Latest */,
8600
- String(cachedCursor)
8601
- );
8602
- const mentionCandidates = searchResult.tweets;
8603
- if (mentionCandidates.length > 0 && searchResult.previous) {
8604
- await this.runtime.setCache(cursorKey, searchResult.previous);
8605
- } else if (!searchResult.previous && !searchResult.next) {
8606
- await this.runtime.setCache(cursorKey, "");
8670
+ util2.assertNever = assertNever;
8671
+ util2.arrayToEnum = (items) => {
8672
+ const obj = {};
8673
+ for (const item of items) {
8674
+ obj[item] = item;
8675
+ }
8676
+ return obj;
8677
+ };
8678
+ util2.getValidEnumValues = (obj) => {
8679
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
8680
+ const filtered = {};
8681
+ for (const k of validKeys) {
8682
+ filtered[k] = obj[k];
8683
+ }
8684
+ return util2.objectValues(filtered);
8685
+ };
8686
+ util2.objectValues = (obj) => {
8687
+ return util2.objectKeys(obj).map(function(e) {
8688
+ return obj[e];
8689
+ });
8690
+ };
8691
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
8692
+ const keys = [];
8693
+ for (const key in object) {
8694
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
8695
+ keys.push(key);
8607
8696
  }
8608
- await this.processMentionTweets(mentionCandidates);
8609
- await this.client.cacheLatestCheckedTweetId();
8610
- logger7.log("Finished checking Twitter interactions");
8611
- } catch (error) {
8612
- logger7.error("Error handling Twitter interactions:", error);
8613
8697
  }
8698
+ return keys;
8699
+ };
8700
+ util2.find = (arr, checker) => {
8701
+ for (const item of arr) {
8702
+ if (checker(item))
8703
+ return item;
8704
+ }
8705
+ return void 0;
8706
+ };
8707
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
8708
+ function joinValues(array, separator = " | ") {
8709
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
8614
8710
  }
8615
- /**
8616
- * Processes all incoming tweets that mention the bot.
8617
- * For each new tweet:
8618
- * - Ensures world, room, and connection exist
8619
- * - Saves the tweet as memory
8620
- * - Emits thread-related events (THREAD_CREATED / THREAD_UPDATED)
8621
- * - Delegates tweet content to `handleTweet` for reply generation
8622
- *
8623
- * Note: MENTION_RECEIVED is currently disabled (see TODO below)
8624
- */
8625
- async processMentionTweets(mentionCandidates) {
8626
- logger7.log(
8627
- "Completed checking mentioned tweets:",
8628
- mentionCandidates.length
8629
- );
8630
- let uniqueTweetCandidates = [...mentionCandidates];
8631
- uniqueTweetCandidates = uniqueTweetCandidates.sort((a, b) => a.id.localeCompare(b.id)).filter((tweet) => tweet.userId !== this.client.profile.id);
8632
- for (const tweet of uniqueTweetCandidates) {
8633
- if (!this.client.lastCheckedTweetId || BigInt(tweet.id) > this.client.lastCheckedTweetId) {
8634
- const tweetId = createUniqueUuid5(this.runtime, tweet.id);
8635
- const existingResponse = await this.runtime.getMemoryById(tweetId);
8636
- if (existingResponse) {
8637
- logger7.log(`Already responded to tweet ${tweet.id}, skipping`);
8638
- continue;
8639
- }
8640
- logger7.log("New Tweet found", tweet.permanentUrl);
8641
- const entityId = createUniqueUuid5(
8642
- this.runtime,
8643
- tweet.userId === this.client.profile.id ? this.runtime.agentId : tweet.userId
8644
- );
8645
- const worldId = createUniqueUuid5(this.runtime, tweet.userId);
8646
- const roomId = createUniqueUuid5(this.runtime, tweet.conversationId);
8647
- await this.runtime.ensureConnection({
8648
- entityId,
8649
- roomId,
8650
- userName: tweet.username,
8651
- worldName: `${tweet.name}'s Twitter`,
8652
- name: tweet.name,
8653
- source: "twitter",
8654
- type: ChannelType3.GROUP,
8655
- channelId: tweet.conversationId,
8656
- serverId: tweet.userId,
8657
- worldId,
8658
- metadata: {
8659
- ownership: { ownerId: tweet.userId },
8660
- twitter: {
8661
- username: tweet.username,
8662
- id: tweet.userId,
8663
- name: tweet.name
8711
+ util2.joinValues = joinValues;
8712
+ util2.jsonStringifyReplacer = (_, value) => {
8713
+ if (typeof value === "bigint") {
8714
+ return value.toString();
8715
+ }
8716
+ return value;
8717
+ };
8718
+ })(util || (util = {}));
8719
+ var objectUtil;
8720
+ (function(objectUtil2) {
8721
+ objectUtil2.mergeShapes = (first, second) => {
8722
+ return {
8723
+ ...first,
8724
+ ...second
8725
+ // second overwrites first
8726
+ };
8727
+ };
8728
+ })(objectUtil || (objectUtil = {}));
8729
+ var ZodParsedType = util.arrayToEnum([
8730
+ "string",
8731
+ "nan",
8732
+ "number",
8733
+ "integer",
8734
+ "float",
8735
+ "boolean",
8736
+ "date",
8737
+ "bigint",
8738
+ "symbol",
8739
+ "function",
8740
+ "undefined",
8741
+ "null",
8742
+ "array",
8743
+ "object",
8744
+ "unknown",
8745
+ "promise",
8746
+ "void",
8747
+ "never",
8748
+ "map",
8749
+ "set"
8750
+ ]);
8751
+ var getParsedType = (data) => {
8752
+ const t = typeof data;
8753
+ switch (t) {
8754
+ case "undefined":
8755
+ return ZodParsedType.undefined;
8756
+ case "string":
8757
+ return ZodParsedType.string;
8758
+ case "number":
8759
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
8760
+ case "boolean":
8761
+ return ZodParsedType.boolean;
8762
+ case "function":
8763
+ return ZodParsedType.function;
8764
+ case "bigint":
8765
+ return ZodParsedType.bigint;
8766
+ case "symbol":
8767
+ return ZodParsedType.symbol;
8768
+ case "object":
8769
+ if (Array.isArray(data)) {
8770
+ return ZodParsedType.array;
8771
+ }
8772
+ if (data === null) {
8773
+ return ZodParsedType.null;
8774
+ }
8775
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
8776
+ return ZodParsedType.promise;
8777
+ }
8778
+ if (typeof Map !== "undefined" && data instanceof Map) {
8779
+ return ZodParsedType.map;
8780
+ }
8781
+ if (typeof Set !== "undefined" && data instanceof Set) {
8782
+ return ZodParsedType.set;
8783
+ }
8784
+ if (typeof Date !== "undefined" && data instanceof Date) {
8785
+ return ZodParsedType.date;
8786
+ }
8787
+ return ZodParsedType.object;
8788
+ default:
8789
+ return ZodParsedType.unknown;
8790
+ }
8791
+ };
8792
+
8793
+ // node_modules/zod/dist/esm/v3/ZodError.js
8794
+ var ZodIssueCode = util.arrayToEnum([
8795
+ "invalid_type",
8796
+ "invalid_literal",
8797
+ "custom",
8798
+ "invalid_union",
8799
+ "invalid_union_discriminator",
8800
+ "invalid_enum_value",
8801
+ "unrecognized_keys",
8802
+ "invalid_arguments",
8803
+ "invalid_return_type",
8804
+ "invalid_date",
8805
+ "invalid_string",
8806
+ "too_small",
8807
+ "too_big",
8808
+ "invalid_intersection_types",
8809
+ "not_multiple_of",
8810
+ "not_finite"
8811
+ ]);
8812
+ var quotelessJson = (obj) => {
8813
+ const json = JSON.stringify(obj, null, 2);
8814
+ return json.replace(/"([^"]+)":/g, "$1:");
8815
+ };
8816
+ var ZodError = class _ZodError extends Error {
8817
+ get errors() {
8818
+ return this.issues;
8819
+ }
8820
+ constructor(issues) {
8821
+ super();
8822
+ this.issues = [];
8823
+ this.addIssue = (sub) => {
8824
+ this.issues = [...this.issues, sub];
8825
+ };
8826
+ this.addIssues = (subs = []) => {
8827
+ this.issues = [...this.issues, ...subs];
8828
+ };
8829
+ const actualProto = new.target.prototype;
8830
+ if (Object.setPrototypeOf) {
8831
+ Object.setPrototypeOf(this, actualProto);
8832
+ } else {
8833
+ this.__proto__ = actualProto;
8834
+ }
8835
+ this.name = "ZodError";
8836
+ this.issues = issues;
8837
+ }
8838
+ format(_mapper) {
8839
+ const mapper = _mapper || function(issue) {
8840
+ return issue.message;
8841
+ };
8842
+ const fieldErrors = { _errors: [] };
8843
+ const processError = (error) => {
8844
+ for (const issue of error.issues) {
8845
+ if (issue.code === "invalid_union") {
8846
+ issue.unionErrors.map(processError);
8847
+ } else if (issue.code === "invalid_return_type") {
8848
+ processError(issue.returnTypeError);
8849
+ } else if (issue.code === "invalid_arguments") {
8850
+ processError(issue.argumentsError);
8851
+ } else if (issue.path.length === 0) {
8852
+ fieldErrors._errors.push(mapper(issue));
8853
+ } else {
8854
+ let curr = fieldErrors;
8855
+ let i = 0;
8856
+ while (i < issue.path.length) {
8857
+ const el = issue.path[i];
8858
+ const terminal = i === issue.path.length - 1;
8859
+ if (!terminal) {
8860
+ curr[el] = curr[el] || { _errors: [] };
8861
+ } else {
8862
+ curr[el] = curr[el] || { _errors: [] };
8863
+ curr[el]._errors.push(mapper(issue));
8664
8864
  }
8665
- }
8666
- });
8667
- const memory = {
8668
- id: tweetId,
8669
- agentId: this.runtime.agentId,
8670
- content: {
8671
- text: tweet.text,
8672
- url: tweet.permanentUrl,
8673
- attachments: tweet.photos?.map((photo, index) => ({
8674
- id: photo.id,
8675
- url: photo.url,
8676
- contentType: ContentType.IMAGE
8677
- // TODO: check if we can read this.
8678
- })) || [],
8679
- inReplyTo: tweet.inReplyToStatusId ? createUniqueUuid5(this.runtime, tweet.inReplyToStatusId) : void 0,
8680
- source: "twitter",
8681
- channelType: ChannelType3.GROUP,
8682
- tweet
8683
- },
8684
- entityId,
8685
- roomId,
8686
- createdAt: tweet.timestamp * 1e3
8687
- };
8688
- await this.runtime.createMemory(memory, "messages");
8689
- if (tweet.thread.length > 1) {
8690
- const threadPayload = {
8691
- runtime: this.runtime,
8692
- tweets: convertToCoreTweets(tweet.thread),
8693
- user: {
8694
- id: tweet.userId,
8695
- username: tweet.username,
8696
- name: tweet.name
8697
- },
8698
- source: "twitter"
8699
- };
8700
- if (tweet.thread[tweet.thread.length - 1].id === tweet.id) {
8701
- this.runtime.emitEvent("TWITTER_THREAD_UPDATED" /* THREAD_UPDATED */, {
8702
- ...threadPayload,
8703
- newTweet: convertToCoreTweet(tweet)
8704
- });
8705
- } else if (tweet.thread[0].id === tweet.id) {
8706
- this.runtime.emitEvent(
8707
- "TWITTER_THREAD_CREATED" /* THREAD_CREATED */,
8708
- threadPayload
8709
- );
8865
+ curr = curr[el];
8866
+ i++;
8710
8867
  }
8711
8868
  }
8712
- await this.handleTweet({
8713
- tweet,
8714
- message: memory,
8715
- thread: tweet.thread
8716
- });
8717
- this.client.lastCheckedTweetId = BigInt(tweet.id);
8718
8869
  }
8870
+ };
8871
+ processError(this);
8872
+ return fieldErrors;
8873
+ }
8874
+ static assert(value) {
8875
+ if (!(value instanceof _ZodError)) {
8876
+ throw new Error(`Not a ZodError: ${value}`);
8719
8877
  }
8720
8878
  }
8721
- /**
8722
- * Handles Twitter interactions such as likes, retweets, and quotes.
8723
- * For each interaction:
8724
- * - Creates a memory object
8725
- * - Emits platform-specific events (LIKE_RECEIVED, RETWEET_RECEIVED, QUOTE_RECEIVED)
8726
- * - Emits a generic REACTION_RECEIVED event with metadata
8727
- */
8728
- async handleInteraction(interaction) {
8729
- if (interaction?.targetTweet?.conversationId) {
8730
- const memory = this.createMemoryObject(
8731
- interaction.type,
8732
- `${interaction.id}-${interaction.type}`,
8733
- interaction.userId,
8734
- interaction.targetTweet.conversationId
8735
- );
8736
- await this.runtime.createMemory(memory, "messages");
8737
- const reactionMessage = {
8738
- id: createUniqueUuid5(this.runtime, interaction.targetTweetId),
8739
- content: {
8740
- text: interaction.targetTweet.text,
8741
- source: "twitter"
8742
- },
8743
- entityId: createUniqueUuid5(
8744
- this.runtime,
8745
- interaction.targetTweet.userId
8746
- ),
8747
- roomId: createUniqueUuid5(
8748
- this.runtime,
8749
- interaction.targetTweet.conversationId
8750
- ),
8751
- agentId: this.runtime.agentId
8752
- };
8753
- const basePayload = {
8754
- runtime: this.runtime,
8755
- user: {
8756
- id: interaction.userId,
8757
- username: interaction.username,
8758
- name: interaction.name
8759
- },
8760
- source: "twitter"
8761
- };
8762
- switch (interaction.type) {
8763
- case "like": {
8764
- const likePayload = {
8765
- ...basePayload,
8766
- tweet: interaction.targetTweet
8767
- };
8768
- this.runtime.emitEvent("TWITTER_LIKE_RECEIVED" /* LIKE_RECEIVED */, likePayload);
8769
- this.runtime.emitEvent(EventType2.REACTION_RECEIVED, {
8770
- ...basePayload,
8771
- reaction: {
8879
+ toString() {
8880
+ return this.message;
8881
+ }
8882
+ get message() {
8883
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
8884
+ }
8885
+ get isEmpty() {
8886
+ return this.issues.length === 0;
8887
+ }
8888
+ flatten(mapper = (issue) => issue.message) {
8889
+ const fieldErrors = {};
8890
+ const formErrors = [];
8891
+ for (const sub of this.issues) {
8892
+ if (sub.path.length > 0) {
8893
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
8894
+ fieldErrors[sub.path[0]].push(mapper(sub));
8895
+ } else {
8896
+ formErrors.push(mapper(sub));
8897
+ }
8898
+ }
8899
+ return { formErrors, fieldErrors };
8900
+ }
8901
+ get formErrors() {
8902
+ return this.flatten();
8903
+ }
8904
+ };
8905
+ ZodError.create = (issues) => {
8906
+ const error = new ZodError(issues);
8907
+ return error;
8908
+ };
8909
+
8910
+ // node_modules/zod/dist/esm/v3/locales/en.js
8911
+ var errorMap = (issue, _ctx) => {
8912
+ let message;
8913
+ switch (issue.code) {
8914
+ case ZodIssueCode.invalid_type:
8915
+ if (issue.received === ZodParsedType.undefined) {
8916
+ message = "Required";
8917
+ } else {
8918
+ message = `Expected ${issue.expected}, received ${issue.received}`;
8919
+ }
8920
+ break;
8921
+ case ZodIssueCode.invalid_literal:
8922
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
8923
+ break;
8924
+ case ZodIssueCode.unrecognized_keys:
8925
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
8926
+ break;
8927
+ case ZodIssueCode.invalid_union:
8928
+ message = `Invalid input`;
8929
+ break;
8930
+ case ZodIssueCode.invalid_union_discriminator:
8931
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
8932
+ break;
8933
+ case ZodIssueCode.invalid_enum_value:
8934
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
8935
+ break;
8936
+ case ZodIssueCode.invalid_arguments:
8937
+ message = `Invalid function arguments`;
8938
+ break;
8939
+ case ZodIssueCode.invalid_return_type:
8940
+ message = `Invalid function return type`;
8941
+ break;
8942
+ case ZodIssueCode.invalid_date:
8943
+ message = `Invalid date`;
8944
+ break;
8945
+ case ZodIssueCode.invalid_string:
8946
+ if (typeof issue.validation === "object") {
8947
+ if ("includes" in issue.validation) {
8948
+ message = `Invalid input: must include "${issue.validation.includes}"`;
8949
+ if (typeof issue.validation.position === "number") {
8950
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
8951
+ }
8952
+ } else if ("startsWith" in issue.validation) {
8953
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
8954
+ } else if ("endsWith" in issue.validation) {
8955
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
8956
+ } else {
8957
+ util.assertNever(issue.validation);
8958
+ }
8959
+ } else if (issue.validation !== "regex") {
8960
+ message = `Invalid ${issue.validation}`;
8961
+ } else {
8962
+ message = "Invalid";
8963
+ }
8964
+ break;
8965
+ case ZodIssueCode.too_small:
8966
+ if (issue.type === "array")
8967
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
8968
+ else if (issue.type === "string")
8969
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
8970
+ else if (issue.type === "number")
8971
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
8972
+ else if (issue.type === "date")
8973
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
8974
+ else
8975
+ message = "Invalid input";
8976
+ break;
8977
+ case ZodIssueCode.too_big:
8978
+ if (issue.type === "array")
8979
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
8980
+ else if (issue.type === "string")
8981
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
8982
+ else if (issue.type === "number")
8983
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
8984
+ else if (issue.type === "bigint")
8985
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
8986
+ else if (issue.type === "date")
8987
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
8988
+ else
8989
+ message = "Invalid input";
8990
+ break;
8991
+ case ZodIssueCode.custom:
8992
+ message = `Invalid input`;
8993
+ break;
8994
+ case ZodIssueCode.invalid_intersection_types:
8995
+ message = `Intersection results could not be merged`;
8996
+ break;
8997
+ case ZodIssueCode.not_multiple_of:
8998
+ message = `Number must be a multiple of ${issue.multipleOf}`;
8999
+ break;
9000
+ case ZodIssueCode.not_finite:
9001
+ message = "Number must be finite";
9002
+ break;
9003
+ default:
9004
+ message = _ctx.defaultError;
9005
+ util.assertNever(issue);
9006
+ }
9007
+ return { message };
9008
+ };
9009
+ var en_default = errorMap;
9010
+
9011
+ // node_modules/zod/dist/esm/v3/errors.js
9012
+ var overrideErrorMap = en_default;
9013
+ function setErrorMap(map) {
9014
+ overrideErrorMap = map;
9015
+ }
9016
+ function getErrorMap() {
9017
+ return overrideErrorMap;
9018
+ }
9019
+
9020
+ // node_modules/zod/dist/esm/v3/helpers/parseUtil.js
9021
+ var makeIssue = (params) => {
9022
+ const { data, path: path3, errorMaps, issueData } = params;
9023
+ const fullPath = [...path3, ...issueData.path || []];
9024
+ const fullIssue = {
9025
+ ...issueData,
9026
+ path: fullPath
9027
+ };
9028
+ if (issueData.message !== void 0) {
9029
+ return {
9030
+ ...issueData,
9031
+ path: fullPath,
9032
+ message: issueData.message
9033
+ };
9034
+ }
9035
+ let errorMessage = "";
9036
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
9037
+ for (const map of maps) {
9038
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
9039
+ }
9040
+ return {
9041
+ ...issueData,
9042
+ path: fullPath,
9043
+ message: errorMessage
9044
+ };
9045
+ };
9046
+ var EMPTY_PATH = [];
9047
+ function addIssueToContext(ctx, issueData) {
9048
+ const overrideMap = getErrorMap();
9049
+ const issue = makeIssue({
9050
+ issueData,
9051
+ data: ctx.data,
9052
+ path: ctx.path,
9053
+ errorMaps: [
9054
+ ctx.common.contextualErrorMap,
9055
+ // contextual error map is first priority
9056
+ ctx.schemaErrorMap,
9057
+ // then schema-bound map if available
9058
+ overrideMap,
9059
+ // then global override map
9060
+ overrideMap === en_default ? void 0 : en_default
9061
+ // then global default map
9062
+ ].filter((x) => !!x)
9063
+ });
9064
+ ctx.common.issues.push(issue);
9065
+ }
9066
+ var ParseStatus = class _ParseStatus {
9067
+ constructor() {
9068
+ this.value = "valid";
9069
+ }
9070
+ dirty() {
9071
+ if (this.value === "valid")
9072
+ this.value = "dirty";
9073
+ }
9074
+ abort() {
9075
+ if (this.value !== "aborted")
9076
+ this.value = "aborted";
9077
+ }
9078
+ static mergeArray(status, results) {
9079
+ const arrayValue = [];
9080
+ for (const s of results) {
9081
+ if (s.status === "aborted")
9082
+ return INVALID;
9083
+ if (s.status === "dirty")
9084
+ status.dirty();
9085
+ arrayValue.push(s.value);
9086
+ }
9087
+ return { status: status.value, value: arrayValue };
9088
+ }
9089
+ static async mergeObjectAsync(status, pairs) {
9090
+ const syncPairs = [];
9091
+ for (const pair of pairs) {
9092
+ const key = await pair.key;
9093
+ const value = await pair.value;
9094
+ syncPairs.push({
9095
+ key,
9096
+ value
9097
+ });
9098
+ }
9099
+ return _ParseStatus.mergeObjectSync(status, syncPairs);
9100
+ }
9101
+ static mergeObjectSync(status, pairs) {
9102
+ const finalObject = {};
9103
+ for (const pair of pairs) {
9104
+ const { key, value } = pair;
9105
+ if (key.status === "aborted")
9106
+ return INVALID;
9107
+ if (value.status === "aborted")
9108
+ return INVALID;
9109
+ if (key.status === "dirty")
9110
+ status.dirty();
9111
+ if (value.status === "dirty")
9112
+ status.dirty();
9113
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
9114
+ finalObject[key.value] = value.value;
9115
+ }
9116
+ }
9117
+ return { status: status.value, value: finalObject };
9118
+ }
9119
+ };
9120
+ var INVALID = Object.freeze({
9121
+ status: "aborted"
9122
+ });
9123
+ var DIRTY = (value) => ({ status: "dirty", value });
9124
+ var OK = (value) => ({ status: "valid", value });
9125
+ var isAborted = (x) => x.status === "aborted";
9126
+ var isDirty = (x) => x.status === "dirty";
9127
+ var isValid = (x) => x.status === "valid";
9128
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
9129
+
9130
+ // node_modules/zod/dist/esm/v3/helpers/errorUtil.js
9131
+ var errorUtil;
9132
+ (function(errorUtil2) {
9133
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
9134
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
9135
+ })(errorUtil || (errorUtil = {}));
9136
+
9137
+ // node_modules/zod/dist/esm/v3/types.js
9138
+ var ParseInputLazyPath = class {
9139
+ constructor(parent, value, path3, key) {
9140
+ this._cachedPath = [];
9141
+ this.parent = parent;
9142
+ this.data = value;
9143
+ this._path = path3;
9144
+ this._key = key;
9145
+ }
9146
+ get path() {
9147
+ if (!this._cachedPath.length) {
9148
+ if (Array.isArray(this._key)) {
9149
+ this._cachedPath.push(...this._path, ...this._key);
9150
+ } else {
9151
+ this._cachedPath.push(...this._path, this._key);
9152
+ }
9153
+ }
9154
+ return this._cachedPath;
9155
+ }
9156
+ };
9157
+ var handleResult = (ctx, result) => {
9158
+ if (isValid(result)) {
9159
+ return { success: true, data: result.value };
9160
+ } else {
9161
+ if (!ctx.common.issues.length) {
9162
+ throw new Error("Validation failed but no issues detected.");
9163
+ }
9164
+ return {
9165
+ success: false,
9166
+ get error() {
9167
+ if (this._error)
9168
+ return this._error;
9169
+ const error = new ZodError(ctx.common.issues);
9170
+ this._error = error;
9171
+ return this._error;
9172
+ }
9173
+ };
9174
+ }
9175
+ };
9176
+ function processCreateParams(params) {
9177
+ if (!params)
9178
+ return {};
9179
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
9180
+ if (errorMap2 && (invalid_type_error || required_error)) {
9181
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
9182
+ }
9183
+ if (errorMap2)
9184
+ return { errorMap: errorMap2, description };
9185
+ const customMap = (iss, ctx) => {
9186
+ const { message } = params;
9187
+ if (iss.code === "invalid_enum_value") {
9188
+ return { message: message ?? ctx.defaultError };
9189
+ }
9190
+ if (typeof ctx.data === "undefined") {
9191
+ return { message: message ?? required_error ?? ctx.defaultError };
9192
+ }
9193
+ if (iss.code !== "invalid_type")
9194
+ return { message: ctx.defaultError };
9195
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
9196
+ };
9197
+ return { errorMap: customMap, description };
9198
+ }
9199
+ var ZodType = class {
9200
+ get description() {
9201
+ return this._def.description;
9202
+ }
9203
+ _getType(input) {
9204
+ return getParsedType(input.data);
9205
+ }
9206
+ _getOrReturnCtx(input, ctx) {
9207
+ return ctx || {
9208
+ common: input.parent.common,
9209
+ data: input.data,
9210
+ parsedType: getParsedType(input.data),
9211
+ schemaErrorMap: this._def.errorMap,
9212
+ path: input.path,
9213
+ parent: input.parent
9214
+ };
9215
+ }
9216
+ _processInputParams(input) {
9217
+ return {
9218
+ status: new ParseStatus(),
9219
+ ctx: {
9220
+ common: input.parent.common,
9221
+ data: input.data,
9222
+ parsedType: getParsedType(input.data),
9223
+ schemaErrorMap: this._def.errorMap,
9224
+ path: input.path,
9225
+ parent: input.parent
9226
+ }
9227
+ };
9228
+ }
9229
+ _parseSync(input) {
9230
+ const result = this._parse(input);
9231
+ if (isAsync(result)) {
9232
+ throw new Error("Synchronous parse encountered promise.");
9233
+ }
9234
+ return result;
9235
+ }
9236
+ _parseAsync(input) {
9237
+ const result = this._parse(input);
9238
+ return Promise.resolve(result);
9239
+ }
9240
+ parse(data, params) {
9241
+ const result = this.safeParse(data, params);
9242
+ if (result.success)
9243
+ return result.data;
9244
+ throw result.error;
9245
+ }
9246
+ safeParse(data, params) {
9247
+ const ctx = {
9248
+ common: {
9249
+ issues: [],
9250
+ async: params?.async ?? false,
9251
+ contextualErrorMap: params?.errorMap
9252
+ },
9253
+ path: params?.path || [],
9254
+ schemaErrorMap: this._def.errorMap,
9255
+ parent: null,
9256
+ data,
9257
+ parsedType: getParsedType(data)
9258
+ };
9259
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
9260
+ return handleResult(ctx, result);
9261
+ }
9262
+ "~validate"(data) {
9263
+ const ctx = {
9264
+ common: {
9265
+ issues: [],
9266
+ async: !!this["~standard"].async
9267
+ },
9268
+ path: [],
9269
+ schemaErrorMap: this._def.errorMap,
9270
+ parent: null,
9271
+ data,
9272
+ parsedType: getParsedType(data)
9273
+ };
9274
+ if (!this["~standard"].async) {
9275
+ try {
9276
+ const result = this._parseSync({ data, path: [], parent: ctx });
9277
+ return isValid(result) ? {
9278
+ value: result.value
9279
+ } : {
9280
+ issues: ctx.common.issues
9281
+ };
9282
+ } catch (err) {
9283
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
9284
+ this["~standard"].async = true;
9285
+ }
9286
+ ctx.common = {
9287
+ issues: [],
9288
+ async: true
9289
+ };
9290
+ }
9291
+ }
9292
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
9293
+ value: result.value
9294
+ } : {
9295
+ issues: ctx.common.issues
9296
+ });
9297
+ }
9298
+ async parseAsync(data, params) {
9299
+ const result = await this.safeParseAsync(data, params);
9300
+ if (result.success)
9301
+ return result.data;
9302
+ throw result.error;
9303
+ }
9304
+ async safeParseAsync(data, params) {
9305
+ const ctx = {
9306
+ common: {
9307
+ issues: [],
9308
+ contextualErrorMap: params?.errorMap,
9309
+ async: true
9310
+ },
9311
+ path: params?.path || [],
9312
+ schemaErrorMap: this._def.errorMap,
9313
+ parent: null,
9314
+ data,
9315
+ parsedType: getParsedType(data)
9316
+ };
9317
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
9318
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
9319
+ return handleResult(ctx, result);
9320
+ }
9321
+ refine(check, message) {
9322
+ const getIssueProperties = (val) => {
9323
+ if (typeof message === "string" || typeof message === "undefined") {
9324
+ return { message };
9325
+ } else if (typeof message === "function") {
9326
+ return message(val);
9327
+ } else {
9328
+ return message;
9329
+ }
9330
+ };
9331
+ return this._refinement((val, ctx) => {
9332
+ const result = check(val);
9333
+ const setError = () => ctx.addIssue({
9334
+ code: ZodIssueCode.custom,
9335
+ ...getIssueProperties(val)
9336
+ });
9337
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
9338
+ return result.then((data) => {
9339
+ if (!data) {
9340
+ setError();
9341
+ return false;
9342
+ } else {
9343
+ return true;
9344
+ }
9345
+ });
9346
+ }
9347
+ if (!result) {
9348
+ setError();
9349
+ return false;
9350
+ } else {
9351
+ return true;
9352
+ }
9353
+ });
9354
+ }
9355
+ refinement(check, refinementData) {
9356
+ return this._refinement((val, ctx) => {
9357
+ if (!check(val)) {
9358
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
9359
+ return false;
9360
+ } else {
9361
+ return true;
9362
+ }
9363
+ });
9364
+ }
9365
+ _refinement(refinement) {
9366
+ return new ZodEffects({
9367
+ schema: this,
9368
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
9369
+ effect: { type: "refinement", refinement }
9370
+ });
9371
+ }
9372
+ superRefine(refinement) {
9373
+ return this._refinement(refinement);
9374
+ }
9375
+ constructor(def) {
9376
+ this.spa = this.safeParseAsync;
9377
+ this._def = def;
9378
+ this.parse = this.parse.bind(this);
9379
+ this.safeParse = this.safeParse.bind(this);
9380
+ this.parseAsync = this.parseAsync.bind(this);
9381
+ this.safeParseAsync = this.safeParseAsync.bind(this);
9382
+ this.spa = this.spa.bind(this);
9383
+ this.refine = this.refine.bind(this);
9384
+ this.refinement = this.refinement.bind(this);
9385
+ this.superRefine = this.superRefine.bind(this);
9386
+ this.optional = this.optional.bind(this);
9387
+ this.nullable = this.nullable.bind(this);
9388
+ this.nullish = this.nullish.bind(this);
9389
+ this.array = this.array.bind(this);
9390
+ this.promise = this.promise.bind(this);
9391
+ this.or = this.or.bind(this);
9392
+ this.and = this.and.bind(this);
9393
+ this.transform = this.transform.bind(this);
9394
+ this.brand = this.brand.bind(this);
9395
+ this.default = this.default.bind(this);
9396
+ this.catch = this.catch.bind(this);
9397
+ this.describe = this.describe.bind(this);
9398
+ this.pipe = this.pipe.bind(this);
9399
+ this.readonly = this.readonly.bind(this);
9400
+ this.isNullable = this.isNullable.bind(this);
9401
+ this.isOptional = this.isOptional.bind(this);
9402
+ this["~standard"] = {
9403
+ version: 1,
9404
+ vendor: "zod",
9405
+ validate: (data) => this["~validate"](data)
9406
+ };
9407
+ }
9408
+ optional() {
9409
+ return ZodOptional.create(this, this._def);
9410
+ }
9411
+ nullable() {
9412
+ return ZodNullable.create(this, this._def);
9413
+ }
9414
+ nullish() {
9415
+ return this.nullable().optional();
9416
+ }
9417
+ array() {
9418
+ return ZodArray.create(this);
9419
+ }
9420
+ promise() {
9421
+ return ZodPromise.create(this, this._def);
9422
+ }
9423
+ or(option) {
9424
+ return ZodUnion.create([this, option], this._def);
9425
+ }
9426
+ and(incoming) {
9427
+ return ZodIntersection.create(this, incoming, this._def);
9428
+ }
9429
+ transform(transform) {
9430
+ return new ZodEffects({
9431
+ ...processCreateParams(this._def),
9432
+ schema: this,
9433
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
9434
+ effect: { type: "transform", transform }
9435
+ });
9436
+ }
9437
+ default(def) {
9438
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
9439
+ return new ZodDefault({
9440
+ ...processCreateParams(this._def),
9441
+ innerType: this,
9442
+ defaultValue: defaultValueFunc,
9443
+ typeName: ZodFirstPartyTypeKind.ZodDefault
9444
+ });
9445
+ }
9446
+ brand() {
9447
+ return new ZodBranded({
9448
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
9449
+ type: this,
9450
+ ...processCreateParams(this._def)
9451
+ });
9452
+ }
9453
+ catch(def) {
9454
+ const catchValueFunc = typeof def === "function" ? def : () => def;
9455
+ return new ZodCatch({
9456
+ ...processCreateParams(this._def),
9457
+ innerType: this,
9458
+ catchValue: catchValueFunc,
9459
+ typeName: ZodFirstPartyTypeKind.ZodCatch
9460
+ });
9461
+ }
9462
+ describe(description) {
9463
+ const This = this.constructor;
9464
+ return new This({
9465
+ ...this._def,
9466
+ description
9467
+ });
9468
+ }
9469
+ pipe(target) {
9470
+ return ZodPipeline.create(this, target);
9471
+ }
9472
+ readonly() {
9473
+ return ZodReadonly.create(this);
9474
+ }
9475
+ isOptional() {
9476
+ return this.safeParse(void 0).success;
9477
+ }
9478
+ isNullable() {
9479
+ return this.safeParse(null).success;
9480
+ }
9481
+ };
9482
+ var cuidRegex = /^c[^\s-]{8,}$/i;
9483
+ var cuid2Regex = /^[0-9a-z]+$/;
9484
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
9485
+ 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;
9486
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
9487
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
9488
+ 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)?)??$/;
9489
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
9490
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
9491
+ var emojiRegex;
9492
+ 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])$/;
9493
+ 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])$/;
9494
+ 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]))$/;
9495
+ 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])$/;
9496
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
9497
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
9498
+ 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])))`;
9499
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
9500
+ function timeRegexSource(args) {
9501
+ let secondsRegexSource = `[0-5]\\d`;
9502
+ if (args.precision) {
9503
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
9504
+ } else if (args.precision == null) {
9505
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
9506
+ }
9507
+ const secondsQuantifier = args.precision ? "+" : "?";
9508
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
9509
+ }
9510
+ function timeRegex(args) {
9511
+ return new RegExp(`^${timeRegexSource(args)}$`);
9512
+ }
9513
+ function datetimeRegex(args) {
9514
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
9515
+ const opts = [];
9516
+ opts.push(args.local ? `Z?` : `Z`);
9517
+ if (args.offset)
9518
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
9519
+ regex = `${regex}(${opts.join("|")})`;
9520
+ return new RegExp(`^${regex}$`);
9521
+ }
9522
+ function isValidIP(ip, version) {
9523
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
9524
+ return true;
9525
+ }
9526
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
9527
+ return true;
9528
+ }
9529
+ return false;
9530
+ }
9531
+ function isValidJWT(jwt, alg) {
9532
+ if (!jwtRegex.test(jwt))
9533
+ return false;
9534
+ try {
9535
+ const [header] = jwt.split(".");
9536
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
9537
+ const decoded = JSON.parse(atob(base64));
9538
+ if (typeof decoded !== "object" || decoded === null)
9539
+ return false;
9540
+ if ("typ" in decoded && decoded?.typ !== "JWT")
9541
+ return false;
9542
+ if (!decoded.alg)
9543
+ return false;
9544
+ if (alg && decoded.alg !== alg)
9545
+ return false;
9546
+ return true;
9547
+ } catch {
9548
+ return false;
9549
+ }
9550
+ }
9551
+ function isValidCidr(ip, version) {
9552
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
9553
+ return true;
9554
+ }
9555
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
9556
+ return true;
9557
+ }
9558
+ return false;
9559
+ }
9560
+ var ZodString = class _ZodString extends ZodType {
9561
+ _parse(input) {
9562
+ if (this._def.coerce) {
9563
+ input.data = String(input.data);
9564
+ }
9565
+ const parsedType = this._getType(input);
9566
+ if (parsedType !== ZodParsedType.string) {
9567
+ const ctx2 = this._getOrReturnCtx(input);
9568
+ addIssueToContext(ctx2, {
9569
+ code: ZodIssueCode.invalid_type,
9570
+ expected: ZodParsedType.string,
9571
+ received: ctx2.parsedType
9572
+ });
9573
+ return INVALID;
9574
+ }
9575
+ const status = new ParseStatus();
9576
+ let ctx = void 0;
9577
+ for (const check of this._def.checks) {
9578
+ if (check.kind === "min") {
9579
+ if (input.data.length < check.value) {
9580
+ ctx = this._getOrReturnCtx(input, ctx);
9581
+ addIssueToContext(ctx, {
9582
+ code: ZodIssueCode.too_small,
9583
+ minimum: check.value,
9584
+ type: "string",
9585
+ inclusive: true,
9586
+ exact: false,
9587
+ message: check.message
9588
+ });
9589
+ status.dirty();
9590
+ }
9591
+ } else if (check.kind === "max") {
9592
+ if (input.data.length > check.value) {
9593
+ ctx = this._getOrReturnCtx(input, ctx);
9594
+ addIssueToContext(ctx, {
9595
+ code: ZodIssueCode.too_big,
9596
+ maximum: check.value,
9597
+ type: "string",
9598
+ inclusive: true,
9599
+ exact: false,
9600
+ message: check.message
9601
+ });
9602
+ status.dirty();
9603
+ }
9604
+ } else if (check.kind === "length") {
9605
+ const tooBig = input.data.length > check.value;
9606
+ const tooSmall = input.data.length < check.value;
9607
+ if (tooBig || tooSmall) {
9608
+ ctx = this._getOrReturnCtx(input, ctx);
9609
+ if (tooBig) {
9610
+ addIssueToContext(ctx, {
9611
+ code: ZodIssueCode.too_big,
9612
+ maximum: check.value,
9613
+ type: "string",
9614
+ inclusive: true,
9615
+ exact: true,
9616
+ message: check.message
9617
+ });
9618
+ } else if (tooSmall) {
9619
+ addIssueToContext(ctx, {
9620
+ code: ZodIssueCode.too_small,
9621
+ minimum: check.value,
9622
+ type: "string",
9623
+ inclusive: true,
9624
+ exact: true,
9625
+ message: check.message
9626
+ });
9627
+ }
9628
+ status.dirty();
9629
+ }
9630
+ } else if (check.kind === "email") {
9631
+ if (!emailRegex.test(input.data)) {
9632
+ ctx = this._getOrReturnCtx(input, ctx);
9633
+ addIssueToContext(ctx, {
9634
+ validation: "email",
9635
+ code: ZodIssueCode.invalid_string,
9636
+ message: check.message
9637
+ });
9638
+ status.dirty();
9639
+ }
9640
+ } else if (check.kind === "emoji") {
9641
+ if (!emojiRegex) {
9642
+ emojiRegex = new RegExp(_emojiRegex, "u");
9643
+ }
9644
+ if (!emojiRegex.test(input.data)) {
9645
+ ctx = this._getOrReturnCtx(input, ctx);
9646
+ addIssueToContext(ctx, {
9647
+ validation: "emoji",
9648
+ code: ZodIssueCode.invalid_string,
9649
+ message: check.message
9650
+ });
9651
+ status.dirty();
9652
+ }
9653
+ } else if (check.kind === "uuid") {
9654
+ if (!uuidRegex.test(input.data)) {
9655
+ ctx = this._getOrReturnCtx(input, ctx);
9656
+ addIssueToContext(ctx, {
9657
+ validation: "uuid",
9658
+ code: ZodIssueCode.invalid_string,
9659
+ message: check.message
9660
+ });
9661
+ status.dirty();
9662
+ }
9663
+ } else if (check.kind === "nanoid") {
9664
+ if (!nanoidRegex.test(input.data)) {
9665
+ ctx = this._getOrReturnCtx(input, ctx);
9666
+ addIssueToContext(ctx, {
9667
+ validation: "nanoid",
9668
+ code: ZodIssueCode.invalid_string,
9669
+ message: check.message
9670
+ });
9671
+ status.dirty();
9672
+ }
9673
+ } else if (check.kind === "cuid") {
9674
+ if (!cuidRegex.test(input.data)) {
9675
+ ctx = this._getOrReturnCtx(input, ctx);
9676
+ addIssueToContext(ctx, {
9677
+ validation: "cuid",
9678
+ code: ZodIssueCode.invalid_string,
9679
+ message: check.message
9680
+ });
9681
+ status.dirty();
9682
+ }
9683
+ } else if (check.kind === "cuid2") {
9684
+ if (!cuid2Regex.test(input.data)) {
9685
+ ctx = this._getOrReturnCtx(input, ctx);
9686
+ addIssueToContext(ctx, {
9687
+ validation: "cuid2",
9688
+ code: ZodIssueCode.invalid_string,
9689
+ message: check.message
9690
+ });
9691
+ status.dirty();
9692
+ }
9693
+ } else if (check.kind === "ulid") {
9694
+ if (!ulidRegex.test(input.data)) {
9695
+ ctx = this._getOrReturnCtx(input, ctx);
9696
+ addIssueToContext(ctx, {
9697
+ validation: "ulid",
9698
+ code: ZodIssueCode.invalid_string,
9699
+ message: check.message
9700
+ });
9701
+ status.dirty();
9702
+ }
9703
+ } else if (check.kind === "url") {
9704
+ try {
9705
+ new URL(input.data);
9706
+ } catch {
9707
+ ctx = this._getOrReturnCtx(input, ctx);
9708
+ addIssueToContext(ctx, {
9709
+ validation: "url",
9710
+ code: ZodIssueCode.invalid_string,
9711
+ message: check.message
9712
+ });
9713
+ status.dirty();
9714
+ }
9715
+ } else if (check.kind === "regex") {
9716
+ check.regex.lastIndex = 0;
9717
+ const testResult = check.regex.test(input.data);
9718
+ if (!testResult) {
9719
+ ctx = this._getOrReturnCtx(input, ctx);
9720
+ addIssueToContext(ctx, {
9721
+ validation: "regex",
9722
+ code: ZodIssueCode.invalid_string,
9723
+ message: check.message
9724
+ });
9725
+ status.dirty();
9726
+ }
9727
+ } else if (check.kind === "trim") {
9728
+ input.data = input.data.trim();
9729
+ } else if (check.kind === "includes") {
9730
+ if (!input.data.includes(check.value, check.position)) {
9731
+ ctx = this._getOrReturnCtx(input, ctx);
9732
+ addIssueToContext(ctx, {
9733
+ code: ZodIssueCode.invalid_string,
9734
+ validation: { includes: check.value, position: check.position },
9735
+ message: check.message
9736
+ });
9737
+ status.dirty();
9738
+ }
9739
+ } else if (check.kind === "toLowerCase") {
9740
+ input.data = input.data.toLowerCase();
9741
+ } else if (check.kind === "toUpperCase") {
9742
+ input.data = input.data.toUpperCase();
9743
+ } else if (check.kind === "startsWith") {
9744
+ if (!input.data.startsWith(check.value)) {
9745
+ ctx = this._getOrReturnCtx(input, ctx);
9746
+ addIssueToContext(ctx, {
9747
+ code: ZodIssueCode.invalid_string,
9748
+ validation: { startsWith: check.value },
9749
+ message: check.message
9750
+ });
9751
+ status.dirty();
9752
+ }
9753
+ } else if (check.kind === "endsWith") {
9754
+ if (!input.data.endsWith(check.value)) {
9755
+ ctx = this._getOrReturnCtx(input, ctx);
9756
+ addIssueToContext(ctx, {
9757
+ code: ZodIssueCode.invalid_string,
9758
+ validation: { endsWith: check.value },
9759
+ message: check.message
9760
+ });
9761
+ status.dirty();
9762
+ }
9763
+ } else if (check.kind === "datetime") {
9764
+ const regex = datetimeRegex(check);
9765
+ if (!regex.test(input.data)) {
9766
+ ctx = this._getOrReturnCtx(input, ctx);
9767
+ addIssueToContext(ctx, {
9768
+ code: ZodIssueCode.invalid_string,
9769
+ validation: "datetime",
9770
+ message: check.message
9771
+ });
9772
+ status.dirty();
9773
+ }
9774
+ } else if (check.kind === "date") {
9775
+ const regex = dateRegex;
9776
+ if (!regex.test(input.data)) {
9777
+ ctx = this._getOrReturnCtx(input, ctx);
9778
+ addIssueToContext(ctx, {
9779
+ code: ZodIssueCode.invalid_string,
9780
+ validation: "date",
9781
+ message: check.message
9782
+ });
9783
+ status.dirty();
9784
+ }
9785
+ } else if (check.kind === "time") {
9786
+ const regex = timeRegex(check);
9787
+ if (!regex.test(input.data)) {
9788
+ ctx = this._getOrReturnCtx(input, ctx);
9789
+ addIssueToContext(ctx, {
9790
+ code: ZodIssueCode.invalid_string,
9791
+ validation: "time",
9792
+ message: check.message
9793
+ });
9794
+ status.dirty();
9795
+ }
9796
+ } else if (check.kind === "duration") {
9797
+ if (!durationRegex.test(input.data)) {
9798
+ ctx = this._getOrReturnCtx(input, ctx);
9799
+ addIssueToContext(ctx, {
9800
+ validation: "duration",
9801
+ code: ZodIssueCode.invalid_string,
9802
+ message: check.message
9803
+ });
9804
+ status.dirty();
9805
+ }
9806
+ } else if (check.kind === "ip") {
9807
+ if (!isValidIP(input.data, check.version)) {
9808
+ ctx = this._getOrReturnCtx(input, ctx);
9809
+ addIssueToContext(ctx, {
9810
+ validation: "ip",
9811
+ code: ZodIssueCode.invalid_string,
9812
+ message: check.message
9813
+ });
9814
+ status.dirty();
9815
+ }
9816
+ } else if (check.kind === "jwt") {
9817
+ if (!isValidJWT(input.data, check.alg)) {
9818
+ ctx = this._getOrReturnCtx(input, ctx);
9819
+ addIssueToContext(ctx, {
9820
+ validation: "jwt",
9821
+ code: ZodIssueCode.invalid_string,
9822
+ message: check.message
9823
+ });
9824
+ status.dirty();
9825
+ }
9826
+ } else if (check.kind === "cidr") {
9827
+ if (!isValidCidr(input.data, check.version)) {
9828
+ ctx = this._getOrReturnCtx(input, ctx);
9829
+ addIssueToContext(ctx, {
9830
+ validation: "cidr",
9831
+ code: ZodIssueCode.invalid_string,
9832
+ message: check.message
9833
+ });
9834
+ status.dirty();
9835
+ }
9836
+ } else if (check.kind === "base64") {
9837
+ if (!base64Regex.test(input.data)) {
9838
+ ctx = this._getOrReturnCtx(input, ctx);
9839
+ addIssueToContext(ctx, {
9840
+ validation: "base64",
9841
+ code: ZodIssueCode.invalid_string,
9842
+ message: check.message
9843
+ });
9844
+ status.dirty();
9845
+ }
9846
+ } else if (check.kind === "base64url") {
9847
+ if (!base64urlRegex.test(input.data)) {
9848
+ ctx = this._getOrReturnCtx(input, ctx);
9849
+ addIssueToContext(ctx, {
9850
+ validation: "base64url",
9851
+ code: ZodIssueCode.invalid_string,
9852
+ message: check.message
9853
+ });
9854
+ status.dirty();
9855
+ }
9856
+ } else {
9857
+ util.assertNever(check);
9858
+ }
9859
+ }
9860
+ return { status: status.value, value: input.data };
9861
+ }
9862
+ _regex(regex, validation, message) {
9863
+ return this.refinement((data) => regex.test(data), {
9864
+ validation,
9865
+ code: ZodIssueCode.invalid_string,
9866
+ ...errorUtil.errToObj(message)
9867
+ });
9868
+ }
9869
+ _addCheck(check) {
9870
+ return new _ZodString({
9871
+ ...this._def,
9872
+ checks: [...this._def.checks, check]
9873
+ });
9874
+ }
9875
+ email(message) {
9876
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
9877
+ }
9878
+ url(message) {
9879
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
9880
+ }
9881
+ emoji(message) {
9882
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
9883
+ }
9884
+ uuid(message) {
9885
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
9886
+ }
9887
+ nanoid(message) {
9888
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
9889
+ }
9890
+ cuid(message) {
9891
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
9892
+ }
9893
+ cuid2(message) {
9894
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
9895
+ }
9896
+ ulid(message) {
9897
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
9898
+ }
9899
+ base64(message) {
9900
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
9901
+ }
9902
+ base64url(message) {
9903
+ return this._addCheck({
9904
+ kind: "base64url",
9905
+ ...errorUtil.errToObj(message)
9906
+ });
9907
+ }
9908
+ jwt(options) {
9909
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
9910
+ }
9911
+ ip(options) {
9912
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
9913
+ }
9914
+ cidr(options) {
9915
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
9916
+ }
9917
+ datetime(options) {
9918
+ if (typeof options === "string") {
9919
+ return this._addCheck({
9920
+ kind: "datetime",
9921
+ precision: null,
9922
+ offset: false,
9923
+ local: false,
9924
+ message: options
9925
+ });
9926
+ }
9927
+ return this._addCheck({
9928
+ kind: "datetime",
9929
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
9930
+ offset: options?.offset ?? false,
9931
+ local: options?.local ?? false,
9932
+ ...errorUtil.errToObj(options?.message)
9933
+ });
9934
+ }
9935
+ date(message) {
9936
+ return this._addCheck({ kind: "date", message });
9937
+ }
9938
+ time(options) {
9939
+ if (typeof options === "string") {
9940
+ return this._addCheck({
9941
+ kind: "time",
9942
+ precision: null,
9943
+ message: options
9944
+ });
9945
+ }
9946
+ return this._addCheck({
9947
+ kind: "time",
9948
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
9949
+ ...errorUtil.errToObj(options?.message)
9950
+ });
9951
+ }
9952
+ duration(message) {
9953
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
9954
+ }
9955
+ regex(regex, message) {
9956
+ return this._addCheck({
9957
+ kind: "regex",
9958
+ regex,
9959
+ ...errorUtil.errToObj(message)
9960
+ });
9961
+ }
9962
+ includes(value, options) {
9963
+ return this._addCheck({
9964
+ kind: "includes",
9965
+ value,
9966
+ position: options?.position,
9967
+ ...errorUtil.errToObj(options?.message)
9968
+ });
9969
+ }
9970
+ startsWith(value, message) {
9971
+ return this._addCheck({
9972
+ kind: "startsWith",
9973
+ value,
9974
+ ...errorUtil.errToObj(message)
9975
+ });
9976
+ }
9977
+ endsWith(value, message) {
9978
+ return this._addCheck({
9979
+ kind: "endsWith",
9980
+ value,
9981
+ ...errorUtil.errToObj(message)
9982
+ });
9983
+ }
9984
+ min(minLength, message) {
9985
+ return this._addCheck({
9986
+ kind: "min",
9987
+ value: minLength,
9988
+ ...errorUtil.errToObj(message)
9989
+ });
9990
+ }
9991
+ max(maxLength, message) {
9992
+ return this._addCheck({
9993
+ kind: "max",
9994
+ value: maxLength,
9995
+ ...errorUtil.errToObj(message)
9996
+ });
9997
+ }
9998
+ length(len, message) {
9999
+ return this._addCheck({
10000
+ kind: "length",
10001
+ value: len,
10002
+ ...errorUtil.errToObj(message)
10003
+ });
10004
+ }
10005
+ /**
10006
+ * Equivalent to `.min(1)`
10007
+ */
10008
+ nonempty(message) {
10009
+ return this.min(1, errorUtil.errToObj(message));
10010
+ }
10011
+ trim() {
10012
+ return new _ZodString({
10013
+ ...this._def,
10014
+ checks: [...this._def.checks, { kind: "trim" }]
10015
+ });
10016
+ }
10017
+ toLowerCase() {
10018
+ return new _ZodString({
10019
+ ...this._def,
10020
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
10021
+ });
10022
+ }
10023
+ toUpperCase() {
10024
+ return new _ZodString({
10025
+ ...this._def,
10026
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
10027
+ });
10028
+ }
10029
+ get isDatetime() {
10030
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
10031
+ }
10032
+ get isDate() {
10033
+ return !!this._def.checks.find((ch) => ch.kind === "date");
10034
+ }
10035
+ get isTime() {
10036
+ return !!this._def.checks.find((ch) => ch.kind === "time");
10037
+ }
10038
+ get isDuration() {
10039
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
10040
+ }
10041
+ get isEmail() {
10042
+ return !!this._def.checks.find((ch) => ch.kind === "email");
10043
+ }
10044
+ get isURL() {
10045
+ return !!this._def.checks.find((ch) => ch.kind === "url");
10046
+ }
10047
+ get isEmoji() {
10048
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
10049
+ }
10050
+ get isUUID() {
10051
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
10052
+ }
10053
+ get isNANOID() {
10054
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
10055
+ }
10056
+ get isCUID() {
10057
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
10058
+ }
10059
+ get isCUID2() {
10060
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
10061
+ }
10062
+ get isULID() {
10063
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
10064
+ }
10065
+ get isIP() {
10066
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
10067
+ }
10068
+ get isCIDR() {
10069
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
10070
+ }
10071
+ get isBase64() {
10072
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
10073
+ }
10074
+ get isBase64url() {
10075
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
10076
+ }
10077
+ get minLength() {
10078
+ let min = null;
10079
+ for (const ch of this._def.checks) {
10080
+ if (ch.kind === "min") {
10081
+ if (min === null || ch.value > min)
10082
+ min = ch.value;
10083
+ }
10084
+ }
10085
+ return min;
10086
+ }
10087
+ get maxLength() {
10088
+ let max = null;
10089
+ for (const ch of this._def.checks) {
10090
+ if (ch.kind === "max") {
10091
+ if (max === null || ch.value < max)
10092
+ max = ch.value;
10093
+ }
10094
+ }
10095
+ return max;
10096
+ }
10097
+ };
10098
+ ZodString.create = (params) => {
10099
+ return new ZodString({
10100
+ checks: [],
10101
+ typeName: ZodFirstPartyTypeKind.ZodString,
10102
+ coerce: params?.coerce ?? false,
10103
+ ...processCreateParams(params)
10104
+ });
10105
+ };
10106
+ function floatSafeRemainder(val, step) {
10107
+ const valDecCount = (val.toString().split(".")[1] || "").length;
10108
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
10109
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
10110
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
10111
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
10112
+ return valInt % stepInt / 10 ** decCount;
10113
+ }
10114
+ var ZodNumber = class _ZodNumber extends ZodType {
10115
+ constructor() {
10116
+ super(...arguments);
10117
+ this.min = this.gte;
10118
+ this.max = this.lte;
10119
+ this.step = this.multipleOf;
10120
+ }
10121
+ _parse(input) {
10122
+ if (this._def.coerce) {
10123
+ input.data = Number(input.data);
10124
+ }
10125
+ const parsedType = this._getType(input);
10126
+ if (parsedType !== ZodParsedType.number) {
10127
+ const ctx2 = this._getOrReturnCtx(input);
10128
+ addIssueToContext(ctx2, {
10129
+ code: ZodIssueCode.invalid_type,
10130
+ expected: ZodParsedType.number,
10131
+ received: ctx2.parsedType
10132
+ });
10133
+ return INVALID;
10134
+ }
10135
+ let ctx = void 0;
10136
+ const status = new ParseStatus();
10137
+ for (const check of this._def.checks) {
10138
+ if (check.kind === "int") {
10139
+ if (!util.isInteger(input.data)) {
10140
+ ctx = this._getOrReturnCtx(input, ctx);
10141
+ addIssueToContext(ctx, {
10142
+ code: ZodIssueCode.invalid_type,
10143
+ expected: "integer",
10144
+ received: "float",
10145
+ message: check.message
10146
+ });
10147
+ status.dirty();
10148
+ }
10149
+ } else if (check.kind === "min") {
10150
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
10151
+ if (tooSmall) {
10152
+ ctx = this._getOrReturnCtx(input, ctx);
10153
+ addIssueToContext(ctx, {
10154
+ code: ZodIssueCode.too_small,
10155
+ minimum: check.value,
10156
+ type: "number",
10157
+ inclusive: check.inclusive,
10158
+ exact: false,
10159
+ message: check.message
10160
+ });
10161
+ status.dirty();
10162
+ }
10163
+ } else if (check.kind === "max") {
10164
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
10165
+ if (tooBig) {
10166
+ ctx = this._getOrReturnCtx(input, ctx);
10167
+ addIssueToContext(ctx, {
10168
+ code: ZodIssueCode.too_big,
10169
+ maximum: check.value,
10170
+ type: "number",
10171
+ inclusive: check.inclusive,
10172
+ exact: false,
10173
+ message: check.message
10174
+ });
10175
+ status.dirty();
10176
+ }
10177
+ } else if (check.kind === "multipleOf") {
10178
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
10179
+ ctx = this._getOrReturnCtx(input, ctx);
10180
+ addIssueToContext(ctx, {
10181
+ code: ZodIssueCode.not_multiple_of,
10182
+ multipleOf: check.value,
10183
+ message: check.message
10184
+ });
10185
+ status.dirty();
10186
+ }
10187
+ } else if (check.kind === "finite") {
10188
+ if (!Number.isFinite(input.data)) {
10189
+ ctx = this._getOrReturnCtx(input, ctx);
10190
+ addIssueToContext(ctx, {
10191
+ code: ZodIssueCode.not_finite,
10192
+ message: check.message
10193
+ });
10194
+ status.dirty();
10195
+ }
10196
+ } else {
10197
+ util.assertNever(check);
10198
+ }
10199
+ }
10200
+ return { status: status.value, value: input.data };
10201
+ }
10202
+ gte(value, message) {
10203
+ return this.setLimit("min", value, true, errorUtil.toString(message));
10204
+ }
10205
+ gt(value, message) {
10206
+ return this.setLimit("min", value, false, errorUtil.toString(message));
10207
+ }
10208
+ lte(value, message) {
10209
+ return this.setLimit("max", value, true, errorUtil.toString(message));
10210
+ }
10211
+ lt(value, message) {
10212
+ return this.setLimit("max", value, false, errorUtil.toString(message));
10213
+ }
10214
+ setLimit(kind, value, inclusive, message) {
10215
+ return new _ZodNumber({
10216
+ ...this._def,
10217
+ checks: [
10218
+ ...this._def.checks,
10219
+ {
10220
+ kind,
10221
+ value,
10222
+ inclusive,
10223
+ message: errorUtil.toString(message)
10224
+ }
10225
+ ]
10226
+ });
10227
+ }
10228
+ _addCheck(check) {
10229
+ return new _ZodNumber({
10230
+ ...this._def,
10231
+ checks: [...this._def.checks, check]
10232
+ });
10233
+ }
10234
+ int(message) {
10235
+ return this._addCheck({
10236
+ kind: "int",
10237
+ message: errorUtil.toString(message)
10238
+ });
10239
+ }
10240
+ positive(message) {
10241
+ return this._addCheck({
10242
+ kind: "min",
10243
+ value: 0,
10244
+ inclusive: false,
10245
+ message: errorUtil.toString(message)
10246
+ });
10247
+ }
10248
+ negative(message) {
10249
+ return this._addCheck({
10250
+ kind: "max",
10251
+ value: 0,
10252
+ inclusive: false,
10253
+ message: errorUtil.toString(message)
10254
+ });
10255
+ }
10256
+ nonpositive(message) {
10257
+ return this._addCheck({
10258
+ kind: "max",
10259
+ value: 0,
10260
+ inclusive: true,
10261
+ message: errorUtil.toString(message)
10262
+ });
10263
+ }
10264
+ nonnegative(message) {
10265
+ return this._addCheck({
10266
+ kind: "min",
10267
+ value: 0,
10268
+ inclusive: true,
10269
+ message: errorUtil.toString(message)
10270
+ });
10271
+ }
10272
+ multipleOf(value, message) {
10273
+ return this._addCheck({
10274
+ kind: "multipleOf",
10275
+ value,
10276
+ message: errorUtil.toString(message)
10277
+ });
10278
+ }
10279
+ finite(message) {
10280
+ return this._addCheck({
10281
+ kind: "finite",
10282
+ message: errorUtil.toString(message)
10283
+ });
10284
+ }
10285
+ safe(message) {
10286
+ return this._addCheck({
10287
+ kind: "min",
10288
+ inclusive: true,
10289
+ value: Number.MIN_SAFE_INTEGER,
10290
+ message: errorUtil.toString(message)
10291
+ })._addCheck({
10292
+ kind: "max",
10293
+ inclusive: true,
10294
+ value: Number.MAX_SAFE_INTEGER,
10295
+ message: errorUtil.toString(message)
10296
+ });
10297
+ }
10298
+ get minValue() {
10299
+ let min = null;
10300
+ for (const ch of this._def.checks) {
10301
+ if (ch.kind === "min") {
10302
+ if (min === null || ch.value > min)
10303
+ min = ch.value;
10304
+ }
10305
+ }
10306
+ return min;
10307
+ }
10308
+ get maxValue() {
10309
+ let max = null;
10310
+ for (const ch of this._def.checks) {
10311
+ if (ch.kind === "max") {
10312
+ if (max === null || ch.value < max)
10313
+ max = ch.value;
10314
+ }
10315
+ }
10316
+ return max;
10317
+ }
10318
+ get isInt() {
10319
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
10320
+ }
10321
+ get isFinite() {
10322
+ let max = null;
10323
+ let min = null;
10324
+ for (const ch of this._def.checks) {
10325
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
10326
+ return true;
10327
+ } else if (ch.kind === "min") {
10328
+ if (min === null || ch.value > min)
10329
+ min = ch.value;
10330
+ } else if (ch.kind === "max") {
10331
+ if (max === null || ch.value < max)
10332
+ max = ch.value;
10333
+ }
10334
+ }
10335
+ return Number.isFinite(min) && Number.isFinite(max);
10336
+ }
10337
+ };
10338
+ ZodNumber.create = (params) => {
10339
+ return new ZodNumber({
10340
+ checks: [],
10341
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
10342
+ coerce: params?.coerce || false,
10343
+ ...processCreateParams(params)
10344
+ });
10345
+ };
10346
+ var ZodBigInt = class _ZodBigInt extends ZodType {
10347
+ constructor() {
10348
+ super(...arguments);
10349
+ this.min = this.gte;
10350
+ this.max = this.lte;
10351
+ }
10352
+ _parse(input) {
10353
+ if (this._def.coerce) {
10354
+ try {
10355
+ input.data = BigInt(input.data);
10356
+ } catch {
10357
+ return this._getInvalidInput(input);
10358
+ }
10359
+ }
10360
+ const parsedType = this._getType(input);
10361
+ if (parsedType !== ZodParsedType.bigint) {
10362
+ return this._getInvalidInput(input);
10363
+ }
10364
+ let ctx = void 0;
10365
+ const status = new ParseStatus();
10366
+ for (const check of this._def.checks) {
10367
+ if (check.kind === "min") {
10368
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
10369
+ if (tooSmall) {
10370
+ ctx = this._getOrReturnCtx(input, ctx);
10371
+ addIssueToContext(ctx, {
10372
+ code: ZodIssueCode.too_small,
10373
+ type: "bigint",
10374
+ minimum: check.value,
10375
+ inclusive: check.inclusive,
10376
+ message: check.message
10377
+ });
10378
+ status.dirty();
10379
+ }
10380
+ } else if (check.kind === "max") {
10381
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
10382
+ if (tooBig) {
10383
+ ctx = this._getOrReturnCtx(input, ctx);
10384
+ addIssueToContext(ctx, {
10385
+ code: ZodIssueCode.too_big,
10386
+ type: "bigint",
10387
+ maximum: check.value,
10388
+ inclusive: check.inclusive,
10389
+ message: check.message
10390
+ });
10391
+ status.dirty();
10392
+ }
10393
+ } else if (check.kind === "multipleOf") {
10394
+ if (input.data % check.value !== BigInt(0)) {
10395
+ ctx = this._getOrReturnCtx(input, ctx);
10396
+ addIssueToContext(ctx, {
10397
+ code: ZodIssueCode.not_multiple_of,
10398
+ multipleOf: check.value,
10399
+ message: check.message
10400
+ });
10401
+ status.dirty();
10402
+ }
10403
+ } else {
10404
+ util.assertNever(check);
10405
+ }
10406
+ }
10407
+ return { status: status.value, value: input.data };
10408
+ }
10409
+ _getInvalidInput(input) {
10410
+ const ctx = this._getOrReturnCtx(input);
10411
+ addIssueToContext(ctx, {
10412
+ code: ZodIssueCode.invalid_type,
10413
+ expected: ZodParsedType.bigint,
10414
+ received: ctx.parsedType
10415
+ });
10416
+ return INVALID;
10417
+ }
10418
+ gte(value, message) {
10419
+ return this.setLimit("min", value, true, errorUtil.toString(message));
10420
+ }
10421
+ gt(value, message) {
10422
+ return this.setLimit("min", value, false, errorUtil.toString(message));
10423
+ }
10424
+ lte(value, message) {
10425
+ return this.setLimit("max", value, true, errorUtil.toString(message));
10426
+ }
10427
+ lt(value, message) {
10428
+ return this.setLimit("max", value, false, errorUtil.toString(message));
10429
+ }
10430
+ setLimit(kind, value, inclusive, message) {
10431
+ return new _ZodBigInt({
10432
+ ...this._def,
10433
+ checks: [
10434
+ ...this._def.checks,
10435
+ {
10436
+ kind,
10437
+ value,
10438
+ inclusive,
10439
+ message: errorUtil.toString(message)
10440
+ }
10441
+ ]
10442
+ });
10443
+ }
10444
+ _addCheck(check) {
10445
+ return new _ZodBigInt({
10446
+ ...this._def,
10447
+ checks: [...this._def.checks, check]
10448
+ });
10449
+ }
10450
+ positive(message) {
10451
+ return this._addCheck({
10452
+ kind: "min",
10453
+ value: BigInt(0),
10454
+ inclusive: false,
10455
+ message: errorUtil.toString(message)
10456
+ });
10457
+ }
10458
+ negative(message) {
10459
+ return this._addCheck({
10460
+ kind: "max",
10461
+ value: BigInt(0),
10462
+ inclusive: false,
10463
+ message: errorUtil.toString(message)
10464
+ });
10465
+ }
10466
+ nonpositive(message) {
10467
+ return this._addCheck({
10468
+ kind: "max",
10469
+ value: BigInt(0),
10470
+ inclusive: true,
10471
+ message: errorUtil.toString(message)
10472
+ });
10473
+ }
10474
+ nonnegative(message) {
10475
+ return this._addCheck({
10476
+ kind: "min",
10477
+ value: BigInt(0),
10478
+ inclusive: true,
10479
+ message: errorUtil.toString(message)
10480
+ });
10481
+ }
10482
+ multipleOf(value, message) {
10483
+ return this._addCheck({
10484
+ kind: "multipleOf",
10485
+ value,
10486
+ message: errorUtil.toString(message)
10487
+ });
10488
+ }
10489
+ get minValue() {
10490
+ let min = null;
10491
+ for (const ch of this._def.checks) {
10492
+ if (ch.kind === "min") {
10493
+ if (min === null || ch.value > min)
10494
+ min = ch.value;
10495
+ }
10496
+ }
10497
+ return min;
10498
+ }
10499
+ get maxValue() {
10500
+ let max = null;
10501
+ for (const ch of this._def.checks) {
10502
+ if (ch.kind === "max") {
10503
+ if (max === null || ch.value < max)
10504
+ max = ch.value;
10505
+ }
10506
+ }
10507
+ return max;
10508
+ }
10509
+ };
10510
+ ZodBigInt.create = (params) => {
10511
+ return new ZodBigInt({
10512
+ checks: [],
10513
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
10514
+ coerce: params?.coerce ?? false,
10515
+ ...processCreateParams(params)
10516
+ });
10517
+ };
10518
+ var ZodBoolean = class extends ZodType {
10519
+ _parse(input) {
10520
+ if (this._def.coerce) {
10521
+ input.data = Boolean(input.data);
10522
+ }
10523
+ const parsedType = this._getType(input);
10524
+ if (parsedType !== ZodParsedType.boolean) {
10525
+ const ctx = this._getOrReturnCtx(input);
10526
+ addIssueToContext(ctx, {
10527
+ code: ZodIssueCode.invalid_type,
10528
+ expected: ZodParsedType.boolean,
10529
+ received: ctx.parsedType
10530
+ });
10531
+ return INVALID;
10532
+ }
10533
+ return OK(input.data);
10534
+ }
10535
+ };
10536
+ ZodBoolean.create = (params) => {
10537
+ return new ZodBoolean({
10538
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
10539
+ coerce: params?.coerce || false,
10540
+ ...processCreateParams(params)
10541
+ });
10542
+ };
10543
+ var ZodDate = class _ZodDate extends ZodType {
10544
+ _parse(input) {
10545
+ if (this._def.coerce) {
10546
+ input.data = new Date(input.data);
10547
+ }
10548
+ const parsedType = this._getType(input);
10549
+ if (parsedType !== ZodParsedType.date) {
10550
+ const ctx2 = this._getOrReturnCtx(input);
10551
+ addIssueToContext(ctx2, {
10552
+ code: ZodIssueCode.invalid_type,
10553
+ expected: ZodParsedType.date,
10554
+ received: ctx2.parsedType
10555
+ });
10556
+ return INVALID;
10557
+ }
10558
+ if (Number.isNaN(input.data.getTime())) {
10559
+ const ctx2 = this._getOrReturnCtx(input);
10560
+ addIssueToContext(ctx2, {
10561
+ code: ZodIssueCode.invalid_date
10562
+ });
10563
+ return INVALID;
10564
+ }
10565
+ const status = new ParseStatus();
10566
+ let ctx = void 0;
10567
+ for (const check of this._def.checks) {
10568
+ if (check.kind === "min") {
10569
+ if (input.data.getTime() < check.value) {
10570
+ ctx = this._getOrReturnCtx(input, ctx);
10571
+ addIssueToContext(ctx, {
10572
+ code: ZodIssueCode.too_small,
10573
+ message: check.message,
10574
+ inclusive: true,
10575
+ exact: false,
10576
+ minimum: check.value,
10577
+ type: "date"
10578
+ });
10579
+ status.dirty();
10580
+ }
10581
+ } else if (check.kind === "max") {
10582
+ if (input.data.getTime() > check.value) {
10583
+ ctx = this._getOrReturnCtx(input, ctx);
10584
+ addIssueToContext(ctx, {
10585
+ code: ZodIssueCode.too_big,
10586
+ message: check.message,
10587
+ inclusive: true,
10588
+ exact: false,
10589
+ maximum: check.value,
10590
+ type: "date"
10591
+ });
10592
+ status.dirty();
10593
+ }
10594
+ } else {
10595
+ util.assertNever(check);
10596
+ }
10597
+ }
10598
+ return {
10599
+ status: status.value,
10600
+ value: new Date(input.data.getTime())
10601
+ };
10602
+ }
10603
+ _addCheck(check) {
10604
+ return new _ZodDate({
10605
+ ...this._def,
10606
+ checks: [...this._def.checks, check]
10607
+ });
10608
+ }
10609
+ min(minDate, message) {
10610
+ return this._addCheck({
10611
+ kind: "min",
10612
+ value: minDate.getTime(),
10613
+ message: errorUtil.toString(message)
10614
+ });
10615
+ }
10616
+ max(maxDate, message) {
10617
+ return this._addCheck({
10618
+ kind: "max",
10619
+ value: maxDate.getTime(),
10620
+ message: errorUtil.toString(message)
10621
+ });
10622
+ }
10623
+ get minDate() {
10624
+ let min = null;
10625
+ for (const ch of this._def.checks) {
10626
+ if (ch.kind === "min") {
10627
+ if (min === null || ch.value > min)
10628
+ min = ch.value;
10629
+ }
10630
+ }
10631
+ return min != null ? new Date(min) : null;
10632
+ }
10633
+ get maxDate() {
10634
+ let max = null;
10635
+ for (const ch of this._def.checks) {
10636
+ if (ch.kind === "max") {
10637
+ if (max === null || ch.value < max)
10638
+ max = ch.value;
10639
+ }
10640
+ }
10641
+ return max != null ? new Date(max) : null;
10642
+ }
10643
+ };
10644
+ ZodDate.create = (params) => {
10645
+ return new ZodDate({
10646
+ checks: [],
10647
+ coerce: params?.coerce || false,
10648
+ typeName: ZodFirstPartyTypeKind.ZodDate,
10649
+ ...processCreateParams(params)
10650
+ });
10651
+ };
10652
+ var ZodSymbol = class extends ZodType {
10653
+ _parse(input) {
10654
+ const parsedType = this._getType(input);
10655
+ if (parsedType !== ZodParsedType.symbol) {
10656
+ const ctx = this._getOrReturnCtx(input);
10657
+ addIssueToContext(ctx, {
10658
+ code: ZodIssueCode.invalid_type,
10659
+ expected: ZodParsedType.symbol,
10660
+ received: ctx.parsedType
10661
+ });
10662
+ return INVALID;
10663
+ }
10664
+ return OK(input.data);
10665
+ }
10666
+ };
10667
+ ZodSymbol.create = (params) => {
10668
+ return new ZodSymbol({
10669
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
10670
+ ...processCreateParams(params)
10671
+ });
10672
+ };
10673
+ var ZodUndefined = class extends ZodType {
10674
+ _parse(input) {
10675
+ const parsedType = this._getType(input);
10676
+ if (parsedType !== ZodParsedType.undefined) {
10677
+ const ctx = this._getOrReturnCtx(input);
10678
+ addIssueToContext(ctx, {
10679
+ code: ZodIssueCode.invalid_type,
10680
+ expected: ZodParsedType.undefined,
10681
+ received: ctx.parsedType
10682
+ });
10683
+ return INVALID;
10684
+ }
10685
+ return OK(input.data);
10686
+ }
10687
+ };
10688
+ ZodUndefined.create = (params) => {
10689
+ return new ZodUndefined({
10690
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
10691
+ ...processCreateParams(params)
10692
+ });
10693
+ };
10694
+ var ZodNull = class extends ZodType {
10695
+ _parse(input) {
10696
+ const parsedType = this._getType(input);
10697
+ if (parsedType !== ZodParsedType.null) {
10698
+ const ctx = this._getOrReturnCtx(input);
10699
+ addIssueToContext(ctx, {
10700
+ code: ZodIssueCode.invalid_type,
10701
+ expected: ZodParsedType.null,
10702
+ received: ctx.parsedType
10703
+ });
10704
+ return INVALID;
10705
+ }
10706
+ return OK(input.data);
10707
+ }
10708
+ };
10709
+ ZodNull.create = (params) => {
10710
+ return new ZodNull({
10711
+ typeName: ZodFirstPartyTypeKind.ZodNull,
10712
+ ...processCreateParams(params)
10713
+ });
10714
+ };
10715
+ var ZodAny = class extends ZodType {
10716
+ constructor() {
10717
+ super(...arguments);
10718
+ this._any = true;
10719
+ }
10720
+ _parse(input) {
10721
+ return OK(input.data);
10722
+ }
10723
+ };
10724
+ ZodAny.create = (params) => {
10725
+ return new ZodAny({
10726
+ typeName: ZodFirstPartyTypeKind.ZodAny,
10727
+ ...processCreateParams(params)
10728
+ });
10729
+ };
10730
+ var ZodUnknown = class extends ZodType {
10731
+ constructor() {
10732
+ super(...arguments);
10733
+ this._unknown = true;
10734
+ }
10735
+ _parse(input) {
10736
+ return OK(input.data);
10737
+ }
10738
+ };
10739
+ ZodUnknown.create = (params) => {
10740
+ return new ZodUnknown({
10741
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
10742
+ ...processCreateParams(params)
10743
+ });
10744
+ };
10745
+ var ZodNever = class extends ZodType {
10746
+ _parse(input) {
10747
+ const ctx = this._getOrReturnCtx(input);
10748
+ addIssueToContext(ctx, {
10749
+ code: ZodIssueCode.invalid_type,
10750
+ expected: ZodParsedType.never,
10751
+ received: ctx.parsedType
10752
+ });
10753
+ return INVALID;
10754
+ }
10755
+ };
10756
+ ZodNever.create = (params) => {
10757
+ return new ZodNever({
10758
+ typeName: ZodFirstPartyTypeKind.ZodNever,
10759
+ ...processCreateParams(params)
10760
+ });
10761
+ };
10762
+ var ZodVoid = class extends ZodType {
10763
+ _parse(input) {
10764
+ const parsedType = this._getType(input);
10765
+ if (parsedType !== ZodParsedType.undefined) {
10766
+ const ctx = this._getOrReturnCtx(input);
10767
+ addIssueToContext(ctx, {
10768
+ code: ZodIssueCode.invalid_type,
10769
+ expected: ZodParsedType.void,
10770
+ received: ctx.parsedType
10771
+ });
10772
+ return INVALID;
10773
+ }
10774
+ return OK(input.data);
10775
+ }
10776
+ };
10777
+ ZodVoid.create = (params) => {
10778
+ return new ZodVoid({
10779
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
10780
+ ...processCreateParams(params)
10781
+ });
10782
+ };
10783
+ var ZodArray = class _ZodArray extends ZodType {
10784
+ _parse(input) {
10785
+ const { ctx, status } = this._processInputParams(input);
10786
+ const def = this._def;
10787
+ if (ctx.parsedType !== ZodParsedType.array) {
10788
+ addIssueToContext(ctx, {
10789
+ code: ZodIssueCode.invalid_type,
10790
+ expected: ZodParsedType.array,
10791
+ received: ctx.parsedType
10792
+ });
10793
+ return INVALID;
10794
+ }
10795
+ if (def.exactLength !== null) {
10796
+ const tooBig = ctx.data.length > def.exactLength.value;
10797
+ const tooSmall = ctx.data.length < def.exactLength.value;
10798
+ if (tooBig || tooSmall) {
10799
+ addIssueToContext(ctx, {
10800
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
10801
+ minimum: tooSmall ? def.exactLength.value : void 0,
10802
+ maximum: tooBig ? def.exactLength.value : void 0,
10803
+ type: "array",
10804
+ inclusive: true,
10805
+ exact: true,
10806
+ message: def.exactLength.message
10807
+ });
10808
+ status.dirty();
10809
+ }
10810
+ }
10811
+ if (def.minLength !== null) {
10812
+ if (ctx.data.length < def.minLength.value) {
10813
+ addIssueToContext(ctx, {
10814
+ code: ZodIssueCode.too_small,
10815
+ minimum: def.minLength.value,
10816
+ type: "array",
10817
+ inclusive: true,
10818
+ exact: false,
10819
+ message: def.minLength.message
10820
+ });
10821
+ status.dirty();
10822
+ }
10823
+ }
10824
+ if (def.maxLength !== null) {
10825
+ if (ctx.data.length > def.maxLength.value) {
10826
+ addIssueToContext(ctx, {
10827
+ code: ZodIssueCode.too_big,
10828
+ maximum: def.maxLength.value,
10829
+ type: "array",
10830
+ inclusive: true,
10831
+ exact: false,
10832
+ message: def.maxLength.message
10833
+ });
10834
+ status.dirty();
10835
+ }
10836
+ }
10837
+ if (ctx.common.async) {
10838
+ return Promise.all([...ctx.data].map((item, i) => {
10839
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
10840
+ })).then((result2) => {
10841
+ return ParseStatus.mergeArray(status, result2);
10842
+ });
10843
+ }
10844
+ const result = [...ctx.data].map((item, i) => {
10845
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
10846
+ });
10847
+ return ParseStatus.mergeArray(status, result);
10848
+ }
10849
+ get element() {
10850
+ return this._def.type;
10851
+ }
10852
+ min(minLength, message) {
10853
+ return new _ZodArray({
10854
+ ...this._def,
10855
+ minLength: { value: minLength, message: errorUtil.toString(message) }
10856
+ });
10857
+ }
10858
+ max(maxLength, message) {
10859
+ return new _ZodArray({
10860
+ ...this._def,
10861
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
10862
+ });
10863
+ }
10864
+ length(len, message) {
10865
+ return new _ZodArray({
10866
+ ...this._def,
10867
+ exactLength: { value: len, message: errorUtil.toString(message) }
10868
+ });
10869
+ }
10870
+ nonempty(message) {
10871
+ return this.min(1, message);
10872
+ }
10873
+ };
10874
+ ZodArray.create = (schema, params) => {
10875
+ return new ZodArray({
10876
+ type: schema,
10877
+ minLength: null,
10878
+ maxLength: null,
10879
+ exactLength: null,
10880
+ typeName: ZodFirstPartyTypeKind.ZodArray,
10881
+ ...processCreateParams(params)
10882
+ });
10883
+ };
10884
+ function deepPartialify(schema) {
10885
+ if (schema instanceof ZodObject) {
10886
+ const newShape = {};
10887
+ for (const key in schema.shape) {
10888
+ const fieldSchema = schema.shape[key];
10889
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
10890
+ }
10891
+ return new ZodObject({
10892
+ ...schema._def,
10893
+ shape: () => newShape
10894
+ });
10895
+ } else if (schema instanceof ZodArray) {
10896
+ return new ZodArray({
10897
+ ...schema._def,
10898
+ type: deepPartialify(schema.element)
10899
+ });
10900
+ } else if (schema instanceof ZodOptional) {
10901
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
10902
+ } else if (schema instanceof ZodNullable) {
10903
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
10904
+ } else if (schema instanceof ZodTuple) {
10905
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
10906
+ } else {
10907
+ return schema;
10908
+ }
10909
+ }
10910
+ var ZodObject = class _ZodObject extends ZodType {
10911
+ constructor() {
10912
+ super(...arguments);
10913
+ this._cached = null;
10914
+ this.nonstrict = this.passthrough;
10915
+ this.augment = this.extend;
10916
+ }
10917
+ _getCached() {
10918
+ if (this._cached !== null)
10919
+ return this._cached;
10920
+ const shape = this._def.shape();
10921
+ const keys = util.objectKeys(shape);
10922
+ this._cached = { shape, keys };
10923
+ return this._cached;
10924
+ }
10925
+ _parse(input) {
10926
+ const parsedType = this._getType(input);
10927
+ if (parsedType !== ZodParsedType.object) {
10928
+ const ctx2 = this._getOrReturnCtx(input);
10929
+ addIssueToContext(ctx2, {
10930
+ code: ZodIssueCode.invalid_type,
10931
+ expected: ZodParsedType.object,
10932
+ received: ctx2.parsedType
10933
+ });
10934
+ return INVALID;
10935
+ }
10936
+ const { status, ctx } = this._processInputParams(input);
10937
+ const { shape, keys: shapeKeys } = this._getCached();
10938
+ const extraKeys = [];
10939
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
10940
+ for (const key in ctx.data) {
10941
+ if (!shapeKeys.includes(key)) {
10942
+ extraKeys.push(key);
10943
+ }
10944
+ }
10945
+ }
10946
+ const pairs = [];
10947
+ for (const key of shapeKeys) {
10948
+ const keyValidator = shape[key];
10949
+ const value = ctx.data[key];
10950
+ pairs.push({
10951
+ key: { status: "valid", value: key },
10952
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
10953
+ alwaysSet: key in ctx.data
10954
+ });
10955
+ }
10956
+ if (this._def.catchall instanceof ZodNever) {
10957
+ const unknownKeys = this._def.unknownKeys;
10958
+ if (unknownKeys === "passthrough") {
10959
+ for (const key of extraKeys) {
10960
+ pairs.push({
10961
+ key: { status: "valid", value: key },
10962
+ value: { status: "valid", value: ctx.data[key] }
10963
+ });
10964
+ }
10965
+ } else if (unknownKeys === "strict") {
10966
+ if (extraKeys.length > 0) {
10967
+ addIssueToContext(ctx, {
10968
+ code: ZodIssueCode.unrecognized_keys,
10969
+ keys: extraKeys
10970
+ });
10971
+ status.dirty();
10972
+ }
10973
+ } else if (unknownKeys === "strip") {
10974
+ } else {
10975
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
10976
+ }
10977
+ } else {
10978
+ const catchall = this._def.catchall;
10979
+ for (const key of extraKeys) {
10980
+ const value = ctx.data[key];
10981
+ pairs.push({
10982
+ key: { status: "valid", value: key },
10983
+ value: catchall._parse(
10984
+ new ParseInputLazyPath(ctx, value, ctx.path, key)
10985
+ //, ctx.child(key), value, getParsedType(value)
10986
+ ),
10987
+ alwaysSet: key in ctx.data
10988
+ });
10989
+ }
10990
+ }
10991
+ if (ctx.common.async) {
10992
+ return Promise.resolve().then(async () => {
10993
+ const syncPairs = [];
10994
+ for (const pair of pairs) {
10995
+ const key = await pair.key;
10996
+ const value = await pair.value;
10997
+ syncPairs.push({
10998
+ key,
10999
+ value,
11000
+ alwaysSet: pair.alwaysSet
11001
+ });
11002
+ }
11003
+ return syncPairs;
11004
+ }).then((syncPairs) => {
11005
+ return ParseStatus.mergeObjectSync(status, syncPairs);
11006
+ });
11007
+ } else {
11008
+ return ParseStatus.mergeObjectSync(status, pairs);
11009
+ }
11010
+ }
11011
+ get shape() {
11012
+ return this._def.shape();
11013
+ }
11014
+ strict(message) {
11015
+ errorUtil.errToObj;
11016
+ return new _ZodObject({
11017
+ ...this._def,
11018
+ unknownKeys: "strict",
11019
+ ...message !== void 0 ? {
11020
+ errorMap: (issue, ctx) => {
11021
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
11022
+ if (issue.code === "unrecognized_keys")
11023
+ return {
11024
+ message: errorUtil.errToObj(message).message ?? defaultError
11025
+ };
11026
+ return {
11027
+ message: defaultError
11028
+ };
11029
+ }
11030
+ } : {}
11031
+ });
11032
+ }
11033
+ strip() {
11034
+ return new _ZodObject({
11035
+ ...this._def,
11036
+ unknownKeys: "strip"
11037
+ });
11038
+ }
11039
+ passthrough() {
11040
+ return new _ZodObject({
11041
+ ...this._def,
11042
+ unknownKeys: "passthrough"
11043
+ });
11044
+ }
11045
+ // const AugmentFactory =
11046
+ // <Def extends ZodObjectDef>(def: Def) =>
11047
+ // <Augmentation extends ZodRawShape>(
11048
+ // augmentation: Augmentation
11049
+ // ): ZodObject<
11050
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
11051
+ // Def["unknownKeys"],
11052
+ // Def["catchall"]
11053
+ // > => {
11054
+ // return new ZodObject({
11055
+ // ...def,
11056
+ // shape: () => ({
11057
+ // ...def.shape(),
11058
+ // ...augmentation,
11059
+ // }),
11060
+ // }) as any;
11061
+ // };
11062
+ extend(augmentation) {
11063
+ return new _ZodObject({
11064
+ ...this._def,
11065
+ shape: () => ({
11066
+ ...this._def.shape(),
11067
+ ...augmentation
11068
+ })
11069
+ });
11070
+ }
11071
+ /**
11072
+ * Prior to zod@1.0.12 there was a bug in the
11073
+ * inferred type of merged objects. Please
11074
+ * upgrade if you are experiencing issues.
11075
+ */
11076
+ merge(merging) {
11077
+ const merged = new _ZodObject({
11078
+ unknownKeys: merging._def.unknownKeys,
11079
+ catchall: merging._def.catchall,
11080
+ shape: () => ({
11081
+ ...this._def.shape(),
11082
+ ...merging._def.shape()
11083
+ }),
11084
+ typeName: ZodFirstPartyTypeKind.ZodObject
11085
+ });
11086
+ return merged;
11087
+ }
11088
+ // merge<
11089
+ // Incoming extends AnyZodObject,
11090
+ // Augmentation extends Incoming["shape"],
11091
+ // NewOutput extends {
11092
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
11093
+ // ? Augmentation[k]["_output"]
11094
+ // : k extends keyof Output
11095
+ // ? Output[k]
11096
+ // : never;
11097
+ // },
11098
+ // NewInput extends {
11099
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
11100
+ // ? Augmentation[k]["_input"]
11101
+ // : k extends keyof Input
11102
+ // ? Input[k]
11103
+ // : never;
11104
+ // }
11105
+ // >(
11106
+ // merging: Incoming
11107
+ // ): ZodObject<
11108
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
11109
+ // Incoming["_def"]["unknownKeys"],
11110
+ // Incoming["_def"]["catchall"],
11111
+ // NewOutput,
11112
+ // NewInput
11113
+ // > {
11114
+ // const merged: any = new ZodObject({
11115
+ // unknownKeys: merging._def.unknownKeys,
11116
+ // catchall: merging._def.catchall,
11117
+ // shape: () =>
11118
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
11119
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
11120
+ // }) as any;
11121
+ // return merged;
11122
+ // }
11123
+ setKey(key, schema) {
11124
+ return this.augment({ [key]: schema });
11125
+ }
11126
+ // merge<Incoming extends AnyZodObject>(
11127
+ // merging: Incoming
11128
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
11129
+ // ZodObject<
11130
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
11131
+ // Incoming["_def"]["unknownKeys"],
11132
+ // Incoming["_def"]["catchall"]
11133
+ // > {
11134
+ // // const mergedShape = objectUtil.mergeShapes(
11135
+ // // this._def.shape(),
11136
+ // // merging._def.shape()
11137
+ // // );
11138
+ // const merged: any = new ZodObject({
11139
+ // unknownKeys: merging._def.unknownKeys,
11140
+ // catchall: merging._def.catchall,
11141
+ // shape: () =>
11142
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
11143
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
11144
+ // }) as any;
11145
+ // return merged;
11146
+ // }
11147
+ catchall(index) {
11148
+ return new _ZodObject({
11149
+ ...this._def,
11150
+ catchall: index
11151
+ });
11152
+ }
11153
+ pick(mask) {
11154
+ const shape = {};
11155
+ for (const key of util.objectKeys(mask)) {
11156
+ if (mask[key] && this.shape[key]) {
11157
+ shape[key] = this.shape[key];
11158
+ }
11159
+ }
11160
+ return new _ZodObject({
11161
+ ...this._def,
11162
+ shape: () => shape
11163
+ });
11164
+ }
11165
+ omit(mask) {
11166
+ const shape = {};
11167
+ for (const key of util.objectKeys(this.shape)) {
11168
+ if (!mask[key]) {
11169
+ shape[key] = this.shape[key];
11170
+ }
11171
+ }
11172
+ return new _ZodObject({
11173
+ ...this._def,
11174
+ shape: () => shape
11175
+ });
11176
+ }
11177
+ /**
11178
+ * @deprecated
11179
+ */
11180
+ deepPartial() {
11181
+ return deepPartialify(this);
11182
+ }
11183
+ partial(mask) {
11184
+ const newShape = {};
11185
+ for (const key of util.objectKeys(this.shape)) {
11186
+ const fieldSchema = this.shape[key];
11187
+ if (mask && !mask[key]) {
11188
+ newShape[key] = fieldSchema;
11189
+ } else {
11190
+ newShape[key] = fieldSchema.optional();
11191
+ }
11192
+ }
11193
+ return new _ZodObject({
11194
+ ...this._def,
11195
+ shape: () => newShape
11196
+ });
11197
+ }
11198
+ required(mask) {
11199
+ const newShape = {};
11200
+ for (const key of util.objectKeys(this.shape)) {
11201
+ if (mask && !mask[key]) {
11202
+ newShape[key] = this.shape[key];
11203
+ } else {
11204
+ const fieldSchema = this.shape[key];
11205
+ let newField = fieldSchema;
11206
+ while (newField instanceof ZodOptional) {
11207
+ newField = newField._def.innerType;
11208
+ }
11209
+ newShape[key] = newField;
11210
+ }
11211
+ }
11212
+ return new _ZodObject({
11213
+ ...this._def,
11214
+ shape: () => newShape
11215
+ });
11216
+ }
11217
+ keyof() {
11218
+ return createZodEnum(util.objectKeys(this.shape));
11219
+ }
11220
+ };
11221
+ ZodObject.create = (shape, params) => {
11222
+ return new ZodObject({
11223
+ shape: () => shape,
11224
+ unknownKeys: "strip",
11225
+ catchall: ZodNever.create(),
11226
+ typeName: ZodFirstPartyTypeKind.ZodObject,
11227
+ ...processCreateParams(params)
11228
+ });
11229
+ };
11230
+ ZodObject.strictCreate = (shape, params) => {
11231
+ return new ZodObject({
11232
+ shape: () => shape,
11233
+ unknownKeys: "strict",
11234
+ catchall: ZodNever.create(),
11235
+ typeName: ZodFirstPartyTypeKind.ZodObject,
11236
+ ...processCreateParams(params)
11237
+ });
11238
+ };
11239
+ ZodObject.lazycreate = (shape, params) => {
11240
+ return new ZodObject({
11241
+ shape,
11242
+ unknownKeys: "strip",
11243
+ catchall: ZodNever.create(),
11244
+ typeName: ZodFirstPartyTypeKind.ZodObject,
11245
+ ...processCreateParams(params)
11246
+ });
11247
+ };
11248
+ var ZodUnion = class extends ZodType {
11249
+ _parse(input) {
11250
+ const { ctx } = this._processInputParams(input);
11251
+ const options = this._def.options;
11252
+ function handleResults(results) {
11253
+ for (const result of results) {
11254
+ if (result.result.status === "valid") {
11255
+ return result.result;
11256
+ }
11257
+ }
11258
+ for (const result of results) {
11259
+ if (result.result.status === "dirty") {
11260
+ ctx.common.issues.push(...result.ctx.common.issues);
11261
+ return result.result;
11262
+ }
11263
+ }
11264
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
11265
+ addIssueToContext(ctx, {
11266
+ code: ZodIssueCode.invalid_union,
11267
+ unionErrors
11268
+ });
11269
+ return INVALID;
11270
+ }
11271
+ if (ctx.common.async) {
11272
+ return Promise.all(options.map(async (option) => {
11273
+ const childCtx = {
11274
+ ...ctx,
11275
+ common: {
11276
+ ...ctx.common,
11277
+ issues: []
11278
+ },
11279
+ parent: null
11280
+ };
11281
+ return {
11282
+ result: await option._parseAsync({
11283
+ data: ctx.data,
11284
+ path: ctx.path,
11285
+ parent: childCtx
11286
+ }),
11287
+ ctx: childCtx
11288
+ };
11289
+ })).then(handleResults);
11290
+ } else {
11291
+ let dirty = void 0;
11292
+ const issues = [];
11293
+ for (const option of options) {
11294
+ const childCtx = {
11295
+ ...ctx,
11296
+ common: {
11297
+ ...ctx.common,
11298
+ issues: []
11299
+ },
11300
+ parent: null
11301
+ };
11302
+ const result = option._parseSync({
11303
+ data: ctx.data,
11304
+ path: ctx.path,
11305
+ parent: childCtx
11306
+ });
11307
+ if (result.status === "valid") {
11308
+ return result;
11309
+ } else if (result.status === "dirty" && !dirty) {
11310
+ dirty = { result, ctx: childCtx };
11311
+ }
11312
+ if (childCtx.common.issues.length) {
11313
+ issues.push(childCtx.common.issues);
11314
+ }
11315
+ }
11316
+ if (dirty) {
11317
+ ctx.common.issues.push(...dirty.ctx.common.issues);
11318
+ return dirty.result;
11319
+ }
11320
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
11321
+ addIssueToContext(ctx, {
11322
+ code: ZodIssueCode.invalid_union,
11323
+ unionErrors
11324
+ });
11325
+ return INVALID;
11326
+ }
11327
+ }
11328
+ get options() {
11329
+ return this._def.options;
11330
+ }
11331
+ };
11332
+ ZodUnion.create = (types, params) => {
11333
+ return new ZodUnion({
11334
+ options: types,
11335
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
11336
+ ...processCreateParams(params)
11337
+ });
11338
+ };
11339
+ var getDiscriminator = (type) => {
11340
+ if (type instanceof ZodLazy) {
11341
+ return getDiscriminator(type.schema);
11342
+ } else if (type instanceof ZodEffects) {
11343
+ return getDiscriminator(type.innerType());
11344
+ } else if (type instanceof ZodLiteral) {
11345
+ return [type.value];
11346
+ } else if (type instanceof ZodEnum) {
11347
+ return type.options;
11348
+ } else if (type instanceof ZodNativeEnum) {
11349
+ return util.objectValues(type.enum);
11350
+ } else if (type instanceof ZodDefault) {
11351
+ return getDiscriminator(type._def.innerType);
11352
+ } else if (type instanceof ZodUndefined) {
11353
+ return [void 0];
11354
+ } else if (type instanceof ZodNull) {
11355
+ return [null];
11356
+ } else if (type instanceof ZodOptional) {
11357
+ return [void 0, ...getDiscriminator(type.unwrap())];
11358
+ } else if (type instanceof ZodNullable) {
11359
+ return [null, ...getDiscriminator(type.unwrap())];
11360
+ } else if (type instanceof ZodBranded) {
11361
+ return getDiscriminator(type.unwrap());
11362
+ } else if (type instanceof ZodReadonly) {
11363
+ return getDiscriminator(type.unwrap());
11364
+ } else if (type instanceof ZodCatch) {
11365
+ return getDiscriminator(type._def.innerType);
11366
+ } else {
11367
+ return [];
11368
+ }
11369
+ };
11370
+ var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
11371
+ _parse(input) {
11372
+ const { ctx } = this._processInputParams(input);
11373
+ if (ctx.parsedType !== ZodParsedType.object) {
11374
+ addIssueToContext(ctx, {
11375
+ code: ZodIssueCode.invalid_type,
11376
+ expected: ZodParsedType.object,
11377
+ received: ctx.parsedType
11378
+ });
11379
+ return INVALID;
11380
+ }
11381
+ const discriminator = this.discriminator;
11382
+ const discriminatorValue = ctx.data[discriminator];
11383
+ const option = this.optionsMap.get(discriminatorValue);
11384
+ if (!option) {
11385
+ addIssueToContext(ctx, {
11386
+ code: ZodIssueCode.invalid_union_discriminator,
11387
+ options: Array.from(this.optionsMap.keys()),
11388
+ path: [discriminator]
11389
+ });
11390
+ return INVALID;
11391
+ }
11392
+ if (ctx.common.async) {
11393
+ return option._parseAsync({
11394
+ data: ctx.data,
11395
+ path: ctx.path,
11396
+ parent: ctx
11397
+ });
11398
+ } else {
11399
+ return option._parseSync({
11400
+ data: ctx.data,
11401
+ path: ctx.path,
11402
+ parent: ctx
11403
+ });
11404
+ }
11405
+ }
11406
+ get discriminator() {
11407
+ return this._def.discriminator;
11408
+ }
11409
+ get options() {
11410
+ return this._def.options;
11411
+ }
11412
+ get optionsMap() {
11413
+ return this._def.optionsMap;
11414
+ }
11415
+ /**
11416
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
11417
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
11418
+ * have a different value for each object in the union.
11419
+ * @param discriminator the name of the discriminator property
11420
+ * @param types an array of object schemas
11421
+ * @param params
11422
+ */
11423
+ static create(discriminator, options, params) {
11424
+ const optionsMap = /* @__PURE__ */ new Map();
11425
+ for (const type of options) {
11426
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
11427
+ if (!discriminatorValues.length) {
11428
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
11429
+ }
11430
+ for (const value of discriminatorValues) {
11431
+ if (optionsMap.has(value)) {
11432
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
11433
+ }
11434
+ optionsMap.set(value, type);
11435
+ }
11436
+ }
11437
+ return new _ZodDiscriminatedUnion({
11438
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
11439
+ discriminator,
11440
+ options,
11441
+ optionsMap,
11442
+ ...processCreateParams(params)
11443
+ });
11444
+ }
11445
+ };
11446
+ function mergeValues(a, b) {
11447
+ const aType = getParsedType(a);
11448
+ const bType = getParsedType(b);
11449
+ if (a === b) {
11450
+ return { valid: true, data: a };
11451
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
11452
+ const bKeys = util.objectKeys(b);
11453
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
11454
+ const newObj = { ...a, ...b };
11455
+ for (const key of sharedKeys) {
11456
+ const sharedValue = mergeValues(a[key], b[key]);
11457
+ if (!sharedValue.valid) {
11458
+ return { valid: false };
11459
+ }
11460
+ newObj[key] = sharedValue.data;
11461
+ }
11462
+ return { valid: true, data: newObj };
11463
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
11464
+ if (a.length !== b.length) {
11465
+ return { valid: false };
11466
+ }
11467
+ const newArray = [];
11468
+ for (let index = 0; index < a.length; index++) {
11469
+ const itemA = a[index];
11470
+ const itemB = b[index];
11471
+ const sharedValue = mergeValues(itemA, itemB);
11472
+ if (!sharedValue.valid) {
11473
+ return { valid: false };
11474
+ }
11475
+ newArray.push(sharedValue.data);
11476
+ }
11477
+ return { valid: true, data: newArray };
11478
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
11479
+ return { valid: true, data: a };
11480
+ } else {
11481
+ return { valid: false };
11482
+ }
11483
+ }
11484
+ var ZodIntersection = class extends ZodType {
11485
+ _parse(input) {
11486
+ const { status, ctx } = this._processInputParams(input);
11487
+ const handleParsed = (parsedLeft, parsedRight) => {
11488
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
11489
+ return INVALID;
11490
+ }
11491
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
11492
+ if (!merged.valid) {
11493
+ addIssueToContext(ctx, {
11494
+ code: ZodIssueCode.invalid_intersection_types
11495
+ });
11496
+ return INVALID;
11497
+ }
11498
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
11499
+ status.dirty();
11500
+ }
11501
+ return { status: status.value, value: merged.data };
11502
+ };
11503
+ if (ctx.common.async) {
11504
+ return Promise.all([
11505
+ this._def.left._parseAsync({
11506
+ data: ctx.data,
11507
+ path: ctx.path,
11508
+ parent: ctx
11509
+ }),
11510
+ this._def.right._parseAsync({
11511
+ data: ctx.data,
11512
+ path: ctx.path,
11513
+ parent: ctx
11514
+ })
11515
+ ]).then(([left, right]) => handleParsed(left, right));
11516
+ } else {
11517
+ return handleParsed(this._def.left._parseSync({
11518
+ data: ctx.data,
11519
+ path: ctx.path,
11520
+ parent: ctx
11521
+ }), this._def.right._parseSync({
11522
+ data: ctx.data,
11523
+ path: ctx.path,
11524
+ parent: ctx
11525
+ }));
11526
+ }
11527
+ }
11528
+ };
11529
+ ZodIntersection.create = (left, right, params) => {
11530
+ return new ZodIntersection({
11531
+ left,
11532
+ right,
11533
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
11534
+ ...processCreateParams(params)
11535
+ });
11536
+ };
11537
+ var ZodTuple = class _ZodTuple extends ZodType {
11538
+ _parse(input) {
11539
+ const { status, ctx } = this._processInputParams(input);
11540
+ if (ctx.parsedType !== ZodParsedType.array) {
11541
+ addIssueToContext(ctx, {
11542
+ code: ZodIssueCode.invalid_type,
11543
+ expected: ZodParsedType.array,
11544
+ received: ctx.parsedType
11545
+ });
11546
+ return INVALID;
11547
+ }
11548
+ if (ctx.data.length < this._def.items.length) {
11549
+ addIssueToContext(ctx, {
11550
+ code: ZodIssueCode.too_small,
11551
+ minimum: this._def.items.length,
11552
+ inclusive: true,
11553
+ exact: false,
11554
+ type: "array"
11555
+ });
11556
+ return INVALID;
11557
+ }
11558
+ const rest = this._def.rest;
11559
+ if (!rest && ctx.data.length > this._def.items.length) {
11560
+ addIssueToContext(ctx, {
11561
+ code: ZodIssueCode.too_big,
11562
+ maximum: this._def.items.length,
11563
+ inclusive: true,
11564
+ exact: false,
11565
+ type: "array"
11566
+ });
11567
+ status.dirty();
11568
+ }
11569
+ const items = [...ctx.data].map((item, itemIndex) => {
11570
+ const schema = this._def.items[itemIndex] || this._def.rest;
11571
+ if (!schema)
11572
+ return null;
11573
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
11574
+ }).filter((x) => !!x);
11575
+ if (ctx.common.async) {
11576
+ return Promise.all(items).then((results) => {
11577
+ return ParseStatus.mergeArray(status, results);
11578
+ });
11579
+ } else {
11580
+ return ParseStatus.mergeArray(status, items);
11581
+ }
11582
+ }
11583
+ get items() {
11584
+ return this._def.items;
11585
+ }
11586
+ rest(rest) {
11587
+ return new _ZodTuple({
11588
+ ...this._def,
11589
+ rest
11590
+ });
11591
+ }
11592
+ };
11593
+ ZodTuple.create = (schemas, params) => {
11594
+ if (!Array.isArray(schemas)) {
11595
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
11596
+ }
11597
+ return new ZodTuple({
11598
+ items: schemas,
11599
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
11600
+ rest: null,
11601
+ ...processCreateParams(params)
11602
+ });
11603
+ };
11604
+ var ZodRecord = class _ZodRecord extends ZodType {
11605
+ get keySchema() {
11606
+ return this._def.keyType;
11607
+ }
11608
+ get valueSchema() {
11609
+ return this._def.valueType;
11610
+ }
11611
+ _parse(input) {
11612
+ const { status, ctx } = this._processInputParams(input);
11613
+ if (ctx.parsedType !== ZodParsedType.object) {
11614
+ addIssueToContext(ctx, {
11615
+ code: ZodIssueCode.invalid_type,
11616
+ expected: ZodParsedType.object,
11617
+ received: ctx.parsedType
11618
+ });
11619
+ return INVALID;
11620
+ }
11621
+ const pairs = [];
11622
+ const keyType = this._def.keyType;
11623
+ const valueType = this._def.valueType;
11624
+ for (const key in ctx.data) {
11625
+ pairs.push({
11626
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
11627
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
11628
+ alwaysSet: key in ctx.data
11629
+ });
11630
+ }
11631
+ if (ctx.common.async) {
11632
+ return ParseStatus.mergeObjectAsync(status, pairs);
11633
+ } else {
11634
+ return ParseStatus.mergeObjectSync(status, pairs);
11635
+ }
11636
+ }
11637
+ get element() {
11638
+ return this._def.valueType;
11639
+ }
11640
+ static create(first, second, third) {
11641
+ if (second instanceof ZodType) {
11642
+ return new _ZodRecord({
11643
+ keyType: first,
11644
+ valueType: second,
11645
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
11646
+ ...processCreateParams(third)
11647
+ });
11648
+ }
11649
+ return new _ZodRecord({
11650
+ keyType: ZodString.create(),
11651
+ valueType: first,
11652
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
11653
+ ...processCreateParams(second)
11654
+ });
11655
+ }
11656
+ };
11657
+ var ZodMap = class extends ZodType {
11658
+ get keySchema() {
11659
+ return this._def.keyType;
11660
+ }
11661
+ get valueSchema() {
11662
+ return this._def.valueType;
11663
+ }
11664
+ _parse(input) {
11665
+ const { status, ctx } = this._processInputParams(input);
11666
+ if (ctx.parsedType !== ZodParsedType.map) {
11667
+ addIssueToContext(ctx, {
11668
+ code: ZodIssueCode.invalid_type,
11669
+ expected: ZodParsedType.map,
11670
+ received: ctx.parsedType
11671
+ });
11672
+ return INVALID;
11673
+ }
11674
+ const keyType = this._def.keyType;
11675
+ const valueType = this._def.valueType;
11676
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
11677
+ return {
11678
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
11679
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
11680
+ };
11681
+ });
11682
+ if (ctx.common.async) {
11683
+ const finalMap = /* @__PURE__ */ new Map();
11684
+ return Promise.resolve().then(async () => {
11685
+ for (const pair of pairs) {
11686
+ const key = await pair.key;
11687
+ const value = await pair.value;
11688
+ if (key.status === "aborted" || value.status === "aborted") {
11689
+ return INVALID;
11690
+ }
11691
+ if (key.status === "dirty" || value.status === "dirty") {
11692
+ status.dirty();
11693
+ }
11694
+ finalMap.set(key.value, value.value);
11695
+ }
11696
+ return { status: status.value, value: finalMap };
11697
+ });
11698
+ } else {
11699
+ const finalMap = /* @__PURE__ */ new Map();
11700
+ for (const pair of pairs) {
11701
+ const key = pair.key;
11702
+ const value = pair.value;
11703
+ if (key.status === "aborted" || value.status === "aborted") {
11704
+ return INVALID;
11705
+ }
11706
+ if (key.status === "dirty" || value.status === "dirty") {
11707
+ status.dirty();
11708
+ }
11709
+ finalMap.set(key.value, value.value);
11710
+ }
11711
+ return { status: status.value, value: finalMap };
11712
+ }
11713
+ }
11714
+ };
11715
+ ZodMap.create = (keyType, valueType, params) => {
11716
+ return new ZodMap({
11717
+ valueType,
11718
+ keyType,
11719
+ typeName: ZodFirstPartyTypeKind.ZodMap,
11720
+ ...processCreateParams(params)
11721
+ });
11722
+ };
11723
+ var ZodSet = class _ZodSet extends ZodType {
11724
+ _parse(input) {
11725
+ const { status, ctx } = this._processInputParams(input);
11726
+ if (ctx.parsedType !== ZodParsedType.set) {
11727
+ addIssueToContext(ctx, {
11728
+ code: ZodIssueCode.invalid_type,
11729
+ expected: ZodParsedType.set,
11730
+ received: ctx.parsedType
11731
+ });
11732
+ return INVALID;
11733
+ }
11734
+ const def = this._def;
11735
+ if (def.minSize !== null) {
11736
+ if (ctx.data.size < def.minSize.value) {
11737
+ addIssueToContext(ctx, {
11738
+ code: ZodIssueCode.too_small,
11739
+ minimum: def.minSize.value,
11740
+ type: "set",
11741
+ inclusive: true,
11742
+ exact: false,
11743
+ message: def.minSize.message
11744
+ });
11745
+ status.dirty();
11746
+ }
11747
+ }
11748
+ if (def.maxSize !== null) {
11749
+ if (ctx.data.size > def.maxSize.value) {
11750
+ addIssueToContext(ctx, {
11751
+ code: ZodIssueCode.too_big,
11752
+ maximum: def.maxSize.value,
11753
+ type: "set",
11754
+ inclusive: true,
11755
+ exact: false,
11756
+ message: def.maxSize.message
11757
+ });
11758
+ status.dirty();
11759
+ }
11760
+ }
11761
+ const valueType = this._def.valueType;
11762
+ function finalizeSet(elements2) {
11763
+ const parsedSet = /* @__PURE__ */ new Set();
11764
+ for (const element of elements2) {
11765
+ if (element.status === "aborted")
11766
+ return INVALID;
11767
+ if (element.status === "dirty")
11768
+ status.dirty();
11769
+ parsedSet.add(element.value);
11770
+ }
11771
+ return { status: status.value, value: parsedSet };
11772
+ }
11773
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
11774
+ if (ctx.common.async) {
11775
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
11776
+ } else {
11777
+ return finalizeSet(elements);
11778
+ }
11779
+ }
11780
+ min(minSize, message) {
11781
+ return new _ZodSet({
11782
+ ...this._def,
11783
+ minSize: { value: minSize, message: errorUtil.toString(message) }
11784
+ });
11785
+ }
11786
+ max(maxSize, message) {
11787
+ return new _ZodSet({
11788
+ ...this._def,
11789
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
11790
+ });
11791
+ }
11792
+ size(size, message) {
11793
+ return this.min(size, message).max(size, message);
11794
+ }
11795
+ nonempty(message) {
11796
+ return this.min(1, message);
11797
+ }
11798
+ };
11799
+ ZodSet.create = (valueType, params) => {
11800
+ return new ZodSet({
11801
+ valueType,
11802
+ minSize: null,
11803
+ maxSize: null,
11804
+ typeName: ZodFirstPartyTypeKind.ZodSet,
11805
+ ...processCreateParams(params)
11806
+ });
11807
+ };
11808
+ var ZodFunction = class _ZodFunction extends ZodType {
11809
+ constructor() {
11810
+ super(...arguments);
11811
+ this.validate = this.implement;
11812
+ }
11813
+ _parse(input) {
11814
+ const { ctx } = this._processInputParams(input);
11815
+ if (ctx.parsedType !== ZodParsedType.function) {
11816
+ addIssueToContext(ctx, {
11817
+ code: ZodIssueCode.invalid_type,
11818
+ expected: ZodParsedType.function,
11819
+ received: ctx.parsedType
11820
+ });
11821
+ return INVALID;
11822
+ }
11823
+ function makeArgsIssue(args, error) {
11824
+ return makeIssue({
11825
+ data: args,
11826
+ path: ctx.path,
11827
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
11828
+ issueData: {
11829
+ code: ZodIssueCode.invalid_arguments,
11830
+ argumentsError: error
11831
+ }
11832
+ });
11833
+ }
11834
+ function makeReturnsIssue(returns, error) {
11835
+ return makeIssue({
11836
+ data: returns,
11837
+ path: ctx.path,
11838
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
11839
+ issueData: {
11840
+ code: ZodIssueCode.invalid_return_type,
11841
+ returnTypeError: error
11842
+ }
11843
+ });
11844
+ }
11845
+ const params = { errorMap: ctx.common.contextualErrorMap };
11846
+ const fn = ctx.data;
11847
+ if (this._def.returns instanceof ZodPromise) {
11848
+ const me = this;
11849
+ return OK(async function(...args) {
11850
+ const error = new ZodError([]);
11851
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
11852
+ error.addIssue(makeArgsIssue(args, e));
11853
+ throw error;
11854
+ });
11855
+ const result = await Reflect.apply(fn, this, parsedArgs);
11856
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
11857
+ error.addIssue(makeReturnsIssue(result, e));
11858
+ throw error;
11859
+ });
11860
+ return parsedReturns;
11861
+ });
11862
+ } else {
11863
+ const me = this;
11864
+ return OK(function(...args) {
11865
+ const parsedArgs = me._def.args.safeParse(args, params);
11866
+ if (!parsedArgs.success) {
11867
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
11868
+ }
11869
+ const result = Reflect.apply(fn, this, parsedArgs.data);
11870
+ const parsedReturns = me._def.returns.safeParse(result, params);
11871
+ if (!parsedReturns.success) {
11872
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
11873
+ }
11874
+ return parsedReturns.data;
11875
+ });
11876
+ }
11877
+ }
11878
+ parameters() {
11879
+ return this._def.args;
11880
+ }
11881
+ returnType() {
11882
+ return this._def.returns;
11883
+ }
11884
+ args(...items) {
11885
+ return new _ZodFunction({
11886
+ ...this._def,
11887
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
11888
+ });
11889
+ }
11890
+ returns(returnType) {
11891
+ return new _ZodFunction({
11892
+ ...this._def,
11893
+ returns: returnType
11894
+ });
11895
+ }
11896
+ implement(func) {
11897
+ const validatedFunc = this.parse(func);
11898
+ return validatedFunc;
11899
+ }
11900
+ strictImplement(func) {
11901
+ const validatedFunc = this.parse(func);
11902
+ return validatedFunc;
11903
+ }
11904
+ static create(args, returns, params) {
11905
+ return new _ZodFunction({
11906
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
11907
+ returns: returns || ZodUnknown.create(),
11908
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
11909
+ ...processCreateParams(params)
11910
+ });
11911
+ }
11912
+ };
11913
+ var ZodLazy = class extends ZodType {
11914
+ get schema() {
11915
+ return this._def.getter();
11916
+ }
11917
+ _parse(input) {
11918
+ const { ctx } = this._processInputParams(input);
11919
+ const lazySchema = this._def.getter();
11920
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
11921
+ }
11922
+ };
11923
+ ZodLazy.create = (getter, params) => {
11924
+ return new ZodLazy({
11925
+ getter,
11926
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
11927
+ ...processCreateParams(params)
11928
+ });
11929
+ };
11930
+ var ZodLiteral = class extends ZodType {
11931
+ _parse(input) {
11932
+ if (input.data !== this._def.value) {
11933
+ const ctx = this._getOrReturnCtx(input);
11934
+ addIssueToContext(ctx, {
11935
+ received: ctx.data,
11936
+ code: ZodIssueCode.invalid_literal,
11937
+ expected: this._def.value
11938
+ });
11939
+ return INVALID;
11940
+ }
11941
+ return { status: "valid", value: input.data };
11942
+ }
11943
+ get value() {
11944
+ return this._def.value;
11945
+ }
11946
+ };
11947
+ ZodLiteral.create = (value, params) => {
11948
+ return new ZodLiteral({
11949
+ value,
11950
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
11951
+ ...processCreateParams(params)
11952
+ });
11953
+ };
11954
+ function createZodEnum(values, params) {
11955
+ return new ZodEnum({
11956
+ values,
11957
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
11958
+ ...processCreateParams(params)
11959
+ });
11960
+ }
11961
+ var ZodEnum = class _ZodEnum extends ZodType {
11962
+ _parse(input) {
11963
+ if (typeof input.data !== "string") {
11964
+ const ctx = this._getOrReturnCtx(input);
11965
+ const expectedValues = this._def.values;
11966
+ addIssueToContext(ctx, {
11967
+ expected: util.joinValues(expectedValues),
11968
+ received: ctx.parsedType,
11969
+ code: ZodIssueCode.invalid_type
11970
+ });
11971
+ return INVALID;
11972
+ }
11973
+ if (!this._cache) {
11974
+ this._cache = new Set(this._def.values);
11975
+ }
11976
+ if (!this._cache.has(input.data)) {
11977
+ const ctx = this._getOrReturnCtx(input);
11978
+ const expectedValues = this._def.values;
11979
+ addIssueToContext(ctx, {
11980
+ received: ctx.data,
11981
+ code: ZodIssueCode.invalid_enum_value,
11982
+ options: expectedValues
11983
+ });
11984
+ return INVALID;
11985
+ }
11986
+ return OK(input.data);
11987
+ }
11988
+ get options() {
11989
+ return this._def.values;
11990
+ }
11991
+ get enum() {
11992
+ const enumValues = {};
11993
+ for (const val of this._def.values) {
11994
+ enumValues[val] = val;
11995
+ }
11996
+ return enumValues;
11997
+ }
11998
+ get Values() {
11999
+ const enumValues = {};
12000
+ for (const val of this._def.values) {
12001
+ enumValues[val] = val;
12002
+ }
12003
+ return enumValues;
12004
+ }
12005
+ get Enum() {
12006
+ const enumValues = {};
12007
+ for (const val of this._def.values) {
12008
+ enumValues[val] = val;
12009
+ }
12010
+ return enumValues;
12011
+ }
12012
+ extract(values, newDef = this._def) {
12013
+ return _ZodEnum.create(values, {
12014
+ ...this._def,
12015
+ ...newDef
12016
+ });
12017
+ }
12018
+ exclude(values, newDef = this._def) {
12019
+ return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
12020
+ ...this._def,
12021
+ ...newDef
12022
+ });
12023
+ }
12024
+ };
12025
+ ZodEnum.create = createZodEnum;
12026
+ var ZodNativeEnum = class extends ZodType {
12027
+ _parse(input) {
12028
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
12029
+ const ctx = this._getOrReturnCtx(input);
12030
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
12031
+ const expectedValues = util.objectValues(nativeEnumValues);
12032
+ addIssueToContext(ctx, {
12033
+ expected: util.joinValues(expectedValues),
12034
+ received: ctx.parsedType,
12035
+ code: ZodIssueCode.invalid_type
12036
+ });
12037
+ return INVALID;
12038
+ }
12039
+ if (!this._cache) {
12040
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
12041
+ }
12042
+ if (!this._cache.has(input.data)) {
12043
+ const expectedValues = util.objectValues(nativeEnumValues);
12044
+ addIssueToContext(ctx, {
12045
+ received: ctx.data,
12046
+ code: ZodIssueCode.invalid_enum_value,
12047
+ options: expectedValues
12048
+ });
12049
+ return INVALID;
12050
+ }
12051
+ return OK(input.data);
12052
+ }
12053
+ get enum() {
12054
+ return this._def.values;
12055
+ }
12056
+ };
12057
+ ZodNativeEnum.create = (values, params) => {
12058
+ return new ZodNativeEnum({
12059
+ values,
12060
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
12061
+ ...processCreateParams(params)
12062
+ });
12063
+ };
12064
+ var ZodPromise = class extends ZodType {
12065
+ unwrap() {
12066
+ return this._def.type;
12067
+ }
12068
+ _parse(input) {
12069
+ const { ctx } = this._processInputParams(input);
12070
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
12071
+ addIssueToContext(ctx, {
12072
+ code: ZodIssueCode.invalid_type,
12073
+ expected: ZodParsedType.promise,
12074
+ received: ctx.parsedType
12075
+ });
12076
+ return INVALID;
12077
+ }
12078
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
12079
+ return OK(promisified.then((data) => {
12080
+ return this._def.type.parseAsync(data, {
12081
+ path: ctx.path,
12082
+ errorMap: ctx.common.contextualErrorMap
12083
+ });
12084
+ }));
12085
+ }
12086
+ };
12087
+ ZodPromise.create = (schema, params) => {
12088
+ return new ZodPromise({
12089
+ type: schema,
12090
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
12091
+ ...processCreateParams(params)
12092
+ });
12093
+ };
12094
+ var ZodEffects = class extends ZodType {
12095
+ innerType() {
12096
+ return this._def.schema;
12097
+ }
12098
+ sourceType() {
12099
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
12100
+ }
12101
+ _parse(input) {
12102
+ const { status, ctx } = this._processInputParams(input);
12103
+ const effect = this._def.effect || null;
12104
+ const checkCtx = {
12105
+ addIssue: (arg) => {
12106
+ addIssueToContext(ctx, arg);
12107
+ if (arg.fatal) {
12108
+ status.abort();
12109
+ } else {
12110
+ status.dirty();
12111
+ }
12112
+ },
12113
+ get path() {
12114
+ return ctx.path;
12115
+ }
12116
+ };
12117
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
12118
+ if (effect.type === "preprocess") {
12119
+ const processed = effect.transform(ctx.data, checkCtx);
12120
+ if (ctx.common.async) {
12121
+ return Promise.resolve(processed).then(async (processed2) => {
12122
+ if (status.value === "aborted")
12123
+ return INVALID;
12124
+ const result = await this._def.schema._parseAsync({
12125
+ data: processed2,
12126
+ path: ctx.path,
12127
+ parent: ctx
12128
+ });
12129
+ if (result.status === "aborted")
12130
+ return INVALID;
12131
+ if (result.status === "dirty")
12132
+ return DIRTY(result.value);
12133
+ if (status.value === "dirty")
12134
+ return DIRTY(result.value);
12135
+ return result;
12136
+ });
12137
+ } else {
12138
+ if (status.value === "aborted")
12139
+ return INVALID;
12140
+ const result = this._def.schema._parseSync({
12141
+ data: processed,
12142
+ path: ctx.path,
12143
+ parent: ctx
12144
+ });
12145
+ if (result.status === "aborted")
12146
+ return INVALID;
12147
+ if (result.status === "dirty")
12148
+ return DIRTY(result.value);
12149
+ if (status.value === "dirty")
12150
+ return DIRTY(result.value);
12151
+ return result;
12152
+ }
12153
+ }
12154
+ if (effect.type === "refinement") {
12155
+ const executeRefinement = (acc) => {
12156
+ const result = effect.refinement(acc, checkCtx);
12157
+ if (ctx.common.async) {
12158
+ return Promise.resolve(result);
12159
+ }
12160
+ if (result instanceof Promise) {
12161
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
12162
+ }
12163
+ return acc;
12164
+ };
12165
+ if (ctx.common.async === false) {
12166
+ const inner = this._def.schema._parseSync({
12167
+ data: ctx.data,
12168
+ path: ctx.path,
12169
+ parent: ctx
12170
+ });
12171
+ if (inner.status === "aborted")
12172
+ return INVALID;
12173
+ if (inner.status === "dirty")
12174
+ status.dirty();
12175
+ executeRefinement(inner.value);
12176
+ return { status: status.value, value: inner.value };
12177
+ } else {
12178
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
12179
+ if (inner.status === "aborted")
12180
+ return INVALID;
12181
+ if (inner.status === "dirty")
12182
+ status.dirty();
12183
+ return executeRefinement(inner.value).then(() => {
12184
+ return { status: status.value, value: inner.value };
12185
+ });
12186
+ });
12187
+ }
12188
+ }
12189
+ if (effect.type === "transform") {
12190
+ if (ctx.common.async === false) {
12191
+ const base = this._def.schema._parseSync({
12192
+ data: ctx.data,
12193
+ path: ctx.path,
12194
+ parent: ctx
12195
+ });
12196
+ if (!isValid(base))
12197
+ return INVALID;
12198
+ const result = effect.transform(base.value, checkCtx);
12199
+ if (result instanceof Promise) {
12200
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
12201
+ }
12202
+ return { status: status.value, value: result };
12203
+ } else {
12204
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
12205
+ if (!isValid(base))
12206
+ return INVALID;
12207
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
12208
+ status: status.value,
12209
+ value: result
12210
+ }));
12211
+ });
12212
+ }
12213
+ }
12214
+ util.assertNever(effect);
12215
+ }
12216
+ };
12217
+ ZodEffects.create = (schema, effect, params) => {
12218
+ return new ZodEffects({
12219
+ schema,
12220
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
12221
+ effect,
12222
+ ...processCreateParams(params)
12223
+ });
12224
+ };
12225
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
12226
+ return new ZodEffects({
12227
+ schema,
12228
+ effect: { type: "preprocess", transform: preprocess },
12229
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
12230
+ ...processCreateParams(params)
12231
+ });
12232
+ };
12233
+ var ZodOptional = class extends ZodType {
12234
+ _parse(input) {
12235
+ const parsedType = this._getType(input);
12236
+ if (parsedType === ZodParsedType.undefined) {
12237
+ return OK(void 0);
12238
+ }
12239
+ return this._def.innerType._parse(input);
12240
+ }
12241
+ unwrap() {
12242
+ return this._def.innerType;
12243
+ }
12244
+ };
12245
+ ZodOptional.create = (type, params) => {
12246
+ return new ZodOptional({
12247
+ innerType: type,
12248
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
12249
+ ...processCreateParams(params)
12250
+ });
12251
+ };
12252
+ var ZodNullable = class extends ZodType {
12253
+ _parse(input) {
12254
+ const parsedType = this._getType(input);
12255
+ if (parsedType === ZodParsedType.null) {
12256
+ return OK(null);
12257
+ }
12258
+ return this._def.innerType._parse(input);
12259
+ }
12260
+ unwrap() {
12261
+ return this._def.innerType;
12262
+ }
12263
+ };
12264
+ ZodNullable.create = (type, params) => {
12265
+ return new ZodNullable({
12266
+ innerType: type,
12267
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
12268
+ ...processCreateParams(params)
12269
+ });
12270
+ };
12271
+ var ZodDefault = class extends ZodType {
12272
+ _parse(input) {
12273
+ const { ctx } = this._processInputParams(input);
12274
+ let data = ctx.data;
12275
+ if (ctx.parsedType === ZodParsedType.undefined) {
12276
+ data = this._def.defaultValue();
12277
+ }
12278
+ return this._def.innerType._parse({
12279
+ data,
12280
+ path: ctx.path,
12281
+ parent: ctx
12282
+ });
12283
+ }
12284
+ removeDefault() {
12285
+ return this._def.innerType;
12286
+ }
12287
+ };
12288
+ ZodDefault.create = (type, params) => {
12289
+ return new ZodDefault({
12290
+ innerType: type,
12291
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
12292
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
12293
+ ...processCreateParams(params)
12294
+ });
12295
+ };
12296
+ var ZodCatch = class extends ZodType {
12297
+ _parse(input) {
12298
+ const { ctx } = this._processInputParams(input);
12299
+ const newCtx = {
12300
+ ...ctx,
12301
+ common: {
12302
+ ...ctx.common,
12303
+ issues: []
12304
+ }
12305
+ };
12306
+ const result = this._def.innerType._parse({
12307
+ data: newCtx.data,
12308
+ path: newCtx.path,
12309
+ parent: {
12310
+ ...newCtx
12311
+ }
12312
+ });
12313
+ if (isAsync(result)) {
12314
+ return result.then((result2) => {
12315
+ return {
12316
+ status: "valid",
12317
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
12318
+ get error() {
12319
+ return new ZodError(newCtx.common.issues);
12320
+ },
12321
+ input: newCtx.data
12322
+ })
12323
+ };
12324
+ });
12325
+ } else {
12326
+ return {
12327
+ status: "valid",
12328
+ value: result.status === "valid" ? result.value : this._def.catchValue({
12329
+ get error() {
12330
+ return new ZodError(newCtx.common.issues);
12331
+ },
12332
+ input: newCtx.data
12333
+ })
12334
+ };
12335
+ }
12336
+ }
12337
+ removeCatch() {
12338
+ return this._def.innerType;
12339
+ }
12340
+ };
12341
+ ZodCatch.create = (type, params) => {
12342
+ return new ZodCatch({
12343
+ innerType: type,
12344
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
12345
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
12346
+ ...processCreateParams(params)
12347
+ });
12348
+ };
12349
+ var ZodNaN = class extends ZodType {
12350
+ _parse(input) {
12351
+ const parsedType = this._getType(input);
12352
+ if (parsedType !== ZodParsedType.nan) {
12353
+ const ctx = this._getOrReturnCtx(input);
12354
+ addIssueToContext(ctx, {
12355
+ code: ZodIssueCode.invalid_type,
12356
+ expected: ZodParsedType.nan,
12357
+ received: ctx.parsedType
12358
+ });
12359
+ return INVALID;
12360
+ }
12361
+ return { status: "valid", value: input.data };
12362
+ }
12363
+ };
12364
+ ZodNaN.create = (params) => {
12365
+ return new ZodNaN({
12366
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
12367
+ ...processCreateParams(params)
12368
+ });
12369
+ };
12370
+ var BRAND = Symbol("zod_brand");
12371
+ var ZodBranded = class extends ZodType {
12372
+ _parse(input) {
12373
+ const { ctx } = this._processInputParams(input);
12374
+ const data = ctx.data;
12375
+ return this._def.type._parse({
12376
+ data,
12377
+ path: ctx.path,
12378
+ parent: ctx
12379
+ });
12380
+ }
12381
+ unwrap() {
12382
+ return this._def.type;
12383
+ }
12384
+ };
12385
+ var ZodPipeline = class _ZodPipeline extends ZodType {
12386
+ _parse(input) {
12387
+ const { status, ctx } = this._processInputParams(input);
12388
+ if (ctx.common.async) {
12389
+ const handleAsync = async () => {
12390
+ const inResult = await this._def.in._parseAsync({
12391
+ data: ctx.data,
12392
+ path: ctx.path,
12393
+ parent: ctx
12394
+ });
12395
+ if (inResult.status === "aborted")
12396
+ return INVALID;
12397
+ if (inResult.status === "dirty") {
12398
+ status.dirty();
12399
+ return DIRTY(inResult.value);
12400
+ } else {
12401
+ return this._def.out._parseAsync({
12402
+ data: inResult.value,
12403
+ path: ctx.path,
12404
+ parent: ctx
12405
+ });
12406
+ }
12407
+ };
12408
+ return handleAsync();
12409
+ } else {
12410
+ const inResult = this._def.in._parseSync({
12411
+ data: ctx.data,
12412
+ path: ctx.path,
12413
+ parent: ctx
12414
+ });
12415
+ if (inResult.status === "aborted")
12416
+ return INVALID;
12417
+ if (inResult.status === "dirty") {
12418
+ status.dirty();
12419
+ return {
12420
+ status: "dirty",
12421
+ value: inResult.value
12422
+ };
12423
+ } else {
12424
+ return this._def.out._parseSync({
12425
+ data: inResult.value,
12426
+ path: ctx.path,
12427
+ parent: ctx
12428
+ });
12429
+ }
12430
+ }
12431
+ }
12432
+ static create(a, b) {
12433
+ return new _ZodPipeline({
12434
+ in: a,
12435
+ out: b,
12436
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
12437
+ });
12438
+ }
12439
+ };
12440
+ var ZodReadonly = class extends ZodType {
12441
+ _parse(input) {
12442
+ const result = this._def.innerType._parse(input);
12443
+ const freeze = (data) => {
12444
+ if (isValid(data)) {
12445
+ data.value = Object.freeze(data.value);
12446
+ }
12447
+ return data;
12448
+ };
12449
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
12450
+ }
12451
+ unwrap() {
12452
+ return this._def.innerType;
12453
+ }
12454
+ };
12455
+ ZodReadonly.create = (type, params) => {
12456
+ return new ZodReadonly({
12457
+ innerType: type,
12458
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
12459
+ ...processCreateParams(params)
12460
+ });
12461
+ };
12462
+ function cleanParams(params, data) {
12463
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
12464
+ const p2 = typeof p === "string" ? { message: p } : p;
12465
+ return p2;
12466
+ }
12467
+ function custom(check, _params = {}, fatal) {
12468
+ if (check)
12469
+ return ZodAny.create().superRefine((data, ctx) => {
12470
+ const r = check(data);
12471
+ if (r instanceof Promise) {
12472
+ return r.then((r2) => {
12473
+ if (!r2) {
12474
+ const params = cleanParams(_params, data);
12475
+ const _fatal = params.fatal ?? fatal ?? true;
12476
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
12477
+ }
12478
+ });
12479
+ }
12480
+ if (!r) {
12481
+ const params = cleanParams(_params, data);
12482
+ const _fatal = params.fatal ?? fatal ?? true;
12483
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
12484
+ }
12485
+ return;
12486
+ });
12487
+ return ZodAny.create();
12488
+ }
12489
+ var late = {
12490
+ object: ZodObject.lazycreate
12491
+ };
12492
+ var ZodFirstPartyTypeKind;
12493
+ (function(ZodFirstPartyTypeKind2) {
12494
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
12495
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
12496
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
12497
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
12498
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
12499
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
12500
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
12501
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
12502
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
12503
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
12504
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
12505
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
12506
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
12507
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
12508
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
12509
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
12510
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
12511
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
12512
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
12513
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
12514
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
12515
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
12516
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
12517
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
12518
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
12519
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
12520
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
12521
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
12522
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
12523
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
12524
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
12525
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
12526
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
12527
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
12528
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
12529
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
12530
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
12531
+ var instanceOfType = (cls, params = {
12532
+ message: `Input not instance of ${cls.name}`
12533
+ }) => custom((data) => data instanceof cls, params);
12534
+ var stringType = ZodString.create;
12535
+ var numberType = ZodNumber.create;
12536
+ var nanType = ZodNaN.create;
12537
+ var bigIntType = ZodBigInt.create;
12538
+ var booleanType = ZodBoolean.create;
12539
+ var dateType = ZodDate.create;
12540
+ var symbolType = ZodSymbol.create;
12541
+ var undefinedType = ZodUndefined.create;
12542
+ var nullType = ZodNull.create;
12543
+ var anyType = ZodAny.create;
12544
+ var unknownType = ZodUnknown.create;
12545
+ var neverType = ZodNever.create;
12546
+ var voidType = ZodVoid.create;
12547
+ var arrayType = ZodArray.create;
12548
+ var objectType = ZodObject.create;
12549
+ var strictObjectType = ZodObject.strictCreate;
12550
+ var unionType = ZodUnion.create;
12551
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
12552
+ var intersectionType = ZodIntersection.create;
12553
+ var tupleType = ZodTuple.create;
12554
+ var recordType = ZodRecord.create;
12555
+ var mapType = ZodMap.create;
12556
+ var setType = ZodSet.create;
12557
+ var functionType = ZodFunction.create;
12558
+ var lazyType = ZodLazy.create;
12559
+ var literalType = ZodLiteral.create;
12560
+ var enumType = ZodEnum.create;
12561
+ var nativeEnumType = ZodNativeEnum.create;
12562
+ var promiseType = ZodPromise.create;
12563
+ var effectsType = ZodEffects.create;
12564
+ var optionalType = ZodOptional.create;
12565
+ var nullableType = ZodNullable.create;
12566
+ var preprocessType = ZodEffects.createWithPreprocess;
12567
+ var pipelineType = ZodPipeline.create;
12568
+ var ostring = () => stringType().optional();
12569
+ var onumber = () => numberType().optional();
12570
+ var oboolean = () => booleanType().optional();
12571
+ var coerce = {
12572
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
12573
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
12574
+ boolean: (arg) => ZodBoolean.create({
12575
+ ...arg,
12576
+ coerce: true
12577
+ }),
12578
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
12579
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
12580
+ };
12581
+ var NEVER = INVALID;
12582
+
12583
+ // src/environment.ts
12584
+ var twitterEnvSchema = external_exports.object({
12585
+ TWITTER_DRY_RUN: external_exports.boolean(),
12586
+ TWITTER_USERNAME: external_exports.string().min(1, "X/Twitter username is required"),
12587
+ TWITTER_PASSWORD: external_exports.string().min(1, "X/Twitter password is required"),
12588
+ TWITTER_EMAIL: external_exports.string().email("Valid X/Twitter email is required"),
12589
+ TWITTER_2FA_SECRET: external_exports.string().default(void 0),
12590
+ TWITTER_RETRY_LIMIT: external_exports.number().int(),
12591
+ TWITTER_POLL_INTERVAL: external_exports.number().int(),
12592
+ TWITTER_TARGET_USERS: external_exports.string().default(""),
12593
+ TWITTER_ENABLE_POST_GENERATION: external_exports.boolean(),
12594
+ TWITTER_POST_INTERVAL_MIN: external_exports.number().int(),
12595
+ TWITTER_POST_INTERVAL_MAX: external_exports.number().int(),
12596
+ TWITTER_POST_IMMEDIATELY: external_exports.boolean(),
12597
+ TWITTER_SPACES_ENABLE: external_exports.boolean().default(false)
12598
+ });
12599
+ function parseTargetUsers(targetUsersStr) {
12600
+ if (!targetUsersStr?.trim()) {
12601
+ return [];
12602
+ }
12603
+ return targetUsersStr.split(",").map((user) => user.trim()).filter(Boolean);
12604
+ }
12605
+ function shouldTargetUser(username, targetUsersConfig) {
12606
+ if (!targetUsersConfig?.trim()) {
12607
+ return true;
12608
+ }
12609
+ const targetUsers = parseTargetUsers(targetUsersConfig);
12610
+ if (targetUsers.includes("*")) {
12611
+ return true;
12612
+ }
12613
+ const normalizedUsername = username.toLowerCase().replace(/^@/, "");
12614
+ return targetUsers.some(
12615
+ (target) => target.toLowerCase().replace(/^@/, "") === normalizedUsername
12616
+ );
12617
+ }
12618
+
12619
+ // src/interactions.ts
12620
+ var convertToCoreTweet = (tweet) => ({
12621
+ id: tweet.id,
12622
+ text: tweet.text,
12623
+ conversationId: tweet.conversationId,
12624
+ timestamp: tweet.timestamp,
12625
+ userId: tweet.userId,
12626
+ username: tweet.username,
12627
+ name: tweet.name,
12628
+ inReplyToStatusId: tweet.inReplyToStatusId,
12629
+ permanentUrl: tweet.permanentUrl,
12630
+ photos: tweet.photos,
12631
+ hashtags: tweet.hashtags,
12632
+ mentions: tweet.mentions.map((mention) => mention.username),
12633
+ urls: tweet.urls,
12634
+ videos: tweet.videos,
12635
+ thread: tweet.thread
12636
+ });
12637
+ var convertToCoreTweets = (tweets) => tweets.map(convertToCoreTweet);
12638
+ var TwitterInteractionClient = class {
12639
+ /**
12640
+ * Constructor for setting up a new instance with the provided client, runtime, and state.
12641
+ * @param {ClientBase} client - The client being used for communication.
12642
+ * @param {IAgentRuntime} runtime - The runtime environment for the agent.
12643
+ * @param {any} state - The initial state of the agent.
12644
+ */
12645
+ constructor(client, runtime, state) {
12646
+ this.client = client;
12647
+ this.runtime = runtime;
12648
+ this.state = state;
12649
+ this.isDryRun = this.state?.TWITTER_DRY_RUN || this.runtime.getSetting("TWITTER_DRY_RUN");
12650
+ }
12651
+ /**
12652
+ * Asynchronously starts the process of handling Twitter interactions on a loop.
12653
+ * Uses an interval based on the 'TWITTER_POLL_INTERVAL' setting, or defaults to 2 minutes if not set.
12654
+ */
12655
+ async start() {
12656
+ const handleTwitterInteractionsLoop = () => {
12657
+ const interactionInterval = (this.state?.TWITTER_POLL_INTERVAL || this.runtime.getSetting(
12658
+ "TWITTER_POLL_INTERVAL"
12659
+ ) || 120) * 1e3;
12660
+ this.handleTwitterInteractions();
12661
+ setTimeout(handleTwitterInteractionsLoop, interactionInterval);
12662
+ };
12663
+ handleTwitterInteractionsLoop();
12664
+ }
12665
+ /**
12666
+ * Asynchronously handles Twitter interactions by checking for mentions, processing tweets, and updating the last checked tweet ID.
12667
+ */
12668
+ async handleTwitterInteractions() {
12669
+ logger7.log("Checking Twitter interactions");
12670
+ const twitterUsername = this.client.profile?.username;
12671
+ try {
12672
+ const cursorKey = `twitter/${twitterUsername}/mention_cursor`;
12673
+ const cachedCursor = await this.runtime.getCache(cursorKey);
12674
+ const searchResult = await this.client.fetchSearchTweets(
12675
+ `@${twitterUsername}`,
12676
+ 20,
12677
+ 1 /* Latest */,
12678
+ String(cachedCursor)
12679
+ );
12680
+ const mentionCandidates = searchResult.tweets;
12681
+ if (mentionCandidates.length > 0 && searchResult.previous) {
12682
+ await this.runtime.setCache(cursorKey, searchResult.previous);
12683
+ } else if (!searchResult.previous && !searchResult.next) {
12684
+ await this.runtime.setCache(cursorKey, "");
12685
+ }
12686
+ await this.processMentionTweets(mentionCandidates);
12687
+ await this.client.cacheLatestCheckedTweetId();
12688
+ logger7.log("Finished checking Twitter interactions");
12689
+ } catch (error) {
12690
+ logger7.error("Error handling Twitter interactions:", error);
12691
+ }
12692
+ }
12693
+ /**
12694
+ * Processes all incoming tweets that mention the bot.
12695
+ * For each new tweet:
12696
+ * - Ensures world, room, and connection exist
12697
+ * - Saves the tweet as memory
12698
+ * - Emits thread-related events (THREAD_CREATED / THREAD_UPDATED)
12699
+ * - Delegates tweet content to `handleTweet` for reply generation
12700
+ *
12701
+ * Note: MENTION_RECEIVED is currently disabled (see TODO below)
12702
+ */
12703
+ async processMentionTweets(mentionCandidates) {
12704
+ logger7.log(
12705
+ "Completed checking mentioned tweets:",
12706
+ mentionCandidates.length
12707
+ );
12708
+ let uniqueTweetCandidates = [...mentionCandidates];
12709
+ uniqueTweetCandidates = uniqueTweetCandidates.sort((a, b) => a.id.localeCompare(b.id)).filter((tweet) => tweet.userId !== this.client.profile.id);
12710
+ const targetUsersConfig = this.runtime.getSetting("TWITTER_TARGET_USERS") || "";
12711
+ if (targetUsersConfig?.trim()) {
12712
+ uniqueTweetCandidates = uniqueTweetCandidates.filter((tweet) => {
12713
+ const shouldTarget = shouldTargetUser(
12714
+ tweet.username || "",
12715
+ targetUsersConfig
12716
+ );
12717
+ if (!shouldTarget) {
12718
+ logger7.log(
12719
+ `Skipping tweet from @${tweet.username} - not in target users list`
12720
+ );
12721
+ }
12722
+ return shouldTarget;
12723
+ });
12724
+ }
12725
+ for (const tweet of uniqueTweetCandidates) {
12726
+ if (!this.client.lastCheckedTweetId || BigInt(tweet.id) > this.client.lastCheckedTweetId) {
12727
+ const tweetId = createUniqueUuid5(this.runtime, tweet.id);
12728
+ const existingResponse = await this.runtime.getMemoryById(tweetId);
12729
+ if (existingResponse) {
12730
+ logger7.log(`Already responded to tweet ${tweet.id}, skipping`);
12731
+ continue;
12732
+ }
12733
+ const conversationRoomId = createUniqueUuid5(this.runtime, tweet.conversationId);
12734
+ const existingReplies = await this.runtime.getMemories({
12735
+ tableName: "messages",
12736
+ roomId: conversationRoomId,
12737
+ count: 10
12738
+ // Check recent messages in this room
12739
+ });
12740
+ const hasExistingReply = existingReplies.some(
12741
+ (memory2) => memory2.content?.inReplyTo === tweetId || memory2.content?.source === "twitter" && memory2.agentId === this.runtime.agentId && memory2.content?.inReplyTo === tweetId
12742
+ );
12743
+ if (hasExistingReply) {
12744
+ logger7.log(`Already replied to tweet ${tweet.id} (found existing reply), skipping`);
12745
+ continue;
12746
+ }
12747
+ logger7.log("New Tweet found", tweet.permanentUrl);
12748
+ const entityId = createUniqueUuid5(
12749
+ this.runtime,
12750
+ tweet.userId === this.client.profile.id ? this.runtime.agentId : tweet.userId
12751
+ );
12752
+ const worldId = createUniqueUuid5(this.runtime, tweet.userId);
12753
+ const roomId = createUniqueUuid5(this.runtime, tweet.conversationId);
12754
+ await this.runtime.ensureConnection({
12755
+ entityId,
12756
+ roomId,
12757
+ userName: tweet.username,
12758
+ worldName: `${tweet.name}'s Twitter`,
12759
+ name: tweet.name,
12760
+ source: "twitter",
12761
+ type: ChannelType3.GROUP,
12762
+ channelId: tweet.conversationId,
12763
+ serverId: tweet.userId,
12764
+ worldId,
12765
+ metadata: {
12766
+ ownership: { ownerId: tweet.userId },
12767
+ twitter: {
12768
+ username: tweet.username,
12769
+ id: tweet.userId,
12770
+ name: tweet.name
12771
+ }
12772
+ }
12773
+ });
12774
+ const memory = {
12775
+ id: tweetId,
12776
+ agentId: this.runtime.agentId,
12777
+ content: {
12778
+ text: tweet.text,
12779
+ url: tweet.permanentUrl,
12780
+ attachments: tweet.photos?.map((photo, index) => ({
12781
+ id: photo.id,
12782
+ url: photo.url,
12783
+ contentType: ContentType.IMAGE
12784
+ // TODO: check if we can read this.
12785
+ })) || [],
12786
+ inReplyTo: tweet.inReplyToStatusId ? createUniqueUuid5(this.runtime, tweet.inReplyToStatusId) : void 0,
12787
+ source: "twitter",
12788
+ channelType: ChannelType3.GROUP,
12789
+ tweet
12790
+ },
12791
+ entityId,
12792
+ roomId,
12793
+ createdAt: tweet.timestamp * 1e3
12794
+ };
12795
+ await this.runtime.createMemory(memory, "messages");
12796
+ if (tweet.thread.length > 1) {
12797
+ const threadPayload = {
12798
+ runtime: this.runtime,
12799
+ tweets: convertToCoreTweets(tweet.thread),
12800
+ user: {
12801
+ id: tweet.userId,
12802
+ username: tweet.username,
12803
+ name: tweet.name
12804
+ },
12805
+ source: "twitter"
12806
+ };
12807
+ if (tweet.thread[tweet.thread.length - 1].id === tweet.id) {
12808
+ this.runtime.emitEvent("TWITTER_THREAD_UPDATED" /* THREAD_UPDATED */, {
12809
+ ...threadPayload,
12810
+ newTweet: convertToCoreTweet(tweet)
12811
+ });
12812
+ } else if (tweet.thread[0].id === tweet.id) {
12813
+ this.runtime.emitEvent(
12814
+ "TWITTER_THREAD_CREATED" /* THREAD_CREATED */,
12815
+ threadPayload
12816
+ );
12817
+ }
12818
+ }
12819
+ await this.handleTweet({
12820
+ tweet,
12821
+ message: memory,
12822
+ thread: tweet.thread
12823
+ });
12824
+ this.client.lastCheckedTweetId = BigInt(tweet.id);
12825
+ }
12826
+ }
12827
+ }
12828
+ /**
12829
+ * Handles Twitter interactions such as likes, retweets, and quotes.
12830
+ * For each interaction:
12831
+ * - Creates a memory object
12832
+ * - Emits platform-specific events (LIKE_RECEIVED, RETWEET_RECEIVED, QUOTE_RECEIVED)
12833
+ * - Emits a generic REACTION_RECEIVED event with metadata
12834
+ */
12835
+ async handleInteraction(interaction) {
12836
+ if (interaction?.targetTweet?.conversationId) {
12837
+ const memory = this.createMemoryObject(
12838
+ interaction.type,
12839
+ `${interaction.id}-${interaction.type}`,
12840
+ interaction.userId,
12841
+ interaction.targetTweet.conversationId
12842
+ );
12843
+ await this.runtime.createMemory(memory, "messages");
12844
+ const reactionMessage = {
12845
+ id: createUniqueUuid5(this.runtime, interaction.targetTweetId),
12846
+ content: {
12847
+ text: interaction.targetTweet.text,
12848
+ source: "twitter"
12849
+ },
12850
+ entityId: createUniqueUuid5(
12851
+ this.runtime,
12852
+ interaction.targetTweet.userId
12853
+ ),
12854
+ roomId: createUniqueUuid5(
12855
+ this.runtime,
12856
+ interaction.targetTweet.conversationId
12857
+ ),
12858
+ agentId: this.runtime.agentId
12859
+ };
12860
+ const basePayload = {
12861
+ runtime: this.runtime,
12862
+ user: {
12863
+ id: interaction.userId,
12864
+ username: interaction.username,
12865
+ name: interaction.name
12866
+ },
12867
+ source: "twitter"
12868
+ };
12869
+ switch (interaction.type) {
12870
+ case "like": {
12871
+ const likePayload = {
12872
+ ...basePayload,
12873
+ tweet: interaction.targetTweet
12874
+ };
12875
+ this.runtime.emitEvent("TWITTER_LIKE_RECEIVED" /* LIKE_RECEIVED */, likePayload);
12876
+ this.runtime.emitEvent(EventType2.REACTION_RECEIVED, {
12877
+ ...basePayload,
12878
+ reaction: {
8772
12879
  type: "like",
8773
12880
  entityId: createUniqueUuid5(this.runtime, interaction.userId)
8774
12881
  },
@@ -9640,9 +13747,7 @@ var ClientBaseTestSuite = class {
9640
13747
  };
9641
13748
 
9642
13749
  // src/index.ts
9643
- console.log(
9644
- `Twitter plugin loaded with service name: ${TWITTER_SERVICE_NAME}`
9645
- );
13750
+ console.log(`Twitter plugin loaded with service name: ${TWITTER_SERVICE_NAME}`);
9646
13751
  var TwitterClientInstance = class {
9647
13752
  constructor(runtime, state) {
9648
13753
  this.client = new ClientBase(runtime, state);
@@ -9650,11 +13755,7 @@ var TwitterClientInstance = class {
9650
13755
  this.post = new TwitterPostClient(this.client, runtime, state);
9651
13756
  }
9652
13757
  if (runtime.getSetting("TWITTER_INTERACTION_ENABLE") !== false) {
9653
- this.interaction = new TwitterInteractionClient(
9654
- this.client,
9655
- runtime,
9656
- state
9657
- );
13758
+ this.interaction = new TwitterInteractionClient(this.client, runtime, state);
9658
13759
  }
9659
13760
  if (runtime.getSetting("TWITTER_TIMELINE_ENABLE") === true) {
9660
13761
  this.timeline = new TwitterTimelineClient(this.client, runtime, state);
@@ -9718,9 +13819,7 @@ var _TwitterService = class _TwitterService extends Service {
9718
13819
  async emitServerJoinedEvent(runtime, client) {
9719
13820
  try {
9720
13821
  if (!client.client.profile) {
9721
- logger11.warn(
9722
- "Twitter profile not available yet, can't emit WORLD_JOINED event"
9723
- );
13822
+ logger11.warn("Twitter profile not available yet, can't emit WORLD_JOINED event");
9724
13823
  return;
9725
13824
  }
9726
13825
  const profile = client.client.profile;
@@ -9743,10 +13842,7 @@ var _TwitterService = class _TwitterService extends Service {
9743
13842
  }
9744
13843
  }
9745
13844
  };
9746
- const homeTimelineRoomId = createUniqueUuid8(
9747
- runtime,
9748
- `${twitterId}-home`
9749
- );
13845
+ const homeTimelineRoomId = createUniqueUuid8(runtime, `${twitterId}-home`);
9750
13846
  const homeTimelineRoom = {
9751
13847
  id: homeTimelineRoomId,
9752
13848
  name: `${username}'s Timeline`,
@@ -9756,10 +13852,7 @@ var _TwitterService = class _TwitterService extends Service {
9756
13852
  serverId: twitterId,
9757
13853
  worldId
9758
13854
  };
9759
- const mentionsRoomId = createUniqueUuid8(
9760
- runtime,
9761
- `${twitterId}-mentions`
9762
- );
13855
+ const mentionsRoomId = createUniqueUuid8(runtime, `${twitterId}-mentions`);
9763
13856
  const mentionsRoom = {
9764
13857
  id: mentionsRoomId,
9765
13858
  name: `${username}'s Mentions`,
@@ -9783,16 +13876,14 @@ var _TwitterService = class _TwitterService extends Service {
9783
13876
  }
9784
13877
  }
9785
13878
  };
9786
- runtime.emitEvent(
9787
- ["TWITTER_WORLD_JOINED" /* WORLD_JOINED */, EventType4.WORLD_JOINED],
9788
- {
9789
- runtime,
9790
- world,
9791
- rooms: [homeTimelineRoom, mentionsRoom],
9792
- users: [twitterUser],
9793
- source: "twitter"
9794
- }
9795
- );
13879
+ console.log("twitterUser:::::::", twitterUser);
13880
+ runtime.emitEvent(["TWITTER_WORLD_JOINED" /* WORLD_JOINED */, EventType4.WORLD_JOINED], {
13881
+ runtime,
13882
+ world,
13883
+ rooms: [homeTimelineRoom, mentionsRoom],
13884
+ entities: [twitterUser],
13885
+ source: "twitter"
13886
+ });
9796
13887
  logger11.info(`Emitted WORLD_JOINED event for Twitter account ${username}`);
9797
13888
  } catch (error) {
9798
13889
  logger11.error("Failed to emit WORLD_JOINED event for Twitter:", error);
@@ -9829,11 +13920,7 @@ var _TwitterService = class _TwitterService extends Service {
9829
13920
  if (config.TWITTER_USERNAME && // Basic auth
9830
13921
  config.TWITTER_PASSWORD && config.TWITTER_EMAIL) {
9831
13922
  logger11.info("Creating default Twitter client from character settings");
9832
- await twitterClientManager.createClient(
9833
- runtime,
9834
- runtime.agentId,
9835
- config
9836
- );
13923
+ await twitterClientManager.createClient(runtime, runtime.agentId, config);
9837
13924
  }
9838
13925
  } catch (error) {
9839
13926
  logger11.error("Failed to create default Twitter client:", error);