import * as checks from "./checks.js";
import type { $ZodNumberFormats } from "./checks.js";
import type { $ZodBigIntFormats } from "./checks.js";
import * as core from "./core.js";
import { Doc } from "./doc.js";
import type * as errors from "./errors.js";
import type * as JSONSchema from "./json-schema.js";
import { parse, parseAsync } from "./parse.js";
import * as regexes from "./regexes.js";
import type { StandardSchemaV1 } from "./standard-schema.js";
import type { ProcessParams, ToJSONSchemaContext } from "./to-json-schema.js";
import * as util from "./util.js";
import { version } from "./versions.js";

/////////////////////////////   PARSE   //////////////////////////////

export interface ParseContext<T extends errors.$ZodIssueBase = never> {
  /** Customize error messages. */
  readonly error?: errors.$ZodErrorMap<T>;
  /** Include the `input` field in issue objects. Default `false`. */
  readonly reportInput?: boolean;
  /** Skip eval-based fast path. Default `false`. */
  readonly jitless?: boolean;
  /** Abort validation after the first error. Default `false`. */
  // readonly abortEarly?: boolean;
}

/** @internal */
export interface ParseContextInternal<T extends errors.$ZodIssueBase = never> extends ParseContext<T> {
  readonly async?: boolean | undefined;
  readonly direction?: "forward" | "backward";
  readonly skipChecks?: boolean;
  /** Set only by `validate`/`validateAsync`. A container may stop before its next child, never inside one, so a map entry and a tuple's fixed items parse whole. */
  readonly abortEarly?: boolean;
}

/** Gives a container cycle support: `attach` wraps its parse, and `alloc` registers the object it builds into before any child is parsed so a reference back to the same input resolves to it. */
export interface $ZodMemoizer {
  attach(inst: $ZodType): void;
  guard(inst: $ZodType): void;
  alloc<T extends object>(inst: $ZodType, payload: ParsePayload, empty: T, ctx: ParseContextInternal): T;
}

export interface ParsePayload<T = unknown> {
  value: T;
  issues: errors.$ZodRawIssue[];
  /** A way to mark a whole payload as aborted. Used in codecs/pipes. */
  aborted?: boolean;
  /** @internal Set when the value came from a repeat visit to a node still being
   * parsed. Its checks run on the node itself, against the finished value. */
  memo?: boolean | undefined;
}

export type CheckFn<T> = (input: ParsePayload<T>) => util.MaybeAsync<void>;

/////////////////////////////   SCHEMAS   //////////////////////////////

export interface $ZodTypeDef {
  type:
    | "string"
    | "number"
    | "int"
    | "boolean"
    | "bigint"
    | "symbol"
    | "null"
    | "undefined"
    | "void" // merge with undefined?
    | "never"
    | "any"
    | "unknown"
    | "date"
    | "object"
    | "record"
    | "file"
    | "array"
    | "tuple"
    | "union"
    | "intersection"
    | "map"
    | "set"
    | "enum"
    | "literal"
    | "nullable"
    | "optional"
    | "nonoptional"
    | "success"
    | "transform"
    | "default"
    | "prefault"
    | "catch"
    | "nan"
    | "pipe"
    | "readonly"
    | "template_literal"
    | "promise"
    | "lazy"
    | "function"
    | "custom";
  error?: errors.$ZodErrorMap<never> | undefined;
  checks?: checks.$ZodCheck<never>[];
}

export interface _$ZodTypeInternals {
  /** The `@zod/core` version of this schema */
  version: typeof version;

  /** Schema definition. */
  def: $ZodTypeDef;
  // types: Types;

  /** @internal Randomly generated ID for this schema. */
  // id: string;

  /** @internal List of deferred initializers. */
  deferred: util.AnyFunc[] | undefined;

  /** @internal Parses input and runs all checks (refinements). */
  run(payload: ParsePayload<any>, ctx: ParseContextInternal): util.MaybeAsync<ParsePayload>;

  /** @internal Parses input, doesn't run checks. */
  parse(payload: ParsePayload<any>, ctx: ParseContextInternal): util.MaybeAsync<ParsePayload>;

  /** @internal  Stores identifiers for the set of traits implemented by this schema. */
  traits: Set<string>;

  /** @internal Indicates that a schema output type should be considered optional inside objects.
   * @default Required
   */

  /** @internal Three rungs, each strictly stronger than the last:
   *   undefined    — required; the container may not omit this slot
   *   "optional"   — the container may omit it; nothing is supplied in its place
   *   "defaulted"  — the container may omit it AND this schema substitutes a value
   * Consumers asking "may the slot be absent?" test `!== undefined`.
   * $ZodOptional asks the stronger question and tests `=== "defaulted"`. */
  optin?: "optional" | "defaulted" | undefined;
  /** @internal */
  optout?: "optional" | undefined;

  /** @internal The set of literal values that will pass validation. Must be an exhaustive set. Used to determine optionality in z.record().
   *
   * Defined on: enum, const, literal, null, undefined
   * Passthrough: optional, nullable, branded, default, catch, pipe
   * Todo: unions?
   */
  values?: util.PrimitiveSet | undefined;

  /** Default value bubbled up from  */
  // default?: unknown | undefined;

  /** @internal A set of literal discriminators used for the fast path in discriminated unions. */
  propValues?: util.PropValues | undefined;

  /** @internal This flag indicates that a schema validation can be represented with a regular expression. Used to determine allowable schemas in z.templateLiteral(). */
  pattern: RegExp | undefined;

  /** @internal The constructor function of this schema. */
  constr: new (
    def: any
  ) => $ZodType;

  /** @internal A catchall object for bag metadata related to this schema. Commonly modified by checks using `onattach`. */
  bag: Record<string, unknown>;

  /** @internal The set of issues this schema might throw during type checking. */
  isst: errors.$ZodIssueBase;

  /** @internal Subject to change, not a public API. */
  processJSONSchema?:
    | ((ctx: ToJSONSchemaContext, json: JSONSchema.BaseSchema, params: ProcessParams) => void)
    | undefined;

  /** An optional method used to override `toJSONSchema` logic. */
  toJSONSchema?: () => unknown;

  /** @internal The parent of this schema. Only set during certain clone operations. */
  parent?: $ZodType | undefined;
}
/** @internal */
export interface $ZodTypeInternals<out O = unknown, out I = unknown> extends _$ZodTypeInternals {
  /** @internal The inferred output type */
  output: O; //extends { $out: infer O } ? O : Out;
  /** @internal The inferred input type */
  input: I; //extends { $in: infer I } ? I : In;
}

export type $ZodStandardSchema<T> = StandardSchemaV1.Props<core.input<T>, core.output<T>>;

export type SomeType = { _zod: _$ZodTypeInternals };

export interface $ZodType<
  O = unknown,
  I = unknown,
  Internals extends $ZodTypeInternals<O, I> = $ZodTypeInternals<O, I>,
> {
  _zod: Internals;
  "~standard": $ZodStandardSchema<this>;
}
export interface _$ZodType<T extends $ZodTypeInternals = $ZodTypeInternals>
  extends $ZodType<T["output"], T["input"], T> {}

export const $ZodType: core.$constructor<$ZodType> = /*@__PURE__*/ core.$constructor<$ZodType>(
  "$ZodType",
  (inst, def) => {
    inst ??= {} as any;

    inst._zod.def = def; // set _def property
    inst._zod.bag = inst._zod.bag || {}; // initialize _bag object
    inst._zod.version = version;

    const defChecks = inst._zod.def.checks;
    // if inst is itself a checks.$ZodCheck, run it as a check
    const checks: checks.$ZodCheck<never>[] = inst._zod.traits.has("$ZodCheck")
      ? [inst as any, ...(defChecks ?? [])]
      : defChecks?.length
        ? [...defChecks]
        : [];

    for (const ch of checks) {
      for (const fn of ch._zod.onattach) {
        fn(inst);
      }
    }

    if (checks.length === 0) {
      // deferred initializer inst._zod.parse is not yet defined
      inst._zod.deferred ??= [];
      inst._zod.deferred?.push(() => {
        inst._zod.run = inst._zod.parse;
      });
    } else {
      const runChecks = (
        payload: ParsePayload,
        checks: checks.$ZodCheck<never>[],
        ctx?: ParseContextInternal | undefined
      ): util.MaybeAsync<ParsePayload> => {
        if (payload.memo) return payload;

        let isAborted = util.aborted(payload);

        let asyncResult!: Promise<unknown> | undefined;
        for (const ch of checks) {
          if (ch._zod.def.when) {
            if (util.explicitlyAborted(payload)) continue;
            const shouldRun = ch._zod.def.when(payload);
            if (!shouldRun) continue;
          } else if (isAborted) {
            continue;
          }
          const currLen = payload.issues.length;
          const _ = ch._zod.check(payload as any) as any as ParsePayload;

          if (_ instanceof Promise && ctx?.async === false) {
            throw new core.$ZodAsyncError();
          }
          if (asyncResult || _ instanceof Promise) {
            asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
              await _;
              const nextLen = payload.issues.length;
              if (nextLen === currLen) return;
              util.attachSchema(payload.issues, currLen, inst);
              if (!isAborted) isAborted = util.aborted(payload, currLen);
            });
          } else {
            const nextLen = payload.issues.length;
            if (nextLen === currLen) continue;
            util.attachSchema(payload.issues, currLen, inst);
            if (!isAborted) isAborted = util.aborted(payload, currLen);
          }
        }

        if (asyncResult) {
          return asyncResult.then(() => {
            return payload;
          });
        }
        return payload;
      };

      const handleCanaryResult = (canary: ParsePayload, payload: ParsePayload, ctx: ParseContextInternal) => {
        // abort if the canary is aborted
        if (util.aborted(canary)) {
          canary.aborted = true;
          return canary;
        }

        // run checks first, then
        const checkResult = runChecks(payload, checks, ctx);
        if (checkResult instanceof Promise) {
          if (ctx.async === false) throw new core.$ZodAsyncError();
          return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
        }
        return inst._zod.parse(checkResult, ctx);
      };

      inst._zod.run = (payload, ctx) => {
        if (ctx.skipChecks) {
          return inst._zod.parse(payload, ctx);
        }
        if (ctx.direction === "backward") {
          // run canary initial pass (no checks)
          const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });

          if (canary instanceof Promise) {
            return canary.then((canary) => {
              return handleCanaryResult(canary, payload, ctx);
            });
          }

          return handleCanaryResult(canary, payload, ctx);
        }

        // forward
        const result = inst._zod.parse(payload, ctx);
        if (result instanceof Promise) {
          if (ctx.async === false) throw new core.$ZodAsyncError();
          return result.then((result) => runChecks(result, checks, ctx));
        }

        return runChecks(result, checks, ctx);
      };
    }
  },
  {
    // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.
    get "~standard"(): StandardSchemaV1.Props<any, any> {
      return util.hide(this, "~standard", standardProps(this));
    },
    set "~standard"(value: StandardSchemaV1.Props<any, any>) {
      util.own(this, "~standard", value);
    },
  }
);

/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */
// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through
const toStandardResult = (r: ParsePayload, ctx: ParseContextInternal) =>
  r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };

async function validateAsync(inst: $ZodType, value: unknown) {
  const ctx: ParseContextInternal = { async: true };
  return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)) as ParsePayload, ctx);
}

export function standardProps(inst: $ZodType): StandardSchemaV1.Props<any, any> {
  return {
    validate: (value: unknown) => {
      const ctx: ParseContextInternal = { async: false };
      try {
        const r = inst._zod.run({ value, issues: [] }, ctx);
        if (!(r instanceof Promise)) return toStandardResult(r, ctx);
      } catch (_) {}
      // async function so a synchronously throwing check rejects instead of escaping validate
      return validateAsync(inst, value);
    },
    vendor: "zod",
    version: 1 as const,
  };
}

export { clone } from "./util.js";

//////////////////////////////////////////
//////////////////////////////////////////
//////////                      //////////
//////////      $ZodString      //////////
//////////                      //////////
//////////////////////////////////////////
//////////////////////////////////////////
export interface $ZodStringDef extends $ZodTypeDef {
  type: "string";
  coerce?: boolean;
  checks?: checks.$ZodCheck<string>[];
}

export interface $ZodStringInternals<Input> extends $ZodTypeInternals<string, Input> {
  def: $ZodStringDef;
  /** @deprecated Internal API, use with caution (not deprecated) */
  pattern: RegExp;

  /** @deprecated Internal API, use with caution (not deprecated) */
  isst: errors.$ZodIssueInvalidType;
  bag: util.LoosePartial<{
    minimum: number;
    maximum: number;
    patterns: Set<RegExp>;
    format: string;
    contentEncoding: string;
    /** the pattern admits strings its `format` keyword forbids, so `toJSONSchema` must not emit it */
    laxFormat: boolean;
  }>;
}

export interface $ZodString<Input = unknown> extends _$ZodType<$ZodStringInternals<Input>> {
  // _zod: $ZodStringInternals<Input>;
}

export const $ZodString: core.$constructor<$ZodString> = /*@__PURE__*/ core.$constructor("$ZodString", (inst, def) => {
  $ZodType.init(inst, def);
  // a format's own pattern, else unbounded; a template literal derives the check-aware form itself
  inst._zod.pattern = (def as $ZodStringFormatDef).pattern ?? regexes.anyString;
  inst._zod.parse = (payload, _) => {
    if (def.coerce)
      try {
        payload.value = String(payload.value);
      } catch (_) {}

    if (typeof payload.value === "string") return payload;

    payload.issues.push({
      expected: "string",
      code: "invalid_type",

      input: payload.value,
      inst,
    });
    return payload;
  };
});

//////////////////////////////   ZodStringFormat   //////////////////////////////

export interface $ZodStringFormatDef<Format extends string = string>
  extends $ZodStringDef,
    checks.$ZodCheckStringFormatDef<Format> {}

export interface $ZodStringFormatInternals<Format extends string = string>
  extends $ZodStringInternals<string>,
    checks.$ZodCheckStringFormatInternals {
  def: $ZodStringFormatDef<Format>;
}
export interface $ZodStringFormat<Format extends string = string> extends $ZodType {
  _zod: $ZodStringFormatInternals<Format>;
}

export const $ZodStringFormat: core.$constructor<$ZodStringFormat> = /*@__PURE__*/ core.$constructor(
  "$ZodStringFormat",
  (inst, def): void => {
    // check initialization must come first
    checks.$ZodCheckStringFormat.init(inst, def);
    $ZodString.init(inst, def);
  }
);

//////////////////////////////   ZodGUID   //////////////////////////////
export interface $ZodGUIDDef extends $ZodStringFormatDef<"guid"> {}
export interface $ZodGUIDInternals extends $ZodStringFormatInternals<"guid"> {}

export interface $ZodGUID extends $ZodType {
  _zod: $ZodGUIDInternals;
}

export const $ZodGUID: core.$constructor<$ZodGUID> = /*@__PURE__*/ core.$constructor("$ZodGUID", (inst, def): void => {
  def.pattern ??= regexes.guid;
  $ZodStringFormat.init(inst, def);
});

//////////////////////////////   ZodUUID   //////////////////////////////

export interface $ZodUUIDDef extends $ZodStringFormatDef<"uuid"> {
  version?: "v1" | "v2" | "v3" | "v4" | "v5" | "v6" | "v7" | "v8";
}

export interface $ZodUUIDInternals extends $ZodStringFormatInternals<"uuid"> {
  def: $ZodUUIDDef;
}

export interface $ZodUUID extends $ZodType {
  _zod: $ZodUUIDInternals;
}

export const $ZodUUID: core.$constructor<$ZodUUID> = /*@__PURE__*/ core.$constructor("$ZodUUID", (inst, def): void => {
  if (def.version) {
    const versionMap: Record<string, number> = {
      v1: 1,
      v2: 2,
      v3: 3,
      v4: 4,
      v5: 5,
      v6: 6,
      v7: 7,
      v8: 8,
    };
    const v = versionMap[def.version];
    if (v === undefined) throw new Error(`Invalid UUID version: "${def.version}"`);
    def.pattern ??= regexes.uuid(v);
  } else def.pattern ??= regexes.uuid();
  $ZodStringFormat.init(inst, def);
});

//////////////////////////////   ZodEmail   //////////////////////////////

export interface $ZodEmailDef extends $ZodStringFormatDef<"email"> {}
export interface $ZodEmailInternals extends $ZodStringFormatInternals<"email"> {}
export interface $ZodEmail extends $ZodType {
  _zod: $ZodEmailInternals;
}

export const $ZodEmail: core.$constructor<$ZodEmail> = /*@__PURE__*/ core.$constructor(
  "$ZodEmail",
  (inst, def): void => {
    def.pattern ??= regexes.email;
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodURL   //////////////////////////////

export interface $ZodURLDef extends $ZodStringFormatDef<"url"> {
  hostname?: RegExp | undefined;
  protocol?: RegExp | undefined;
  normalize?: boolean | undefined;
}
export interface $ZodURLInternals extends $ZodStringFormatInternals<"url"> {
  def: $ZodURLDef;
}

export interface $ZodURL extends $ZodType {
  _zod: $ZodURLInternals;
}

/** The `://` guard rejected the input before the URL constructor saw it. */
export const URL_BAD_FORMAT = 1;
/** The URL parser rejected the input. */
export const URL_UNPARSEABLE = 2;

export function canParseURL(input: string): boolean {
  try {
    if (typeof URL !== "undefined" && typeof URL.canParse === "function") return URL.canParse(input);
    new URL(input);
    return true;
  } catch {
    return false;
  }
}

export function validateURL(
  trimmed: string,
  def: Pick<$ZodURLDef, "protocol" | "hostname" | "normalize">
): URL | true | typeof URL_BAD_FORMAT | typeof URL_UNPARSEABLE {
  if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) {
    return canParseURL(trimmed) || URL_UNPARSEABLE;
  }
  return parseURLObject(trimmed, def);
}

/** Parses a URL while preserving the non-normalizing HTTP guard. */
export function parseURLObject(
  trimmed: string,
  def: Pick<$ZodURLDef, "protocol" | "normalize">
): URL | typeof URL_BAD_FORMAT | typeof URL_UNPARSEABLE {
  // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted
  if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\/\//i.test(trimmed)) {
    return URL_BAD_FORMAT;
  }

  try {
    if (typeof URL !== "undefined") {
      const URLStatic = URL as typeof URL & { parse?: (input: string) => URL | null };
      if (typeof URLStatic.parse === "function") return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;
    }
    // @ts-ignore
    return new URL(trimmed);
  } catch {
    return URL_UNPARSEABLE;
  }
}

const asciiTabOrNewline = /[\t\n\r]/g;

/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */
export function stripTabAndNewline(value: string): string {
  return value.replace(asciiTabOrNewline, "");
}

export function urlHostnameOk(url: URL, hostname: RegExp): boolean {
  hostname.lastIndex = 0;
  return hostname.test(url.hostname);
}

export function urlProtocolOk(url: URL, protocol: RegExp): boolean {
  protocol.lastIndex = 0;
  return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
}

export const $ZodURL: core.$constructor<$ZodURL> = /*@__PURE__*/ core.$constructor("$ZodURL", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    try {
      // Trim whitespace from input
      const trimmed = payload.value.trim();
      const url = validateURL(trimmed, def);

      if (url === URL_BAD_FORMAT) {
        payload.issues.push({
          code: "invalid_format",
          format: "url",
          note: "Invalid URL format",
          input: payload.value,
          inst,
          continue: !def.abort,
        });
        return;
      }

      if (url === URL_UNPARSEABLE) {
        payload.issues.push({
          code: "invalid_format",
          format: "url",
          input: payload.value,
          inst,
          continue: !def.abort,
        });
        return;
      }

      if (url === true) {
        payload.value = stripTabAndNewline(trimmed);
        return;
      }

      if (def.hostname && !urlHostnameOk(url, def.hostname)) {
        payload.issues.push({
          code: "invalid_format",
          format: "url",
          note: "Invalid hostname",
          pattern: def.hostname.source,
          input: payload.value,
          inst,
          continue: !def.abort,
        });
      }

      if (def.protocol && !urlProtocolOk(url, def.protocol)) {
        payload.issues.push({
          code: "invalid_format",
          format: "url",
          note: "Invalid protocol",
          pattern: def.protocol.source,
          input: payload.value,
          inst,
          continue: !def.abort,
        });
      }

      // Set the output value based on normalize flag
      payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);

      return;
    } catch (_) {
      payload.issues.push({
        code: "invalid_format",
        format: "url",
        input: payload.value,
        inst,
        continue: !def.abort,
      });
    }
  };
});

//////////////////////////////   ZodEmoji   //////////////////////////////

export interface $ZodEmojiDef extends $ZodStringFormatDef<"emoji"> {}
export interface $ZodEmojiInternals extends $ZodStringFormatInternals<"emoji"> {}

export interface $ZodEmoji extends $ZodType {
  _zod: $ZodEmojiInternals;
}

export const $ZodEmoji: core.$constructor<$ZodEmoji> = /*@__PURE__*/ core.$constructor(
  "$ZodEmoji",
  (inst, def): void => {
    def.pattern ??= regexes.emoji();
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodNanoID   //////////////////////////////

export interface $ZodNanoIDDef extends $ZodStringFormatDef<"nanoid"> {
  length?: number | undefined;
}
export interface $ZodNanoIDInternals extends $ZodStringFormatInternals<"nanoid"> {
  def: $ZodNanoIDDef;
}

export interface $ZodNanoID extends $ZodType {
  _zod: $ZodNanoIDInternals;
}

export const $ZodNanoID: core.$constructor<$ZodNanoID> = /*@__PURE__*/ core.$constructor(
  "$ZodNanoID",
  (inst, def): void => {
    if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))
      throw new Error(`Invalid nanoid length: ${def.length}`);
    def.pattern ??= def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length);
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodCUID   //////////////////////////////

/**
 * @deprecated CUID v1 is deprecated by its authors due to information leakage
 * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.
 * See https://github.com/paralleldrive/cuid.
 */
export interface $ZodCUIDDef extends $ZodStringFormatDef<"cuid"> {}
/**
 * @deprecated CUID v1 is deprecated by its authors due to information leakage
 * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.
 * See https://github.com/paralleldrive/cuid.
 */
export interface $ZodCUIDInternals extends $ZodStringFormatInternals<"cuid"> {}

/**
 * @deprecated CUID v1 is deprecated by its authors due to information leakage
 * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.
 * See https://github.com/paralleldrive/cuid.
 */
export interface $ZodCUID extends $ZodType {
  _zod: $ZodCUIDInternals;
}

/**
 * @deprecated CUID v1 is deprecated by its authors due to information leakage
 * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.
 * See https://github.com/paralleldrive/cuid.
 */
export const $ZodCUID: core.$constructor<$ZodCUID> = /*@__PURE__*/ core.$constructor("$ZodCUID", (inst, def): void => {
  def.pattern ??= regexes.cuid;
  $ZodStringFormat.init(inst, def);
});

//////////////////////////////   ZodCUID2   //////////////////////////////

export interface $ZodCUID2Def extends $ZodStringFormatDef<"cuid2"> {}
export interface $ZodCUID2Internals extends $ZodStringFormatInternals<"cuid2"> {}

export interface $ZodCUID2 extends $ZodType {
  _zod: $ZodCUID2Internals;
}

export const $ZodCUID2: core.$constructor<$ZodCUID2> = /*@__PURE__*/ core.$constructor(
  "$ZodCUID2",
  (inst, def): void => {
    def.pattern ??= regexes.cuid2;
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodULID   //////////////////////////////

export interface $ZodULIDDef extends $ZodStringFormatDef<"ulid"> {}
export interface $ZodULIDInternals extends $ZodStringFormatInternals<"ulid"> {}

export interface $ZodULID extends $ZodType {
  _zod: $ZodULIDInternals;
}

export const $ZodULID: core.$constructor<$ZodULID> = /*@__PURE__*/ core.$constructor("$ZodULID", (inst, def): void => {
  def.pattern ??= regexes.ulid;
  $ZodStringFormat.init(inst, def);
});

//////////////////////////////   ZodXID   //////////////////////////////

export interface $ZodXIDDef extends $ZodStringFormatDef<"xid"> {}
export interface $ZodXIDInternals extends $ZodStringFormatInternals<"xid"> {}

export interface $ZodXID extends $ZodType {
  _zod: $ZodXIDInternals;
}

export const $ZodXID: core.$constructor<$ZodXID> = /*@__PURE__*/ core.$constructor("$ZodXID", (inst, def): void => {
  def.pattern ??= regexes.xid;
  $ZodStringFormat.init(inst, def);
});

//////////////////////////////   ZodKSUID   //////////////////////////////

export interface $ZodKSUIDDef extends $ZodStringFormatDef<"ksuid"> {}
export interface $ZodKSUIDInternals extends $ZodStringFormatInternals<"ksuid"> {}

export interface $ZodKSUID extends $ZodType {
  _zod: $ZodKSUIDInternals;
}

export const $ZodKSUID: core.$constructor<$ZodKSUID> = /*@__PURE__*/ core.$constructor(
  "$ZodKSUID",
  (inst, def): void => {
    def.pattern ??= regexes.ksuid;
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodISODateTime   //////////////////////////////

export interface $ZodISODateTimeDef extends $ZodStringFormatDef<"datetime"> {
  precision: number | null;
  offset: boolean;
  local: boolean;
}

export interface $ZodISODateTimeInternals extends $ZodStringFormatInternals {
  def: $ZodISODateTimeDef;
}

export interface $ZodISODateTime extends $ZodType {
  _zod: $ZodISODateTimeInternals;
}

export const $ZodISODateTime: core.$constructor<$ZodISODateTime> = /*@__PURE__*/ core.$constructor(
  "$ZodISODateTime",
  (inst, def): void => {
    def.pattern ??= regexes.datetime(def);
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodISODate   //////////////////////////////

export interface $ZodISODateDef extends $ZodStringFormatDef<"date"> {}
export interface $ZodISODateInternals extends $ZodStringFormatInternals<"date"> {}

export interface $ZodISODate extends $ZodType {
  _zod: $ZodISODateInternals;
}

export const $ZodISODate: core.$constructor<$ZodISODate> = /*@__PURE__*/ core.$constructor(
  "$ZodISODate",
  (inst, def): void => {
    def.pattern ??= regexes.date;
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodISOTime   //////////////////////////////

export interface $ZodISOTimeDef extends $ZodStringFormatDef<"time"> {
  precision?: number | null;
}

export interface $ZodISOTimeInternals extends $ZodStringFormatInternals<"time"> {
  def: $ZodISOTimeDef;
}

export interface $ZodISOTime extends $ZodType {
  _zod: $ZodISOTimeInternals;
}

export const $ZodISOTime: core.$constructor<$ZodISOTime> = /*@__PURE__*/ core.$constructor(
  "$ZodISOTime",
  (inst, def): void => {
    def.pattern ??= regexes.time(def);
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodISODuration   //////////////////////////////

export interface $ZodISODurationDef extends $ZodStringFormatDef<"duration"> {}
export interface $ZodISODurationInternals extends $ZodStringFormatInternals<"duration"> {}

export interface $ZodISODuration extends $ZodType {
  _zod: $ZodISODurationInternals;
}

export const $ZodISODuration: core.$constructor<$ZodISODuration> = /*@__PURE__*/ core.$constructor(
  "$ZodISODuration",
  (inst, def): void => {
    def.pattern ??= regexes.duration;
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodIPv4   //////////////////////////////

export interface $ZodIPv4Def extends $ZodStringFormatDef<"ipv4"> {
  version?: "v4";
}

export interface $ZodIPv4Internals extends $ZodStringFormatInternals<"ipv4"> {
  def: $ZodIPv4Def;
}

export interface $ZodIPv4 extends $ZodType {
  _zod: $ZodIPv4Internals;
}

export const $ZodIPv4: core.$constructor<$ZodIPv4> = /*@__PURE__*/ core.$constructor("$ZodIPv4", (inst, def): void => {
  def.pattern ??= regexes.ipv4;
  $ZodStringFormat.init(inst, def);
});

//////////////////////////////   ZodIPv6   //////////////////////////////

export interface $ZodIPv6Def extends $ZodStringFormatDef<"ipv6"> {
  version?: "v6";
}

export interface $ZodIPv6Internals extends $ZodStringFormatInternals<"ipv6"> {
  def: $ZodIPv6Def;
}

export interface $ZodIPv6 extends $ZodType {
  _zod: $ZodIPv6Internals;
}

/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */
const ipv6Alphabet = /^[0-9a-fA-F:.]+$/;

export function isValidIPv6(value: string): boolean {
  if (!ipv6Alphabet.test(value)) return false;
  return canParseURL(`http://[${value}]`);
}

export const $ZodIPv6: core.$constructor<$ZodIPv6> = /*@__PURE__*/ core.$constructor("$ZodIPv6", (inst, def): void => {
  def.pattern ??= regexes.ipv6;
  $ZodStringFormat.init(inst, def);

  inst._zod.check = (payload) => {
    if (!isValidIPv6(payload.value)) {
      payload.issues.push({
        code: "invalid_format",
        format: "ipv6",
        input: payload.value,
        inst,
        continue: !def.abort,
      });
    }
  };
});

//////////////////////////////   ZodMAC   //////////////////////////////
export interface $ZodMACDef extends $ZodStringFormatDef<"mac"> {
  delimiter?: string;
}

export interface $ZodMACInternals extends $ZodStringFormatInternals<"mac"> {
  def: $ZodMACDef;
}

export interface $ZodMAC extends $ZodType {
  _zod: $ZodMACInternals;
}

export const $ZodMAC: core.$constructor<$ZodMAC> = /*@__PURE__*/ core.$constructor("$ZodMAC", (inst, def): void => {
  def.pattern ??= regexes.mac(def.delimiter);
  $ZodStringFormat.init(inst, def);
});

//////////////////////////////   ZodCIDRv4   //////////////////////////////

export interface $ZodCIDRv4Def extends $ZodStringFormatDef<"cidrv4"> {
  version?: "v4";
}

export interface $ZodCIDRv4Internals extends $ZodStringFormatInternals<"cidrv4"> {
  def: $ZodCIDRv4Def;
}

export interface $ZodCIDRv4 extends $ZodType {
  _zod: $ZodCIDRv4Internals;
}

export const $ZodCIDRv4: core.$constructor<$ZodCIDRv4> = /*@__PURE__*/ core.$constructor(
  "$ZodCIDRv4",
  (inst, def): void => {
    def.pattern ??= regexes.cidrv4;
    $ZodStringFormat.init(inst, def);
  }
);

//////////////////////////////   ZodCIDRv6   //////////////////////////////

export interface $ZodCIDRv6Def extends $ZodStringFormatDef<"cidrv6"> {
  version?: "v6";
}

export interface $ZodCIDRv6Internals extends $ZodStringFormatInternals<"cidrv6"> {
  def: $ZodCIDRv6Def;
}

export interface $ZodCIDRv6 extends $ZodType {
  _zod: $ZodCIDRv6Internals;
}

export function isValidCIDRv6(value: string): boolean {
  const parts = value.split("/");
  if (parts.length !== 2) return false;
  const [address, prefix] = parts;
  if (!prefix) return false;
  const prefixNum = Number(prefix);
  if (`${prefixNum}` !== prefix) return false;
  if (prefixNum < 0 || prefixNum > 128) return false;
  return isValidIPv6(address);
}

export const $ZodCIDRv6: core.$constructor<$ZodCIDRv6> = /*@__PURE__*/ core.$constructor(
  "$ZodCIDRv6",
  (inst, def): void => {
    def.pattern ??= regexes.cidrv6; // not used for validation
    $ZodStringFormat.init(inst, def);

    inst._zod.check = (payload) => {
      if (!isValidCIDRv6(payload.value)) {
        payload.issues.push({
          code: "invalid_format",
          format: "cidrv6",
          input: payload.value,
          inst,
          continue: !def.abort,
        });
      }
    };
  }
);

//////////////////////////////   ZodBase64   //////////////////////////////
export function isValidBase64(data: string): boolean {
  if (data === "") return true;
  // atob ignores whitespace, so reject it up front.
  if (/\s/.test(data)) return false;
  if (data.length % 4 !== 0) return false;
  try {
    // @ts-ignore
    atob(data);
    return true;
  } catch {
    return false;
  }
}

export interface $ZodBase64Def extends $ZodStringFormatDef<"base64"> {}
export interface $ZodBase64Internals extends $ZodStringFormatInternals<"base64"> {}

export interface $ZodBase64 extends $ZodType {
  _zod: $ZodBase64Internals;
}

// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding
export const base64Charset: RegExp = /^[0-9a-zA-Z+/]*={0,2}$/;

export const $ZodBase64: core.$constructor<$ZodBase64> = /*@__PURE__*/ core.$constructor(
  "$ZodBase64",
  (inst, def): void => {
    def.pattern ??= base64Charset;
    $ZodStringFormat.init(inst, def);

    inst._zod.check = (payload) => {
      if (isValidBase64(payload.value)) return;

      payload.issues.push({
        code: "invalid_format",
        format: "base64",
        input: payload.value,
        inst,
        continue: !def.abort,
      });
    };
  }
);

//////////////////////////////   ZodBase64URL   //////////////////////////////
// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string
export const base64urlCharset: RegExp = /^[A-Za-z0-9_-]*$/;

export function isValidBase64URL(data: string): boolean {
  if (!base64urlCharset.test(data)) return false;
  const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/"));
  const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
  return isValidBase64(padded);
}

export interface $ZodBase64URLDef extends $ZodStringFormatDef<"base64url"> {}
export interface $ZodBase64URLInternals extends $ZodStringFormatInternals<"base64url"> {}

export interface $ZodBase64URL extends $ZodType {
  _zod: $ZodBase64URLInternals;
}

export const $ZodBase64URL: core.$constructor<$ZodBase64URL> = /*@__PURE__*/ core.$constructor(
  "$ZodBase64URL",
  (inst, def): void => {
    def.pattern ??= base64urlCharset;
    $ZodStringFormat.init(inst, def);

    inst._zod.check = (payload) => {
      if (isValidBase64URL(payload.value)) return;

      payload.issues.push({
        code: "invalid_format",
        format: "base64url",
        input: payload.value,
        inst,
        continue: !def.abort,
      });
    };
  }
);

//////////////////////////////   ZodE164   //////////////////////////////

export interface $ZodE164Def extends $ZodStringFormatDef<"e164"> {}
export interface $ZodE164Internals extends $ZodStringFormatInternals<"e164"> {}

export interface $ZodE164 extends $ZodType {
  _zod: $ZodE164Internals;
}

export const $ZodE164: core.$constructor<$ZodE164> = /*@__PURE__*/ core.$constructor("$ZodE164", (inst, def): void => {
  def.pattern ??= regexes.e164;
  $ZodStringFormat.init(inst, def);
});

//////////////////////////////   ZodCreditCard   //////////////////////////////

const CC_SANITIZE = /[- ]/g;

/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */
function isLuhnAlgo(digits: string): boolean {
  let length = digits.length;
  let bit = 1;
  let sum = 0;
  while (length) {
    const value = digits.charCodeAt(--length) - 48;
    bit ^= 1;
    sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value]! : value;
  }
  return sum % 10 === 0;
}

export function isValidCreditCard(input: string): boolean {
  if (!regexes.creditCard.test(input)) return false;
  return isLuhnAlgo(input.replace(CC_SANITIZE, ""));
}

export interface $ZodCreditCardDef extends $ZodStringFormatDef<"credit_card"> {}
export interface $ZodCreditCardInternals extends $ZodStringFormatInternals<"credit_card"> {
  def: $ZodCreditCardDef;
}

export interface $ZodCreditCard extends $ZodType {
  _zod: $ZodCreditCardInternals;
}

export const $ZodCreditCard: core.$constructor<$ZodCreditCard> = /*@__PURE__*/ core.$constructor(
  "$ZodCreditCard",
  (inst, def): void => {
    // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.
    def.pattern ??= regexes.creditCard;
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
      if (isValidCreditCard(payload.value)) return;
      payload.issues.push({
        code: "invalid_format",
        format: "credit_card",
        input: payload.value,
        inst,
        continue: !def.abort,
      });
    };
  }
);

//////////////////////////////   ZodIBAN   //////////////////////////////

// iso 7064 mod 97-10 checksum without BigInt
function isIso7064Mod97(iban: string): boolean {
  let remainder = 0;
  const len = iban.length;
  for (let i = 4; i < len; i++) {
    const code = iban.charCodeAt(i);
    remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;
  }
  for (let i = 0; i < 4; i++) {
    const code = iban.charCodeAt(i);
    remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;
  }
  return remainder === 1;
}

export function isValidIBAN(input: string): boolean {
  if (!regexes.iban.test(input)) return false;
  return isIso7064Mod97(input);
}

export interface $ZodIBANDef extends $ZodStringFormatDef<"iban"> {}
export interface $ZodIBANInternals extends $ZodStringFormatInternals<"iban"> {
  def: $ZodIBANDef;
}

export interface $ZodIBAN extends $ZodType {
  _zod: $ZodIBANInternals;
}

export const $ZodIBAN: core.$constructor<$ZodIBAN> = /*@__PURE__*/ core.$constructor("$ZodIBAN", (inst, def): void => {
  // shape only — checksum is not expressible as a pattern
  def.pattern ??= regexes.iban;
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (isValidIBAN(payload.value)) return;
    payload.issues.push({
      code: "invalid_format",
      format: "iban",
      input: payload.value,
      inst,
      continue: !def.abort,
    });
  };
});

//////////////////////////////   ZodJWT   //////////////////////////////

export function isValidJWT(token: string, algorithm: util.JWTAlgorithm | null = null): boolean {
  try {
    const tokensParts = token.split(".");
    if (tokensParts.length !== 3) return false;
    const [header] = tokensParts;
    if (!header) return false;
    // @ts-ignore
    const parsedHeader = JSON.parse(atob(header));
    if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
    if (!parsedHeader.alg) return false;
    if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
    return true;
  } catch {
    return false;
  }
}

export interface $ZodJWTDef extends $ZodStringFormatDef<"jwt"> {
  alg?: util.JWTAlgorithm | undefined;
}

export interface $ZodJWTInternals extends $ZodStringFormatInternals<"jwt"> {
  def: $ZodJWTDef;
}

export interface $ZodJWT extends $ZodType {
  _zod: $ZodJWTInternals;
}

export const $ZodJWT: core.$constructor<$ZodJWT> = /*@__PURE__*/ core.$constructor("$ZodJWT", (inst, def): void => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (isValidJWT(payload.value, def.alg)) return;

    payload.issues.push({
      code: "invalid_format",
      format: "jwt",
      input: payload.value,
      inst,
      continue: !def.abort,
    });
  };
});

//////////////////////////////   ZodCustomStringFormat   //////////////////////////////

export interface $ZodCustomStringFormatDef<Format extends string = string> extends $ZodStringFormatDef<Format> {
  fn: (val: string) => unknown;
}

export interface $ZodCustomStringFormatInternals<Format extends string = string>
  extends $ZodStringFormatInternals<Format> {
  def: $ZodCustomStringFormatDef<Format>;
}

export interface $ZodCustomStringFormat<Format extends string = string> extends $ZodStringFormat<Format> {
  _zod: $ZodCustomStringFormatInternals<Format>;
}

export const $ZodCustomStringFormat: core.$constructor<$ZodCustomStringFormat> = /*@__PURE__*/ core.$constructor(
  "$ZodCustomStringFormat",
  (inst, def): void => {
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
      if (def.fn(payload.value)) return;

      payload.issues.push({
        code: "invalid_format",
        format: def.format,
        input: payload.value,
        inst,
        continue: !def.abort,
      });
    };
  }
);

/////////////////////////////////////////
/////////////////////////////////////////
//////////                     //////////
//////////      ZodNumber      //////////
//////////                     //////////
/////////////////////////////////////////
/////////////////////////////////////////

export interface $ZodNumberDef extends $ZodTypeDef {
  type: "number";
  coerce?: boolean;
  // checks: checks.$ZodCheck<number>[];
}

export interface $ZodNumberInternals<Input = unknown> extends $ZodTypeInternals<number, Input> {
  def: $ZodNumberDef;
  /** @deprecated Internal API, use with caution (not deprecated) */
  pattern: RegExp;
  /** @deprecated Internal API, use with caution (not deprecated) */
  isst: errors.$ZodIssueInvalidType;
  bag: util.LoosePartial<{
    minimum: number;
    maximum: number;
    exclusiveMinimum: number;
    exclusiveMaximum: number;
    format: string;
    pattern: RegExp;
  }>;
}

export interface $ZodNumber<Input = unknown> extends $ZodType {
  _zod: $ZodNumberInternals<Input>;
}

export const $ZodNumber: core.$constructor<$ZodNumber> = /*@__PURE__*/ core.$constructor("$ZodNumber", (inst, def) => {
  $ZodType.init(inst, def);

  inst._zod.pattern = regexes.number;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Number(payload.value);
      } catch (_) {}
    const input = payload.value;
    if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
      return payload;
    }

    const received =
      typeof input === "number"
        ? Number.isNaN(input)
          ? "NaN"
          : !Number.isFinite(input)
            ? String(input)
            : undefined
        : undefined;

    payload.issues.push({
      expected: "number",
      code: "invalid_type",

      input,
      inst,
      ...(received ? { received } : {}),
    });
    return payload;
  };
});

///////////////////////////////////////////////
//////////      ZodNumberFormat      //////////
///////////////////////////////////////////////
export interface $ZodNumberFormatDef<Format extends $ZodNumberFormats = $ZodNumberFormats>
  extends $ZodNumberDef,
    checks.$ZodCheckNumberFormatDef<Format> {}

export interface $ZodNumberFormatInternals<Format extends $ZodNumberFormats = $ZodNumberFormats>
  extends $ZodNumberInternals<number>,
    checks.$ZodCheckNumberFormatInternals<Format> {
  def: $ZodNumberFormatDef<Format>;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodNumberFormat<Format extends $ZodNumberFormats = $ZodNumberFormats> extends $ZodType {
  _zod: $ZodNumberFormatInternals<Format>;
}

export const $ZodNumberFormat: core.$constructor<$ZodNumberFormat> = /*@__PURE__*/ core.$constructor(
  "$ZodNumberFormat",
  (inst, def) => {
    checks.$ZodCheckNumberFormat.init(inst, def);
    $ZodNumber.init(inst, def); // no format checks
  }
);

///////////////////////////////////////////
///////////////////////////////////////////
//////////                      ///////////
//////////      $ZodBoolean      //////////
//////////                      ///////////
///////////////////////////////////////////
///////////////////////////////////////////

export interface $ZodBooleanDef extends $ZodTypeDef {
  type: "boolean";
  coerce?: boolean;
  checks?: checks.$ZodCheck<boolean>[];
}

export interface $ZodBooleanInternals<T = unknown> extends $ZodTypeInternals<boolean, T> {
  pattern: RegExp;
  def: $ZodBooleanDef;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodBoolean<T = unknown> extends $ZodType {
  _zod: $ZodBooleanInternals<T>;
}

export const $ZodBoolean: core.$constructor<$ZodBoolean> = /*@__PURE__*/ core.$constructor(
  "$ZodBoolean",
  (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = regexes.boolean;

    inst._zod.parse = (payload, _ctx) => {
      if (def.coerce)
        try {
          payload.value = Boolean(payload.value);
        } catch (_) {}
      const input = payload.value;
      if (typeof input === "boolean") return payload;
      payload.issues.push({
        expected: "boolean",
        code: "invalid_type",

        input,
        inst,
      });
      return payload;
    };
  }
);

//////////////////////////////////////////
//////////////////////////////////////////
//////////                      //////////
//////////      $ZodBigInt      //////////
//////////                      //////////
//////////////////////////////////////////
//////////////////////////////////////////

export interface $ZodBigIntDef extends $ZodTypeDef {
  type: "bigint";
  coerce?: boolean;
  // checks: checks.$ZodCheck<bigint>[];
}

export interface $ZodBigIntInternals<T = unknown> extends $ZodTypeInternals<bigint, T> {
  pattern: RegExp;
  /** @internal Internal API, use with caution */
  def: $ZodBigIntDef;
  isst: errors.$ZodIssueInvalidType;
  bag: util.LoosePartial<{
    minimum: bigint;
    maximum: bigint;
    format: string;
  }>;
}

export interface $ZodBigInt<T = unknown> extends $ZodType {
  _zod: $ZodBigIntInternals<T>;
}

export const $ZodBigInt: core.$constructor<$ZodBigInt> = /*@__PURE__*/ core.$constructor("$ZodBigInt", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = regexes.bigint;

  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = BigInt(payload.value);
      } catch (_) {}

    if (typeof payload.value === "bigint") return payload;
    payload.issues.push({
      expected: "bigint",
      code: "invalid_type",

      input: payload.value,
      inst,
    });
    return payload;
  };
});

///////////////////////////////////////////////
//////////      ZodBigIntFormat      //////////
///////////////////////////////////////////////
export interface $ZodBigIntFormatDef<Format extends $ZodBigIntFormats = $ZodBigIntFormats>
  extends $ZodBigIntDef,
    checks.$ZodCheckBigIntFormatDef<Format> {
  check: "bigint_format";
}

export interface $ZodBigIntFormatInternals<Format extends $ZodBigIntFormats = $ZodBigIntFormats>
  extends $ZodBigIntInternals<bigint>,
    checks.$ZodCheckBigIntFormatInternals<Format> {
  def: $ZodBigIntFormatDef<Format>;
}

export interface $ZodBigIntFormat<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends $ZodType {
  _zod: $ZodBigIntFormatInternals<Format>;
}

export const $ZodBigIntFormat: core.$constructor<$ZodBigIntFormat> = /*@__PURE__*/ core.$constructor(
  "$ZodBigIntFormat",
  (inst, def) => {
    checks.$ZodCheckBigIntFormat.init(inst, def);
    $ZodBigInt.init(inst, def); // no format checks
  }
);

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////       $ZodSymbol       //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
export interface $ZodSymbolDef extends $ZodTypeDef {
  type: "symbol";
}

export interface $ZodSymbolInternals extends $ZodTypeInternals<symbol, symbol> {
  def: $ZodSymbolDef;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodSymbol extends $ZodType {
  _zod: $ZodSymbolInternals;
}

export const $ZodSymbol: core.$constructor<$ZodSymbol> = /*@__PURE__*/ core.$constructor("$ZodSymbol", (inst, def) => {
  $ZodType.init(inst, def);

  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "symbol") return payload;
    payload.issues.push({
      expected: "symbol",
      code: "invalid_type",

      input,
      inst,
    });
    return payload;
  };
});

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////      $ZodUndefined     //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
export interface $ZodUndefinedDef extends $ZodTypeDef {
  type: "undefined";
}

export interface $ZodUndefinedInternals extends $ZodTypeInternals<undefined, undefined> {
  pattern: RegExp;
  def: $ZodUndefinedDef;
  values: util.PrimitiveSet;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodUndefined extends $ZodType {
  _zod: $ZodUndefinedInternals;
}

export const $ZodUndefined: core.$constructor<$ZodUndefined> = /*@__PURE__*/ core.$constructor(
  "$ZodUndefined",
  (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = regexes.undefined;
    inst._zod.values = new Set([undefined]);

    inst._zod.parse = (payload, _ctx) => {
      const input = payload.value;
      if (typeof input === "undefined") return payload;
      payload.issues.push({
        expected: "undefined",
        code: "invalid_type",

        input,
        inst,
      });
      return payload;
    };
  }
);

///////////////////////////////////////
///////////////////////////////////////
//////////                   //////////
//////////      $ZodNull      /////////
//////////                   //////////
///////////////////////////////////////
///////////////////////////////////////

export interface $ZodNullDef extends $ZodTypeDef {
  type: "null";
}

export interface $ZodNullInternals extends $ZodTypeInternals<null, null> {
  pattern: RegExp;
  def: $ZodNullDef;
  values: util.PrimitiveSet;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodNull extends $ZodType {
  _zod: $ZodNullInternals;
}

export const $ZodNull: core.$constructor<$ZodNull> = /*@__PURE__*/ core.$constructor("$ZodNull", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = regexes.null;
  inst._zod.values = new Set([null]);

  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input === null) return payload;
    payload.issues.push({
      expected: "null",
      code: "invalid_type",

      input,
      inst,
    });
    return payload;
  };
});

//////////////////////////////////////
//////////////////////////////////////
//////////                  //////////
//////////      $ZodAny     //////////
//////////                  //////////
//////////////////////////////////////
//////////////////////////////////////

export interface $ZodAnyDef extends $ZodTypeDef {
  type: "any";
}

export interface $ZodAnyInternals extends $ZodTypeInternals<any, any> {
  def: $ZodAnyDef;
  isst: never;
}

export interface $ZodAny extends $ZodType {
  _zod: $ZodAnyInternals;
}

export const $ZodAny: core.$constructor<$ZodAny> = /*@__PURE__*/ core.$constructor("$ZodAny", (inst, def) => {
  $ZodType.init(inst, def);

  inst._zod.parse = (payload) => payload;
});

//////////////////////////////////////////
//////////////////////////////////////////
//////////                      //////////
//////////      $ZodUnknown     //////////
//////////                      //////////
//////////////////////////////////////////
//////////////////////////////////////////

export interface $ZodUnknownDef extends $ZodTypeDef {
  type: "unknown";
}

export interface $ZodUnknownInternals extends $ZodTypeInternals<unknown, unknown> {
  def: $ZodUnknownDef;
  isst: never;
}

export interface $ZodUnknown extends $ZodType {
  _zod: $ZodUnknownInternals;
}

export const $ZodUnknown: core.$constructor<$ZodUnknown> = /*@__PURE__*/ core.$constructor(
  "$ZodUnknown",
  (inst, def) => {
    $ZodType.init(inst, def);

    inst._zod.parse = (payload) => payload;
  }
);

/////////////////////////////////////////
/////////////////////////////////////////
//////////                     //////////
//////////      $ZodNever      //////////
//////////                     //////////
/////////////////////////////////////////
/////////////////////////////////////////

export interface $ZodNeverDef extends $ZodTypeDef {
  type: "never";
}

export interface $ZodNeverInternals extends $ZodTypeInternals<never, never> {
  def: $ZodNeverDef;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodNever extends $ZodType {
  _zod: $ZodNeverInternals;
}

export const $ZodNever: core.$constructor<$ZodNever> = /*@__PURE__*/ core.$constructor("$ZodNever", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    payload.issues.push({
      expected: "never",
      code: "invalid_type",

      input: payload.value,
      inst,
    });
    return payload;
  };
});

////////////////////////////////////////
////////////////////////////////////////
//////////                    //////////
//////////      $ZodVoid      //////////
//////////                    //////////
////////////////////////////////////////
////////////////////////////////////////

export interface $ZodVoidDef extends $ZodTypeDef {
  type: "void";
}

export interface $ZodVoidInternals extends $ZodTypeInternals<void, void> {
  def: $ZodVoidDef;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodVoid extends $ZodType {
  _zod: $ZodVoidInternals;
}

export const $ZodVoid: core.$constructor<$ZodVoid> = /*@__PURE__*/ core.$constructor("$ZodVoid", (inst, def) => {
  $ZodType.init(inst, def);

  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined") return payload;
    payload.issues.push({
      expected: "void",
      code: "invalid_type",

      input,
      inst,
    });
    return payload;
  };
});

///////////////////////////////////////
///////////////////////////////////////
//////////                     ////////
//////////      $ZodDate        ////////
//////////                     ////////
///////////////////////////////////////
///////////////////////////////////////
export interface $ZodDateDef extends $ZodTypeDef {
  type: "date";
  coerce?: boolean;
}

export interface $ZodDateInternals<T = unknown> extends $ZodTypeInternals<Date, T> {
  def: $ZodDateDef;
  isst: errors.$ZodIssueInvalidType; // | errors.$ZodIssueInvalidDate;
  bag: util.LoosePartial<{
    minimum: Date;
    maximum: Date;
    format: string;
  }>;
}

export interface $ZodDate<T = unknown> extends $ZodType {
  _zod: $ZodDateInternals<T>;
}

export const $ZodDate: core.$constructor<$ZodDate> = /*@__PURE__*/ core.$constructor("$ZodDate", (inst, def) => {
  $ZodType.init(inst, def);

  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce) {
      try {
        payload.value = new Date(payload.value as string | number | Date);
      } catch (_err: any) {}
    }
    const input = payload.value;

    const isDate = input instanceof Date;
    const isValidDate = isDate && !Number.isNaN(input.getTime());
    if (isValidDate) return payload;
    payload.issues.push({
      expected: "date",
      code: "invalid_type",

      input,
      ...(isDate ? { received: "Invalid Date" } : {}),
      inst,
    });

    return payload;
  };
});

/////////////////////////////////////////
/////////////////////////////////////////
//////////                     //////////
//////////      $ZodArray      //////////
//////////                     //////////
/////////////////////////////////////////
/////////////////////////////////////////

export interface $ZodArrayDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "array";
  element: T;
}

export interface $ZodArrayInternals<T extends SomeType = $ZodType> extends _$ZodTypeInternals {
  //$ZodTypeInternals<core.output<T>[], core.input<T>[]> {
  def: $ZodArrayDef<T>;
  isst: errors.$ZodIssueInvalidType;
  output: core.output<T>[];
  input: core.input<T>[];
}

export interface $ZodArray<T extends SomeType = $ZodType> extends $ZodType<any, any, $ZodArrayInternals<T>> {}

function handleArrayResult(result: ParsePayload<any>, final: ParsePayload<any[]>, index: number) {
  if (result.issues.length) {
    final.issues.push(...util.prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}

export const $ZodArray: core.$constructor<$ZodArray> = /*@__PURE__*/ core.$constructor("$ZodArray", (inst, def) => {
  $ZodType.init(inst, def);

  const memo = core.globalConfig.memoizer;
  memo?.attach(inst);

  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;

    if (!Array.isArray(input)) {
      payload.issues.push({
        expected: "array",
        code: "invalid_type",

        input,
        inst,
      });
      return payload;
    }

    payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);
    const proms: Promise<any>[] = [];
    const abortEarly = ctx?.abortEarly;
    for (let i = 0; i < input.length; i++) {
      const item = input[i];
      const result = def.element._zod.run(
        {
          value: item,
          issues: [],
        },
        ctx
      );

      if (result instanceof Promise) {
        proms.push(result.then((result) => handleArrayResult(result, payload, i)));
      } else {
        handleArrayResult(result, payload, i);
        // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional
        if (abortEarly && result.issues.length !== 0 && util.aborted(result)) break;
      }
    }

    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }

    return payload; //handleArrayResultsAsync(parseResults, final);
  };
});

//////////////////////////////////////////
//////////////////////////////////////////
//////////                      //////////
//////////      $ZodObject      //////////
//////////                      //////////
//////////////////////////////////////////
//////////////////////////////////////////

type OptionalOutSchema = { _zod: { optout: "optional" } };
type OptionalInSchema = { _zod: { optin: "optional" | "defaulted" } };

export type $InferObjectOutput<T extends $ZodLooseShape, Extra extends Record<string, unknown>> = string extends keyof T
  ? util.IsAny<T[keyof T]> extends true
    ? Record<string, unknown>
    : { [k in string]: core.output<T[keyof T]> }
  : keyof (T & Extra) extends never
    ? Record<string, never>
    : util.Prettify<
        {
          -readonly [k in keyof T as T[k] extends OptionalOutSchema ? never : k]: T[k]["_zod"]["output"];
        } & {
          -readonly [k in keyof T as T[k] extends OptionalOutSchema ? k : never]?: T[k]["_zod"]["output"];
        } & Extra
      >;

// experimental
// export type $InferObjectOutput<T extends $ZodLooseShape, Extra extends Record<string, unknown>> = keyof (T &
//   Extra) extends never
//   ? Record<string, never>
//   : string extends keyof T
//     ? util.Prettify<
//         {
//           [k: string]: util.IsAny<T[string]["_zod"]["output"]> extends true ? unknown : T[string]["_zod"]["output"];
//         } & $InferObjectOutputNoIndex<util.OmitIndexSignature<T>, Extra>
//       >
//     : util.Prettify<$InferObjectOutputNoIndex<T, Extra>>;

// export type $InferObjectOutputNoIndex<T extends $ZodLooseShape, Extra extends Record<string, unknown>> = {
//   [k in keyof T as string extends k
//     ? never
//     : k extends string
//       ? T[k] extends OptionalOutSchema
//         ? never
//         : k
//       : never]: T[k]["_zod"]["output"];
// } & {
//   [k in keyof T as string extends k
//     ? never
//     : k extends string
//       ? T[k] extends OptionalOutSchema
//         ? k
//         : never
//       : never]?: T[k]["_zod"]["output"];
// } & Extra;

export type $InferObjectInput<T extends $ZodLooseShape, Extra extends Record<string, unknown>> = string extends keyof T
  ? util.IsAny<T[keyof T]> extends true
    ? Record<string, unknown>
    : { [k in string]: core.input<T[keyof T]> }
  : keyof (T & Extra) extends never
    ? Record<string, never>
    : util.Prettify<
        {
          -readonly [k in keyof T as T[k] extends OptionalInSchema ? never : k]: T[k]["_zod"]["input"];
        } & {
          -readonly [k in keyof T as T[k] extends OptionalInSchema ? k : never]?: T[k]["_zod"]["input"];
        } & Extra
      >;

function handlePropertyResult(
  result: ParsePayload,
  final: ParsePayload,
  key: PropertyKey,
  input: any,
  optin: "optional" | "defaulted" | undefined,
  optout: "optional" | undefined
) {
  const isPresent = key in input;
  const isOptionalOut = optout === "optional";
  // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.
  if (!isPresent && isOptionalOut && optin === "optional") {
    return;
  }
  if (result.issues.length) {
    // For optional-in/out schemas, ignore errors on absent keys.
    if (optin !== undefined && isOptionalOut && !isPresent) {
      return;
    }
    final.issues.push(...util.prefixIssues(key, result.issues));
  }

  if (!isPresent && optin === undefined) {
    if (!result.issues.length) {
      final.issues.push({
        code: "invalid_type",
        expected: "nonoptional",
        input: undefined,
        path: [key],
      });
    }
    return;
  }

  if (result.value === undefined) {
    if (isPresent || (optin === "defaulted" && !isOptionalOut)) {
      (final.value as any)[key] = undefined;
    }
  } else {
    (final.value as any)[key] = result.value;
  }
}

export type $ZodObjectConfig = { out: Record<string, unknown>; in: Record<string, unknown> };

export type $loose = {
  out: Record<string, unknown>;
  in: Record<string, unknown>;
};
export type $strict = {
  out: {};
  in: {};
};
export type $strip = {
  out: {};
  in: {};
};

export type $catchall<T extends SomeType> = {
  out: { [k: string]: core.output<T> };
  in: { [k: string]: core.input<T> };
};

export type $ZodShape = Readonly<{ [k: string]: $ZodType }>;

export interface $ZodObjectDef<Shape extends $ZodShape = $ZodShape> extends $ZodTypeDef {
  type: "object";
  shape: Shape;
  catchall?: $ZodType | undefined;
}

export interface $ZodObjectInternals<
  /** @ts-ignore Cast variance */
  out Shape extends $ZodShape = $ZodShape,
  out Config extends $ZodObjectConfig = $ZodObjectConfig,
> extends _$ZodTypeInternals {
  def: $ZodObjectDef<Shape>;
  config: Config;
  isst: errors.$ZodIssueInvalidType | errors.$ZodIssueUnrecognizedKeys;
  propValues: util.PropValues;
  output: $InferObjectOutput<Shape, Config["out"]>;
  input: $InferObjectInput<Shape, Config["in"]>;
  optin?: "optional" | undefined;
  optout?: "optional" | undefined;
}
export type $ZodLooseShape = Record<string, any>;

export interface $ZodObject<
  /** @ts-ignore Cast variance */
  out Shape extends Readonly<$ZodShape> = Readonly<$ZodShape>,
  out Params extends $ZodObjectConfig = $ZodObjectConfig,
> extends $ZodType<any, any, $ZodObjectInternals<Shape, Params>> {}

// one shared instance; a fresh [] per schema cost 56 bytes retained
const NO_SYMBOL_KEYS: symbol[] = [];

function normalizeDef(def: $ZodObjectDef) {
  const keys = Object.keys(def.shape);
  const ownSymbols = Object.getOwnPropertySymbols(def.shape);
  const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;
  // aliases `keys` when there are no symbols, so a string-only shape keeps one array
  const allKeys: (string | symbol)[] = symbolKeys.length ? [...keys, ...symbolKeys] : keys;
  for (const k of allKeys) {
    if (!(def.shape as any)?.[k]?._zod?.traits?.has("$ZodType")) {
      throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);
    }
  }
  const okeys = util.optionalKeys(def.shape);

  return {
    ...def,
    allKeys,
    symbolKeys,
    // string-only: handleCatchall matches it against `for...in`, which never yields a symbol
    keySet: new Set(keys),
    numKeys: keys.length,
    optionalKeys: new Set(okeys),
  };
}

function handleCatchall(
  proms: Promise<any>[],
  input: any,
  payload: ParsePayload,
  ctx: ParseContextInternal,
  def: ReturnType<typeof normalizeDef>,
  inst: $ZodObject,
  abortEarly: boolean
) {
  const unrecognized: string[] = [];
  const keySet = def.keySet;
  const _catchall = def.catchall!._zod;
  const t = _catchall.def.type;
  const optin = _catchall.optin;
  const optout = _catchall.optout;
  // starts at 0, not the current length: the shape phase already ran and may have aborted
  let seen = 0;
  for (const key in input) {
    if (abortEarly && payload.issues.length !== seen) {
      if (util.aborted(payload, seen)) break;
      seen = payload.issues.length;
    }
    // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.
    if (keySet.has(key)) continue;
    // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.
    if (key === "__proto__") {
      if (t === "never") unrecognized.push(key);
      continue;
    }
    if (t === "never") {
      unrecognized.push(key);
      continue;
    }
    const r = _catchall.run({ value: input[key], issues: [] }, ctx);

    if (r instanceof Promise) {
      proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
    } else {
      handlePropertyResult(r, payload, key, input, optin, optout);
    }
  }

  if (unrecognized.length) {
    payload.issues.push({
      code: "unrecognized_keys",
      keys: unrecognized,
      input,
      inst,
      // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.
      continue: true,
    });
  }

  if (!proms.length) return payload;
  return Promise.all(proms).then(() => {
    return payload;
  });
}

export const $ZodObject: core.$constructor<$ZodObject> = /*@__PURE__*/ core.$constructor("$ZodObject", (inst, def) => {
  // requires cast because technically $ZodObject doesn't extend
  $ZodType.init(inst, def);
  const desc = Object.getOwnPropertyDescriptor(def, "shape");
  // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it
  const sh = desc?.get ? (desc.get as util.ShapeGetter).raw : (def.shape ?? {});
  if (sh) {
    // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.
    const get: util.ShapeGetter = () => {
      const newSh = { ...sh };
      Object.defineProperty(def, "shape", { value: newSh });
      get.raw = newSh;
      return newSh;
    };
    get.raw = sh;
    Object.defineProperty(def, "shape", { get });
  }

  const _normalized = util.cached(() => normalizeDef(def));

  util.defineLazyInternal(inst, "propValues", (zod) => {
    const shape = zod.def.shape;
    const propValues: util.PropValues = {};
    for (const key in shape) {
      const field = shape[key]!._zod;
      if (field.values) {
        if (!Object.prototype.hasOwnProperty.call(propValues, key)) {
          util.assignProp(propValues, key, new Set());
        }
        for (const v of field.values) propValues[key].add(v);
        // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.
        if (field.optin !== undefined) propValues[key].add(undefined);
      }
    }
    return propValues;
  });

  const isObject = util.isObject;
  const catchall = def.catchall;

  let value!: typeof _normalized.value;
  const memo = core.globalConfig.memoizer;
  memo?.attach(inst);

  inst._zod.parse = (payload, ctx) => {
    value ??= _normalized.value;
    const input = payload.value;
    if (!isObject(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst,
      });
      return payload;
    }

    payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};

    const proms: Promise<any>[] = [];
    const shape = value.shape;
    const abortEarly = ctx?.abortEarly;
    let seen = payload.issues.length;

    for (const key of value.allKeys) {
      if (abortEarly && payload.issues.length !== seen) {
        if (util.aborted(payload, seen)) break;
        seen = payload.issues.length;
      }
      if (key === "__proto__") continue;
      const el = (shape as any)[key]!;
      const optin = el._zod.optin;
      const optout = el._zod.optout;

      const r = el._zod.run({ value: input[key], issues: [] }, ctx);
      if (r instanceof Promise) {
        proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
      } else {
        handlePropertyResult(r, payload, key, input, optin, optout);
      }
    }

    if (!catchall) {
      return proms.length ? Promise.all(proms).then(() => payload) : payload;
    }

    return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);
  };
});

export const $ZodObjectJIT: core.$constructor<$ZodObject> = /*@__PURE__*/ core.$constructor(
  "$ZodObjectJIT",
  (inst, def) => {
    // requires cast because technically $ZodObject doesn't extend
    $ZodObject.init(inst, def);

    const superParse = inst._zod.parse;
    const _normalized = util.cached(() => normalizeDef(def));

    const memo = core.globalConfig.memoizer;

    const generateFastpass = (shape: any) => {
      const normalized = _normalized.value;
      const syms = normalized.symbolKeys;
      // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope
      const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms });

      const parseStr = (k: string) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;

      // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input
      const prefixStr = (id: string, k: string) => `
          let ${id}_ab = false;
          for (let i = 0; i < ${id}.issues.length; i++) {
            const iss = ${id}.issues[i];
            iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
            payload.issues.push(iss);
            if (iss.continue !== true) ${id}_ab = true;
          }
          if (${id}_ab && ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }`;

      doc.write(`const input = payload.value;`);

      const ids: any = Object.create(null);
      let counter = 0;
      for (const key of normalized.allKeys) {
        ids[key] = `key_${counter++}`;
      }

      // A: preserve key order {
      doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);
      for (const key of normalized.allKeys) {
        if (key === "__proto__") continue;
        const id = ids[key];
        const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util.esc(key);
        const isPresent = `${k} in input`;
        const schema = shape[key];
        const optin = schema?._zod?.optin;
        const isOptionalIn = optin !== undefined;
        const isOptionalOut = schema?._zod?.optout === "optional";

        doc.write(`const ${id} = ${parseStr(k)};`);

        if (isOptionalIn && isOptionalOut) {
          // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.
          const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;
          doc.write(`
        const ${id}_present = ${isPresent};
        if (!${id}.issues.length || ${id}_present) {
          if (${id}.issues.length) {${prefixStr(id, k)}
          }

          if (${assign}) {
            newResult[${k}] = ${id}.value;
          }
        }

      `);
        } else if (!isOptionalIn) {
          doc.write(`
        const ${id}_present = ${isPresent};
        if (${id}.issues.length) {${prefixStr(id, k)}
        }
        if (!${id}_present && !${id}.issues.length) {
          payload.issues.push({
            code: "invalid_type",
            expected: "nonoptional",
            input: undefined,
            path: [${k}]
          });
          if (ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }
        }

        if (${id}_present) {
          newResult[${k}] = ${id}.value;
        }

      `);
        } else {
          doc.write(`
        if (${id}.issues.length) {${prefixStr(id, k)}
        }
      `);
          if (optin === "defaulted") {
            doc.write(`newResult[${k}] = ${id}.value;`);
          } else {
            doc.write(`
        if (${id}.value !== undefined || ${isPresent}) {
          newResult[${k}] = ${id}.value;
        }
      `);
          }
        }
      }

      doc.write(`payload.value = newResult;`);
      doc.write(`return payload;`);
      // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone
      return doc.compile() as (payload: any, ctx: any) => any;
    };

    let fastpass!: ReturnType<typeof generateFastpass>;

    const isObject = util.isObject;
    const jit = !core.globalConfig.jitless;
    const allowsEval = util.allowsEval;

    const fastEnabled = jit && allowsEval.value; // && !def.catchall;
    const catchall = def.catchall;

    let value!: typeof _normalized.value;

    inst._zod.parse = (payload, ctx) => {
      value ??= _normalized.value;
      const input = payload.value;
      if (!isObject(input)) {
        payload.issues.push({
          expected: "object",
          code: "invalid_type",
          input,
          inst,
        });
        return payload;
      }

      if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
        // always synchronous
        if (!fastpass) fastpass = generateFastpass(def.shape);
        payload = fastpass(payload, ctx);

        if (!catchall) return payload;
        return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);
      }

      return superParse(payload, ctx);
    };
  }
);

/////////////////////////////////////////
/////////////////////////////////////////
//////////                    ///////////
//////////      $ZodUnion      //////////
//////////                    ///////////
/////////////////////////////////////////
/////////////////////////////////////////
// use generic to distribute union types
export type $InferUnionOutput<T extends SomeType> = T extends any ? core.output<T> : never;
export type $InferUnionInput<T extends SomeType> = T extends any ? core.input<T> : never;
export interface $ZodUnionDef<Options extends readonly SomeType[] = readonly $ZodType[]> extends $ZodTypeDef {
  type: "union";
  options: Options;
  inclusive?: boolean;
}

type IsOptionalIn<T extends SomeType> = T extends OptionalInSchema ? true : false;
type IsOptionalOut<T extends SomeType> = T extends OptionalOutSchema ? true : false;

export interface $ZodUnionInternals<T extends readonly SomeType[] = readonly $ZodType[]> extends _$ZodTypeInternals {
  def: $ZodUnionDef<T>;
  isst: errors.$ZodIssueInvalidUnion;
  pattern: T[number]["_zod"]["pattern"];
  values: T[number]["_zod"]["values"]; //GetValues<T[number]>;
  output: $InferUnionOutput<T[number]>;
  input: $InferUnionInput<T[number]>;
  // if any element in the union is optional, then the union is optional
  optin: IsOptionalIn<T[number]> extends false ? "optional" | "defaulted" | undefined : "optional" | "defaulted";
  optout: IsOptionalOut<T[number]> extends false ? "optional" | undefined : "optional";
}

export interface $ZodUnion<T extends readonly SomeType[] = readonly $ZodType[]>
  extends $ZodType<any, any, $ZodUnionInternals<T>> {
  _zod: $ZodUnionInternals<T>;
}

function handleUnionResults(results: ParsePayload[], final: ParsePayload, inst: $ZodUnion, ctx?: ParseContext) {
  for (const result of results) {
    if (result.issues.length === 0) {
      final.value = result.value;
      return final;
    }
  }

  const nonaborted = results.filter((r) => !util.aborted(r));
  if (nonaborted.length === 1) {
    final.value = nonaborted[0].value;
    return nonaborted[0];
  }

  final.issues.push({
    code: "invalid_union",

    input: final.value,
    inst,
    errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
  });

  return final;
}

export const $ZodUnion: core.$constructor<$ZodUnion> = /*@__PURE__*/ core.$constructor("$ZodUnion", (inst, def) => {
  $ZodType.init(inst, def);

  util.defineLazyInternal(inst, "optin", (zod) =>
    zod.def.options.some((o) => o._zod.optin === "defaulted")
      ? "defaulted"
      : zod.def.options.some((o) => o._zod.optin !== undefined)
        ? "optional"
        : undefined
  );

  util.defineLazyInternal(inst, "optout", (zod) =>
    zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined
  );

  util.defineLazyInternal(inst, "values", (zod) => {
    if (zod.def.options.every((o) => o._zod.values)) {
      return new Set<util.Primitive>(zod.def.options.flatMap((option) => Array.from(option._zod.values!)));
    }
    return undefined;
  });

  util.defineLazyInternal(inst, "pattern", (zod) => {
    if (zod.def.options.every((o) => o._zod.pattern)) {
      const patterns = zod.def.options.map((o) => o._zod.pattern);
      return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p!.source)).join("|")})$`);
    }
    return undefined;
  });

  const first = def.options.length === 1 ? def.options[0]._zod.run : null;

  inst._zod.parse = (payload, ctx) => {
    if (first) {
      return first(payload, ctx);
    }
    let async = false;

    const results: util.MaybeAsync<ParsePayload>[] = [];
    for (const option of def.options) {
      const result = option._zod.run(
        {
          value: payload.value,
          issues: [],
        },
        ctx
      );
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        if (result.issues.length === 0) return result;
        results.push(result);
      }
    }

    if (!async) return handleUnionResults(results as ParsePayload[], payload, inst, ctx);
    return Promise.all(results).then((results) => {
      return handleUnionResults(results as ParsePayload[], payload, inst, ctx);
    });
  };
});

function handleExclusiveUnionResults(
  results: ParsePayload[],
  final: ParsePayload,
  inst: $ZodUnion,
  ctx?: ParseContext
) {
  const matches: number[] = [];
  for (let i = 0; i < results.length; i++) {
    if (results[i].issues.length === 0) matches.push(i);
  }

  if (matches.length === 1) {
    final.value = results[matches[0]].value;
    return final;
  }

  if (matches.length === 0) {
    // No matches - same as regular union
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
    });
  } else {
    // Multiple matches - exclusive union failure
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: [],
      inclusive: false,
      matches,
    });
  }

  return final;
}

export interface $ZodXorInternals<T extends readonly SomeType[] = readonly $ZodType[]> extends $ZodUnionInternals<T> {}

export interface $ZodXor<T extends readonly SomeType[] = readonly $ZodType[]>
  extends $ZodType<any, any, $ZodXorInternals<T>> {
  _zod: $ZodXorInternals<T>;
}

export const $ZodXor: core.$constructor<$ZodXor> = /*@__PURE__*/ core.$constructor("$ZodXor", (inst, def) => {
  $ZodUnion.init(inst, def);
  def.inclusive = false;

  const first = def.options.length === 1 ? def.options[0]._zod.run : null;

  inst._zod.parse = (payload, ctx) => {
    if (first) {
      return first(payload, ctx);
    }
    let async = false;

    const results: util.MaybeAsync<ParsePayload>[] = [];
    for (const option of def.options) {
      const result = option._zod.run(
        {
          value: payload.value,
          issues: [],
        },
        ctx
      );
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        results.push(result);
      }
    }

    if (!async) return handleExclusiveUnionResults(results as ParsePayload[], payload, inst, ctx);
    return Promise.all(results).then((results) => {
      return handleExclusiveUnionResults(results as ParsePayload[], payload, inst, ctx);
    });
  };
});

//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//////////                                  //////////
//////////      $ZodDiscriminatedUnion      //////////
//////////                                  //////////
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////

export interface $ZodDiscriminatedUnionDef<
  Options extends readonly SomeType[] = readonly $ZodType[],
  Disc extends string = string,
> extends $ZodUnionDef<Options> {
  discriminator: Disc;
  unionFallback?: boolean;
}

export interface $ZodDiscriminatedUnionInternals<
  Options extends readonly SomeType[] = readonly $ZodType[],
  Disc extends string = string,
> extends $ZodUnionInternals<Options> {
  def: $ZodDiscriminatedUnionDef<Options, Disc>;
  propValues: util.PropValues;
  bag: util.LoosePartial<{
    optionsMap: Map<util.Primitive, $ZodType | null>;
  }>;
}

/** The discriminator values a member of `Options` can declare. An omittable discriminator contributes `undefined`, matching what `propValues` claims for it. */
export type $DiscriminatorValue<Options extends readonly SomeType[], Disc extends string> = {
  [I in keyof Options]: Options[I] extends { _zod: { output: infer Out } }
    ? Disc extends keyof Out
      ? Out[Disc]
      : never
    : never;
}[number];

/** The member of `Options` that declares `V`. */
export type $DiscriminatedOption<Options extends readonly SomeType[], Disc extends string, V> = {
  [I in keyof Options]: Options[I] extends { _zod: { output: infer Out } }
    ? Disc extends keyof Out
      ? V extends Out[Disc]
        ? Options[I]
        : never
      : never
    : never;
}[number];

/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */
export function getDiscriminatedOption<
  Options extends readonly SomeType[],
  Disc extends string,
  const V extends $DiscriminatorValue<Options, Disc>,
>(union: $ZodDiscriminatedUnion<Options, Disc>, value: V): $DiscriminatedOption<Options, Disc, V> {
  const internals = union._zod;
  let map = internals.bag.optionsMap;
  if (!map) {
    map = discriminatorMap(internals.def);
    internals.bag.optionsMap = map;
  }
  const option = map.get(value as util.Primitive);
  if (option === null) throw new Error(`Ambiguous discriminator value "${String(value)}"`);
  return option as any;
}

function discriminatorMap(def: $ZodDiscriminatedUnionDef<readonly SomeType[]>): Map<util.Primitive, $ZodType | null> {
  const map = new Map<util.Primitive, $ZodType | null>();
  for (const option of def.options as readonly $ZodType[]) {
    const values = option._zod.propValues?.[def.discriminator];
    if (!values || values.size === 0)
      throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
    for (const value of values) {
      if (map.has(value)) {
        if (value !== undefined) throw new Error(`Duplicate discriminator value "${String(value)}"`);
        // keep the collision marked so a later member cannot reclaim it
        map.set(value, null);
      } else {
        map.set(value, option);
      }
    }
  }
  return map;
}

export interface $ZodDiscriminatedUnion<
  Options extends readonly SomeType[] = readonly $ZodType[],
  Disc extends string = string,
> extends $ZodType {
  _zod: $ZodDiscriminatedUnionInternals<Options, Disc>;
}

export const $ZodDiscriminatedUnion: core.$constructor<$ZodDiscriminatedUnion> =
  /*@__PURE__*/
  core.$constructor("$ZodDiscriminatedUnion", (inst, def) => {
    def.inclusive = false;

    $ZodUnion.init(inst, def);

    const _super = inst._zod.parse;
    util.defineLazyInternal(inst, "propValues", (zod) => {
      const propValues: util.PropValues = {};
      let undefinedCount = 0;
      for (const option of zod.def.options) {
        const pv = option._zod.propValues;
        if (!pv || Object.keys(pv).length === 0)
          throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);
        if (pv[zod.def.discriminator]?.has(undefined)) undefinedCount++;
        for (const [k, v] of Object.entries(pv!)) {
          if (!Object.prototype.hasOwnProperty.call(propValues, k)) {
            util.assignProp(propValues, k, new Set());
          }
          for (const val of v) {
            propValues[k].add(val);
          }
        }
      }
      if (!zod.def.unionFallback && undefinedCount > 1) propValues[zod.def.discriminator]?.delete(undefined);
      return propValues;
    });

    // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.
    def.options.forEach((option, i) => {
      const propShape = util.rawShape(option._zod.def);
      if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {
        throw new Error(`Invalid discriminated union option at index "${i}"`);
      }
    });

    const disc = util.cached(() => discriminatorMap(def));

    inst._zod.parse = (payload, ctx) => {
      const input = payload.value;
      if (!util.isObject(input)) {
        payload.issues.push({
          code: "invalid_type",

          expected: "object",
          input,
          inst,
        });
        return payload;
      }

      const value = input?.[def.discriminator];
      const opt = disc.value.get(value as util.Primitive);
      // forward metadata cannot choose an encoder for an absent tag
      if (opt && (value !== undefined || ctx.direction !== "backward")) {
        return opt._zod.run(payload, ctx) as any;
      }

      // Fall back to union matching when the fast discriminator path fails:
      // - explicitly enabled via unionFallback, or
      // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions
      if (def.unionFallback || ctx.direction === "backward") {
        return _super(payload, ctx);
      }

      // no matching discriminator
      payload.issues.push({
        code: "invalid_union",
        errors: [],
        note: "No matching discriminator",
        discriminator: def.discriminator,
        options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),
        input,
        path: [def.discriminator],
        inst,
      });

      return payload;
    };
  });

////////////////////////////////////////////////
////////////////////////////////////////////////
//////////                            //////////
//////////      $ZodIntersection      //////////
//////////                            //////////
////////////////////////////////////////////////
////////////////////////////////////////////////

export interface $ZodIntersectionDef<Left extends SomeType = $ZodType, Right extends SomeType = $ZodType>
  extends $ZodTypeDef {
  type: "intersection";
  left: Left;
  right: Right;
}

export interface $ZodIntersectionInternals<A extends SomeType = $ZodType, B extends SomeType = $ZodType>
  extends _$ZodTypeInternals {
  // $ZodTypeInternals<core.output<A> & core.output<B>, core.input<A> & core.input<B>>
  def: $ZodIntersectionDef<A, B>;
  isst: never;
  optin: A["_zod"]["optin"] | B["_zod"]["optin"];
  optout: A["_zod"]["optout"] | B["_zod"]["optout"];
  output: core.output<A> & core.output<B>;
  input: core.input<A> & core.input<B>;
}

export interface $ZodIntersection<A extends SomeType = $ZodType, B extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodIntersectionInternals<A, B>;
}

export const $ZodIntersection: core.$constructor<$ZodIntersection> = /*@__PURE__*/ core.$constructor(
  "$ZodIntersection",
  (inst, def) => {
    $ZodType.init(inst, def);

    inst._zod.parse = (payload, ctx) => {
      const input = payload.value;
      const left = def.left._zod.run({ value: input, issues: [] }, ctx);
      const right = def.right._zod.run({ value: input, issues: [] }, ctx);
      const async = left instanceof Promise || right instanceof Promise;

      if (async) {
        return Promise.all([left, right]).then(([left, right]) => {
          return handleIntersectionResults(payload, left, right);
        });
      }

      return handleIntersectionResults(payload, left, right);
    };
  }
);

export function mergeValues(
  a: any,
  b: any
): { valid: true; data: any } | { valid: false; mergeErrorPath: (string | number)[] } {
  // const aType = parse.t(a);
  // const bType = parse.t(b);

  if (a === b) {
    return { valid: true, data: a };
  }
  if (a instanceof Date && b instanceof Date && +a === +b) {
    return { valid: true, data: a };
  }
  if (util.isPlainObject(a) && util.isPlainObject(b)) {
    const bKeys = Object.keys(b);
    const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);

    const newObj: any = { ...a, ...b };
    if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) delete newObj.__proto__;
    for (const key of sharedKeys) {
      if (key === "__proto__") continue;
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [key, ...sharedValue.mergeErrorPath],
        };
      }
      newObj[key] = sharedValue.data;
    }

    return { valid: true, data: newObj };
  }
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) {
      return { valid: false, mergeErrorPath: [] };
    }

    const newArray: unknown[] = [];
    for (let index = 0; index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues(itemA, itemB);

      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [index, ...sharedValue.mergeErrorPath],
        };
      }

      newArray.push(sharedValue.data);
    }

    return { valid: true, data: newArray };
  }

  return { valid: false, mergeErrorPath: [] };
}

function handleIntersectionResults(result: ParsePayload, left: ParsePayload, right: ParsePayload): ParsePayload {
  // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.
  const unrecKeys = new Map<string, { l?: true; r?: true }>();
  let unrecIssue: errors.$ZodRawIssue | undefined;
  const keyIssues = new Map<string, errors.$ZodRawIssue>();

  const collect = (iss: errors.$ZodRawIssue, side: "l" | "r"): boolean => {
    let keys: string[];
    if (iss.code === "unrecognized_keys" && !iss.path?.length) {
      unrecIssue ??= iss;
      keys = iss.keys as string[];
    } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) {
      const k = String(iss.path[0]);
      if (!keyIssues.has(k)) keyIssues.set(k, iss);
      keys = [k];
    } else {
      return false;
    }
    for (const k of keys) {
      if (!unrecKeys.has(k)) unrecKeys.set(k, {});
      unrecKeys.get(k)![side] = true;
    }
    return true;
  };

  for (const iss of left.issues) {
    if (!collect(iss, "l")) result.issues.push(iss);
  }

  for (const iss of right.issues) {
    if (!collect(iss, "r")) result.issues.push(iss);
  }

  // Report only keys rejected by BOTH sides
  const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
  if (bothKeys.length) {
    const aggregated = unrecIssue ? bothKeys.filter((k) => (unrecIssue!.keys as string[]).includes(k)) : [];
    if (aggregated.length) result.issues.push({ ...unrecIssue!, keys: aggregated });
    for (const k of bothKeys) {
      if (!aggregated.includes(k) && keyIssues.has(k)) result.issues.push(keyIssues.get(k)!);
    }
  }

  const merged = mergeValues(left.value, right.value);

  if (!merged.valid) {
    if (util.aborted(result)) return result;
    throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
  }

  result.value = merged.data;
  return result;
}

/////////////////////////////////////////
/////////////////////////////////////////
//////////                     //////////
//////////      $ZodTuple      //////////
//////////                     //////////
/////////////////////////////////////////
/////////////////////////////////////////

export interface $ZodTupleDef<
  T extends util.TupleItems = readonly $ZodType[],
  Rest extends SomeType | null = $ZodType | null,
> extends $ZodTypeDef {
  type: "tuple";
  items: T;
  rest: Rest;
}

export type $InferTupleInputType<T extends util.TupleItems, Rest extends SomeType | null> = [
  ...TupleInputTypeWithOptionals<T>,
  ...(Rest extends SomeType ? core.input<Rest>[] : []),
];
type TupleInputTypeNoOptionals<T extends util.TupleItems> = {
  [k in keyof T]: core.input<T[k]>;
};
type TupleInputTypeWithOptionals<T extends util.TupleItems> = T extends readonly [
  ...infer Prefix extends SomeType[],
  infer Tail extends SomeType,
]
  ? Tail["_zod"]["optin"] extends "optional" | "defaulted"
    ? [...TupleInputTypeWithOptionals<Prefix>, core.input<Tail>?]
    : TupleInputTypeNoOptionals<T>
  : [];

export type $InferTupleOutputType<T extends util.TupleItems, Rest extends SomeType | null> = [
  ...TupleOutputTypeWithOptionals<T>,
  ...(Rest extends SomeType ? core.output<Rest>[] : []),
];
type TupleOutputTypeNoOptionals<T extends util.TupleItems> = {
  [k in keyof T]: core.output<T[k]>;
};
type TupleOutputTypeWithOptionals<T extends util.TupleItems> = T extends readonly [
  ...infer Prefix extends SomeType[],
  infer Tail extends SomeType,
]
  ? Tail["_zod"]["optout"] extends "optional"
    ? [...TupleOutputTypeWithOptionals<Prefix>, core.output<Tail>?]
    : TupleOutputTypeNoOptionals<T>
  : [];

export interface $ZodTupleInternals<
  T extends util.TupleItems = readonly $ZodType[],
  Rest extends SomeType | null = $ZodType | null,
> extends _$ZodTypeInternals {
  def: $ZodTupleDef<T, Rest>;
  isst: errors.$ZodIssueInvalidType | errors.$ZodIssueTooBig<unknown[]> | errors.$ZodIssueTooSmall<unknown[]>;
  // $ZodTypeInternals<$InferTupleOutputType<T, Rest>, $InferTupleInputType<T, Rest>>
  output: $InferTupleOutputType<T, Rest>;
  input: $InferTupleInputType<T, Rest>;
}

export interface $ZodTuple<
  T extends util.TupleItems = readonly $ZodType[],
  Rest extends SomeType | null = $ZodType | null,
> extends $ZodType {
  _zod: $ZodTupleInternals<T, Rest>;
}

export const $ZodTuple: core.$constructor<$ZodTuple> = /*@__PURE__*/ core.$constructor("$ZodTuple", (inst, def) => {
  $ZodType.init(inst, def);
  const items = def.items;
  const memo = core.globalConfig.memoizer;
  memo?.attach(inst);

  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        input,
        inst,
        expected: "tuple",
        code: "invalid_type",
      });
      return payload;
    }

    payload.value = memo ? memo.alloc(inst, payload, [] as unknown[], ctx) : [];
    const proms: Promise<any>[] = [];

    const optinStart = getTupleOptStart(items, "optin");
    const optoutStart = getTupleOptStart(items, "optout");

    if (!def.rest) {
      if (input.length < optinStart) {
        payload.issues.push({
          code: "too_small",
          minimum: optinStart,
          inclusive: true,
          input,
          inst,
          origin: "array" as const,
        });
        return payload;
      }
      if (input.length > items.length) {
        payload.issues.push({
          code: "too_big",
          maximum: items.length,
          inclusive: true,
          input,
          inst,
          origin: "array" as const,
        });
      }
    }

    // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.
    const itemResults: ParsePayload[] = new Array(items.length);
    // only tracked when there is a rest loop to skip
    const abortEarly = def.rest ? ctx?.abortEarly : undefined;
    let itemAborted = false;
    for (let i = 0; i < items.length; i++) {
      const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);
      if (r instanceof Promise) {
        proms.push(
          r.then((rr) => {
            itemResults[i] = rr;
          })
        );
      } else {
        itemResults[i] = r;
        if (abortEarly && !itemAborted && r.issues.length) itemAborted = util.aborted(r);
      }
    }

    // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues
    if (def.rest && !itemAborted) {
      let i = items.length - 1;
      const rest = input.slice(items.length);
      let seen = payload.issues.length;
      for (const el of rest) {
        if (abortEarly && payload.issues.length !== seen) {
          if (util.aborted(payload, seen)) break;
          seen = payload.issues.length;
        }
        i++;
        const result = def.rest._zod.run({ value: el, issues: [] }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((r) => handleTupleResult(r, payload, i)));
        } else {
          handleTupleResult(result, payload, i);
        }
      }
    }

    if (proms.length) {
      return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
    }
    return handleTupleResults(itemResults, payload, items, input, optoutStart);
  };
});

function getTupleOptStart(items: readonly $ZodType[], key: "optin" | "optout") {
  for (let i = items.length - 1; i >= 0; i--) {
    // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.
    const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional";
    if (!omittable) return i + 1;
  }
  return 0;
}

function handleTupleResult(result: ParsePayload, final: ParsePayload<any[]>, index: number) {
  if (result.issues.length) {
    final.issues.push(...util.prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}

function handleTupleResults(
  itemResults: ParsePayload[],
  final: ParsePayload<any[]>,
  items: readonly $ZodType[],
  input: unknown[],
  optoutStart: number
) {
  // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.
  for (let i = 0; i < items.length; i++) {
    const r = itemResults[i];
    const isPresent = i < input.length;
    // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.
    if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") {
      final.value.length = i;
      break;
    }
    if (r.issues.length) {
      if (!isPresent && i >= optoutStart) {
        final.value.length = i;
        break;
      }
      final.issues.push(...util.prefixIssues(i, r.issues));
    }
    final.value[i] = r.value;
  }

  // Drop trailing slots that produced `undefined` for absent input
  // (the array analog of an absent optional key on an object). The
  // `i >= input.length` floor is critical: an explicit `undefined`
  // *inside* the input must be preserved even when the schema is
  // optional-out (e.g. `z.string().or(z.undefined())` accepting an
  // explicit undefined value).
  for (let i = final.value.length - 1; i >= input.length; i--) {
    if (items[i]._zod.optout === "optional" && final.value[i] === undefined) {
      final.value.length = i;
    } else {
      break;
    }
  }
  return final;
}

//////////////////////////////////////////
//////////////////////////////////////////
//////////                      //////////
//////////      $ZodRecord      //////////
//////////                      //////////
//////////////////////////////////////////
//////////////////////////////////////////

export type $ZodRecordKey = $ZodType<string | number | symbol, unknown>; // $HasValues | $HasPattern;
export interface $ZodRecordDef<Key extends $ZodRecordKey = $ZodRecordKey, Value extends SomeType = $ZodType>
  extends $ZodTypeDef {
  type: "record";
  keyType: Key;
  valueType: Value;
  /** @default "strict" - errors on keys not matching keyType. "loose" passes through non-matching keys unchanged. */
  mode?: "strict" | "loose";
  partial?: boolean;
}

// export type $InferZodRecordOutput<
//   Key extends $ZodRecordKey = $ZodRecordKey,
//   Value extends SomeType = $ZodType,
// > = undefined extends Key["_zod"]["values"]
//   ? string extends core.output<Key>
//     ? Record<core.output<Key>, core.output<Value>>
//     : number extends core.output<Key>
//       ? Record<core.output<Key>, core.output<Value>>
//       : symbol extends core.output<Key>
//         ? Record<core.output<Key>, core.output<Value>>
//         : Record<core.output<Key>, core.output<Value>>
//   : Record<core.output<Key>, core.output<Value>>;
export type $InferZodRecordOutput<
  Key extends $ZodRecordKey = $ZodRecordKey,
  Value extends SomeType = $ZodType,
> = Key extends $partial
  ? Partial<Record<core.output<Key>, core.output<Value>>>
  : Record<core.output<Key>, core.output<Value>>;

// export type $InferZodRecordInput<
//   Key extends $ZodRecordKey = $ZodRecordKey,
//   Value extends SomeType = $ZodType,
// > = undefined extends Key["_zod"]["values"]
//   ? string extends core.input<Key>
//     ? Record<core.input<Key>, core.input<Value>>
//     : number extends core.input<Key>
//       ? Record<core.input<Key>, core.input<Value>>
//       : symbol extends core.input<Key>
//         ? Record<core.input<Key>, core.input<Value>>
//         : Record<core.input<Key>, core.input<Value>>
//   : Record<core.input<Key>, core.input<Value>>;

export type $InferZodRecordInput<
  Key extends $ZodRecordKey = $ZodRecordKey,
  Value extends SomeType = $ZodType,
> = Key extends $partial
  ? Partial<Record<core.input<Key> & PropertyKey, core.input<Value>>>
  : // A value schema that accepts an absent slot makes the key omittable on the way in, exactly as it does in an object shape. The output side keeps every key, since the parser fills each one.
    [Value] extends [OptionalInSchema]
    ? Partial<Record<core.input<Key> & PropertyKey, core.input<Value>>>
    : Record<core.input<Key> & PropertyKey, core.input<Value>>;

export interface $ZodRecordInternals<Key extends $ZodRecordKey = $ZodRecordKey, Value extends SomeType = $ZodType>
  extends $ZodTypeInternals<$InferZodRecordOutput<Key, Value>, $InferZodRecordInput<Key, Value>> {
  def: $ZodRecordDef<Key, Value>;
  isst: errors.$ZodIssueInvalidType | errors.$ZodIssueInvalidKey<Record<PropertyKey, unknown>>;
  optin?: "optional" | undefined;
  optout?: "optional" | undefined;
}

export type $partial = { "~~partial": true };
export interface $ZodRecord<Key extends $ZodRecordKey = $ZodRecordKey, Value extends SomeType = $ZodType>
  extends $ZodType {
  _zod: $ZodRecordInternals<Key, Value>;
}

export const $ZodRecord: core.$constructor<$ZodRecord> = /*@__PURE__*/ core.$constructor("$ZodRecord", (inst, def) => {
  $ZodType.init(inst, def);
  const memo = core.globalConfig.memoizer;
  memo?.attach(inst);

  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;

    if (!util.isPlainObject(input)) {
      payload.issues.push({
        expected: "record",
        code: "invalid_type",

        input,
        inst,
      });
      return payload;
    }

    // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing
    const proms: Promise<any>[] = [];

    const values = def.keyType._zod.values;
    if (values && !def.partial) {
      payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
      const recordKeys = new Set<string | symbol>();
      for (const key of values) {
        if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
          recordKeys.add(typeof key === "number" ? key.toString() : key);
          // A declared __proto__ is stripped but is not an unrecognized key.
          if (key === "__proto__") continue;
          const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
          if (keyResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (keyResult.issues.length) {
            payload.issues.push({
              code: "invalid_key",
              origin: "record",
              issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
              input: key,
              path: [key],
              inst,
            });
            continue;
          }
          const outKey = keyResult.value as PropertyKey;
          if (outKey === "__proto__") continue;
          const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);

          if (result instanceof Promise) {
            proms.push(
              result.then((result) => {
                if (result.issues.length) {
                  payload.issues.push(...util.prefixIssues(key, result.issues));
                }
                payload.value[outKey] = result.value;
              })
            );
          } else {
            if (result.issues.length) {
              payload.issues.push(...util.prefixIssues(key, result.issues));
            }
            payload.value[outKey] = result.value;
          }
        }
      }

      let unrecognized!: string[];
      for (const key in input) {
        if (!recordKeys.has(key)) {
          if (def.mode === "loose") {
            // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into
            if (key === "__proto__") continue;
            payload.value[key] = input[key];
          } else {
            unrecognized = unrecognized ?? [];
            unrecognized.push(key);
          }
        }
      }
      if (unrecognized && unrecognized.length > 0) {
        payload.issues.push({
          code: "unrecognized_keys",

          input,
          inst,
          keys: unrecognized,
          continue: true,
        });
      }
    } else {
      payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
      // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.
      let unrecognized!: string[];
      // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()
      for (const key of Reflect.ownKeys(input)) {
        if (key === "__proto__") continue;
        if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue;
        let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
        if (keyResult instanceof Promise) {
          throw new Error("Async schemas not supported in object keys currently");
        }

        // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals
        const checkNumericKey = typeof key === "string" && regexes.number.test(key) && keyResult.issues.length;
        if (checkNumericKey) {
          const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
          if (retryResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (retryResult.issues.length === 0) {
            keyResult = retryResult;
          }
        }

        if (keyResult.issues.length) {
          if (def.mode === "loose") {
            // Pass through unchanged
            payload.value[key] = input[key];
          } else if (values) {
            unrecognized = unrecognized ?? [];
            unrecognized.push(key as string);
          } else {
            // Default "strict" behavior: error on invalid key
            payload.issues.push({
              code: "invalid_key",
              origin: "record",
              issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
              input: key,
              path: [key],
              inst,
            });
          }
          continue;
        }

        // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under
        const outKey = keyResult.value as PropertyKey;
        if (outKey === "__proto__") continue;

        const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);

        if (result instanceof Promise) {
          proms.push(
            result.then((result) => {
              if (result.issues.length) {
                payload.issues.push(...util.prefixIssues(key, result.issues));
              }
              payload.value[outKey] = result.value;
            })
          );
        } else {
          if (result.issues.length) {
            payload.issues.push(...util.prefixIssues(key, result.issues));
          }
          payload.value[outKey] = result.value;
        }
      }

      if (unrecognized && unrecognized.length > 0) {
        payload.issues.push({
          code: "unrecognized_keys",

          input,
          inst,
          keys: unrecognized,
          continue: true,
        });
      }
    }

    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});

///////////////////////////////////////
///////////////////////////////////////
//////////                   //////////
//////////      $ZodMap      //////////
//////////                   //////////
///////////////////////////////////////
///////////////////////////////////////
export interface $ZodMapDef<Key extends SomeType = $ZodType, Value extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "map";
  keyType: Key;
  valueType: Value;
}

export interface $ZodMapInternals<Key extends SomeType = $ZodType, Value extends SomeType = $ZodType>
  extends $ZodTypeInternals<Map<core.output<Key>, core.output<Value>>, Map<core.input<Key>, core.input<Value>>> {
  def: $ZodMapDef<Key, Value>;
  isst: errors.$ZodIssueInvalidType | errors.$ZodIssueInvalidKey | errors.$ZodIssueInvalidElement<unknown>;
  optin?: "optional" | undefined;
  optout?: "optional" | undefined;
}

export interface $ZodMap<Key extends SomeType = $ZodType, Value extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodMapInternals<Key, Value>;
}

export const $ZodMap: core.$constructor<$ZodMap> = /*@__PURE__*/ core.$constructor("$ZodMap", (inst, def) => {
  $ZodType.init(inst, def);
  const memo = core.globalConfig.memoizer;
  memo?.attach(inst);

  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Map)) {
      payload.issues.push({
        expected: "map",
        code: "invalid_type",

        input,
        inst,
      });
      return payload;
    }

    const proms: Promise<any>[] = [];
    payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();
    const abortEarly = ctx?.abortEarly;
    let seen = payload.issues.length;

    for (const [key, value] of input) {
      if (abortEarly && payload.issues.length !== seen) {
        if (util.aborted(payload, seen)) break;
        seen = payload.issues.length;
      }
      const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
      const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);

      if (keyResult instanceof Promise || valueResult instanceof Promise) {
        proms.push(
          Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {
            handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
          })
        );
      } else {
        handleMapResult(keyResult as ParsePayload, valueResult as ParsePayload, payload, key, input, inst, ctx);
      }
    }

    if (proms.length) return Promise.all(proms).then(() => payload);
    return payload;
  };
});

function handleMapResult(
  keyResult: ParsePayload,
  valueResult: ParsePayload,
  final: ParsePayload<Map<unknown, unknown>>,
  key: unknown,
  input: Map<any, any>,
  inst: $ZodMap,
  ctx?: ParseContext | undefined
): void {
  if (keyResult.issues.length) {
    if (util.propertyKeyTypes.has(typeof key)) {
      final.issues.push(...util.prefixIssues(key as PropertyKey, keyResult.issues));
    } else {
      final.issues.push({
        code: "invalid_key",

        origin: "map",
        input,
        inst,
        issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
      });
    }
  }
  if (valueResult.issues.length) {
    if (util.propertyKeyTypes.has(typeof key)) {
      final.issues.push(...util.prefixIssues(key as PropertyKey, valueResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_element",

        input,
        inst,
        key: key,
        issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
      });
    }
  }
  final.value.set(keyResult.value, valueResult.value);
}

///////////////////////////////////////
///////////////////////////////////////
//////////                   //////////
//////////      $ZodSet      //////////
//////////                   //////////
///////////////////////////////////////
///////////////////////////////////////
export interface $ZodSetDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "set";
  valueType: T;
}

export interface $ZodSetInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<Set<core.output<T>>, Set<core.input<T>>> {
  def: $ZodSetDef<T>;
  isst: errors.$ZodIssueInvalidType;
  optin?: "optional" | undefined;
  optout?: "optional" | undefined;
}

export interface $ZodSet<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodSetInternals<T>;
}

export const $ZodSet: core.$constructor<$ZodSet> = /*@__PURE__*/ core.$constructor("$ZodSet", (inst, def) => {
  $ZodType.init(inst, def);
  const memo = core.globalConfig.memoizer;
  memo?.attach(inst);

  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Set)) {
      payload.issues.push({
        input,
        inst,
        expected: "set",
        code: "invalid_type",
      });
      return payload;
    }

    const proms: Promise<any>[] = [];
    payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();
    const abortEarly = ctx?.abortEarly;
    let seen = payload.issues.length;
    for (const item of input) {
      if (abortEarly && payload.issues.length !== seen) {
        if (util.aborted(payload, seen)) break;
        seen = payload.issues.length;
      }
      const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result) => handleSetResult(result, payload)));
      } else handleSetResult(result, payload);
    }

    if (proms.length) return Promise.all(proms).then(() => payload);
    return payload;
  };
});

function handleSetResult(result: ParsePayload, final: ParsePayload<Set<any>>) {
  if (result.issues.length) {
    final.issues.push(...result.issues);
  }
  final.value.add(result.value);
}

////////////////////////////////////////
////////////////////////////////////////
//////////                    //////////
//////////      $ZodEnum      //////////
//////////                    //////////
////////////////////////////////////////
////////////////////////////////////////
export type $InferEnumOutput<T extends util.EnumLike> = T[keyof T] & {};
export type $InferEnumInput<T extends util.EnumLike> = T[keyof T] & {};

export interface $ZodEnumDef<T extends util.EnumLike = util.EnumLike> extends $ZodTypeDef {
  type: "enum";
  entries: T;
}

export interface $ZodEnumInternals<
  /** @ts-ignore Cast variance */
  out T extends util.EnumLike = util.EnumLike,
> extends $ZodTypeInternals<$InferEnumOutput<T>, $InferEnumInput<T>> {
  // enum: T;

  def: $ZodEnumDef<T>;
  /** @deprecated Internal API, use with caution (not deprecated) */
  values: util.PrimitiveSet;
  /** @deprecated Internal API, use with caution (not deprecated) */
  pattern: RegExp;
  isst: errors.$ZodIssueInvalidValue;
}

export interface $ZodEnum<T extends util.EnumLike = util.EnumLike> extends $ZodType {
  _zod: $ZodEnumInternals<T>;
}

export const $ZodEnum: core.$constructor<$ZodEnum> = /*@__PURE__*/ core.$constructor("$ZodEnum", (inst, def) => {
  $ZodType.init(inst, def);

  const values = util.getEnumValues(def.entries);
  const valuesSet = new Set<util.Primitive>(values);
  inst._zod.values = valuesSet;

  util.defineLazyInternal(inst, "pattern", (zod) => {
    const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));
    // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches ""
    return new RegExp(
      patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"
    );
  });

  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (valuesSet.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",

      values,
      input,
      inst,
    });
    return payload;
  };
});

////////////////////////////////////////
////////////////////////////////////////
//////////                    //////////
//////////      $ZodLiteral      //////////
//////////                    //////////
////////////////////////////////////////
////////////////////////////////////////

export interface $ZodLiteralDef<T extends util.Literal> extends $ZodTypeDef {
  type: "literal";
  values: T[];
}

export interface $ZodLiteralInternals<T extends util.Literal = util.Literal> extends $ZodTypeInternals<T, T> {
  def: $ZodLiteralDef<T>;
  values: Set<T>;
  pattern: RegExp;
  isst: errors.$ZodIssueInvalidValue;
}

export interface $ZodLiteral<T extends util.Literal = util.Literal> extends $ZodType {
  _zod: $ZodLiteralInternals<T>;
}

export const $ZodLiteral: core.$constructor<$ZodLiteral> = /*@__PURE__*/ core.$constructor(
  "$ZodLiteral",
  (inst, def) => {
    $ZodType.init(inst, def);

    const values = new Set<util.Literal>(def.values);
    inst._zod.values = values;

    util.defineLazyInternal(inst, "pattern", (zod) => {
      const vals = zod.def.values;
      // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches ""
      return new RegExp(
        vals.length
          ? `^(${vals
              .map((o: util.Literal) =>
                typeof o === "string" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)
              )
              .join("|")})$`
          : "^[^\\s\\S]$"
      );
    });

    inst._zod.parse = (payload, _ctx) => {
      const input = payload.value;
      if (values.has(input)) {
        return payload;
      }
      payload.issues.push({
        code: "invalid_value",

        values: def.values,
        input,
        inst,
      });
      return payload;
    };
  }
);

////////////////////////////////////////
////////////////////////////////////////
//////////                    //////////
//////////      $ZodConst      //////////
//////////                    //////////
////////////////////////////////////////
////////////////////////////////////////

// export interface $ZodConstDef extends $ZodTypeDef {
//   type: "const";
//   value: unknown;
// }

// export _interface $ZodConstInternals<T extends util.Literal = util.Literal> extends $ZodTypeInternals<T, T> {
//   _def: $ZodConstDef;
//   _values: util.PrimitiveSet;
//   _pattern: RegExp;
//   _isst: errors.$ZodIssueInvalidValue;
// }

// export const $ZodConst: core.$constructor<{_zod: $ZodConstInternals}> = /*@__PURE__*/ core.$constructor("$ZodConst", (inst, def) => {
//   $ZodType.init(inst, def);

//   if (util.primitiveTypes.has(typeof def.value) || def.value === null) {
//     inst._zod.values = new Set<util.Primitive>(def.value as any);
//   }

//   if (util.propertyKeyTypes.has(typeof def.value)) {
//     inst._zod.pattern = new RegExp(
//       `^(${typeof def.value === "string" ? util.escapeRegex(def.value) : (def.value as any).toString()})$`
//     );
//   } else {
//     throw new Error("Const value cannot be converted to regex");
//   }

//   inst._zod.parse = (payload, _ctx) => {
//     payload.value = def.value; // always override
//     return payload;
//   };
// });

//////////////////////////////////////////
//////////////////////////////////////////
//////////                      //////////
//////////      $ZodFile        //////////
//////////                      //////////
//////////////////////////////////////////
//////////////////////////////////////////

// provide a fallback in case the File interface isn't provided in the environment
type _File = typeof globalThis extends { File: infer F extends new (...args: any[]) => any } ? InstanceType<F> : {};
/** Do not reference this directly. */
export interface File extends _File {
  readonly type: string;
  readonly size: number;
}

export interface $ZodFileDef extends $ZodTypeDef {
  type: "file";
}

export interface $ZodFileInternals extends $ZodTypeInternals<File, File> {
  def: $ZodFileDef;
  isst: errors.$ZodIssueInvalidType;
  bag: util.LoosePartial<{
    minimum: number;
    maximum: number;
    mime: util.MimeTypes[];
  }>;
}

export interface $ZodFile extends $ZodType {
  _zod: $ZodFileInternals;
}

export const $ZodFile: core.$constructor<$ZodFile> = /*@__PURE__*/ core.$constructor("$ZodFile", (inst, def) => {
  $ZodType.init(inst, def);

  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    // @ts-ignore
    if (input instanceof File) return payload;
    payload.issues.push({
      expected: "file",
      code: "invalid_type",

      input,
      inst,
    });
    return payload;
  };
});

//////////////////////////////////////////////
//////////////////////////////////////////////
//////////                          //////////
//////////        $ZodTransform        //////////
//////////                          //////////
//////////////////////////////////////////////
//////////////////////////////////////////////
export interface $ZodTransformDef extends $ZodTypeDef {
  type: "transform";
  transform: (input: unknown, payload: ParsePayload<unknown>) => util.MaybeAsync<unknown>;
}
export interface $ZodTransformInternals<O = unknown, I = unknown> extends $ZodTypeInternals<O, I> {
  def: $ZodTransformDef;
  isst: never;
}

export interface $ZodTransform<O = unknown, I = unknown> extends $ZodType {
  _zod: $ZodTransformInternals<O, I>;
}

export const $ZodTransform: core.$constructor<$ZodTransform> = /*@__PURE__*/ core.$constructor(
  "$ZodTransform",
  (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.optin = "optional";
    core.globalConfig.memoizer?.guard(inst);

    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        throw new core.$ZodEncodeError(inst.constructor.name);
      }

      const _out = def.transform(payload.value, payload);
      if (ctx.async) {
        const output = _out instanceof Promise ? _out : Promise.resolve(_out);
        return output.then((output) => {
          payload.value = output;
          return payload;
        });
      }

      if (_out instanceof Promise) {
        throw new core.$ZodAsyncError();
      }

      payload.value = _out;
      return payload;
    };
  }
);

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////      $ZodOptional      //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
export interface $ZodOptionalDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "optional";
  innerType: T;
}

export interface $ZodOptionalInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<core.output<T> | undefined, core.input<T> | undefined> {
  def: $ZodOptionalDef<T>;
  optin: "optional" | "defaulted";
  optout: "optional";
  isst: never;
  values: T["_zod"]["values"];
  pattern: T["_zod"]["pattern"];
}

export interface $ZodOptional<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodOptionalInternals<T>;
}

function handleOptionalResult(payload: ParsePayload, result: ParsePayload) {
  // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.
  payload.value = result.issues.length ? undefined : result.value;
  return payload;
}

export const $ZodOptional: core.$constructor<$ZodOptional> = /*@__PURE__*/ core.$constructor(
  "$ZodOptional",
  (inst, def) => {
    $ZodType.init(inst, def);
    // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.
    util.defineLazyInternal(inst, "optin", (zod) =>
      zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"
    );
    inst._zod.optout = "optional";

    util.defineLazyInternal(inst, "values", (zod) => {
      const values = (zod.def as $ZodOptionalDef).innerType._zod.values;
      return values ? new Set([...values, undefined]) : undefined;
    });
    util.defineLazyInternal(inst, "pattern", (zod) => {
      const pattern = (zod.def as $ZodOptionalDef).innerType._zod.pattern;
      return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;
    });

    inst._zod.parse = (payload, ctx) => {
      if (payload.value === undefined) {
        // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.
        if (def.innerType._zod.optin !== "defaulted") return payload;
        // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.
        const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);
        if (result instanceof Promise) return result.then((result) => handleOptionalResult(payload, result));
        return handleOptionalResult(payload, result);
      }
      return def.innerType._zod.run(payload, ctx);
    };
  }
);

////////////////////////////////////////////////
////////////////////////////////////////////////
//////////                            //////////
//////////      $ZodExactOptional     //////////
//////////                            //////////
////////////////////////////////////////////////
////////////////////////////////////////////////

// Def extends $ZodOptionalDef (no additional fields needed)
export interface $ZodExactOptionalDef<T extends SomeType = $ZodType> extends $ZodOptionalDef<T> {}

// Internals extends $ZodOptionalInternals but narrows output/input types (removes | undefined)
export interface $ZodExactOptionalInternals<T extends SomeType = $ZodType> extends $ZodOptionalInternals<T> {
  def: $ZodExactOptionalDef<T>;
  output: core.output<T>; // NO | undefined (narrowed from parent)
  input: core.input<T>; // NO | undefined (narrowed from parent)
}

export interface $ZodExactOptional<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodExactOptionalInternals<T>;
}

export const $ZodExactOptional: core.$constructor<$ZodExactOptional> = /*@__PURE__*/ core.$constructor(
  "$ZodExactOptional",
  (inst, def) => {
    // Call parent init - inherits optin/optout = "optional"
    $ZodOptional.init(inst, def);

    // Override values/pattern to NOT add undefined
    util.defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
    util.defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern);

    // Override parse to just delegate (no undefined handling)
    inst._zod.parse = (payload, ctx) => {
      return def.innerType._zod.run(payload, ctx);
    };
  }
);

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////      $ZodNullable      //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
export interface $ZodNullableDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "nullable";
  innerType: T;
}

export interface $ZodNullableInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<core.output<T> | null, core.input<T> | null> {
  def: $ZodNullableDef<T>;
  optin: T["_zod"]["optin"];
  optout: T["_zod"]["optout"];
  isst: never;
  values: T["_zod"]["values"];
  pattern: T["_zod"]["pattern"];
}

export interface $ZodNullable<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodNullableInternals<T>;
}

export const $ZodNullable: core.$constructor<$ZodNullable> = /*@__PURE__*/ core.$constructor(
  "$ZodNullable",
  (inst, def) => {
    $ZodType.init(inst, def);
    util.defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin);
    util.defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);

    util.defineLazyInternal(inst, "pattern", (zod) => {
      const pattern = zod.def.innerType._zod.pattern;
      return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;
    });

    util.defineLazyInternal(inst, "values", (zod) => {
      return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;
    });

    inst._zod.parse = (payload, ctx) => {
      // Forward direction (decode): allow null to pass through
      if (payload.value === null) return payload;
      return def.innerType._zod.run(payload, ctx);
    };
  }
);
// );

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////      $ZodDefault       //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
export interface $ZodDefaultDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "default";
  innerType: T;
  /** The default value. May be a getter. */
  defaultValue: util.NoUndefined<core.output<T>>;
}

export interface $ZodDefaultInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<util.NoUndefined<core.output<T>>, core.input<T> | undefined> {
  def: $ZodDefaultDef<T>;
  optin: "defaulted";
  optout?: "optional" | undefined; // required
  isst: never;
  values: T["_zod"]["values"];
}

export interface $ZodDefault<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodDefaultInternals<T>;
}

export const $ZodDefault: core.$constructor<$ZodDefault> = /*@__PURE__*/ core.$constructor(
  "$ZodDefault",
  (inst, def) => {
    $ZodType.init(inst, def);

    // inst._zod.qin = "true";
    inst._zod.optin = "defaulted";
    util.defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);

    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        return def.innerType._zod.run(payload, ctx);
      }

      // Forward direction (decode): apply defaults for undefined input
      if (payload.value === undefined) {
        payload.value = def.defaultValue;
        /**
         * $ZodDefault returns the default value immediately in forward direction.
         * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe.   */
        return payload;
      }
      // Forward direction: continue with default handling
      const result = def.innerType._zod.run(payload, ctx);
      if (result instanceof Promise) {
        return result.then((result) => handleDefaultResult(result, def));
      }
      return handleDefaultResult(result, def);
    };
  }
);

function handleDefaultResult(payload: ParsePayload, def: $ZodDefaultDef) {
  if (payload.value === undefined) {
    payload.value = def.defaultValue;
  }
  return payload;
}

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////      $ZodPrefault      //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////

export interface $ZodPrefaultDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "prefault";
  innerType: T;
  /** The default value. May be a getter. */
  defaultValue: core.input<T>;
}

export interface $ZodPrefaultInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<core.output<T>, core.input<T> | undefined> {
  def: $ZodPrefaultDef<T>;
  optin: "defaulted";
  optout?: "optional" | undefined;
  isst: never;
  values: T["_zod"]["values"];
}

export interface $ZodPrefault<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodPrefaultInternals<T>;
}

export const $ZodPrefault: core.$constructor<$ZodPrefault> = /*@__PURE__*/ core.$constructor(
  "$ZodPrefault",
  (inst, def) => {
    $ZodType.init(inst, def);

    inst._zod.optin = "defaulted";
    util.defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);

    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        return def.innerType._zod.run(payload, ctx);
      }

      // Forward direction (decode): apply prefault for undefined input
      if (payload.value === undefined) {
        payload.value = def.defaultValue;
      }
      return def.innerType._zod.run(payload, ctx);
    };
  }
);

///////////////////////////////////////////////
///////////////////////////////////////////////
//////////                           //////////
//////////      $ZodNonOptional      //////////
//////////                           //////////
///////////////////////////////////////////////
///////////////////////////////////////////////
export interface $ZodNonOptionalDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "nonoptional";
  innerType: T;
}

export interface $ZodNonOptionalInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<util.NoUndefined<core.output<T>>, util.NoUndefined<core.input<T>>> {
  def: $ZodNonOptionalDef<T>;
  isst: errors.$ZodIssueInvalidType;
  values: T["_zod"]["values"];
  optin: "optional" | undefined;
  optout: "optional" | undefined;
}

export interface $ZodNonOptional<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodNonOptionalInternals<T>;
}

export const $ZodNonOptional: core.$constructor<$ZodNonOptional> = /*@__PURE__*/ core.$constructor(
  "$ZodNonOptional",
  (inst, def) => {
    $ZodType.init(inst, def);

    util.defineLazyInternal(inst, "values", (zod) => {
      const v = zod.def.innerType._zod.values;
      return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
    });

    inst._zod.parse = (payload, ctx) => {
      const result = def.innerType._zod.run(payload, ctx);
      if (result instanceof Promise) {
        return result.then((result) => handleNonOptionalResult(result, inst));
      }
      return handleNonOptionalResult(result, inst);
    };
  }
);

function handleNonOptionalResult(payload: ParsePayload, inst: $ZodNonOptional) {
  if (!payload.issues.length && payload.value === undefined) {
    payload.issues.push({
      code: "invalid_type",
      expected: "nonoptional",
      input: payload.value,
      inst,
    });
  }
  return payload;
}

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////      $ZodCoalesce      //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
// export interface $ZodCoalesceDef<T extends $ZodType = $ZodType> extends $ZodTypeDef {
//   type: "coalesce";
//   innerType: T;
//   defaultValue: () => NonNullable<T['_zod']["output"]>;
// }

// export _interface $ZodCoalesceInternals<T extends $ZodType = $ZodType>
//   extends $ZodTypeInternals<NonNullable<T['_zod']["output"]>, T['_zod']["input"] | undefined | null> {
//   _def: $ZodCoalesceDef<T>;
//   _isst: errors.$ZodIssueInvalidType;
//   _qin: "true";
// }

// function handleCoalesceResult(payload: ParsePayload, def: $ZodCoalesceDef) {
//   payload.value ??= def.defaultValue();
//   return payload;
// }

// export const $ZodCoalesce: core.$constructor<{_zod: $ZodCoalesceInternals}> = /*@__PURE__*/ core.$constructor(
//   "$ZodCoalesce",
//   (inst, def) => {
//     $ZodType.init(inst, def);
// inst._zod.qin = "true";
//     inst._zod.parse = (payload, ctx) => {
//       const result = def.innerType._zod.run(payload, ctx);
//       if (result instanceof Promise) {
//         return result.then((result) => handleCoalesceResult(result, def));
//       }
//       return handleCoalesceResult(result, def);
//     };
//   }
// );

/////////////////////////////////////////////
/////////////////////////////////////////////
//////////                         //////////
//////////      $ZodSuccess        //////////
//////////                         //////////
/////////////////////////////////////////////
/////////////////////////////////////////////
export interface $ZodSuccessDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "success";
  innerType: T;
}

export interface $ZodSuccessInternals<T extends SomeType = $ZodType> extends $ZodTypeInternals<boolean, core.input<T>> {
  def: $ZodSuccessDef<T>;
  isst: never;
  optin: T["_zod"]["optin"];
  optout: "optional" | undefined;
}

export interface $ZodSuccess<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodSuccessInternals<T>;
}

export const $ZodSuccess: core.$constructor<$ZodSuccess> = /*@__PURE__*/ core.$constructor(
  "$ZodSuccess",
  (inst, def) => {
    $ZodType.init(inst, def);

    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        throw new core.$ZodEncodeError("ZodSuccess");
      }

      const result = def.innerType._zod.run(payload, ctx);
      if (result instanceof Promise) {
        return result.then((result) => {
          payload.value = result.issues.length === 0;
          return payload;
        });
      }
      payload.value = result.issues.length === 0;
      return payload;
    };
  }
);

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////       $ZodCatch        //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
export interface $ZodCatchCtx extends ParsePayload {
  /** @deprecated Use `ctx.issues` */
  error: { issues: errors.$ZodIssue[] };
  /** @deprecated Use `ctx.value` */
  input: unknown;
}
export interface $ZodCatchDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "catch";
  innerType: T;
  catchValue: (ctx: $ZodCatchCtx) => unknown;
}

export interface $ZodCatchInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<core.output<T>, core.input<T>> {
  def: $ZodCatchDef<T>;
  optin: T["_zod"]["optin"];
  optout: T["_zod"]["optout"];
  isst: never;
  values: T["_zod"]["values"];
}

export interface $ZodCatch<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodCatchInternals<T>;
}

function handleCatchResult(payload: ParsePayload, result: ParsePayload, def: $ZodCatchDef, ctx: ParseContextInternal) {
  if (!result.issues.length) {
    payload.value = result.value;
    // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.
    if (result.memo) payload.memo = true;
    return payload;
  }

  // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.
  payload.value = def.catchValue({
    ...result,
    value: payload.value,
    error: {
      issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
    },
    input: payload.value,
  });
  return payload;
}

export const $ZodCatch: core.$constructor<$ZodCatch> = /*@__PURE__*/ core.$constructor("$ZodCatch", (inst, def) => {
  $ZodType.init(inst, def);
  util.defineLazyInternal(inst, "optin", (zod) =>
    zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"
  );
  util.defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
  util.defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);

  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }

    // Forward direction (decode): apply catch logic
    const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);
    if (result instanceof Promise) {
      return result.then((result) => handleCatchResult(payload, result, def, ctx));
    }

    return handleCatchResult(payload, result, def, ctx);
  };
});

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////        $ZodNaN         //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
export interface $ZodNaNDef extends $ZodTypeDef {
  type: "nan";
}

export interface $ZodNaNInternals extends $ZodTypeInternals<number, number> {
  def: $ZodNaNDef;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodNaN extends $ZodType {
  _zod: $ZodNaNInternals;
}

export const $ZodNaN: core.$constructor<$ZodNaN> = /*@__PURE__*/ core.$constructor("$ZodNaN", (inst, def) => {
  $ZodType.init(inst, def);

  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
      payload.issues.push({
        input: payload.value,
        inst,
        expected: "nan",
        code: "invalid_type",
      });
      return payload;
    }
    return payload;
  };
});

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////      $ZodPipe      //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
export interface $ZodPipeDef<A extends SomeType = $ZodType, B extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "pipe";
  in: A;
  out: B;
  /** Only defined inside $ZodCodec instances. */
  transform?: (value: core.output<A>, payload: ParsePayload<core.output<A>>) => util.MaybeAsync<core.input<B>>;
  /** Only defined inside $ZodCodec instances. */
  reverseTransform?: (value: core.input<B>, payload: ParsePayload<core.input<B>>) => util.MaybeAsync<core.output<A>>;
}

export interface $ZodPipeInternals<A extends SomeType = $ZodType, B extends SomeType = $ZodType>
  extends $ZodTypeInternals<core.output<B>, core.input<A>> {
  def: $ZodPipeDef<A, B>;
  isst: never;
  values: A["_zod"]["values"];
  optin: A["_zod"]["optin"];
  optout: B["_zod"]["optout"];
  propValues: A["_zod"]["propValues"];
}

export interface $ZodPipe<A extends SomeType = $ZodType, B extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodPipeInternals<A, B>;
}

export const $ZodPipe: core.$constructor<$ZodPipe> = /*@__PURE__*/ core.$constructor("$ZodPipe", (inst, def) => {
  $ZodType.init(inst, def);
  util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values);
  util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin);
  util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout);
  util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);

  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right) => handlePipeResult(right, def.in, ctx));
      }
      return handlePipeResult(right, def.in, ctx);
    }

    const left = def.in._zod.run(payload, ctx);
    if (left instanceof Promise) {
      return left.then((left) => handlePipeResult(left, def.out, ctx));
    }
    return handlePipeResult(left, def.out, ctx);
  };
});

function handlePipeResult(left: ParsePayload, next: $ZodType, ctx: ParseContextInternal) {
  // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.
  if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) {
    // prevent further checks
    left.aborted = true;
    return left;
  }
  return next._zod.run({ value: left.value, issues: left.issues }, ctx);
}

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////      $ZodCodec         //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////
export interface $ZodCodecDef<A extends SomeType = $ZodType, B extends SomeType = $ZodType> extends $ZodPipeDef<A, B> {
  transform: (value: core.output<A>, payload: ParsePayload<core.output<A>>) => util.MaybeAsync<core.input<B>>;
  reverseTransform: (value: core.input<B>, payload: ParsePayload<core.input<B>>) => util.MaybeAsync<core.output<A>>;
}

export interface $ZodCodecInternals<A extends SomeType = $ZodType, B extends SomeType = $ZodType>
  extends $ZodTypeInternals<core.output<B>, core.input<A>> {
  def: $ZodCodecDef<A, B>;
  isst: never;
  values: A["_zod"]["values"];
  optin: A["_zod"]["optin"];
  optout: B["_zod"]["optout"];
  propValues: A["_zod"]["propValues"];
}

export interface $ZodCodec<A extends SomeType = $ZodType, B extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodCodecInternals<A, B>;
}

export const $ZodCodec: core.$constructor<$ZodCodec> = /*@__PURE__*/ core.$constructor("$ZodCodec", (inst, def) => {
  $ZodType.init(inst, def);
  util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values);
  util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin);
  util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout);
  util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);

  inst._zod.parse = (payload, ctx) => {
    const direction = ctx.direction || "forward";
    if (direction === "forward") {
      const left = def.in._zod.run(payload, ctx);
      if (left instanceof Promise) {
        return left.then((left) => handleCodecAResult(left, def, ctx));
      }
      return handleCodecAResult(left, def, ctx);
    } else {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right) => handleCodecAResult(right, def, ctx));
      }
      return handleCodecAResult(right, def, ctx);
    }
  };
});

function handleCodecAResult(result: ParsePayload, def: $ZodCodecDef, ctx: ParseContextInternal) {
  if (result.issues.length) {
    // prevent further checks
    result.aborted = true;
    return result;
  }

  const direction = ctx.direction || "forward";

  if (direction === "forward") {
    const transformed = def.transform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));
    }
    return handleCodecTxResult(result, transformed, def.out, ctx);
  } else {
    const transformed = def.reverseTransform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));
    }
    return handleCodecTxResult(result, transformed, def.in, ctx);
  }
}

function handleCodecTxResult(left: ParsePayload, value: any, nextSchema: SomeType, ctx: ParseContextInternal) {
  // Check if transform added any issues
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }

  return nextSchema._zod.run({ value, issues: left.issues }, ctx);
}

/////////////////////////////////////////////////
/////////////////////////////////////////////////
//////////                             //////////
//////////      $ZodPreprocess         //////////
//////////                             //////////
/////////////////////////////////////////////////
/////////////////////////////////////////////////
export interface $ZodPreprocessDef<B extends SomeType = $ZodType, I = unknown>
  extends $ZodPipeDef<$ZodTransform<unknown, I>, B> {
  in: $ZodTransform<unknown, I>;
  out: B;
}

export interface $ZodPreprocessInternals<B extends SomeType = $ZodType, I = unknown>
  extends $ZodPipeInternals<$ZodTransform<unknown, I>, B> {
  def: $ZodPreprocessDef<B, I>;
  optin: B["_zod"]["optin"];
  optout: B["_zod"]["optout"];
}

export interface $ZodPreprocess<B extends SomeType = $ZodType, I = unknown>
  extends $ZodPipe<$ZodTransform<unknown, I>, B> {
  _zod: $ZodPreprocessInternals<B, I>;
}

export const $ZodPreprocess: core.$constructor<$ZodPreprocess> = /*@__PURE__*/ core.$constructor(
  "$ZodPreprocess",
  (inst, def) => {
    $ZodPipe.init(inst, def);
  }
);

////////////////////////////////////////////
////////////////////////////////////////////
//////////                        //////////
//////////      $ZodReadonly      //////////
//////////                        //////////
////////////////////////////////////////////
////////////////////////////////////////////

export interface $ZodReadonlyDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "readonly";
  innerType: T;
}

export interface $ZodReadonlyInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<util.MakeReadonly<core.output<T>>, util.MakeReadonly<core.input<T>>> {
  def: $ZodReadonlyDef<T>;
  optin: T["_zod"]["optin"];
  optout: T["_zod"]["optout"];
  isst: never;
  propValues: T["_zod"]["propValues"];
  values: T["_zod"]["values"];
}

export interface $ZodReadonly<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodReadonlyInternals<T>;
}

export const $ZodReadonly: core.$constructor<$ZodReadonly> = /*@__PURE__*/ core.$constructor(
  "$ZodReadonly",
  (inst, def) => {
    $ZodType.init(inst, def);
    util.defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues);
    util.defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
    util.defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin);
    util.defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout);

    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        return def.innerType._zod.run(payload, ctx);
      }
      const result = def.innerType._zod.run(payload, ctx);
      if (result instanceof Promise) {
        return result.then(handleReadonlyResult);
      }
      return handleReadonlyResult(result);
    };
  }
);

function handleReadonlyResult(payload: ParsePayload): ParsePayload {
  // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.
  if (!payload.memo) payload.value = Object.freeze(payload.value);
  return payload;
}

/////////////////////////////////////////////
/////////////////////////////////////////////
//////////                         //////////
//////////   $ZodTemplateLiteral   //////////
//////////                         //////////
/////////////////////////////////////////////
/////////////////////////////////////////////

export interface $ZodTemplateLiteralDef extends $ZodTypeDef {
  type: "template_literal";
  parts: $ZodTemplateLiteralPart[];
  format?: string | undefined;
}
export interface $ZodTemplateLiteralInternals<Template extends string = string>
  extends $ZodTypeInternals<Template, Template> {
  pattern: RegExp;
  def: $ZodTemplateLiteralDef;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodTemplateLiteral<Template extends string = string> extends $ZodType {
  _zod: $ZodTemplateLiteralInternals<Template>;
}

type LiteralPart = Exclude<util.Literal, symbol>; //string | number | boolean | null | undefined;
interface SchemaPartInternals extends $ZodTypeInternals<LiteralPart, LiteralPart> {
  pattern: RegExp;
}
interface SchemaPart extends $ZodType {
  _zod: SchemaPartInternals;
}
export type $ZodTemplateLiteralPart = LiteralPart | SchemaPart;

type UndefinedToEmptyString<T> = T extends undefined ? "" : T;
type AppendToTemplateLiteral<
  Template extends string,
  Suffix extends LiteralPart | $ZodType,
> = Suffix extends LiteralPart
  ? `${Template}${UndefinedToEmptyString<Suffix>}`
  : Suffix extends $ZodType
    ? `${Template}${core.output<Suffix> extends infer T extends LiteralPart ? UndefinedToEmptyString<T> : never}`
    : never;

export type ConcatenateTupleOfStrings<T extends string[]> = T extends [
  infer First extends string,
  ...infer Rest extends string[],
]
  ? Rest extends string[]
    ? First extends ""
      ? ConcatenateTupleOfStrings<Rest>
      : `${First}${ConcatenateTupleOfStrings<Rest>}`
    : never
  : "";
export type ConvertPartsToStringTuple<Parts extends $ZodTemplateLiteralPart[]> = {
  [K in keyof Parts]: Parts[K] extends LiteralPart
    ? `${UndefinedToEmptyString<Parts[K]>}`
    : Parts[K] extends $ZodType
      ? `${core.output<Parts[K]> extends infer T extends LiteralPart ? UndefinedToEmptyString<T> : never}`
      : never;
};

export type ToTemplateLiteral<Parts extends $ZodTemplateLiteralPart[]> = ConcatenateTupleOfStrings<
  ConvertPartsToStringTuple<Parts>
>;
// type lkjasd = ConcatenateTupleOfStrings<["Hello", " ", "World", "!"]>; // "Hello World!"
export type $PartsToTemplateLiteral<Parts extends $ZodTemplateLiteralPart[]> = [] extends Parts
  ? ``
  : Parts extends [...infer Rest, infer Last extends $ZodTemplateLiteralPart]
    ? Rest extends $ZodTemplateLiteralPart[]
      ? AppendToTemplateLiteral<$PartsToTemplateLiteral<Rest>, Last>
      : never
    : never;

// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it
function leafPattern(schema: $ZodType): string | undefined {
  const def = schema._zod.def as { pattern?: RegExp; format?: string; checks?: checks.$ZodCheck[] };
  let pattern = def.pattern;
  let isInt = !!def.format?.includes("int");
  let minimum: number | undefined;
  let maximum: number | undefined;
  for (const ch of def.checks ?? []) {
    const d = ch._zod.def as { pattern?: RegExp; format?: string; minimum?: number; maximum?: number; length?: number };
    if (d.pattern) pattern = d.pattern;
    isInt ||= !!d.format?.includes("int");
    const lo = d.minimum ?? d.length;
    const hi = d.maximum ?? d.length;
    if (lo !== undefined && (minimum === undefined || lo > minimum)) minimum = lo;
    if (hi !== undefined && (maximum === undefined || hi < maximum)) maximum = hi;
  }
  if (pattern) return pattern.source;
  // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier
  if (minimum !== undefined && maximum !== undefined && minimum > maximum) return "(?!)";
  if (minimum !== undefined || maximum !== undefined) return regexes.string({ minimum, maximum }).source;
  const own = schema._zod.pattern;
  return (isInt && own === regexes.number ? regexes.integer : own)?.source;
}

// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern
function partPattern(schema: $ZodType): string | undefined {
  const def = schema._zod.def as { innerType?: $ZodType; options?: $ZodType[] };
  const own = schema._zod.pattern?.source;
  // lazy resolves its inner on the internals, not the def
  const inner = def.innerType ?? (schema._zod as { innerType?: $ZodType }).innerType;
  if (inner) {
    const before = inner._zod.pattern?.source;
    const after = partPattern(inner);
    if (own && before && after && after !== before) {
      return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));
    }
    return own;
  }
  if (def.options) {
    const sources = def.options.map(partPattern);
    if (sources.every(Boolean)) return `^(${sources.map((s) => util.cleanRegex(s!)).join("|")})$`;
  }
  return leafPattern(schema);
}

export const $ZodTemplateLiteral: core.$constructor<$ZodTemplateLiteral> = /*@__PURE__*/ core.$constructor(
  "$ZodTemplateLiteral",
  (inst, def) => {
    $ZodType.init(inst, def);
    const regexParts: string[] = [];
    for (const part of def.parts) {
      if (typeof part === "object" && part !== null) {
        // is Zod schema
        const source = partPattern(part);
        if (!source) {
          throw new Error(`Invalid template literal part, no pattern found: ${[...(part as any)._zod.traits].shift()}`);
        }
        regexParts.push(util.cleanRegex(source));
      } else if (part === null || util.primitiveTypes.has(typeof part)) {
        regexParts.push(util.escapeRegex(`${part}`));
      } else {
        throw new Error(`Invalid template literal part: ${part}`);
      }
    }
    inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);

    inst._zod.parse = (payload, _ctx) => {
      if (typeof payload.value !== "string") {
        payload.issues.push({
          input: payload.value,
          inst,
          expected: "string",
          code: "invalid_type",
        });
        return payload;
      }

      inst._zod.pattern.lastIndex = 0;

      if (!inst._zod.pattern.test(payload.value)) {
        payload.issues.push({
          input: payload.value,
          inst,

          code: "invalid_format",
          format: def.format ?? "template_literal",
          pattern: inst._zod.pattern.source,
        });
        return payload;
      }

      return payload;
    };
  }
);

//////////////////////////////////////////
//////////////////////////////////////////
//////////                      //////////
//////////     $ZodFunction     //////////
//////////                      //////////
//////////////////////////////////////////
//////////////////////////////////////////
export type $ZodFunctionArgs = $ZodType<unknown[], unknown[]>;
export type $ZodFunctionIn = $ZodFunctionArgs;
export type $ZodFunctionOut = $ZodType;

export type $InferInnerFunctionType<Args extends $ZodFunctionIn, Returns extends $ZodFunctionOut> = (
  ...args: $ZodFunctionIn extends Args ? never[] : core.output<Args>
) => core.input<Returns>;

export type $InferInnerFunctionTypeAsync<Args extends $ZodFunctionIn, Returns extends $ZodFunctionOut> = (
  ...args: $ZodFunctionIn extends Args ? never[] : core.output<Args>
) => util.MaybeAsync<core.input<Returns>>;

export type $InferOuterFunctionType<Args extends $ZodFunctionIn, Returns extends $ZodFunctionOut> = (
  ...args: $ZodFunctionIn extends Args ? never[] : core.input<Args>
) => core.output<Returns>;

export type $InferOuterFunctionTypeAsync<Args extends $ZodFunctionIn, Returns extends $ZodFunctionOut> = (
  ...args: $ZodFunctionIn extends Args ? never[] : core.input<Args>
) => Promise<core.output<Returns>>;

export interface $ZodFunctionDef<
  In extends $ZodFunctionIn = $ZodFunctionIn,
  Out extends $ZodFunctionOut = $ZodFunctionOut,
> extends $ZodTypeDef {
  type: "function";
  input: In;
  output: Out;
}

export interface $ZodFunctionInternals<Args extends $ZodFunctionIn, Returns extends $ZodFunctionOut>
  extends $ZodTypeInternals<$InferOuterFunctionType<Args, Returns>, $InferInnerFunctionType<Args, Returns>> {
  def: $ZodFunctionDef<Args, Returns>;
  isst: errors.$ZodIssueInvalidType;
}

export interface $ZodFunction<
  Args extends $ZodFunctionIn = $ZodFunctionIn,
  Returns extends $ZodFunctionOut = $ZodFunctionOut,
> extends $ZodType<any, any, $ZodFunctionInternals<Args, Returns>> {
  /** @deprecated */
  _def: $ZodFunctionDef<Args, Returns>;
  _input: $InferInnerFunctionType<Args, Returns>;
  _output: $InferOuterFunctionType<Args, Returns>;

  implement<F extends $InferInnerFunctionType<Args, Returns>>(
    func: F
  ): // allow for return type inference
  (
    ...args: Parameters<this["_output"]>
  ) => ReturnType<F> extends ReturnType<this["_output"]> ? ReturnType<F> : ReturnType<this["_output"]>;

  implementAsync<F extends $InferInnerFunctionTypeAsync<Args, Returns>>(
    func: F
  ): F extends $InferOuterFunctionTypeAsync<Args, Returns> ? F : $InferOuterFunctionTypeAsync<Args, Returns>;

  input<const Items extends util.TupleItems, const Rest extends $ZodFunctionOut = $ZodFunctionOut>(
    args: Items,
    rest?: Rest
  ): $ZodFunction<$ZodTuple<Items, Rest>, Returns>;
  input<NewArgs extends $ZodFunctionIn>(args: NewArgs): $ZodFunction<NewArgs, Returns>;
  input(...args: any[]): $ZodFunction<any, Returns>;

  output<NewReturns extends $ZodType>(output: NewReturns): $ZodFunction<Args, NewReturns>;
}

export interface $ZodFunctionParams<I extends $ZodFunctionIn, O extends $ZodType> {
  input?: I;
  output?: O;
}

export const $ZodFunction: core.$constructor<$ZodFunction> = /*@__PURE__*/ core.$constructor(
  "$ZodFunction",
  (inst, def) => {
    $ZodType.init(inst, def);
    // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.
    Object.defineProperty(inst, "_def", { value: def });
    inst._zod.def = def;

    inst.implement = (func) => {
      if (typeof func !== "function") {
        throw new Error("implement() must be called with a function");
      }
      // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.
      return Object.defineProperty(
        function (this: any, ...args: never[]) {
          const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;
          const result = Reflect.apply(func, this, parsedArgs as never[]);
          if (inst._def.output) {
            return parse(inst._def.output, result);
          }
          return result as any;
        },
        "_zod",
        { value: inst._zod, enumerable: false }
      ) as any;
    };

    inst.implementAsync = (func) => {
      if (typeof func !== "function") {
        throw new Error("implementAsync() must be called with a function");
      }
      return Object.defineProperty(
        async function (this: any, ...args: never[]) {
          const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;
          const result = await Reflect.apply(func, this, parsedArgs as never[]);
          if (inst._def.output) {
            return await parseAsync(inst._def.output, result);
          }
          return result;
        },
        "_zod",
        { value: inst._zod, enumerable: false }
      ) as any;
    };

    inst._zod.parse = (payload, _ctx) => {
      if (typeof payload.value !== "function") {
        payload.issues.push({
          code: "invalid_type",
          expected: "function",
          input: payload.value,
          inst,
        });
        return payload;
      }

      // Check if output is a promise type to determine if we should use async implementation
      const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise";

      if (hasPromiseOutput) {
        payload.value = inst.implementAsync(payload.value);
      } else {
        payload.value = inst.implement(payload.value);
      }
      return payload;
    };

    inst.input = (...args: any[]): $ZodFunction<any, any> => {
      const F: any = inst.constructor;
      if (Array.isArray(args[0])) {
        return new F({
          type: "function",
          input: new $ZodTuple({
            type: "tuple",
            items: args[0],
            rest: args[1],
          }),
          output: inst._def.output,
        });
      }

      return new F({
        type: "function",
        input: args[0],
        output: inst._def.output,
      });
    };

    inst.output = (output) => {
      const F: any = inst.constructor;
      return new F({
        type: "function",
        input: inst._def.input,
        output,
      });
    };

    return inst;
  }
);

/////////////////////////////////////////
/////////////////////////////////////////
//////////                     //////////
//////////     $ZodPromise     //////////
//////////                     //////////
/////////////////////////////////////////
/////////////////////////////////////////
export interface $ZodPromiseDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "promise";
  innerType: T;
}

export interface $ZodPromiseInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<Promise<core.output<T>>, util.MaybeAsync<core.input<T>>> {
  def: $ZodPromiseDef<T>;
  isst: never;
}

export interface $ZodPromise<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodPromiseInternals<T>;
}

export const $ZodPromise: core.$constructor<$ZodPromise> = /*@__PURE__*/ core.$constructor(
  "$ZodPromise",
  (inst, def) => {
    $ZodType.init(inst, def);

    inst._zod.parse = (payload, ctx) => {
      return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
    };
  }
);

//////////////////////////////////////////
//////////////////////////////////////////
//////////                      //////////
//////////      $ZodLazy        //////////
//////////                      //////////
//////////////////////////////////////////
//////////////////////////////////////////

export interface $ZodLazyDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
  type: "lazy";
  getter: () => T;
}

export interface $ZodLazyInternals<T extends SomeType = $ZodType>
  extends $ZodTypeInternals<core.output<T>, core.input<T>> {
  def: $ZodLazyDef<T>;
  isst: never;
  /** Auto-cached way to retrieve the inner schema */
  innerType: T;
  pattern: T["_zod"]["pattern"];
  propValues: T["_zod"]["propValues"];
  optin: T["_zod"]["optin"];
  optout: T["_zod"]["optout"];
}

export interface $ZodLazy<T extends SomeType = $ZodType> extends $ZodType {
  _zod: $ZodLazyInternals<T>;
}

export const $ZodLazy: core.$constructor<$ZodLazy> = /*@__PURE__*/ core.$constructor("$ZodLazy", (inst, def) => {
  $ZodType.init(inst, def);

  // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.
  util.defineLazy(inst._zod, "innerType", () => {
    const d = def as $ZodLazyDef & { _cachedInner?: $ZodType };
    if (!d._cachedInner) d._cachedInner = def.getter() as $ZodType;
    return d._cachedInner;
  });
  util.defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern);
  util.defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues);
  util.defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined);
  util.defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined);
  inst._zod.parse = (payload, ctx) => {
    const inner = inst._zod.innerType;
    return inner._zod.run(payload, ctx);
  };
});

////////////////////////////////////////
////////////////////////////////////////
//////////                    //////////
//////////     $ZodCustom     //////////
//////////                    //////////
////////////////////////////////////////
////////////////////////////////////////
export interface $ZodCustomDef<O = unknown> extends $ZodTypeDef, checks.$ZodCheckDef {
  type: "custom";
  check: "custom";
  path?: PropertyKey[] | undefined;
  error?: errors.$ZodErrorMap | undefined;
  params?: Record<string, any> | undefined;
  fn: (arg: O) => unknown;
}

export interface $ZodCustomInternals<O = unknown, I = unknown>
  extends $ZodTypeInternals<O, I>,
    checks.$ZodCheckInternals<O> {
  def: $ZodCustomDef;
  issc: errors.$ZodIssue;
  isst: never;
  bag: util.LoosePartial<{
    Class: typeof util.Class;
  }>;
}

export interface $ZodCustom<O = unknown, I = unknown> extends $ZodType {
  _zod: $ZodCustomInternals<O, I>;
}

export const $ZodCustom: core.$constructor<$ZodCustom> = /*@__PURE__*/ core.$constructor("$ZodCustom", (inst, def) => {
  checks.$ZodCheck.init(inst, def);
  $ZodType.init(inst, def);

  inst._zod.parse = (payload, _) => {
    return payload;
  };

  inst._zod.check = (payload) => {
    const input = payload.value;
    const r = def.fn(input as any);
    if (r instanceof Promise) {
      return r.then((r) => handleRefineResult(r, payload, input, inst));
    }
    handleRefineResult(r, payload, input, inst);
    return;
  };
});

function handleRefineResult(result: unknown, payload: ParsePayload, input: unknown, inst: $ZodCustom): void {
  if (!result) {
    const _iss: any = {
      code: "custom",
      input,
      inst, // incorporates params.error into issue reporting
      path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting
      continue: !inst._zod.def.abort,
      // params: inst._zod.def.params,
    };
    if (inst._zod.def.params) _iss.params = inst._zod.def.params;
    payload.issues.push(util.issue(_iss));
  }
}

export type $ZodTypes =
  | $ZodString
  | $ZodNumber
  | $ZodBigInt
  | $ZodBoolean
  | $ZodDate
  | $ZodSymbol
  | $ZodUndefined
  | $ZodNullable
  | $ZodNull
  | $ZodAny
  | $ZodUnknown
  | $ZodNever
  | $ZodVoid
  | $ZodArray
  | $ZodObject
  | $ZodUnion
  | $ZodIntersection
  | $ZodTuple
  | $ZodRecord
  | $ZodMap
  | $ZodSet
  | $ZodLiteral
  | $ZodEnum
  | $ZodFunction
  | $ZodPromise
  | $ZodLazy
  | $ZodOptional
  | $ZodDefault
  | $ZodPrefault
  | $ZodTemplateLiteral
  | $ZodCustom
  | $ZodTransform
  | $ZodNonOptional
  | $ZodReadonly
  | $ZodNaN
  | $ZodPipe
  | $ZodSuccess
  | $ZodCatch
  | $ZodFile;

export type $ZodStringFormatTypes =
  | $ZodGUID
  | $ZodUUID
  | $ZodEmail
  | $ZodURL
  | $ZodEmoji
  | $ZodNanoID
  | $ZodCUID
  | $ZodCUID2
  | $ZodULID
  | $ZodXID
  | $ZodKSUID
  | $ZodISODateTime
  | $ZodISODate
  | $ZodISOTime
  | $ZodISODuration
  | $ZodIPv4
  | $ZodIPv6
  | $ZodMAC
  | $ZodCIDRv4
  | $ZodCIDRv6
  | $ZodBase64
  | $ZodBase64URL
  | $ZodE164
  | $ZodCreditCard
  | $ZodIBAN
  | $ZodJWT
  | $ZodCustomStringFormat<"hex">
  | $ZodCustomStringFormat<util.HashFormat>
  | $ZodCustomStringFormat<"hostname">
  | $ZodCustomStringFormat<"currency_code">;
