(function () {
    'use strict';

    var util$1;
    (function (util) {
        util.assertEqual = (_) => { };
        function assertIs(_arg) { }
        util.assertIs = assertIs;
        function assertNever(_x) {
            throw new Error();
        }
        util.assertNever = assertNever;
        util.arrayToEnum = (items) => {
            const obj = {};
            for (const item of items) {
                obj[item] = item;
            }
            return obj;
        };
        util.getValidEnumValues = (obj) => {
            const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
            const filtered = {};
            for (const k of validKeys) {
                filtered[k] = obj[k];
            }
            return util.objectValues(filtered);
        };
        util.objectValues = (obj) => {
            return util.objectKeys(obj).map(function (e) {
                return obj[e];
            });
        };
        util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
            ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
            : (object) => {
                const keys = [];
                for (const key in object) {
                    if (Object.prototype.hasOwnProperty.call(object, key)) {
                        keys.push(key);
                    }
                }
                return keys;
            };
        util.find = (arr, checker) => {
            for (const item of arr) {
                if (checker(item))
                    return item;
            }
            return undefined;
        };
        util.isInteger = typeof Number.isInteger === "function"
            ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
            : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
        function joinValues(array, separator = " | ") {
            return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
        }
        util.joinValues = joinValues;
        util.jsonStringifyReplacer = (_, value) => {
            if (typeof value === "bigint") {
                return value.toString();
            }
            return value;
        };
    })(util$1 || (util$1 = {}));
    var objectUtil$1;
    (function (objectUtil) {
        objectUtil.mergeShapes = (first, second) => {
            return {
                ...first,
                ...second, // second overwrites first
            };
        };
    })(objectUtil$1 || (objectUtil$1 = {}));
    const ZodParsedType$1 = util$1.arrayToEnum([
        "string",
        "nan",
        "number",
        "integer",
        "float",
        "boolean",
        "date",
        "bigint",
        "symbol",
        "function",
        "undefined",
        "null",
        "array",
        "object",
        "unknown",
        "promise",
        "void",
        "never",
        "map",
        "set",
    ]);
    const getParsedType$1 = (data) => {
        const t = typeof data;
        switch (t) {
            case "undefined":
                return ZodParsedType$1.undefined;
            case "string":
                return ZodParsedType$1.string;
            case "number":
                return Number.isNaN(data) ? ZodParsedType$1.nan : ZodParsedType$1.number;
            case "boolean":
                return ZodParsedType$1.boolean;
            case "function":
                return ZodParsedType$1.function;
            case "bigint":
                return ZodParsedType$1.bigint;
            case "symbol":
                return ZodParsedType$1.symbol;
            case "object":
                if (Array.isArray(data)) {
                    return ZodParsedType$1.array;
                }
                if (data === null) {
                    return ZodParsedType$1.null;
                }
                if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
                    return ZodParsedType$1.promise;
                }
                if (typeof Map !== "undefined" && data instanceof Map) {
                    return ZodParsedType$1.map;
                }
                if (typeof Set !== "undefined" && data instanceof Set) {
                    return ZodParsedType$1.set;
                }
                if (typeof Date !== "undefined" && data instanceof Date) {
                    return ZodParsedType$1.date;
                }
                return ZodParsedType$1.object;
            default:
                return ZodParsedType$1.unknown;
        }
    };

    const ZodIssueCode$1 = util$1.arrayToEnum([
        "invalid_type",
        "invalid_literal",
        "custom",
        "invalid_union",
        "invalid_union_discriminator",
        "invalid_enum_value",
        "unrecognized_keys",
        "invalid_arguments",
        "invalid_return_type",
        "invalid_date",
        "invalid_string",
        "too_small",
        "too_big",
        "invalid_intersection_types",
        "not_multiple_of",
        "not_finite",
    ]);
    let ZodError$1 = class ZodError extends Error {
        get errors() {
            return this.issues;
        }
        constructor(issues) {
            super();
            this.issues = [];
            this.addIssue = (sub) => {
                this.issues = [...this.issues, sub];
            };
            this.addIssues = (subs = []) => {
                this.issues = [...this.issues, ...subs];
            };
            const actualProto = new.target.prototype;
            if (Object.setPrototypeOf) {
                // eslint-disable-next-line ban/ban
                Object.setPrototypeOf(this, actualProto);
            }
            else {
                this.__proto__ = actualProto;
            }
            this.name = "ZodError";
            this.issues = issues;
        }
        format(_mapper) {
            const mapper = _mapper ||
                function (issue) {
                    return issue.message;
                };
            const fieldErrors = { _errors: [] };
            const processError = (error) => {
                for (const issue of error.issues) {
                    if (issue.code === "invalid_union") {
                        issue.unionErrors.map(processError);
                    }
                    else if (issue.code === "invalid_return_type") {
                        processError(issue.returnTypeError);
                    }
                    else if (issue.code === "invalid_arguments") {
                        processError(issue.argumentsError);
                    }
                    else if (issue.path.length === 0) {
                        fieldErrors._errors.push(mapper(issue));
                    }
                    else {
                        let curr = fieldErrors;
                        let i = 0;
                        while (i < issue.path.length) {
                            const el = issue.path[i];
                            const terminal = i === issue.path.length - 1;
                            if (!terminal) {
                                curr[el] = curr[el] || { _errors: [] };
                                // if (typeof el === "string") {
                                //   curr[el] = curr[el] || { _errors: [] };
                                // } else if (typeof el === "number") {
                                //   const errorArray: any = [];
                                //   errorArray._errors = [];
                                //   curr[el] = curr[el] || errorArray;
                                // }
                            }
                            else {
                                curr[el] = curr[el] || { _errors: [] };
                                curr[el]._errors.push(mapper(issue));
                            }
                            curr = curr[el];
                            i++;
                        }
                    }
                }
            };
            processError(this);
            return fieldErrors;
        }
        static assert(value) {
            if (!(value instanceof ZodError)) {
                throw new Error(`Not a ZodError: ${value}`);
            }
        }
        toString() {
            return this.message;
        }
        get message() {
            return JSON.stringify(this.issues, util$1.jsonStringifyReplacer, 2);
        }
        get isEmpty() {
            return this.issues.length === 0;
        }
        flatten(mapper = (issue) => issue.message) {
            const fieldErrors = {};
            const formErrors = [];
            for (const sub of this.issues) {
                if (sub.path.length > 0) {
                    const firstEl = sub.path[0];
                    fieldErrors[firstEl] = fieldErrors[firstEl] || [];
                    fieldErrors[firstEl].push(mapper(sub));
                }
                else {
                    formErrors.push(mapper(sub));
                }
            }
            return { formErrors, fieldErrors };
        }
        get formErrors() {
            return this.flatten();
        }
    };
    ZodError$1.create = (issues) => {
        const error = new ZodError$1(issues);
        return error;
    };

    const errorMap$1 = (issue, _ctx) => {
        let message;
        switch (issue.code) {
            case ZodIssueCode$1.invalid_type:
                if (issue.received === ZodParsedType$1.undefined) {
                    message = "Required";
                }
                else {
                    message = `Expected ${issue.expected}, received ${issue.received}`;
                }
                break;
            case ZodIssueCode$1.invalid_literal:
                message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util$1.jsonStringifyReplacer)}`;
                break;
            case ZodIssueCode$1.unrecognized_keys:
                message = `Unrecognized key(s) in object: ${util$1.joinValues(issue.keys, ", ")}`;
                break;
            case ZodIssueCode$1.invalid_union:
                message = `Invalid input`;
                break;
            case ZodIssueCode$1.invalid_union_discriminator:
                message = `Invalid discriminator value. Expected ${util$1.joinValues(issue.options)}`;
                break;
            case ZodIssueCode$1.invalid_enum_value:
                message = `Invalid enum value. Expected ${util$1.joinValues(issue.options)}, received '${issue.received}'`;
                break;
            case ZodIssueCode$1.invalid_arguments:
                message = `Invalid function arguments`;
                break;
            case ZodIssueCode$1.invalid_return_type:
                message = `Invalid function return type`;
                break;
            case ZodIssueCode$1.invalid_date:
                message = `Invalid date`;
                break;
            case ZodIssueCode$1.invalid_string:
                if (typeof issue.validation === "object") {
                    if ("includes" in issue.validation) {
                        message = `Invalid input: must include "${issue.validation.includes}"`;
                        if (typeof issue.validation.position === "number") {
                            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
                        }
                    }
                    else if ("startsWith" in issue.validation) {
                        message = `Invalid input: must start with "${issue.validation.startsWith}"`;
                    }
                    else if ("endsWith" in issue.validation) {
                        message = `Invalid input: must end with "${issue.validation.endsWith}"`;
                    }
                    else {
                        util$1.assertNever(issue.validation);
                    }
                }
                else if (issue.validation !== "regex") {
                    message = `Invalid ${issue.validation}`;
                }
                else {
                    message = "Invalid";
                }
                break;
            case ZodIssueCode$1.too_small:
                if (issue.type === "array")
                    message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
                else if (issue.type === "string")
                    message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
                else if (issue.type === "number")
                    message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
                else if (issue.type === "bigint")
                    message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
                else if (issue.type === "date")
                    message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
                else
                    message = "Invalid input";
                break;
            case ZodIssueCode$1.too_big:
                if (issue.type === "array")
                    message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
                else if (issue.type === "string")
                    message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
                else if (issue.type === "number")
                    message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
                else if (issue.type === "bigint")
                    message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
                else if (issue.type === "date")
                    message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
                else
                    message = "Invalid input";
                break;
            case ZodIssueCode$1.custom:
                message = `Invalid input`;
                break;
            case ZodIssueCode$1.invalid_intersection_types:
                message = `Intersection results could not be merged`;
                break;
            case ZodIssueCode$1.not_multiple_of:
                message = `Number must be a multiple of ${issue.multipleOf}`;
                break;
            case ZodIssueCode$1.not_finite:
                message = "Number must be finite";
                break;
            default:
                message = _ctx.defaultError;
                util$1.assertNever(issue);
        }
        return { message };
    };

    let overrideErrorMap$1 = errorMap$1;
    function getErrorMap$1() {
        return overrideErrorMap$1;
    }

    const makeIssue$1 = (params) => {
        const { data, path, errorMaps, issueData } = params;
        const fullPath = [...path, ...(issueData.path || [])];
        const fullIssue = {
            ...issueData,
            path: fullPath,
        };
        if (issueData.message !== undefined) {
            return {
                ...issueData,
                path: fullPath,
                message: issueData.message,
            };
        }
        let errorMessage = "";
        const maps = errorMaps
            .filter((m) => !!m)
            .slice()
            .reverse();
        for (const map of maps) {
            errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
        }
        return {
            ...issueData,
            path: fullPath,
            message: errorMessage,
        };
    };
    function addIssueToContext$1(ctx, issueData) {
        const overrideMap = getErrorMap$1();
        const issue = makeIssue$1({
            issueData: issueData,
            data: ctx.data,
            path: ctx.path,
            errorMaps: [
                ctx.common.contextualErrorMap, // contextual error map is first priority
                ctx.schemaErrorMap, // then schema-bound map if available
                overrideMap, // then global override map
                overrideMap === errorMap$1 ? undefined : errorMap$1, // then global default map
            ].filter((x) => !!x),
        });
        ctx.common.issues.push(issue);
    }
    let ParseStatus$1 = class ParseStatus {
        constructor() {
            this.value = "valid";
        }
        dirty() {
            if (this.value === "valid")
                this.value = "dirty";
        }
        abort() {
            if (this.value !== "aborted")
                this.value = "aborted";
        }
        static mergeArray(status, results) {
            const arrayValue = [];
            for (const s of results) {
                if (s.status === "aborted")
                    return INVALID$1;
                if (s.status === "dirty")
                    status.dirty();
                arrayValue.push(s.value);
            }
            return { status: status.value, value: arrayValue };
        }
        static async mergeObjectAsync(status, pairs) {
            const syncPairs = [];
            for (const pair of pairs) {
                const key = await pair.key;
                const value = await pair.value;
                syncPairs.push({
                    key,
                    value,
                });
            }
            return ParseStatus.mergeObjectSync(status, syncPairs);
        }
        static mergeObjectSync(status, pairs) {
            const finalObject = {};
            for (const pair of pairs) {
                const { key, value } = pair;
                if (key.status === "aborted")
                    return INVALID$1;
                if (value.status === "aborted")
                    return INVALID$1;
                if (key.status === "dirty")
                    status.dirty();
                if (value.status === "dirty")
                    status.dirty();
                if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
                    finalObject[key.value] = value.value;
                }
            }
            return { status: status.value, value: finalObject };
        }
    };
    const INVALID$1 = Object.freeze({
        status: "aborted",
    });
    const DIRTY$1 = (value) => ({ status: "dirty", value });
    const OK$1 = (value) => ({ status: "valid", value });
    const isAborted$1 = (x) => x.status === "aborted";
    const isDirty$1 = (x) => x.status === "dirty";
    const isValid$1 = (x) => x.status === "valid";
    const isAsync$1 = (x) => typeof Promise !== "undefined" && x instanceof Promise;

    var errorUtil$1;
    (function (errorUtil) {
        errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
        // biome-ignore lint:
        errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
    })(errorUtil$1 || (errorUtil$1 = {}));

    let ParseInputLazyPath$1 = class ParseInputLazyPath {
        constructor(parent, value, path, key) {
            this._cachedPath = [];
            this.parent = parent;
            this.data = value;
            this._path = path;
            this._key = key;
        }
        get path() {
            if (!this._cachedPath.length) {
                if (Array.isArray(this._key)) {
                    this._cachedPath.push(...this._path, ...this._key);
                }
                else {
                    this._cachedPath.push(...this._path, this._key);
                }
            }
            return this._cachedPath;
        }
    };
    const handleResult$1 = (ctx, result) => {
        if (isValid$1(result)) {
            return { success: true, data: result.value };
        }
        else {
            if (!ctx.common.issues.length) {
                throw new Error("Validation failed but no issues detected.");
            }
            return {
                success: false,
                get error() {
                    if (this._error)
                        return this._error;
                    const error = new ZodError$1(ctx.common.issues);
                    this._error = error;
                    return this._error;
                },
            };
        }
    };
    function processCreateParams$1(params) {
        if (!params)
            return {};
        const { errorMap, invalid_type_error, required_error, description } = params;
        if (errorMap && (invalid_type_error || required_error)) {
            throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
        }
        if (errorMap)
            return { errorMap: errorMap, description };
        const customMap = (iss, ctx) => {
            const { message } = params;
            if (iss.code === "invalid_enum_value") {
                return { message: message ?? ctx.defaultError };
            }
            if (typeof ctx.data === "undefined") {
                return { message: message ?? required_error ?? ctx.defaultError };
            }
            if (iss.code !== "invalid_type")
                return { message: ctx.defaultError };
            return { message: message ?? invalid_type_error ?? ctx.defaultError };
        };
        return { errorMap: customMap, description };
    }
    let ZodType$1 = class ZodType {
        get description() {
            return this._def.description;
        }
        _getType(input) {
            return getParsedType$1(input.data);
        }
        _getOrReturnCtx(input, ctx) {
            return (ctx || {
                common: input.parent.common,
                data: input.data,
                parsedType: getParsedType$1(input.data),
                schemaErrorMap: this._def.errorMap,
                path: input.path,
                parent: input.parent,
            });
        }
        _processInputParams(input) {
            return {
                status: new ParseStatus$1(),
                ctx: {
                    common: input.parent.common,
                    data: input.data,
                    parsedType: getParsedType$1(input.data),
                    schemaErrorMap: this._def.errorMap,
                    path: input.path,
                    parent: input.parent,
                },
            };
        }
        _parseSync(input) {
            const result = this._parse(input);
            if (isAsync$1(result)) {
                throw new Error("Synchronous parse encountered promise.");
            }
            return result;
        }
        _parseAsync(input) {
            const result = this._parse(input);
            return Promise.resolve(result);
        }
        parse(data, params) {
            const result = this.safeParse(data, params);
            if (result.success)
                return result.data;
            throw result.error;
        }
        safeParse(data, params) {
            const ctx = {
                common: {
                    issues: [],
                    async: params?.async ?? false,
                    contextualErrorMap: params?.errorMap,
                },
                path: params?.path || [],
                schemaErrorMap: this._def.errorMap,
                parent: null,
                data,
                parsedType: getParsedType$1(data),
            };
            const result = this._parseSync({ data, path: ctx.path, parent: ctx });
            return handleResult$1(ctx, result);
        }
        "~validate"(data) {
            const ctx = {
                common: {
                    issues: [],
                    async: !!this["~standard"].async,
                },
                path: [],
                schemaErrorMap: this._def.errorMap,
                parent: null,
                data,
                parsedType: getParsedType$1(data),
            };
            if (!this["~standard"].async) {
                try {
                    const result = this._parseSync({ data, path: [], parent: ctx });
                    return isValid$1(result)
                        ? {
                            value: result.value,
                        }
                        : {
                            issues: ctx.common.issues,
                        };
                }
                catch (err) {
                    if (err?.message?.toLowerCase()?.includes("encountered")) {
                        this["~standard"].async = true;
                    }
                    ctx.common = {
                        issues: [],
                        async: true,
                    };
                }
            }
            return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid$1(result)
                ? {
                    value: result.value,
                }
                : {
                    issues: ctx.common.issues,
                });
        }
        async parseAsync(data, params) {
            const result = await this.safeParseAsync(data, params);
            if (result.success)
                return result.data;
            throw result.error;
        }
        async safeParseAsync(data, params) {
            const ctx = {
                common: {
                    issues: [],
                    contextualErrorMap: params?.errorMap,
                    async: true,
                },
                path: params?.path || [],
                schemaErrorMap: this._def.errorMap,
                parent: null,
                data,
                parsedType: getParsedType$1(data),
            };
            const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
            const result = await (isAsync$1(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
            return handleResult$1(ctx, result);
        }
        refine(check, message) {
            const getIssueProperties = (val) => {
                if (typeof message === "string" || typeof message === "undefined") {
                    return { message };
                }
                else if (typeof message === "function") {
                    return message(val);
                }
                else {
                    return message;
                }
            };
            return this._refinement((val, ctx) => {
                const result = check(val);
                const setError = () => ctx.addIssue({
                    code: ZodIssueCode$1.custom,
                    ...getIssueProperties(val),
                });
                if (typeof Promise !== "undefined" && result instanceof Promise) {
                    return result.then((data) => {
                        if (!data) {
                            setError();
                            return false;
                        }
                        else {
                            return true;
                        }
                    });
                }
                if (!result) {
                    setError();
                    return false;
                }
                else {
                    return true;
                }
            });
        }
        refinement(check, refinementData) {
            return this._refinement((val, ctx) => {
                if (!check(val)) {
                    ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
                    return false;
                }
                else {
                    return true;
                }
            });
        }
        _refinement(refinement) {
            return new ZodEffects$1({
                schema: this,
                typeName: ZodFirstPartyTypeKind$1.ZodEffects,
                effect: { type: "refinement", refinement },
            });
        }
        superRefine(refinement) {
            return this._refinement(refinement);
        }
        constructor(def) {
            /** Alias of safeParseAsync */
            this.spa = this.safeParseAsync;
            this._def = def;
            this.parse = this.parse.bind(this);
            this.safeParse = this.safeParse.bind(this);
            this.parseAsync = this.parseAsync.bind(this);
            this.safeParseAsync = this.safeParseAsync.bind(this);
            this.spa = this.spa.bind(this);
            this.refine = this.refine.bind(this);
            this.refinement = this.refinement.bind(this);
            this.superRefine = this.superRefine.bind(this);
            this.optional = this.optional.bind(this);
            this.nullable = this.nullable.bind(this);
            this.nullish = this.nullish.bind(this);
            this.array = this.array.bind(this);
            this.promise = this.promise.bind(this);
            this.or = this.or.bind(this);
            this.and = this.and.bind(this);
            this.transform = this.transform.bind(this);
            this.brand = this.brand.bind(this);
            this.default = this.default.bind(this);
            this.catch = this.catch.bind(this);
            this.describe = this.describe.bind(this);
            this.pipe = this.pipe.bind(this);
            this.readonly = this.readonly.bind(this);
            this.isNullable = this.isNullable.bind(this);
            this.isOptional = this.isOptional.bind(this);
            this["~standard"] = {
                version: 1,
                vendor: "zod",
                validate: (data) => this["~validate"](data),
            };
        }
        optional() {
            return ZodOptional$1.create(this, this._def);
        }
        nullable() {
            return ZodNullable$1.create(this, this._def);
        }
        nullish() {
            return this.nullable().optional();
        }
        array() {
            return ZodArray$1.create(this);
        }
        promise() {
            return ZodPromise$1.create(this, this._def);
        }
        or(option) {
            return ZodUnion$1.create([this, option], this._def);
        }
        and(incoming) {
            return ZodIntersection$1.create(this, incoming, this._def);
        }
        transform(transform) {
            return new ZodEffects$1({
                ...processCreateParams$1(this._def),
                schema: this,
                typeName: ZodFirstPartyTypeKind$1.ZodEffects,
                effect: { type: "transform", transform },
            });
        }
        default(def) {
            const defaultValueFunc = typeof def === "function" ? def : () => def;
            return new ZodDefault$1({
                ...processCreateParams$1(this._def),
                innerType: this,
                defaultValue: defaultValueFunc,
                typeName: ZodFirstPartyTypeKind$1.ZodDefault,
            });
        }
        brand() {
            return new ZodBranded$1({
                typeName: ZodFirstPartyTypeKind$1.ZodBranded,
                type: this,
                ...processCreateParams$1(this._def),
            });
        }
        catch(def) {
            const catchValueFunc = typeof def === "function" ? def : () => def;
            return new ZodCatch$1({
                ...processCreateParams$1(this._def),
                innerType: this,
                catchValue: catchValueFunc,
                typeName: ZodFirstPartyTypeKind$1.ZodCatch,
            });
        }
        describe(description) {
            const This = this.constructor;
            return new This({
                ...this._def,
                description,
            });
        }
        pipe(target) {
            return ZodPipeline$1.create(this, target);
        }
        readonly() {
            return ZodReadonly$1.create(this);
        }
        isOptional() {
            return this.safeParse(undefined).success;
        }
        isNullable() {
            return this.safeParse(null).success;
        }
    };
    const cuidRegex$1 = /^c[^\s-]{8,}$/i;
    const cuid2Regex$1 = /^[0-9a-z]+$/;
    const ulidRegex$1 = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    // const uuidRegex =
    //   /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
    const uuidRegex$1 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    const nanoidRegex$1 = /^[a-z0-9_-]{21}$/i;
    const jwtRegex$1 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    const durationRegex$1 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    // from https://stackoverflow.com/a/46181/1550155
    // old version: too slow, didn't support unicode
    // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
    //old email regex
    // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
    // eslint-disable-next-line
    // const emailRegex =
    //   /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
    // const emailRegex =
    //   /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    // const emailRegex =
    //   /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
    const emailRegex$1 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    // const emailRegex =
    //   /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
    // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
    const _emojiRegex$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    let emojiRegex$1;
    // faster, simpler, safer
    const ipv4Regex$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    const ipv4CidrRegex$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
    // const ipv6Regex =
    // /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
    const ipv6Regex$1 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    const ipv6CidrRegex$1 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
    const base64Regex$1 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    // https://base64.guru/standards/base64url
    const base64urlRegex$1 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    // simple
    // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
    // no leap year validation
    // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
    // with leap year validation
    const dateRegexSource$1 = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
    const dateRegex$1 = new RegExp(`^${dateRegexSource$1}$`);
    function timeRegexSource$1(args) {
        let secondsRegexSource = `[0-5]\\d`;
        if (args.precision) {
            secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
        }
        else if (args.precision == null) {
            secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
        }
        const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero
        return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
    }
    function timeRegex$1(args) {
        return new RegExp(`^${timeRegexSource$1(args)}$`);
    }
    // Adapted from https://stackoverflow.com/a/3143231
    function datetimeRegex$1(args) {
        let regex = `${dateRegexSource$1}T${timeRegexSource$1(args)}`;
        const opts = [];
        opts.push(args.local ? `Z?` : `Z`);
        if (args.offset)
            opts.push(`([+-]\\d{2}:?\\d{2})`);
        regex = `${regex}(${opts.join("|")})`;
        return new RegExp(`^${regex}$`);
    }
    function isValidIP$1(ip, version) {
        if ((version === "v4" || !version) && ipv4Regex$1.test(ip)) {
            return true;
        }
        if ((version === "v6" || !version) && ipv6Regex$1.test(ip)) {
            return true;
        }
        return false;
    }
    function isValidJWT$1(jwt, alg) {
        if (!jwtRegex$1.test(jwt))
            return false;
        try {
            const [header] = jwt.split(".");
            if (!header)
                return false;
            // Convert base64url to base64
            const base64 = header
                .replace(/-/g, "+")
                .replace(/_/g, "/")
                .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
            const decoded = JSON.parse(atob(base64));
            if (typeof decoded !== "object" || decoded === null)
                return false;
            if ("typ" in decoded && decoded?.typ !== "JWT")
                return false;
            if (!decoded.alg)
                return false;
            if (alg && decoded.alg !== alg)
                return false;
            return true;
        }
        catch {
            return false;
        }
    }
    function isValidCidr$1(ip, version) {
        if ((version === "v4" || !version) && ipv4CidrRegex$1.test(ip)) {
            return true;
        }
        if ((version === "v6" || !version) && ipv6CidrRegex$1.test(ip)) {
            return true;
        }
        return false;
    }
    let ZodString$1 = class ZodString extends ZodType$1 {
        _parse(input) {
            if (this._def.coerce) {
                input.data = String(input.data);
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.string) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.string,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            const status = new ParseStatus$1();
            let ctx = undefined;
            for (const check of this._def.checks) {
                if (check.kind === "min") {
                    if (input.data.length < check.value) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.too_small,
                            minimum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: false,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "max") {
                    if (input.data.length > check.value) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.too_big,
                            maximum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: false,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "length") {
                    const tooBig = input.data.length > check.value;
                    const tooSmall = input.data.length < check.value;
                    if (tooBig || tooSmall) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        if (tooBig) {
                            addIssueToContext$1(ctx, {
                                code: ZodIssueCode$1.too_big,
                                maximum: check.value,
                                type: "string",
                                inclusive: true,
                                exact: true,
                                message: check.message,
                            });
                        }
                        else if (tooSmall) {
                            addIssueToContext$1(ctx, {
                                code: ZodIssueCode$1.too_small,
                                minimum: check.value,
                                type: "string",
                                inclusive: true,
                                exact: true,
                                message: check.message,
                            });
                        }
                        status.dirty();
                    }
                }
                else if (check.kind === "email") {
                    if (!emailRegex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "email",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "emoji") {
                    if (!emojiRegex$1) {
                        emojiRegex$1 = new RegExp(_emojiRegex$1, "u");
                    }
                    if (!emojiRegex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "emoji",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "uuid") {
                    if (!uuidRegex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "uuid",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "nanoid") {
                    if (!nanoidRegex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "nanoid",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "cuid") {
                    if (!cuidRegex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "cuid",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "cuid2") {
                    if (!cuid2Regex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "cuid2",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "ulid") {
                    if (!ulidRegex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "ulid",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "url") {
                    try {
                        new URL(input.data);
                    }
                    catch {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "url",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "regex") {
                    check.regex.lastIndex = 0;
                    const testResult = check.regex.test(input.data);
                    if (!testResult) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "regex",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "trim") {
                    input.data = input.data.trim();
                }
                else if (check.kind === "includes") {
                    if (!input.data.includes(check.value, check.position)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.invalid_string,
                            validation: { includes: check.value, position: check.position },
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "toLowerCase") {
                    input.data = input.data.toLowerCase();
                }
                else if (check.kind === "toUpperCase") {
                    input.data = input.data.toUpperCase();
                }
                else if (check.kind === "startsWith") {
                    if (!input.data.startsWith(check.value)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.invalid_string,
                            validation: { startsWith: check.value },
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "endsWith") {
                    if (!input.data.endsWith(check.value)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.invalid_string,
                            validation: { endsWith: check.value },
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "datetime") {
                    const regex = datetimeRegex$1(check);
                    if (!regex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.invalid_string,
                            validation: "datetime",
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "date") {
                    const regex = dateRegex$1;
                    if (!regex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.invalid_string,
                            validation: "date",
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "time") {
                    const regex = timeRegex$1(check);
                    if (!regex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.invalid_string,
                            validation: "time",
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "duration") {
                    if (!durationRegex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "duration",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "ip") {
                    if (!isValidIP$1(input.data, check.version)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "ip",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "jwt") {
                    if (!isValidJWT$1(input.data, check.alg)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "jwt",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "cidr") {
                    if (!isValidCidr$1(input.data, check.version)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "cidr",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "base64") {
                    if (!base64Regex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "base64",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "base64url") {
                    if (!base64urlRegex$1.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            validation: "base64url",
                            code: ZodIssueCode$1.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else {
                    util$1.assertNever(check);
                }
            }
            return { status: status.value, value: input.data };
        }
        _regex(regex, validation, message) {
            return this.refinement((data) => regex.test(data), {
                validation,
                code: ZodIssueCode$1.invalid_string,
                ...errorUtil$1.errToObj(message),
            });
        }
        _addCheck(check) {
            return new ZodString({
                ...this._def,
                checks: [...this._def.checks, check],
            });
        }
        email(message) {
            return this._addCheck({ kind: "email", ...errorUtil$1.errToObj(message) });
        }
        url(message) {
            return this._addCheck({ kind: "url", ...errorUtil$1.errToObj(message) });
        }
        emoji(message) {
            return this._addCheck({ kind: "emoji", ...errorUtil$1.errToObj(message) });
        }
        uuid(message) {
            return this._addCheck({ kind: "uuid", ...errorUtil$1.errToObj(message) });
        }
        nanoid(message) {
            return this._addCheck({ kind: "nanoid", ...errorUtil$1.errToObj(message) });
        }
        cuid(message) {
            return this._addCheck({ kind: "cuid", ...errorUtil$1.errToObj(message) });
        }
        cuid2(message) {
            return this._addCheck({ kind: "cuid2", ...errorUtil$1.errToObj(message) });
        }
        ulid(message) {
            return this._addCheck({ kind: "ulid", ...errorUtil$1.errToObj(message) });
        }
        base64(message) {
            return this._addCheck({ kind: "base64", ...errorUtil$1.errToObj(message) });
        }
        base64url(message) {
            // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
            return this._addCheck({
                kind: "base64url",
                ...errorUtil$1.errToObj(message),
            });
        }
        jwt(options) {
            return this._addCheck({ kind: "jwt", ...errorUtil$1.errToObj(options) });
        }
        ip(options) {
            return this._addCheck({ kind: "ip", ...errorUtil$1.errToObj(options) });
        }
        cidr(options) {
            return this._addCheck({ kind: "cidr", ...errorUtil$1.errToObj(options) });
        }
        datetime(options) {
            if (typeof options === "string") {
                return this._addCheck({
                    kind: "datetime",
                    precision: null,
                    offset: false,
                    local: false,
                    message: options,
                });
            }
            return this._addCheck({
                kind: "datetime",
                precision: typeof options?.precision === "undefined" ? null : options?.precision,
                offset: options?.offset ?? false,
                local: options?.local ?? false,
                ...errorUtil$1.errToObj(options?.message),
            });
        }
        date(message) {
            return this._addCheck({ kind: "date", message });
        }
        time(options) {
            if (typeof options === "string") {
                return this._addCheck({
                    kind: "time",
                    precision: null,
                    message: options,
                });
            }
            return this._addCheck({
                kind: "time",
                precision: typeof options?.precision === "undefined" ? null : options?.precision,
                ...errorUtil$1.errToObj(options?.message),
            });
        }
        duration(message) {
            return this._addCheck({ kind: "duration", ...errorUtil$1.errToObj(message) });
        }
        regex(regex, message) {
            return this._addCheck({
                kind: "regex",
                regex: regex,
                ...errorUtil$1.errToObj(message),
            });
        }
        includes(value, options) {
            return this._addCheck({
                kind: "includes",
                value: value,
                position: options?.position,
                ...errorUtil$1.errToObj(options?.message),
            });
        }
        startsWith(value, message) {
            return this._addCheck({
                kind: "startsWith",
                value: value,
                ...errorUtil$1.errToObj(message),
            });
        }
        endsWith(value, message) {
            return this._addCheck({
                kind: "endsWith",
                value: value,
                ...errorUtil$1.errToObj(message),
            });
        }
        min(minLength, message) {
            return this._addCheck({
                kind: "min",
                value: minLength,
                ...errorUtil$1.errToObj(message),
            });
        }
        max(maxLength, message) {
            return this._addCheck({
                kind: "max",
                value: maxLength,
                ...errorUtil$1.errToObj(message),
            });
        }
        length(len, message) {
            return this._addCheck({
                kind: "length",
                value: len,
                ...errorUtil$1.errToObj(message),
            });
        }
        /**
         * Equivalent to `.min(1)`
         */
        nonempty(message) {
            return this.min(1, errorUtil$1.errToObj(message));
        }
        trim() {
            return new ZodString({
                ...this._def,
                checks: [...this._def.checks, { kind: "trim" }],
            });
        }
        toLowerCase() {
            return new ZodString({
                ...this._def,
                checks: [...this._def.checks, { kind: "toLowerCase" }],
            });
        }
        toUpperCase() {
            return new ZodString({
                ...this._def,
                checks: [...this._def.checks, { kind: "toUpperCase" }],
            });
        }
        get isDatetime() {
            return !!this._def.checks.find((ch) => ch.kind === "datetime");
        }
        get isDate() {
            return !!this._def.checks.find((ch) => ch.kind === "date");
        }
        get isTime() {
            return !!this._def.checks.find((ch) => ch.kind === "time");
        }
        get isDuration() {
            return !!this._def.checks.find((ch) => ch.kind === "duration");
        }
        get isEmail() {
            return !!this._def.checks.find((ch) => ch.kind === "email");
        }
        get isURL() {
            return !!this._def.checks.find((ch) => ch.kind === "url");
        }
        get isEmoji() {
            return !!this._def.checks.find((ch) => ch.kind === "emoji");
        }
        get isUUID() {
            return !!this._def.checks.find((ch) => ch.kind === "uuid");
        }
        get isNANOID() {
            return !!this._def.checks.find((ch) => ch.kind === "nanoid");
        }
        get isCUID() {
            return !!this._def.checks.find((ch) => ch.kind === "cuid");
        }
        get isCUID2() {
            return !!this._def.checks.find((ch) => ch.kind === "cuid2");
        }
        get isULID() {
            return !!this._def.checks.find((ch) => ch.kind === "ulid");
        }
        get isIP() {
            return !!this._def.checks.find((ch) => ch.kind === "ip");
        }
        get isCIDR() {
            return !!this._def.checks.find((ch) => ch.kind === "cidr");
        }
        get isBase64() {
            return !!this._def.checks.find((ch) => ch.kind === "base64");
        }
        get isBase64url() {
            // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
            return !!this._def.checks.find((ch) => ch.kind === "base64url");
        }
        get minLength() {
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
            }
            return min;
        }
        get maxLength() {
            let max = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return max;
        }
    };
    ZodString$1.create = (params) => {
        return new ZodString$1({
            checks: [],
            typeName: ZodFirstPartyTypeKind$1.ZodString,
            coerce: params?.coerce ?? false,
            ...processCreateParams$1(params),
        });
    };
    // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
    function floatSafeRemainder$1(val, step) {
        const valDecCount = (val.toString().split(".")[1] || "").length;
        const stepDecCount = (step.toString().split(".")[1] || "").length;
        const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
        const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
        const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
        return (valInt % stepInt) / 10 ** decCount;
    }
    let ZodNumber$1 = class ZodNumber extends ZodType$1 {
        constructor() {
            super(...arguments);
            this.min = this.gte;
            this.max = this.lte;
            this.step = this.multipleOf;
        }
        _parse(input) {
            if (this._def.coerce) {
                input.data = Number(input.data);
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.number) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.number,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            let ctx = undefined;
            const status = new ParseStatus$1();
            for (const check of this._def.checks) {
                if (check.kind === "int") {
                    if (!util$1.isInteger(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.invalid_type,
                            expected: "integer",
                            received: "float",
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "min") {
                    const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
                    if (tooSmall) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.too_small,
                            minimum: check.value,
                            type: "number",
                            inclusive: check.inclusive,
                            exact: false,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "max") {
                    const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
                    if (tooBig) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.too_big,
                            maximum: check.value,
                            type: "number",
                            inclusive: check.inclusive,
                            exact: false,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "multipleOf") {
                    if (floatSafeRemainder$1(input.data, check.value) !== 0) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.not_multiple_of,
                            multipleOf: check.value,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "finite") {
                    if (!Number.isFinite(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.not_finite,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else {
                    util$1.assertNever(check);
                }
            }
            return { status: status.value, value: input.data };
        }
        gte(value, message) {
            return this.setLimit("min", value, true, errorUtil$1.toString(message));
        }
        gt(value, message) {
            return this.setLimit("min", value, false, errorUtil$1.toString(message));
        }
        lte(value, message) {
            return this.setLimit("max", value, true, errorUtil$1.toString(message));
        }
        lt(value, message) {
            return this.setLimit("max", value, false, errorUtil$1.toString(message));
        }
        setLimit(kind, value, inclusive, message) {
            return new ZodNumber({
                ...this._def,
                checks: [
                    ...this._def.checks,
                    {
                        kind,
                        value,
                        inclusive,
                        message: errorUtil$1.toString(message),
                    },
                ],
            });
        }
        _addCheck(check) {
            return new ZodNumber({
                ...this._def,
                checks: [...this._def.checks, check],
            });
        }
        int(message) {
            return this._addCheck({
                kind: "int",
                message: errorUtil$1.toString(message),
            });
        }
        positive(message) {
            return this._addCheck({
                kind: "min",
                value: 0,
                inclusive: false,
                message: errorUtil$1.toString(message),
            });
        }
        negative(message) {
            return this._addCheck({
                kind: "max",
                value: 0,
                inclusive: false,
                message: errorUtil$1.toString(message),
            });
        }
        nonpositive(message) {
            return this._addCheck({
                kind: "max",
                value: 0,
                inclusive: true,
                message: errorUtil$1.toString(message),
            });
        }
        nonnegative(message) {
            return this._addCheck({
                kind: "min",
                value: 0,
                inclusive: true,
                message: errorUtil$1.toString(message),
            });
        }
        multipleOf(value, message) {
            return this._addCheck({
                kind: "multipleOf",
                value: value,
                message: errorUtil$1.toString(message),
            });
        }
        finite(message) {
            return this._addCheck({
                kind: "finite",
                message: errorUtil$1.toString(message),
            });
        }
        safe(message) {
            return this._addCheck({
                kind: "min",
                inclusive: true,
                value: Number.MIN_SAFE_INTEGER,
                message: errorUtil$1.toString(message),
            })._addCheck({
                kind: "max",
                inclusive: true,
                value: Number.MAX_SAFE_INTEGER,
                message: errorUtil$1.toString(message),
            });
        }
        get minValue() {
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
            }
            return min;
        }
        get maxValue() {
            let max = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return max;
        }
        get isInt() {
            return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util$1.isInteger(ch.value)));
        }
        get isFinite() {
            let max = null;
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
                    return true;
                }
                else if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
                else if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return Number.isFinite(min) && Number.isFinite(max);
        }
    };
    ZodNumber$1.create = (params) => {
        return new ZodNumber$1({
            checks: [],
            typeName: ZodFirstPartyTypeKind$1.ZodNumber,
            coerce: params?.coerce || false,
            ...processCreateParams$1(params),
        });
    };
    let ZodBigInt$1 = class ZodBigInt extends ZodType$1 {
        constructor() {
            super(...arguments);
            this.min = this.gte;
            this.max = this.lte;
        }
        _parse(input) {
            if (this._def.coerce) {
                try {
                    input.data = BigInt(input.data);
                }
                catch {
                    return this._getInvalidInput(input);
                }
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.bigint) {
                return this._getInvalidInput(input);
            }
            let ctx = undefined;
            const status = new ParseStatus$1();
            for (const check of this._def.checks) {
                if (check.kind === "min") {
                    const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
                    if (tooSmall) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.too_small,
                            type: "bigint",
                            minimum: check.value,
                            inclusive: check.inclusive,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "max") {
                    const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
                    if (tooBig) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.too_big,
                            type: "bigint",
                            maximum: check.value,
                            inclusive: check.inclusive,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "multipleOf") {
                    if (input.data % check.value !== BigInt(0)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.not_multiple_of,
                            multipleOf: check.value,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else {
                    util$1.assertNever(check);
                }
            }
            return { status: status.value, value: input.data };
        }
        _getInvalidInput(input) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext$1(ctx, {
                code: ZodIssueCode$1.invalid_type,
                expected: ZodParsedType$1.bigint,
                received: ctx.parsedType,
            });
            return INVALID$1;
        }
        gte(value, message) {
            return this.setLimit("min", value, true, errorUtil$1.toString(message));
        }
        gt(value, message) {
            return this.setLimit("min", value, false, errorUtil$1.toString(message));
        }
        lte(value, message) {
            return this.setLimit("max", value, true, errorUtil$1.toString(message));
        }
        lt(value, message) {
            return this.setLimit("max", value, false, errorUtil$1.toString(message));
        }
        setLimit(kind, value, inclusive, message) {
            return new ZodBigInt({
                ...this._def,
                checks: [
                    ...this._def.checks,
                    {
                        kind,
                        value,
                        inclusive,
                        message: errorUtil$1.toString(message),
                    },
                ],
            });
        }
        _addCheck(check) {
            return new ZodBigInt({
                ...this._def,
                checks: [...this._def.checks, check],
            });
        }
        positive(message) {
            return this._addCheck({
                kind: "min",
                value: BigInt(0),
                inclusive: false,
                message: errorUtil$1.toString(message),
            });
        }
        negative(message) {
            return this._addCheck({
                kind: "max",
                value: BigInt(0),
                inclusive: false,
                message: errorUtil$1.toString(message),
            });
        }
        nonpositive(message) {
            return this._addCheck({
                kind: "max",
                value: BigInt(0),
                inclusive: true,
                message: errorUtil$1.toString(message),
            });
        }
        nonnegative(message) {
            return this._addCheck({
                kind: "min",
                value: BigInt(0),
                inclusive: true,
                message: errorUtil$1.toString(message),
            });
        }
        multipleOf(value, message) {
            return this._addCheck({
                kind: "multipleOf",
                value,
                message: errorUtil$1.toString(message),
            });
        }
        get minValue() {
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
            }
            return min;
        }
        get maxValue() {
            let max = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return max;
        }
    };
    ZodBigInt$1.create = (params) => {
        return new ZodBigInt$1({
            checks: [],
            typeName: ZodFirstPartyTypeKind$1.ZodBigInt,
            coerce: params?.coerce ?? false,
            ...processCreateParams$1(params),
        });
    };
    let ZodBoolean$1 = class ZodBoolean extends ZodType$1 {
        _parse(input) {
            if (this._def.coerce) {
                input.data = Boolean(input.data);
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.boolean) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.boolean,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            return OK$1(input.data);
        }
    };
    ZodBoolean$1.create = (params) => {
        return new ZodBoolean$1({
            typeName: ZodFirstPartyTypeKind$1.ZodBoolean,
            coerce: params?.coerce || false,
            ...processCreateParams$1(params),
        });
    };
    let ZodDate$1 = class ZodDate extends ZodType$1 {
        _parse(input) {
            if (this._def.coerce) {
                input.data = new Date(input.data);
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.date) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.date,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            if (Number.isNaN(input.data.getTime())) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_date,
                });
                return INVALID$1;
            }
            const status = new ParseStatus$1();
            let ctx = undefined;
            for (const check of this._def.checks) {
                if (check.kind === "min") {
                    if (input.data.getTime() < check.value) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.too_small,
                            message: check.message,
                            inclusive: true,
                            exact: false,
                            minimum: check.value,
                            type: "date",
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "max") {
                    if (input.data.getTime() > check.value) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.too_big,
                            message: check.message,
                            inclusive: true,
                            exact: false,
                            maximum: check.value,
                            type: "date",
                        });
                        status.dirty();
                    }
                }
                else {
                    util$1.assertNever(check);
                }
            }
            return {
                status: status.value,
                value: new Date(input.data.getTime()),
            };
        }
        _addCheck(check) {
            return new ZodDate({
                ...this._def,
                checks: [...this._def.checks, check],
            });
        }
        min(minDate, message) {
            return this._addCheck({
                kind: "min",
                value: minDate.getTime(),
                message: errorUtil$1.toString(message),
            });
        }
        max(maxDate, message) {
            return this._addCheck({
                kind: "max",
                value: maxDate.getTime(),
                message: errorUtil$1.toString(message),
            });
        }
        get minDate() {
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
            }
            return min != null ? new Date(min) : null;
        }
        get maxDate() {
            let max = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return max != null ? new Date(max) : null;
        }
    };
    ZodDate$1.create = (params) => {
        return new ZodDate$1({
            checks: [],
            coerce: params?.coerce || false,
            typeName: ZodFirstPartyTypeKind$1.ZodDate,
            ...processCreateParams$1(params),
        });
    };
    let ZodSymbol$1 = class ZodSymbol extends ZodType$1 {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.symbol) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.symbol,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            return OK$1(input.data);
        }
    };
    ZodSymbol$1.create = (params) => {
        return new ZodSymbol$1({
            typeName: ZodFirstPartyTypeKind$1.ZodSymbol,
            ...processCreateParams$1(params),
        });
    };
    let ZodUndefined$1 = class ZodUndefined extends ZodType$1 {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.undefined) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.undefined,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            return OK$1(input.data);
        }
    };
    ZodUndefined$1.create = (params) => {
        return new ZodUndefined$1({
            typeName: ZodFirstPartyTypeKind$1.ZodUndefined,
            ...processCreateParams$1(params),
        });
    };
    let ZodNull$1 = class ZodNull extends ZodType$1 {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.null) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.null,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            return OK$1(input.data);
        }
    };
    ZodNull$1.create = (params) => {
        return new ZodNull$1({
            typeName: ZodFirstPartyTypeKind$1.ZodNull,
            ...processCreateParams$1(params),
        });
    };
    let ZodAny$1 = class ZodAny extends ZodType$1 {
        constructor() {
            super(...arguments);
            // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
            this._any = true;
        }
        _parse(input) {
            return OK$1(input.data);
        }
    };
    ZodAny$1.create = (params) => {
        return new ZodAny$1({
            typeName: ZodFirstPartyTypeKind$1.ZodAny,
            ...processCreateParams$1(params),
        });
    };
    let ZodUnknown$1 = class ZodUnknown extends ZodType$1 {
        constructor() {
            super(...arguments);
            // required
            this._unknown = true;
        }
        _parse(input) {
            return OK$1(input.data);
        }
    };
    ZodUnknown$1.create = (params) => {
        return new ZodUnknown$1({
            typeName: ZodFirstPartyTypeKind$1.ZodUnknown,
            ...processCreateParams$1(params),
        });
    };
    let ZodNever$1 = class ZodNever extends ZodType$1 {
        _parse(input) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext$1(ctx, {
                code: ZodIssueCode$1.invalid_type,
                expected: ZodParsedType$1.never,
                received: ctx.parsedType,
            });
            return INVALID$1;
        }
    };
    ZodNever$1.create = (params) => {
        return new ZodNever$1({
            typeName: ZodFirstPartyTypeKind$1.ZodNever,
            ...processCreateParams$1(params),
        });
    };
    let ZodVoid$1 = class ZodVoid extends ZodType$1 {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.undefined) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.void,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            return OK$1(input.data);
        }
    };
    ZodVoid$1.create = (params) => {
        return new ZodVoid$1({
            typeName: ZodFirstPartyTypeKind$1.ZodVoid,
            ...processCreateParams$1(params),
        });
    };
    let ZodArray$1 = class ZodArray extends ZodType$1 {
        _parse(input) {
            const { ctx, status } = this._processInputParams(input);
            const def = this._def;
            if (ctx.parsedType !== ZodParsedType$1.array) {
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.array,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            if (def.exactLength !== null) {
                const tooBig = ctx.data.length > def.exactLength.value;
                const tooSmall = ctx.data.length < def.exactLength.value;
                if (tooBig || tooSmall) {
                    addIssueToContext$1(ctx, {
                        code: tooBig ? ZodIssueCode$1.too_big : ZodIssueCode$1.too_small,
                        minimum: (tooSmall ? def.exactLength.value : undefined),
                        maximum: (tooBig ? def.exactLength.value : undefined),
                        type: "array",
                        inclusive: true,
                        exact: true,
                        message: def.exactLength.message,
                    });
                    status.dirty();
                }
            }
            if (def.minLength !== null) {
                if (ctx.data.length < def.minLength.value) {
                    addIssueToContext$1(ctx, {
                        code: ZodIssueCode$1.too_small,
                        minimum: def.minLength.value,
                        type: "array",
                        inclusive: true,
                        exact: false,
                        message: def.minLength.message,
                    });
                    status.dirty();
                }
            }
            if (def.maxLength !== null) {
                if (ctx.data.length > def.maxLength.value) {
                    addIssueToContext$1(ctx, {
                        code: ZodIssueCode$1.too_big,
                        maximum: def.maxLength.value,
                        type: "array",
                        inclusive: true,
                        exact: false,
                        message: def.maxLength.message,
                    });
                    status.dirty();
                }
            }
            if (ctx.common.async) {
                return Promise.all([...ctx.data].map((item, i) => {
                    return def.type._parseAsync(new ParseInputLazyPath$1(ctx, item, ctx.path, i));
                })).then((result) => {
                    return ParseStatus$1.mergeArray(status, result);
                });
            }
            const result = [...ctx.data].map((item, i) => {
                return def.type._parseSync(new ParseInputLazyPath$1(ctx, item, ctx.path, i));
            });
            return ParseStatus$1.mergeArray(status, result);
        }
        get element() {
            return this._def.type;
        }
        min(minLength, message) {
            return new ZodArray({
                ...this._def,
                minLength: { value: minLength, message: errorUtil$1.toString(message) },
            });
        }
        max(maxLength, message) {
            return new ZodArray({
                ...this._def,
                maxLength: { value: maxLength, message: errorUtil$1.toString(message) },
            });
        }
        length(len, message) {
            return new ZodArray({
                ...this._def,
                exactLength: { value: len, message: errorUtil$1.toString(message) },
            });
        }
        nonempty(message) {
            return this.min(1, message);
        }
    };
    ZodArray$1.create = (schema, params) => {
        return new ZodArray$1({
            type: schema,
            minLength: null,
            maxLength: null,
            exactLength: null,
            typeName: ZodFirstPartyTypeKind$1.ZodArray,
            ...processCreateParams$1(params),
        });
    };
    function deepPartialify$1(schema) {
        if (schema instanceof ZodObject$1) {
            const newShape = {};
            for (const key in schema.shape) {
                const fieldSchema = schema.shape[key];
                newShape[key] = ZodOptional$1.create(deepPartialify$1(fieldSchema));
            }
            return new ZodObject$1({
                ...schema._def,
                shape: () => newShape,
            });
        }
        else if (schema instanceof ZodArray$1) {
            return new ZodArray$1({
                ...schema._def,
                type: deepPartialify$1(schema.element),
            });
        }
        else if (schema instanceof ZodOptional$1) {
            return ZodOptional$1.create(deepPartialify$1(schema.unwrap()));
        }
        else if (schema instanceof ZodNullable$1) {
            return ZodNullable$1.create(deepPartialify$1(schema.unwrap()));
        }
        else if (schema instanceof ZodTuple$1) {
            return ZodTuple$1.create(schema.items.map((item) => deepPartialify$1(item)));
        }
        else {
            return schema;
        }
    }
    let ZodObject$1 = class ZodObject extends ZodType$1 {
        constructor() {
            super(...arguments);
            this._cached = null;
            /**
             * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
             * If you want to pass through unknown properties, use `.passthrough()` instead.
             */
            this.nonstrict = this.passthrough;
            // extend<
            //   Augmentation extends ZodRawShape,
            //   NewOutput extends util.flatten<{
            //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
            //       ? Augmentation[k]["_output"]
            //       : k extends keyof Output
            //       ? Output[k]
            //       : never;
            //   }>,
            //   NewInput extends util.flatten<{
            //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
            //       ? Augmentation[k]["_input"]
            //       : k extends keyof Input
            //       ? Input[k]
            //       : never;
            //   }>
            // >(
            //   augmentation: Augmentation
            // ): ZodObject<
            //   extendShape<T, Augmentation>,
            //   UnknownKeys,
            //   Catchall,
            //   NewOutput,
            //   NewInput
            // > {
            //   return new ZodObject({
            //     ...this._def,
            //     shape: () => ({
            //       ...this._def.shape(),
            //       ...augmentation,
            //     }),
            //   }) as any;
            // }
            /**
             * @deprecated Use `.extend` instead
             *  */
            this.augment = this.extend;
        }
        _getCached() {
            if (this._cached !== null)
                return this._cached;
            const shape = this._def.shape();
            const keys = util$1.objectKeys(shape);
            this._cached = { shape, keys };
            return this._cached;
        }
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.object) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.object,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            const { status, ctx } = this._processInputParams(input);
            const { shape, keys: shapeKeys } = this._getCached();
            const extraKeys = [];
            if (!(this._def.catchall instanceof ZodNever$1 && this._def.unknownKeys === "strip")) {
                for (const key in ctx.data) {
                    if (!shapeKeys.includes(key)) {
                        extraKeys.push(key);
                    }
                }
            }
            const pairs = [];
            for (const key of shapeKeys) {
                const keyValidator = shape[key];
                const value = ctx.data[key];
                pairs.push({
                    key: { status: "valid", value: key },
                    value: keyValidator._parse(new ParseInputLazyPath$1(ctx, value, ctx.path, key)),
                    alwaysSet: key in ctx.data,
                });
            }
            if (this._def.catchall instanceof ZodNever$1) {
                const unknownKeys = this._def.unknownKeys;
                if (unknownKeys === "passthrough") {
                    for (const key of extraKeys) {
                        pairs.push({
                            key: { status: "valid", value: key },
                            value: { status: "valid", value: ctx.data[key] },
                        });
                    }
                }
                else if (unknownKeys === "strict") {
                    if (extraKeys.length > 0) {
                        addIssueToContext$1(ctx, {
                            code: ZodIssueCode$1.unrecognized_keys,
                            keys: extraKeys,
                        });
                        status.dirty();
                    }
                }
                else if (unknownKeys === "strip") ;
                else {
                    throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
                }
            }
            else {
                // run catchall validation
                const catchall = this._def.catchall;
                for (const key of extraKeys) {
                    const value = ctx.data[key];
                    pairs.push({
                        key: { status: "valid", value: key },
                        value: catchall._parse(new ParseInputLazyPath$1(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
                        ),
                        alwaysSet: key in ctx.data,
                    });
                }
            }
            if (ctx.common.async) {
                return Promise.resolve()
                    .then(async () => {
                    const syncPairs = [];
                    for (const pair of pairs) {
                        const key = await pair.key;
                        const value = await pair.value;
                        syncPairs.push({
                            key,
                            value,
                            alwaysSet: pair.alwaysSet,
                        });
                    }
                    return syncPairs;
                })
                    .then((syncPairs) => {
                    return ParseStatus$1.mergeObjectSync(status, syncPairs);
                });
            }
            else {
                return ParseStatus$1.mergeObjectSync(status, pairs);
            }
        }
        get shape() {
            return this._def.shape();
        }
        strict(message) {
            errorUtil$1.errToObj;
            return new ZodObject({
                ...this._def,
                unknownKeys: "strict",
                ...(message !== undefined
                    ? {
                        errorMap: (issue, ctx) => {
                            const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
                            if (issue.code === "unrecognized_keys")
                                return {
                                    message: errorUtil$1.errToObj(message).message ?? defaultError,
                                };
                            return {
                                message: defaultError,
                            };
                        },
                    }
                    : {}),
            });
        }
        strip() {
            return new ZodObject({
                ...this._def,
                unknownKeys: "strip",
            });
        }
        passthrough() {
            return new ZodObject({
                ...this._def,
                unknownKeys: "passthrough",
            });
        }
        // const AugmentFactory =
        //   <Def extends ZodObjectDef>(def: Def) =>
        //   <Augmentation extends ZodRawShape>(
        //     augmentation: Augmentation
        //   ): ZodObject<
        //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
        //     Def["unknownKeys"],
        //     Def["catchall"]
        //   > => {
        //     return new ZodObject({
        //       ...def,
        //       shape: () => ({
        //         ...def.shape(),
        //         ...augmentation,
        //       }),
        //     }) as any;
        //   };
        extend(augmentation) {
            return new ZodObject({
                ...this._def,
                shape: () => ({
                    ...this._def.shape(),
                    ...augmentation,
                }),
            });
        }
        /**
         * Prior to zod@1.0.12 there was a bug in the
         * inferred type of merged objects. Please
         * upgrade if you are experiencing issues.
         */
        merge(merging) {
            const merged = new ZodObject({
                unknownKeys: merging._def.unknownKeys,
                catchall: merging._def.catchall,
                shape: () => ({
                    ...this._def.shape(),
                    ...merging._def.shape(),
                }),
                typeName: ZodFirstPartyTypeKind$1.ZodObject,
            });
            return merged;
        }
        // merge<
        //   Incoming extends AnyZodObject,
        //   Augmentation extends Incoming["shape"],
        //   NewOutput extends {
        //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
        //       ? Augmentation[k]["_output"]
        //       : k extends keyof Output
        //       ? Output[k]
        //       : never;
        //   },
        //   NewInput extends {
        //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
        //       ? Augmentation[k]["_input"]
        //       : k extends keyof Input
        //       ? Input[k]
        //       : never;
        //   }
        // >(
        //   merging: Incoming
        // ): ZodObject<
        //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
        //   Incoming["_def"]["unknownKeys"],
        //   Incoming["_def"]["catchall"],
        //   NewOutput,
        //   NewInput
        // > {
        //   const merged: any = new ZodObject({
        //     unknownKeys: merging._def.unknownKeys,
        //     catchall: merging._def.catchall,
        //     shape: () =>
        //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
        //     typeName: ZodFirstPartyTypeKind.ZodObject,
        //   }) as any;
        //   return merged;
        // }
        setKey(key, schema) {
            return this.augment({ [key]: schema });
        }
        // merge<Incoming extends AnyZodObject>(
        //   merging: Incoming
        // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
        // ZodObject<
        //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
        //   Incoming["_def"]["unknownKeys"],
        //   Incoming["_def"]["catchall"]
        // > {
        //   // const mergedShape = objectUtil.mergeShapes(
        //   //   this._def.shape(),
        //   //   merging._def.shape()
        //   // );
        //   const merged: any = new ZodObject({
        //     unknownKeys: merging._def.unknownKeys,
        //     catchall: merging._def.catchall,
        //     shape: () =>
        //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
        //     typeName: ZodFirstPartyTypeKind.ZodObject,
        //   }) as any;
        //   return merged;
        // }
        catchall(index) {
            return new ZodObject({
                ...this._def,
                catchall: index,
            });
        }
        pick(mask) {
            const shape = {};
            for (const key of util$1.objectKeys(mask)) {
                if (mask[key] && this.shape[key]) {
                    shape[key] = this.shape[key];
                }
            }
            return new ZodObject({
                ...this._def,
                shape: () => shape,
            });
        }
        omit(mask) {
            const shape = {};
            for (const key of util$1.objectKeys(this.shape)) {
                if (!mask[key]) {
                    shape[key] = this.shape[key];
                }
            }
            return new ZodObject({
                ...this._def,
                shape: () => shape,
            });
        }
        /**
         * @deprecated
         */
        deepPartial() {
            return deepPartialify$1(this);
        }
        partial(mask) {
            const newShape = {};
            for (const key of util$1.objectKeys(this.shape)) {
                const fieldSchema = this.shape[key];
                if (mask && !mask[key]) {
                    newShape[key] = fieldSchema;
                }
                else {
                    newShape[key] = fieldSchema.optional();
                }
            }
            return new ZodObject({
                ...this._def,
                shape: () => newShape,
            });
        }
        required(mask) {
            const newShape = {};
            for (const key of util$1.objectKeys(this.shape)) {
                if (mask && !mask[key]) {
                    newShape[key] = this.shape[key];
                }
                else {
                    const fieldSchema = this.shape[key];
                    let newField = fieldSchema;
                    while (newField instanceof ZodOptional$1) {
                        newField = newField._def.innerType;
                    }
                    newShape[key] = newField;
                }
            }
            return new ZodObject({
                ...this._def,
                shape: () => newShape,
            });
        }
        keyof() {
            return createZodEnum$1(util$1.objectKeys(this.shape));
        }
    };
    ZodObject$1.create = (shape, params) => {
        return new ZodObject$1({
            shape: () => shape,
            unknownKeys: "strip",
            catchall: ZodNever$1.create(),
            typeName: ZodFirstPartyTypeKind$1.ZodObject,
            ...processCreateParams$1(params),
        });
    };
    ZodObject$1.strictCreate = (shape, params) => {
        return new ZodObject$1({
            shape: () => shape,
            unknownKeys: "strict",
            catchall: ZodNever$1.create(),
            typeName: ZodFirstPartyTypeKind$1.ZodObject,
            ...processCreateParams$1(params),
        });
    };
    ZodObject$1.lazycreate = (shape, params) => {
        return new ZodObject$1({
            shape,
            unknownKeys: "strip",
            catchall: ZodNever$1.create(),
            typeName: ZodFirstPartyTypeKind$1.ZodObject,
            ...processCreateParams$1(params),
        });
    };
    let ZodUnion$1 = class ZodUnion extends ZodType$1 {
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            const options = this._def.options;
            function handleResults(results) {
                // return first issue-free validation if it exists
                for (const result of results) {
                    if (result.result.status === "valid") {
                        return result.result;
                    }
                }
                for (const result of results) {
                    if (result.result.status === "dirty") {
                        // add issues from dirty option
                        ctx.common.issues.push(...result.ctx.common.issues);
                        return result.result;
                    }
                }
                // return invalid
                const unionErrors = results.map((result) => new ZodError$1(result.ctx.common.issues));
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_union,
                    unionErrors,
                });
                return INVALID$1;
            }
            if (ctx.common.async) {
                return Promise.all(options.map(async (option) => {
                    const childCtx = {
                        ...ctx,
                        common: {
                            ...ctx.common,
                            issues: [],
                        },
                        parent: null,
                    };
                    return {
                        result: await option._parseAsync({
                            data: ctx.data,
                            path: ctx.path,
                            parent: childCtx,
                        }),
                        ctx: childCtx,
                    };
                })).then(handleResults);
            }
            else {
                let dirty = undefined;
                const issues = [];
                for (const option of options) {
                    const childCtx = {
                        ...ctx,
                        common: {
                            ...ctx.common,
                            issues: [],
                        },
                        parent: null,
                    };
                    const result = option._parseSync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: childCtx,
                    });
                    if (result.status === "valid") {
                        return result;
                    }
                    else if (result.status === "dirty" && !dirty) {
                        dirty = { result, ctx: childCtx };
                    }
                    if (childCtx.common.issues.length) {
                        issues.push(childCtx.common.issues);
                    }
                }
                if (dirty) {
                    ctx.common.issues.push(...dirty.ctx.common.issues);
                    return dirty.result;
                }
                const unionErrors = issues.map((issues) => new ZodError$1(issues));
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_union,
                    unionErrors,
                });
                return INVALID$1;
            }
        }
        get options() {
            return this._def.options;
        }
    };
    ZodUnion$1.create = (types, params) => {
        return new ZodUnion$1({
            options: types,
            typeName: ZodFirstPartyTypeKind$1.ZodUnion,
            ...processCreateParams$1(params),
        });
    };
    function mergeValues$1(a, b) {
        const aType = getParsedType$1(a);
        const bType = getParsedType$1(b);
        if (a === b) {
            return { valid: true, data: a };
        }
        else if (aType === ZodParsedType$1.object && bType === ZodParsedType$1.object) {
            const bKeys = util$1.objectKeys(b);
            const sharedKeys = util$1.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
            const newObj = { ...a, ...b };
            for (const key of sharedKeys) {
                const sharedValue = mergeValues$1(a[key], b[key]);
                if (!sharedValue.valid) {
                    return { valid: false };
                }
                newObj[key] = sharedValue.data;
            }
            return { valid: true, data: newObj };
        }
        else if (aType === ZodParsedType$1.array && bType === ZodParsedType$1.array) {
            if (a.length !== b.length) {
                return { valid: false };
            }
            const newArray = [];
            for (let index = 0; index < a.length; index++) {
                const itemA = a[index];
                const itemB = b[index];
                const sharedValue = mergeValues$1(itemA, itemB);
                if (!sharedValue.valid) {
                    return { valid: false };
                }
                newArray.push(sharedValue.data);
            }
            return { valid: true, data: newArray };
        }
        else if (aType === ZodParsedType$1.date && bType === ZodParsedType$1.date && +a === +b) {
            return { valid: true, data: a };
        }
        else {
            return { valid: false };
        }
    }
    let ZodIntersection$1 = class ZodIntersection extends ZodType$1 {
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            const handleParsed = (parsedLeft, parsedRight) => {
                if (isAborted$1(parsedLeft) || isAborted$1(parsedRight)) {
                    return INVALID$1;
                }
                const merged = mergeValues$1(parsedLeft.value, parsedRight.value);
                if (!merged.valid) {
                    addIssueToContext$1(ctx, {
                        code: ZodIssueCode$1.invalid_intersection_types,
                    });
                    return INVALID$1;
                }
                if (isDirty$1(parsedLeft) || isDirty$1(parsedRight)) {
                    status.dirty();
                }
                return { status: status.value, value: merged.data };
            };
            if (ctx.common.async) {
                return Promise.all([
                    this._def.left._parseAsync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    }),
                    this._def.right._parseAsync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    }),
                ]).then(([left, right]) => handleParsed(left, right));
            }
            else {
                return handleParsed(this._def.left._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }), this._def.right._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }));
            }
        }
    };
    ZodIntersection$1.create = (left, right, params) => {
        return new ZodIntersection$1({
            left: left,
            right: right,
            typeName: ZodFirstPartyTypeKind$1.ZodIntersection,
            ...processCreateParams$1(params),
        });
    };
    // type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];
    let ZodTuple$1 = class ZodTuple extends ZodType$1 {
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            if (ctx.parsedType !== ZodParsedType$1.array) {
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.array,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            if (ctx.data.length < this._def.items.length) {
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.too_small,
                    minimum: this._def.items.length,
                    inclusive: true,
                    exact: false,
                    type: "array",
                });
                return INVALID$1;
            }
            const rest = this._def.rest;
            if (!rest && ctx.data.length > this._def.items.length) {
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.too_big,
                    maximum: this._def.items.length,
                    inclusive: true,
                    exact: false,
                    type: "array",
                });
                status.dirty();
            }
            const items = [...ctx.data]
                .map((item, itemIndex) => {
                const schema = this._def.items[itemIndex] || this._def.rest;
                if (!schema)
                    return null;
                return schema._parse(new ParseInputLazyPath$1(ctx, item, ctx.path, itemIndex));
            })
                .filter((x) => !!x); // filter nulls
            if (ctx.common.async) {
                return Promise.all(items).then((results) => {
                    return ParseStatus$1.mergeArray(status, results);
                });
            }
            else {
                return ParseStatus$1.mergeArray(status, items);
            }
        }
        get items() {
            return this._def.items;
        }
        rest(rest) {
            return new ZodTuple({
                ...this._def,
                rest,
            });
        }
    };
    ZodTuple$1.create = (schemas, params) => {
        if (!Array.isArray(schemas)) {
            throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
        }
        return new ZodTuple$1({
            items: schemas,
            typeName: ZodFirstPartyTypeKind$1.ZodTuple,
            rest: null,
            ...processCreateParams$1(params),
        });
    };
    class ZodRecord extends ZodType$1 {
        get keySchema() {
            return this._def.keyType;
        }
        get valueSchema() {
            return this._def.valueType;
        }
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            if (ctx.parsedType !== ZodParsedType$1.object) {
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.object,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            const pairs = [];
            const keyType = this._def.keyType;
            const valueType = this._def.valueType;
            for (const key in ctx.data) {
                pairs.push({
                    key: keyType._parse(new ParseInputLazyPath$1(ctx, key, ctx.path, key)),
                    value: valueType._parse(new ParseInputLazyPath$1(ctx, ctx.data[key], ctx.path, key)),
                    alwaysSet: key in ctx.data,
                });
            }
            if (ctx.common.async) {
                return ParseStatus$1.mergeObjectAsync(status, pairs);
            }
            else {
                return ParseStatus$1.mergeObjectSync(status, pairs);
            }
        }
        get element() {
            return this._def.valueType;
        }
        static create(first, second, third) {
            if (second instanceof ZodType$1) {
                return new ZodRecord({
                    keyType: first,
                    valueType: second,
                    typeName: ZodFirstPartyTypeKind$1.ZodRecord,
                    ...processCreateParams$1(third),
                });
            }
            return new ZodRecord({
                keyType: ZodString$1.create(),
                valueType: first,
                typeName: ZodFirstPartyTypeKind$1.ZodRecord,
                ...processCreateParams$1(second),
            });
        }
    }
    let ZodMap$1 = class ZodMap extends ZodType$1 {
        get keySchema() {
            return this._def.keyType;
        }
        get valueSchema() {
            return this._def.valueType;
        }
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            if (ctx.parsedType !== ZodParsedType$1.map) {
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.map,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            const keyType = this._def.keyType;
            const valueType = this._def.valueType;
            const pairs = [...ctx.data.entries()].map(([key, value], index) => {
                return {
                    key: keyType._parse(new ParseInputLazyPath$1(ctx, key, ctx.path, [index, "key"])),
                    value: valueType._parse(new ParseInputLazyPath$1(ctx, value, ctx.path, [index, "value"])),
                };
            });
            if (ctx.common.async) {
                const finalMap = new Map();
                return Promise.resolve().then(async () => {
                    for (const pair of pairs) {
                        const key = await pair.key;
                        const value = await pair.value;
                        if (key.status === "aborted" || value.status === "aborted") {
                            return INVALID$1;
                        }
                        if (key.status === "dirty" || value.status === "dirty") {
                            status.dirty();
                        }
                        finalMap.set(key.value, value.value);
                    }
                    return { status: status.value, value: finalMap };
                });
            }
            else {
                const finalMap = new Map();
                for (const pair of pairs) {
                    const key = pair.key;
                    const value = pair.value;
                    if (key.status === "aborted" || value.status === "aborted") {
                        return INVALID$1;
                    }
                    if (key.status === "dirty" || value.status === "dirty") {
                        status.dirty();
                    }
                    finalMap.set(key.value, value.value);
                }
                return { status: status.value, value: finalMap };
            }
        }
    };
    ZodMap$1.create = (keyType, valueType, params) => {
        return new ZodMap$1({
            valueType,
            keyType,
            typeName: ZodFirstPartyTypeKind$1.ZodMap,
            ...processCreateParams$1(params),
        });
    };
    let ZodSet$1 = class ZodSet extends ZodType$1 {
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            if (ctx.parsedType !== ZodParsedType$1.set) {
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.set,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            const def = this._def;
            if (def.minSize !== null) {
                if (ctx.data.size < def.minSize.value) {
                    addIssueToContext$1(ctx, {
                        code: ZodIssueCode$1.too_small,
                        minimum: def.minSize.value,
                        type: "set",
                        inclusive: true,
                        exact: false,
                        message: def.minSize.message,
                    });
                    status.dirty();
                }
            }
            if (def.maxSize !== null) {
                if (ctx.data.size > def.maxSize.value) {
                    addIssueToContext$1(ctx, {
                        code: ZodIssueCode$1.too_big,
                        maximum: def.maxSize.value,
                        type: "set",
                        inclusive: true,
                        exact: false,
                        message: def.maxSize.message,
                    });
                    status.dirty();
                }
            }
            const valueType = this._def.valueType;
            function finalizeSet(elements) {
                const parsedSet = new Set();
                for (const element of elements) {
                    if (element.status === "aborted")
                        return INVALID$1;
                    if (element.status === "dirty")
                        status.dirty();
                    parsedSet.add(element.value);
                }
                return { status: status.value, value: parsedSet };
            }
            const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath$1(ctx, item, ctx.path, i)));
            if (ctx.common.async) {
                return Promise.all(elements).then((elements) => finalizeSet(elements));
            }
            else {
                return finalizeSet(elements);
            }
        }
        min(minSize, message) {
            return new ZodSet({
                ...this._def,
                minSize: { value: minSize, message: errorUtil$1.toString(message) },
            });
        }
        max(maxSize, message) {
            return new ZodSet({
                ...this._def,
                maxSize: { value: maxSize, message: errorUtil$1.toString(message) },
            });
        }
        size(size, message) {
            return this.min(size, message).max(size, message);
        }
        nonempty(message) {
            return this.min(1, message);
        }
    };
    ZodSet$1.create = (valueType, params) => {
        return new ZodSet$1({
            valueType,
            minSize: null,
            maxSize: null,
            typeName: ZodFirstPartyTypeKind$1.ZodSet,
            ...processCreateParams$1(params),
        });
    };
    let ZodLazy$1 = class ZodLazy extends ZodType$1 {
        get schema() {
            return this._def.getter();
        }
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            const lazySchema = this._def.getter();
            return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
        }
    };
    ZodLazy$1.create = (getter, params) => {
        return new ZodLazy$1({
            getter: getter,
            typeName: ZodFirstPartyTypeKind$1.ZodLazy,
            ...processCreateParams$1(params),
        });
    };
    let ZodLiteral$1 = class ZodLiteral extends ZodType$1 {
        _parse(input) {
            if (input.data !== this._def.value) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    received: ctx.data,
                    code: ZodIssueCode$1.invalid_literal,
                    expected: this._def.value,
                });
                return INVALID$1;
            }
            return { status: "valid", value: input.data };
        }
        get value() {
            return this._def.value;
        }
    };
    ZodLiteral$1.create = (value, params) => {
        return new ZodLiteral$1({
            value: value,
            typeName: ZodFirstPartyTypeKind$1.ZodLiteral,
            ...processCreateParams$1(params),
        });
    };
    function createZodEnum$1(values, params) {
        return new ZodEnum$1({
            values,
            typeName: ZodFirstPartyTypeKind$1.ZodEnum,
            ...processCreateParams$1(params),
        });
    }
    let ZodEnum$1 = class ZodEnum extends ZodType$1 {
        _parse(input) {
            if (typeof input.data !== "string") {
                const ctx = this._getOrReturnCtx(input);
                const expectedValues = this._def.values;
                addIssueToContext$1(ctx, {
                    expected: util$1.joinValues(expectedValues),
                    received: ctx.parsedType,
                    code: ZodIssueCode$1.invalid_type,
                });
                return INVALID$1;
            }
            if (!this._cache) {
                this._cache = new Set(this._def.values);
            }
            if (!this._cache.has(input.data)) {
                const ctx = this._getOrReturnCtx(input);
                const expectedValues = this._def.values;
                addIssueToContext$1(ctx, {
                    received: ctx.data,
                    code: ZodIssueCode$1.invalid_enum_value,
                    options: expectedValues,
                });
                return INVALID$1;
            }
            return OK$1(input.data);
        }
        get options() {
            return this._def.values;
        }
        get enum() {
            const enumValues = {};
            for (const val of this._def.values) {
                enumValues[val] = val;
            }
            return enumValues;
        }
        get Values() {
            const enumValues = {};
            for (const val of this._def.values) {
                enumValues[val] = val;
            }
            return enumValues;
        }
        get Enum() {
            const enumValues = {};
            for (const val of this._def.values) {
                enumValues[val] = val;
            }
            return enumValues;
        }
        extract(values, newDef = this._def) {
            return ZodEnum.create(values, {
                ...this._def,
                ...newDef,
            });
        }
        exclude(values, newDef = this._def) {
            return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
                ...this._def,
                ...newDef,
            });
        }
    };
    ZodEnum$1.create = createZodEnum$1;
    let ZodNativeEnum$1 = class ZodNativeEnum extends ZodType$1 {
        _parse(input) {
            const nativeEnumValues = util$1.getValidEnumValues(this._def.values);
            const ctx = this._getOrReturnCtx(input);
            if (ctx.parsedType !== ZodParsedType$1.string && ctx.parsedType !== ZodParsedType$1.number) {
                const expectedValues = util$1.objectValues(nativeEnumValues);
                addIssueToContext$1(ctx, {
                    expected: util$1.joinValues(expectedValues),
                    received: ctx.parsedType,
                    code: ZodIssueCode$1.invalid_type,
                });
                return INVALID$1;
            }
            if (!this._cache) {
                this._cache = new Set(util$1.getValidEnumValues(this._def.values));
            }
            if (!this._cache.has(input.data)) {
                const expectedValues = util$1.objectValues(nativeEnumValues);
                addIssueToContext$1(ctx, {
                    received: ctx.data,
                    code: ZodIssueCode$1.invalid_enum_value,
                    options: expectedValues,
                });
                return INVALID$1;
            }
            return OK$1(input.data);
        }
        get enum() {
            return this._def.values;
        }
    };
    ZodNativeEnum$1.create = (values, params) => {
        return new ZodNativeEnum$1({
            values: values,
            typeName: ZodFirstPartyTypeKind$1.ZodNativeEnum,
            ...processCreateParams$1(params),
        });
    };
    let ZodPromise$1 = class ZodPromise extends ZodType$1 {
        unwrap() {
            return this._def.type;
        }
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            if (ctx.parsedType !== ZodParsedType$1.promise && ctx.common.async === false) {
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.promise,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            const promisified = ctx.parsedType === ZodParsedType$1.promise ? ctx.data : Promise.resolve(ctx.data);
            return OK$1(promisified.then((data) => {
                return this._def.type.parseAsync(data, {
                    path: ctx.path,
                    errorMap: ctx.common.contextualErrorMap,
                });
            }));
        }
    };
    ZodPromise$1.create = (schema, params) => {
        return new ZodPromise$1({
            type: schema,
            typeName: ZodFirstPartyTypeKind$1.ZodPromise,
            ...processCreateParams$1(params),
        });
    };
    let ZodEffects$1 = class ZodEffects extends ZodType$1 {
        innerType() {
            return this._def.schema;
        }
        sourceType() {
            return this._def.schema._def.typeName === ZodFirstPartyTypeKind$1.ZodEffects
                ? this._def.schema.sourceType()
                : this._def.schema;
        }
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            const effect = this._def.effect || null;
            const checkCtx = {
                addIssue: (arg) => {
                    addIssueToContext$1(ctx, arg);
                    if (arg.fatal) {
                        status.abort();
                    }
                    else {
                        status.dirty();
                    }
                },
                get path() {
                    return ctx.path;
                },
            };
            checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
            if (effect.type === "preprocess") {
                const processed = effect.transform(ctx.data, checkCtx);
                if (ctx.common.async) {
                    return Promise.resolve(processed).then(async (processed) => {
                        if (status.value === "aborted")
                            return INVALID$1;
                        const result = await this._def.schema._parseAsync({
                            data: processed,
                            path: ctx.path,
                            parent: ctx,
                        });
                        if (result.status === "aborted")
                            return INVALID$1;
                        if (result.status === "dirty")
                            return DIRTY$1(result.value);
                        if (status.value === "dirty")
                            return DIRTY$1(result.value);
                        return result;
                    });
                }
                else {
                    if (status.value === "aborted")
                        return INVALID$1;
                    const result = this._def.schema._parseSync({
                        data: processed,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (result.status === "aborted")
                        return INVALID$1;
                    if (result.status === "dirty")
                        return DIRTY$1(result.value);
                    if (status.value === "dirty")
                        return DIRTY$1(result.value);
                    return result;
                }
            }
            if (effect.type === "refinement") {
                const executeRefinement = (acc) => {
                    const result = effect.refinement(acc, checkCtx);
                    if (ctx.common.async) {
                        return Promise.resolve(result);
                    }
                    if (result instanceof Promise) {
                        throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
                    }
                    return acc;
                };
                if (ctx.common.async === false) {
                    const inner = this._def.schema._parseSync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (inner.status === "aborted")
                        return INVALID$1;
                    if (inner.status === "dirty")
                        status.dirty();
                    // return value is ignored
                    executeRefinement(inner.value);
                    return { status: status.value, value: inner.value };
                }
                else {
                    return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
                        if (inner.status === "aborted")
                            return INVALID$1;
                        if (inner.status === "dirty")
                            status.dirty();
                        return executeRefinement(inner.value).then(() => {
                            return { status: status.value, value: inner.value };
                        });
                    });
                }
            }
            if (effect.type === "transform") {
                if (ctx.common.async === false) {
                    const base = this._def.schema._parseSync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (!isValid$1(base))
                        return INVALID$1;
                    const result = effect.transform(base.value, checkCtx);
                    if (result instanceof Promise) {
                        throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
                    }
                    return { status: status.value, value: result };
                }
                else {
                    return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
                        if (!isValid$1(base))
                            return INVALID$1;
                        return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
                            status: status.value,
                            value: result,
                        }));
                    });
                }
            }
            util$1.assertNever(effect);
        }
    };
    ZodEffects$1.create = (schema, effect, params) => {
        return new ZodEffects$1({
            schema,
            typeName: ZodFirstPartyTypeKind$1.ZodEffects,
            effect,
            ...processCreateParams$1(params),
        });
    };
    ZodEffects$1.createWithPreprocess = (preprocess, schema, params) => {
        return new ZodEffects$1({
            schema,
            effect: { type: "preprocess", transform: preprocess },
            typeName: ZodFirstPartyTypeKind$1.ZodEffects,
            ...processCreateParams$1(params),
        });
    };
    let ZodOptional$1 = class ZodOptional extends ZodType$1 {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType === ZodParsedType$1.undefined) {
                return OK$1(undefined);
            }
            return this._def.innerType._parse(input);
        }
        unwrap() {
            return this._def.innerType;
        }
    };
    ZodOptional$1.create = (type, params) => {
        return new ZodOptional$1({
            innerType: type,
            typeName: ZodFirstPartyTypeKind$1.ZodOptional,
            ...processCreateParams$1(params),
        });
    };
    let ZodNullable$1 = class ZodNullable extends ZodType$1 {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType === ZodParsedType$1.null) {
                return OK$1(null);
            }
            return this._def.innerType._parse(input);
        }
        unwrap() {
            return this._def.innerType;
        }
    };
    ZodNullable$1.create = (type, params) => {
        return new ZodNullable$1({
            innerType: type,
            typeName: ZodFirstPartyTypeKind$1.ZodNullable,
            ...processCreateParams$1(params),
        });
    };
    let ZodDefault$1 = class ZodDefault extends ZodType$1 {
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            let data = ctx.data;
            if (ctx.parsedType === ZodParsedType$1.undefined) {
                data = this._def.defaultValue();
            }
            return this._def.innerType._parse({
                data,
                path: ctx.path,
                parent: ctx,
            });
        }
        removeDefault() {
            return this._def.innerType;
        }
    };
    ZodDefault$1.create = (type, params) => {
        return new ZodDefault$1({
            innerType: type,
            typeName: ZodFirstPartyTypeKind$1.ZodDefault,
            defaultValue: typeof params.default === "function" ? params.default : () => params.default,
            ...processCreateParams$1(params),
        });
    };
    let ZodCatch$1 = class ZodCatch extends ZodType$1 {
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            // newCtx is used to not collect issues from inner types in ctx
            const newCtx = {
                ...ctx,
                common: {
                    ...ctx.common,
                    issues: [],
                },
            };
            const result = this._def.innerType._parse({
                data: newCtx.data,
                path: newCtx.path,
                parent: {
                    ...newCtx,
                },
            });
            if (isAsync$1(result)) {
                return result.then((result) => {
                    return {
                        status: "valid",
                        value: result.status === "valid"
                            ? result.value
                            : this._def.catchValue({
                                get error() {
                                    return new ZodError$1(newCtx.common.issues);
                                },
                                input: newCtx.data,
                            }),
                    };
                });
            }
            else {
                return {
                    status: "valid",
                    value: result.status === "valid"
                        ? result.value
                        : this._def.catchValue({
                            get error() {
                                return new ZodError$1(newCtx.common.issues);
                            },
                            input: newCtx.data,
                        }),
                };
            }
        }
        removeCatch() {
            return this._def.innerType;
        }
    };
    ZodCatch$1.create = (type, params) => {
        return new ZodCatch$1({
            innerType: type,
            typeName: ZodFirstPartyTypeKind$1.ZodCatch,
            catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
            ...processCreateParams$1(params),
        });
    };
    let ZodNaN$1 = class ZodNaN extends ZodType$1 {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType$1.nan) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext$1(ctx, {
                    code: ZodIssueCode$1.invalid_type,
                    expected: ZodParsedType$1.nan,
                    received: ctx.parsedType,
                });
                return INVALID$1;
            }
            return { status: "valid", value: input.data };
        }
    };
    ZodNaN$1.create = (params) => {
        return new ZodNaN$1({
            typeName: ZodFirstPartyTypeKind$1.ZodNaN,
            ...processCreateParams$1(params),
        });
    };
    let ZodBranded$1 = class ZodBranded extends ZodType$1 {
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            const data = ctx.data;
            return this._def.type._parse({
                data,
                path: ctx.path,
                parent: ctx,
            });
        }
        unwrap() {
            return this._def.type;
        }
    };
    let ZodPipeline$1 = class ZodPipeline extends ZodType$1 {
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            if (ctx.common.async) {
                const handleAsync = async () => {
                    const inResult = await this._def.in._parseAsync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (inResult.status === "aborted")
                        return INVALID$1;
                    if (inResult.status === "dirty") {
                        status.dirty();
                        return DIRTY$1(inResult.value);
                    }
                    else {
                        return this._def.out._parseAsync({
                            data: inResult.value,
                            path: ctx.path,
                            parent: ctx,
                        });
                    }
                };
                return handleAsync();
            }
            else {
                const inResult = this._def.in._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (inResult.status === "aborted")
                    return INVALID$1;
                if (inResult.status === "dirty") {
                    status.dirty();
                    return {
                        status: "dirty",
                        value: inResult.value,
                    };
                }
                else {
                    return this._def.out._parseSync({
                        data: inResult.value,
                        path: ctx.path,
                        parent: ctx,
                    });
                }
            }
        }
        static create(a, b) {
            return new ZodPipeline({
                in: a,
                out: b,
                typeName: ZodFirstPartyTypeKind$1.ZodPipeline,
            });
        }
    };
    let ZodReadonly$1 = class ZodReadonly extends ZodType$1 {
        _parse(input) {
            const result = this._def.innerType._parse(input);
            const freeze = (data) => {
                if (isValid$1(data)) {
                    data.value = Object.freeze(data.value);
                }
                return data;
            };
            return isAsync$1(result) ? result.then((data) => freeze(data)) : freeze(result);
        }
        unwrap() {
            return this._def.innerType;
        }
    };
    ZodReadonly$1.create = (type, params) => {
        return new ZodReadonly$1({
            innerType: type,
            typeName: ZodFirstPartyTypeKind$1.ZodReadonly,
            ...processCreateParams$1(params),
        });
    };
    var ZodFirstPartyTypeKind$1;
    (function (ZodFirstPartyTypeKind) {
        ZodFirstPartyTypeKind["ZodString"] = "ZodString";
        ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
        ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
        ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
        ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
        ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
        ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
        ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
        ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
        ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
        ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
        ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
        ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
        ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
        ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
        ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
        ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
        ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
        ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
        ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
        ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
        ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
        ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
        ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
        ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
        ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
        ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
        ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
        ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
        ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
        ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
        ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
        ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
        ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
        ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
        ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind$1 || (ZodFirstPartyTypeKind$1 = {}));
    const stringType$1 = ZodString$1.create;
    const numberType$1 = ZodNumber$1.create;
    ZodBigInt$1.create;
    const booleanType$1 = ZodBoolean$1.create;
    ZodDate$1.create;
    ZodNever$1.create;
    const arrayType$1 = ZodArray$1.create;
    const objectType$1 = ZodObject$1.create;
    const unionType$1 = ZodUnion$1.create;
    ZodIntersection$1.create;
    ZodTuple$1.create;
    const recordType = ZodRecord.create;
    const literalType$1 = ZodLiteral$1.create;
    const enumType$1 = ZodEnum$1.create;
    ZodPromise$1.create;
    ZodOptional$1.create;
    ZodNullable$1.create;
    const coerce = {
        string: ((arg) => ZodString$1.create({ ...arg, coerce: true })),
        number: ((arg) => ZodNumber$1.create({ ...arg, coerce: true })),
        boolean: ((arg) => ZodBoolean$1.create({
            ...arg,
            coerce: true,
        })),
        bigint: ((arg) => ZodBigInt$1.create({ ...arg, coerce: true })),
        date: ((arg) => ZodDate$1.create({ ...arg, coerce: true })),
    };

    const ProviderSchema = enumType$1(["gmail", "yahoo", "outlook", "imap"]);
    function normalizeRfcMessageId(input) {
        if (typeof input !== "string")
            return undefined;
        const unfolded = input.replace(/\r?\n[\t ]+/g, " ").trim();
        if (!unfolded || /[\r\n\0]/.test(unfolded))
            return undefined;
        const withoutLabel = unfolded.replace(/^message-id\s*:\s*/i, "").trim();
        const bracketed = withoutLabel.match(/^<\s*([^<>]+?)\s*>$/)?.[1];
        const value = (bracketed ?? withoutLabel).trim();
        const separator = value.lastIndexOf("@");
        if (separator <= 0 || separator === value.length - 1)
            return undefined;
        const idLeft = value.slice(0, separator).trim();
        const idRight = value.slice(separator + 1).trim().toLowerCase();
        if (!idLeft || !idRight || /[<>\r\n\0]/.test(idLeft) || /[<>\s\r\n\0]/.test(idRight)) {
            return undefined;
        }
        return `${idLeft}@${idRight}`;
    }
    const RfcMessageIdSchema = stringType$1()
        .trim()
        .min(3)
        .max(998)
        .refine((value) => normalizeRfcMessageId(value) !== undefined, "Invalid RFC Message-ID");
    function normalizeImapEmailId(input) {
        if (typeof input !== "string")
            return undefined;
        const value = input.trim();
        return value && value.length <= 512 && !/[\r\n\0]/.test(value) ? value : undefined;
    }
    const ImapEmailIdSchema = stringType$1()
        .trim()
        .min(1)
        .max(512)
        .refine((value) => normalizeImapEmailId(value) !== undefined, "Invalid IMAP EMAILID");
    const HttpUrlSchema = stringType$1()
        .trim()
        .url()
        .refine((value) => {
        try {
            const protocol = new URL(value).protocol;
            return protocol === "http:" || protocol === "https:";
        }
        catch {
            return false;
        }
    }, "Expected an http:// or https:// URL.");
    const ServerBaseUrlSchema = HttpUrlSchema.refine((value) => {
        const url = new URL(value);
        return (url.pathname === "/" || url.pathname === "") && !url.search && !url.hash;
    }, "Expected a server base URL without a path, query, or hash.");
    function normalizeServerBaseUrl(input) {
        const url = new URL(ServerBaseUrlSchema.parse(input));
        url.pathname = "/";
        url.search = "";
        url.hash = "";
        return url.toString().replace(/\/$/, "");
    }
    const RiskLevelSchema = enumType$1(["low", "medium", "high"]);
    const VerdictLevelSchema = enumType$1(["allow", "warn", "hard_block"]);
    const RecommendedActionSchema = enumType$1([
        "allow",
        "ignore",
        "verify_directly",
        "ask_guardian",
        "archive",
        "move_to_spam"
    ]);
    const VerdictSourceSchema = enumType$1([
        "rules_only",
        "rules+nano",
        "rules+cloud",
        "rules+safeguard",
        "rules+safeguard+nano",
        "rules+safeguard+cloud"
    ]);
    const MessageUnsubscribeMailtoSchema = objectType$1({
        address: stringType$1().email(),
        subject: stringType$1().optional(),
        body: stringType$1().optional()
    });
    const MessageUnsubscribeSchema = objectType$1({
        mailto: MessageUnsubscribeMailtoSchema.optional(),
        httpGetUrl: HttpUrlSchema.optional(),
        httpPostUrl: HttpUrlSchema.optional()
    })
        .refine((value) => Boolean(value.mailto || value.httpGetUrl || value.httpPostUrl), {
        message: "Expected at least one unsubscribe method."
    });
    const MessageSummarySchema = objectType$1({
        messageKey: stringType$1(),
        provider: ProviderSchema,
        accountId: stringType$1(),
        threadKey: stringType$1().optional(),
        subject: stringType$1(),
        fromDisplay: stringType$1(),
        fromAddress: stringType$1().email().optional(),
        replyTo: arrayType$1(stringType$1().email()).optional(),
        receivedAt: stringType$1().datetime(),
        unread: booleanType$1(),
        hasAttachments: booleanType$1(),
        labels: arrayType$1(stringType$1()).optional(),
        snippet: stringType$1().optional(),
        unsubscribe: MessageUnsubscribeSchema.optional()
    });
    const LinkFindingSchema = objectType$1({
        url: stringType$1().url(),
        normalizedUrl: stringType$1().url(),
        actualDomain: stringType$1(),
        visibleText: stringType$1().optional(),
        visibleDomain: stringType$1().optional(),
        redirectChain: arrayType$1(stringType$1().url()).optional(),
        risk: RiskLevelSchema,
        reasons: arrayType$1(stringType$1())
    });
    const AttachmentFindingSchema = objectType$1({
        filename: stringType$1(),
        mimeType: stringType$1(),
        sizeBytes: numberType$1().int().positive().optional(),
        extractedTextPreview: stringType$1().optional(),
        risk: RiskLevelSchema,
        reasons: arrayType$1(stringType$1())
    });
    const DeepScanSummarySchema = objectType$1({
        analyzedLinkCount: numberType$1().int().nonnegative(),
        noFetchCount: numberType$1().int().nonnegative(),
        eligibleCount: numberType$1().int().nonnegative(),
        prioritizedCount: numberType$1().int().nonnegative(),
        liveFetchEnabled: booleanType$1(),
        liveFetchedCount: numberType$1().int().nonnegative(),
        redirectedCount: numberType$1().int().nonnegative(),
        passwordCount: numberType$1().int().nonnegative(),
        paymentCount: numberType$1().int().nonnegative(),
        interactiveCount: numberType$1().int().nonnegative(),
        truncatedCount: numberType$1().int().nonnegative(),
        fetchErrorCount: numberType$1().int().nonnegative()
    });
    const VerdictSchema = objectType$1({
        messageKey: stringType$1(),
        level: VerdictLevelSchema,
        confidence: numberType$1().min(0).max(1),
        requiresAcknowledgement: booleanType$1(),
        reasons: arrayType$1(stringType$1()),
        policyTags: arrayType$1(stringType$1()),
        recommendedAction: RecommendedActionSchema,
        linkFindings: arrayType$1(LinkFindingSchema),
        attachmentFindings: arrayType$1(AttachmentFindingSchema),
        deepScan: DeepScanSummarySchema.optional(),
        source: VerdictSourceSchema,
        updatedAt: stringType$1().datetime()
    });
    enumType$1(["standard", "deep"]);
    const AnalysisStateSchema = enumType$1([
        "queued",
        "rules_running",
        "deep_link_analysis",
        "deep_page_fetch",
        "local_policy_check",
        "deep_review",
        "cloud_second_opinion",
        "complete",
        "error"
    ]);
    const AnalysisJobSchema = objectType$1({
        jobId: stringType$1(),
        messageKey: stringType$1(),
        state: AnalysisStateSchema,
        userMessage: stringType$1(),
        partialReasons: arrayType$1(stringType$1()).optional(),
        startedAt: stringType$1().datetime(),
        completedAt: stringType$1().datetime().optional()
    });
    const SettingsSchema = objectType$1({
        cloudFallbackEnabled: booleanType$1(),
        deepScanEnabled: booleanType$1(),
        deepScanLiveFetchEnabled: booleanType$1(),
        deepScanMaxFetchesPerEmail: numberType$1().int().min(1).max(10),
        deepScanMaxFetchesPerDomain: numberType$1().int().min(1).max(5),
        deepScanMaxRedirects: numberType$1().int().min(1).max(10),
        deepScanMaxPageBytes: numberType$1().int().min(32 * 1024).max(1024 * 1024),
        deepScanFetchTimeoutMs: numberType$1().int().min(1000).max(30_000),
        strictMode: booleanType$1(),
        debugMode: booleanType$1(),
        demoMode: booleanType$1(),
        analysisPaused: booleanType$1(),
        monthlyAiBudgetUsd: numberType$1().positive().nullable().optional(),
        aiBudgetAlertThresholdPct: numberType$1().min(1).max(100).nullable().optional(),
        serverBaseUrl: ServerBaseUrlSchema.optional()
    });
    const FeedItemSchema = objectType$1({
        summary: MessageSummarySchema,
        verdict: VerdictSchema.optional(),
        analysisJob: AnalysisJobSchema.optional()
    });
    const FeedResponseSchema = objectType$1({
        provider: ProviderSchema.optional(),
        days: numberType$1().int().min(1).max(30),
        items: arrayType$1(FeedItemSchema),
        generatedAt: stringType$1().datetime(),
        nextCursor: stringType$1().min(1).optional(),
        hasMore: booleanType$1().optional()
    });
    objectType$1({
        pairingCode: stringType$1().min(6).max(32),
        deviceName: stringType$1().min(2).max(80)
    });
    objectType$1({
        deviceId: stringType$1(),
        deviceToken: stringType$1(),
        expiresAt: stringType$1().datetime().optional()
    });
    const DomRowHintSchema = objectType$1({
        provider: ProviderSchema,
        subject: stringType$1().optional(),
        fromDisplay: stringType$1().optional(),
        fromAddress: stringType$1().optional(),
        snippet: stringType$1().optional(),
        receivedAt: stringType$1().optional(),
        externalId: stringType$1().optional(),
        rfcMessageId: RfcMessageIdSchema.optional(),
        imapEmailId: ImapEmailIdSchema.optional()
    });
    objectType$1({
        hints: DomRowHintSchema,
        skipClientSyncWait: booleanType$1().optional()
    });
    const ResolveRowAvailabilityCodeSchema = enumType$1([
        "provider_not_connected",
        "provider_needs_attention"
    ]);
    const ResolveRowAvailabilitySchema = objectType$1({
        code: ResolveRowAvailabilityCodeSchema,
        provider: ProviderSchema,
        detail: stringType$1()
    });
    const ResolveRowResponseSchema = objectType$1({
        match: objectType$1({
            messageKey: stringType$1(),
            verdict: VerdictSchema.optional(),
            analysisJob: AnalysisJobSchema.optional(),
            summary: MessageSummarySchema
        })
            .nullable(),
        availability: ResolveRowAvailabilitySchema.optional()
    });
    objectType$1({
        messageKey: stringType$1().optional(),
        provider: ProviderSchema,
        hints: DomRowHintSchema.optional(),
        renderedText: stringType$1().optional(),
        manual: booleanType$1().optional()
    });
    const PendingDecisionSchema = objectType$1({
        status: literalType$1("pending"),
        messageKey: stringType$1().optional(),
        jobId: stringType$1(),
        userMessage: stringType$1()
    });
    const IdleDecisionSchema = objectType$1({
        status: literalType$1("idle"),
        messageKey: stringType$1().optional(),
        userMessage: stringType$1(),
        availability: ResolveRowAvailabilitySchema.optional()
    });
    const ResolvedDecisionSchema = objectType$1({
        status: literalType$1("resolved"),
        verdict: VerdictSchema,
        messageKey: stringType$1().optional(),
        job: AnalysisJobSchema.optional()
    });
    const OpenAttemptResponseSchema = unionType$1([
        PendingDecisionSchema,
        IdleDecisionSchema,
        ResolvedDecisionSchema
    ]);
    const MessageVerdictResponseSchema = objectType$1({
        messageKey: stringType$1(),
        summary: MessageSummarySchema,
        verdict: VerdictSchema.optional(),
        job: AnalysisJobSchema.optional()
    });
    const UnsubscribeAiModeSchema = enumType$1([
        "detect_only",
        "assisted",
        "premium_auto"
    ]);
    const UnsubscribeResolutionSourceSchema = enumType$1([
        "deterministic",
        "pass1",
        "pass2"
    ]);
    const UnsubscribeCandidateMethodSchema = enumType$1([
        "http_get",
        "http_post",
        "mailto"
    ]);
    const UnsubscribeCandidateActionSchema = enumType$1([
        "direct_unsubscribe",
        "preferences_center",
        "mailto_unsubscribe"
    ]);
    const UnsubscribeRiskFlagSchema = enumType$1([
        "domain_mismatch",
        "login_required",
        "redirect_chain",
        "preference_center",
        "mailto_only"
    ]);
    const MessageUnsubscribePreviewStatusSchema = enumType$1([
        "available",
        "manual_review",
        "unavailable"
    ]);
    const MessageUnsubscribePreviewSchema = objectType$1({
        status: MessageUnsubscribePreviewStatusSchema,
        mode: UnsubscribeAiModeSchema,
        canExecute: booleanType$1(),
        canOverride: booleanType$1(),
        source: UnsubscribeResolutionSourceSchema.optional(),
        method: UnsubscribeCandidateMethodSchema.optional(),
        action: UnsubscribeCandidateActionSchema.optional(),
        targetDomain: stringType$1().trim().min(1).optional(),
        confidence: numberType$1().min(0).max(1).optional(),
        riskFlags: arrayType$1(UnsubscribeRiskFlagSchema),
        detail: stringType$1().trim().min(1)
    });
    const MessageUnsubscribePreviewResponseSchema = objectType$1({
        messageKey: stringType$1(),
        preview: MessageUnsubscribePreviewSchema
    });
    const MessageRecheckResponseSchema = PendingDecisionSchema;
    const MessageDeepScanResponseSchema = PendingDecisionSchema;
    objectType$1({
        messageKey: stringType$1().optional(),
        provider: ProviderSchema,
        url: stringType$1(),
        visibleText: stringType$1().optional()
    });
    const LinkDecisionSchema = unionType$1([
        objectType$1({
            status: literalType$1("pending"),
            jobId: stringType$1(),
            userMessage: stringType$1()
        }),
        objectType$1({
            status: literalType$1("resolved"),
            verdictLevel: VerdictLevelSchema,
            allowNavigation: booleanType$1(),
            requiresAcknowledgement: booleanType$1(),
            reasons: arrayType$1(stringType$1()),
            realDomain: stringType$1(),
            safeAlternativeUrl: stringType$1().optional()
        })
    ]);
    const ApiErrorSchema = objectType$1({
        error: stringType$1(),
        details: stringType$1().optional()
    });
    objectType$1({
        ok: literalType$1(true)
    });
    unionType$1([
        OpenAttemptResponseSchema,
        objectType$1({
            status: literalType$1("ok")
        })
    ]);
    const MessageActionSchema = enumType$1([
        "archive",
        "spam",
        "trash",
        "unsubscribe"
    ]);
    const ProviderAccountSchema = objectType$1({
        id: stringType$1(),
        provider: ProviderSchema,
        accountId: stringType$1(),
        displayName: stringType$1(),
        status: enumType$1(["connected", "needs_attention"]),
        createdAt: stringType$1().datetime(),
        lastSyncAt: stringType$1().datetime().optional()
    });
    const ProviderRiskTierSchema = enumType$1(["tier1", "tier2", "tier3", "rejected"]);
    const ProviderConnectorTypeSchema = enumType$1(["oauth", "imap"]);
    const ProviderAuthTypeSchema = enumType$1([
        "oauth_delegated",
        "app_password",
        "legacy_imap",
        "local_bridge"
    ]);
    const ProviderSecurityPostureSchema = objectType$1({
        provider: ProviderSchema,
        providerLabel: stringType$1(),
        connectorType: ProviderConnectorTypeSchema,
        authType: ProviderAuthTypeSchema,
        riskTier: ProviderRiskTierSchema,
        oauthSupported: booleanType$1(),
        appSpecificPasswordSupported: booleanType$1(),
        imapSupported: booleanType$1(),
        tlsRequired: booleanType$1(),
        primaryPasswordAllowed: booleanType$1(),
        writeScopesRequired: booleanType$1(),
        securitySummary: stringType$1()
    });
    const ImapProviderPresetSchema = objectType$1({
        id: stringType$1(),
        name: stringType$1(),
        host: stringType$1(),
        port: numberType$1().int().min(1).max(65535),
        secure: booleanType$1(),
        note: stringType$1(),
        usernameHint: stringType$1().optional(),
        domains: arrayType$1(stringType$1()).optional(),
        providerFamily: stringType$1().optional(),
        authMode: stringType$1().optional(),
        authModes: arrayType$1(stringType$1()).optional(),
        preferredAuthMode: stringType$1().optional(),
        setupGuidance: stringType$1().optional(),
        requiresAppPassword: booleanType$1().optional(),
        requiresSecureMailKey: booleanType$1().optional(),
        legacyMigrationNotes: stringType$1().optional(),
        extensionSurface: enumType$1(["tested-webmail", "server-scan-only"]).optional(),
        status: enumType$1(["supported", "hidden", "disabled", "unsupported", "internal_only", "coming_soon"])
            .optional(),
        security: ProviderSecurityPostureSchema.optional()
    });
    const SetupSessionStatusSchema = enumType$1([
        "paired",
        "oauth_pending",
        "imap_code_sent",
        "imap_ready",
        "imap_verified",
        "connected",
        "error"
    ]);
    const SetupSessionSchema = objectType$1({
        sessionId: stringType$1(),
        status: SetupSessionStatusSchema,
        serverBaseUrl: ServerBaseUrlSchema.optional(),
        provider: ProviderSchema.optional(),
        email: stringType$1().email().optional(),
        displayName: stringType$1().optional(),
        maskedDestination: stringType$1().optional(),
        errorMessage: stringType$1().optional(),
        createdAt: stringType$1().datetime(),
        updatedAt: stringType$1().datetime(),
        expiresAt: stringType$1().datetime(),
        account: ProviderAccountSchema.optional()
    });
    objectType$1({
        serverBaseUrl: ServerBaseUrlSchema,
        pairingCode: stringType$1().trim().min(6).max(64),
        deviceName: stringType$1().trim().min(2).max(80)
    });
    const SetupInviteSessionResponseSchema = objectType$1({
        deviceId: stringType$1(),
        deviceToken: stringType$1(),
        session: SetupSessionSchema
    });
    const SetupSessionResponseSchema = objectType$1({
        session: SetupSessionSchema
    });
    const AccountListResponseSchema = objectType$1({
        accounts: arrayType$1(ProviderAccountSchema)
    });
    objectType$1({
        setupSessionId: stringType$1().optional(),
        label: stringType$1().trim().min(1).max(80).optional()
    });
    const AccountOAuthStartResponseSchema = objectType$1({
        setupSessionId: stringType$1(),
        authUrl: HttpUrlSchema,
        scopes: arrayType$1(stringType$1()).optional(),
        security: ProviderSecurityPostureSchema.optional()
    });
    objectType$1({
        setupSessionId: stringType$1().optional(),
        presetId: stringType$1().trim().min(1).max(80).optional(),
        displayName: stringType$1().trim().min(1).max(80),
        email: stringType$1().trim().email(),
        username: stringType$1().trim().max(160).optional(),
        host: stringType$1().trim().min(1).max(255),
        port: coerce.number().int().min(1).max(65535),
        secure: booleanType$1()
    });
    const ImapVerificationSendResponseSchema = objectType$1({
        setupSessionId: stringType$1(),
        maskedDestination: stringType$1(),
        expiresAt: stringType$1().datetime(),
        verificationRequired: booleanType$1().default(true)
    });
    objectType$1({
        setupSessionId: stringType$1(),
        code: stringType$1().trim().min(4).max(32)
    });
    const ImapVerificationVerifyResponseSchema = objectType$1({
        setupSessionId: stringType$1(),
        verified: literalType$1(true)
    });
    const AccountConnectResponseSchema = objectType$1({
        account: ProviderAccountSchema,
        session: SetupSessionSchema.optional()
    });
    const BaseProtectionPresetSchema = enumType$1(["minimal", "moderate", "high"]);
    const ProtectionPresetSchema = enumType$1([
        "minimal",
        "moderate",
        "high",
        "custom"
    ]);
    const OverrideModeSchema = enumType$1(["inherit", "off", "warn", "block"]);
    const EffectiveOptionModeSchema = enumType$1(["off", "warn", "block"]);
    const ProtectionOptionKeySchema = enumType$1([
        "identity.protectedBrandImpersonation",
        "identity.protectedContactImpersonation",
        "identity.authAlignmentFailures",
        "identity.replyToMismatch",
        "identity.lookalikeOrPunycodeDomain",
        "identity.freeMailBusinessImpersonation",
        "identity.newDomainForKnownSender",
        "links.visibleActualMismatch",
        "links.protectedBrandMismatch",
        "links.redirectorOrShortener",
        "links.ipLiteralOrUnsafeScheme",
        "links.nonHttpsLoginOrWeirdPort",
        "links.openRedirectBrandAbuse",
        "links.safeBrowsingHit",
        "content.credentialRequest",
        "content.otpRequest",
        "content.paymentGiftCardWireRequest",
        "content.accountLockUrgency",
        "content.callNowSupportScam",
        "content.qrSignInOrPayment",
        "content.invoiceRefundTollPackageTax",
        "content.oauthConsentLure",
        "content.documentShareLure",
        "content.secrecyRequest",
        "attachments.executableOrScript",
        "attachments.htmlAttachment",
        "attachments.macroOfficeDoc",
        "attachments.encryptedArchive",
        "attachments.nestedEmail",
        "attachments.mimeOrFilenameDeception",
        "attachments.pdfOrDocExternalLinks",
        "context.firstTimeSenderAction",
        "context.rareSenderLinkOrAttachment",
        "context.knownContactUnusualAsk",
        "context.threadHijackSignals",
        "context.providerWarnings",
        "context.priorFamilyReputation",
        "mailbox.forwardingRuleTampering",
        "mailbox.securityMailHidingRules",
        "mailbox.suspiciousOauthGrantAlerts",
        "trust.frequentCorrespondentSuppression",
        "trust.mailingListSuppression",
        "trust.trustedSenderAllowlist"
    ]);
    const ProtectionThresholdsSchema = objectType$1({
        warnScore: numberType$1(),
        hardBlockScore: numberType$1(),
        escalateMinScore: numberType$1(),
        escalateMaxScore: numberType$1(),
        trustCap: numberType$1()
    });
    const ProtectionActionsSchema = objectType$1({
        requireAckOnWarnOpen: booleanType$1(),
        requireAckOnWarnLinks: booleanType$1(),
        requireAckOnHardBlockOpen: booleanType$1(),
        requireAckOnHardBlockLinks: booleanType$1(),
        holdLinksDuringAnalysis: booleanType$1()
    });
    const ProtectionSettingsSchema = objectType$1({
        preset: ProtectionPresetSchema,
        basePreset: BaseProtectionPresetSchema,
        thresholds: ProtectionThresholdsSchema,
        options: recordType(ProtectionOptionKeySchema, OverrideModeSchema),
        actions: ProtectionActionsSchema,
        protectedContacts: arrayType$1(stringType$1()),
        protectedDomains: arrayType$1(stringType$1()),
        trustedSenders: arrayType$1(stringType$1()),
        trustedDomains: arrayType$1(stringType$1())
    });
    const ProtectionPresetDefSchema = objectType$1({
        id: BaseProtectionPresetSchema,
        label: stringType$1(),
        description: stringType$1(),
        thresholds: ProtectionThresholdsSchema,
        actions: ProtectionActionsSchema,
        options: recordType(ProtectionOptionKeySchema, EffectiveOptionModeSchema)
    });
    const ProtectionOptionDefinitionSchema = objectType$1({
        key: ProtectionOptionKeySchema,
        category: stringType$1(),
        label: stringType$1(),
        help: stringType$1(),
        locked: booleanType$1()
    });
    const DeterministicSettingsResponseSchema = objectType$1({
        settings: ProtectionSettingsSchema,
        effectiveOptionModes: recordType(ProtectionOptionKeySchema, EffectiveOptionModeSchema),
        effectiveModeLabel: stringType$1(),
        activeThresholds: ProtectionThresholdsSchema,
        optionSummary: objectType$1({
            blockCount: numberType$1().int().nonnegative(),
            warnCount: numberType$1().int().nonnegative(),
            offCount: numberType$1().int().nonnegative()
        }),
        overrides: arrayType$1(objectType$1({
            key: ProtectionOptionKeySchema,
            mode: OverrideModeSchema,
            effectiveMode: EffectiveOptionModeSchema
        }))
    });
    const ProtectionCatalogResponseSchema = objectType$1({
        presets: arrayType$1(ProtectionPresetDefSchema),
        options: arrayType$1(ProtectionOptionDefinitionSchema)
    });
    const MailboxPolicyResponseSchema = objectType$1({
        account: ProviderAccountSchema,
        policy: DeterministicSettingsResponseSchema
    });
    const DeterministicSettingsUpdateSchema = objectType$1({
        basePreset: BaseProtectionPresetSchema.optional(),
        options: recordType(ProtectionOptionKeySchema, OverrideModeSchema).optional(),
        protectedContacts: arrayType$1(stringType$1()).optional(),
        protectedDomains: arrayType$1(stringType$1()).optional(),
        trustedSenders: arrayType$1(stringType$1()).optional(),
        trustedDomains: arrayType$1(stringType$1()).optional(),
        restorePresetDefaults: booleanType$1().optional()
    });

    const DEEP_SCAN_DISABLED_REASON = "Deep Scan is not enabled on this server.";
    const DEEP_SCAN_STRUCTURAL_ONLY_NOTICE = "Deep Scan is available, but this server is currently limited to structural checks. Live page checks are disabled.";
    function deepScanAvailabilityFromSettings(settings) {
        if (settings?.deepScanEnabled === false) {
            return {
                canRequest: false,
                liveFetchEnabled: false,
                disabledReason: DEEP_SCAN_DISABLED_REASON
            };
        }
        if (settings?.deepScanLiveFetchEnabled === false) {
            return {
                canRequest: true,
                liveFetchEnabled: false,
                notice: DEEP_SCAN_STRUCTURAL_ONLY_NOTICE
            };
        }
        return {
            canRequest: true,
            liveFetchEnabled: true
        };
    }
    function summarizeDeepScanSettings(settings) {
        if (!settings) {
            return {
                headline: "Deep Scan status unavailable",
                detail: "The extension has not loaded this server's Deep Scan settings yet.",
                behavior: "Standard scans still use the normal ArcWardyn safety flow.",
                budget: "Pair the extension or reconnect to the server to load the live Deep Scan policy."
            };
        }
        const availability = deepScanAvailabilityFromSettings(settings);
        const budget = [
            `Budget: up to ${settings.deepScanMaxFetchesPerEmail} live-check${settings.deepScanMaxFetchesPerEmail === 1 ? "" : "s"} per email`,
            `${settings.deepScanMaxFetchesPerDomain} per domain`,
            `${settings.deepScanMaxRedirects} redirect${settings.deepScanMaxRedirects === 1 ? "" : "s"}`,
            `${Math.round(settings.deepScanFetchTimeoutMs / 1000)}s timeout`,
            `${Math.round(settings.deepScanMaxPageBytes / 1024)} KB per page`
        ].join(" • ");
        if (!availability.canRequest) {
            return {
                headline: "Deep Scan disabled",
                detail: DEEP_SCAN_DISABLED_REASON,
                behavior: "Standard scans still follow the normal ArcWardyn review path. Deep Scan is only an extra manual action.",
                budget
            };
        }
        if (!availability.liveFetchEnabled) {
            return {
                headline: "Deep Scan enabled (structural only)",
                detail: DEEP_SCAN_STRUCTURAL_ONLY_NOTICE,
                behavior: "Deep Scan reviews the email and link structure only. Personalized links stay unopened, and the review model only sees structural evidence.",
                budget
            };
        }
        return {
            headline: "Deep Scan enabled",
            detail: "This server allows Deep Scan and controlled cloud page checks for eligible links.",
            behavior: "Personalized links stay unopened. Selected destinations are checked from ArcWardyn cloud workers, not your browser, and the review model receives sanitized evidence.",
            budget
        };
    }

    const EmailSchema = stringType$1().email();
    const EMAIL_ADDRESS_PATTERN = /[A-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?(?:\.[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?)+/gi;
    const STALE_ANALYSIS_JOB_MINUTES = 20;
    function isSupportedEmailAddress(value) {
        return EmailSchema.safeParse(value).success;
    }
    function sanitizeOptionalEmail(value) {
        if (typeof value !== "string")
            return undefined;
        const match = value.match(EMAIL_ADDRESS_PATTERN);
        const normalized = match?.[0]?.toLowerCase();
        return normalized && isSupportedEmailAddress(normalized) ? normalized : undefined;
    }
    function sanitizeEmailList(value) {
        if (!Array.isArray(value))
            return [];
        const seen = new Set();
        const sanitized = [];
        for (const entry of value) {
            if (typeof entry !== "string")
                continue;
            const matches = entry.match(EMAIL_ADDRESS_PATTERN) ?? [];
            for (const match of matches) {
                const normalized = match.toLowerCase();
                if (!isSupportedEmailAddress(normalized))
                    continue;
                if (seen.has(normalized))
                    continue;
                seen.add(normalized);
                sanitized.push(normalized);
            }
        }
        return sanitized;
    }
    function sanitizeFeedResponseBody(body) {
        if (!body || typeof body !== "object")
            return body;
        const payload = body;
        if (!Array.isArray(payload.items))
            return body;
        return {
            ...payload,
            items: payload.items.map((item) => {
                if (!item?.summary || typeof item.summary !== "object") {
                    return item;
                }
                const normalizedItem = normalizeFeedItem(item);
                return {
                    ...normalizedItem,
                    summary: {
                        ...normalizedItem.summary,
                        fromAddress: sanitizeOptionalEmail(normalizedItem.summary.fromAddress),
                        replyTo: sanitizeEmailList(normalizedItem.summary.replyTo)
                    }
                };
            })
        };
    }
    function normalizeFeedItem(item) {
        const analysisJob = sanitizeAnalysisJob(item.analysisJob, item.verdict?.updatedAt);
        return {
            ...item,
            analysisJob
        };
    }
    function sanitizeAnalysisJob(value, verdictUpdatedAt) {
        if (!value || typeof value !== "object")
            return undefined;
        const job = value;
        if (job.state === "complete" || job.state === "error") {
            return undefined;
        }
        const startedAt = typeof job.startedAt === "string" ? Date.parse(job.startedAt) : Number.NaN;
        if (!Number.isFinite(startedAt)) {
            return undefined;
        }
        if (Date.now() - startedAt >= STALE_ANALYSIS_JOB_MINUTES * 60 * 1000) {
            return undefined;
        }
        const verdictUpdatedAtMs = typeof verdictUpdatedAt === "string" ? Date.parse(verdictUpdatedAt) : Number.NaN;
        const completedAtMs = typeof job.completedAt === "string" ? Date.parse(job.completedAt) : Number.NaN;
        if (Number.isFinite(verdictUpdatedAtMs) &&
            ((Number.isFinite(completedAtMs) && verdictUpdatedAtMs >= completedAtMs) ||
                verdictUpdatedAtMs >= startedAt)) {
            return undefined;
        }
        return value;
    }

    var util;
    (function (util) {
        util.assertEqual = (_) => { };
        function assertIs(_arg) { }
        util.assertIs = assertIs;
        function assertNever(_x) {
            throw new Error();
        }
        util.assertNever = assertNever;
        util.arrayToEnum = (items) => {
            const obj = {};
            for (const item of items) {
                obj[item] = item;
            }
            return obj;
        };
        util.getValidEnumValues = (obj) => {
            const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
            const filtered = {};
            for (const k of validKeys) {
                filtered[k] = obj[k];
            }
            return util.objectValues(filtered);
        };
        util.objectValues = (obj) => {
            return util.objectKeys(obj).map(function (e) {
                return obj[e];
            });
        };
        util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
            ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
            : (object) => {
                const keys = [];
                for (const key in object) {
                    if (Object.prototype.hasOwnProperty.call(object, key)) {
                        keys.push(key);
                    }
                }
                return keys;
            };
        util.find = (arr, checker) => {
            for (const item of arr) {
                if (checker(item))
                    return item;
            }
            return undefined;
        };
        util.isInteger = typeof Number.isInteger === "function"
            ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
            : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
        function joinValues(array, separator = " | ") {
            return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
        }
        util.joinValues = joinValues;
        util.jsonStringifyReplacer = (_, value) => {
            if (typeof value === "bigint") {
                return value.toString();
            }
            return value;
        };
    })(util || (util = {}));
    var objectUtil;
    (function (objectUtil) {
        objectUtil.mergeShapes = (first, second) => {
            return {
                ...first,
                ...second, // second overwrites first
            };
        };
    })(objectUtil || (objectUtil = {}));
    const ZodParsedType = util.arrayToEnum([
        "string",
        "nan",
        "number",
        "integer",
        "float",
        "boolean",
        "date",
        "bigint",
        "symbol",
        "function",
        "undefined",
        "null",
        "array",
        "object",
        "unknown",
        "promise",
        "void",
        "never",
        "map",
        "set",
    ]);
    const getParsedType = (data) => {
        const t = typeof data;
        switch (t) {
            case "undefined":
                return ZodParsedType.undefined;
            case "string":
                return ZodParsedType.string;
            case "number":
                return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
            case "boolean":
                return ZodParsedType.boolean;
            case "function":
                return ZodParsedType.function;
            case "bigint":
                return ZodParsedType.bigint;
            case "symbol":
                return ZodParsedType.symbol;
            case "object":
                if (Array.isArray(data)) {
                    return ZodParsedType.array;
                }
                if (data === null) {
                    return ZodParsedType.null;
                }
                if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
                    return ZodParsedType.promise;
                }
                if (typeof Map !== "undefined" && data instanceof Map) {
                    return ZodParsedType.map;
                }
                if (typeof Set !== "undefined" && data instanceof Set) {
                    return ZodParsedType.set;
                }
                if (typeof Date !== "undefined" && data instanceof Date) {
                    return ZodParsedType.date;
                }
                return ZodParsedType.object;
            default:
                return ZodParsedType.unknown;
        }
    };

    const ZodIssueCode = util.arrayToEnum([
        "invalid_type",
        "invalid_literal",
        "custom",
        "invalid_union",
        "invalid_union_discriminator",
        "invalid_enum_value",
        "unrecognized_keys",
        "invalid_arguments",
        "invalid_return_type",
        "invalid_date",
        "invalid_string",
        "too_small",
        "too_big",
        "invalid_intersection_types",
        "not_multiple_of",
        "not_finite",
    ]);
    class ZodError extends Error {
        get errors() {
            return this.issues;
        }
        constructor(issues) {
            super();
            this.issues = [];
            this.addIssue = (sub) => {
                this.issues = [...this.issues, sub];
            };
            this.addIssues = (subs = []) => {
                this.issues = [...this.issues, ...subs];
            };
            const actualProto = new.target.prototype;
            if (Object.setPrototypeOf) {
                // eslint-disable-next-line ban/ban
                Object.setPrototypeOf(this, actualProto);
            }
            else {
                this.__proto__ = actualProto;
            }
            this.name = "ZodError";
            this.issues = issues;
        }
        format(_mapper) {
            const mapper = _mapper ||
                function (issue) {
                    return issue.message;
                };
            const fieldErrors = { _errors: [] };
            const processError = (error) => {
                for (const issue of error.issues) {
                    if (issue.code === "invalid_union") {
                        issue.unionErrors.map(processError);
                    }
                    else if (issue.code === "invalid_return_type") {
                        processError(issue.returnTypeError);
                    }
                    else if (issue.code === "invalid_arguments") {
                        processError(issue.argumentsError);
                    }
                    else if (issue.path.length === 0) {
                        fieldErrors._errors.push(mapper(issue));
                    }
                    else {
                        let curr = fieldErrors;
                        let i = 0;
                        while (i < issue.path.length) {
                            const el = issue.path[i];
                            const terminal = i === issue.path.length - 1;
                            if (!terminal) {
                                curr[el] = curr[el] || { _errors: [] };
                                // if (typeof el === "string") {
                                //   curr[el] = curr[el] || { _errors: [] };
                                // } else if (typeof el === "number") {
                                //   const errorArray: any = [];
                                //   errorArray._errors = [];
                                //   curr[el] = curr[el] || errorArray;
                                // }
                            }
                            else {
                                curr[el] = curr[el] || { _errors: [] };
                                curr[el]._errors.push(mapper(issue));
                            }
                            curr = curr[el];
                            i++;
                        }
                    }
                }
            };
            processError(this);
            return fieldErrors;
        }
        static assert(value) {
            if (!(value instanceof ZodError)) {
                throw new Error(`Not a ZodError: ${value}`);
            }
        }
        toString() {
            return this.message;
        }
        get message() {
            return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
        }
        get isEmpty() {
            return this.issues.length === 0;
        }
        flatten(mapper = (issue) => issue.message) {
            const fieldErrors = {};
            const formErrors = [];
            for (const sub of this.issues) {
                if (sub.path.length > 0) {
                    const firstEl = sub.path[0];
                    fieldErrors[firstEl] = fieldErrors[firstEl] || [];
                    fieldErrors[firstEl].push(mapper(sub));
                }
                else {
                    formErrors.push(mapper(sub));
                }
            }
            return { formErrors, fieldErrors };
        }
        get formErrors() {
            return this.flatten();
        }
    }
    ZodError.create = (issues) => {
        const error = new ZodError(issues);
        return error;
    };

    const errorMap = (issue, _ctx) => {
        let message;
        switch (issue.code) {
            case ZodIssueCode.invalid_type:
                if (issue.received === ZodParsedType.undefined) {
                    message = "Required";
                }
                else {
                    message = `Expected ${issue.expected}, received ${issue.received}`;
                }
                break;
            case ZodIssueCode.invalid_literal:
                message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
                break;
            case ZodIssueCode.unrecognized_keys:
                message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
                break;
            case ZodIssueCode.invalid_union:
                message = `Invalid input`;
                break;
            case ZodIssueCode.invalid_union_discriminator:
                message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
                break;
            case ZodIssueCode.invalid_enum_value:
                message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
                break;
            case ZodIssueCode.invalid_arguments:
                message = `Invalid function arguments`;
                break;
            case ZodIssueCode.invalid_return_type:
                message = `Invalid function return type`;
                break;
            case ZodIssueCode.invalid_date:
                message = `Invalid date`;
                break;
            case ZodIssueCode.invalid_string:
                if (typeof issue.validation === "object") {
                    if ("includes" in issue.validation) {
                        message = `Invalid input: must include "${issue.validation.includes}"`;
                        if (typeof issue.validation.position === "number") {
                            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
                        }
                    }
                    else if ("startsWith" in issue.validation) {
                        message = `Invalid input: must start with "${issue.validation.startsWith}"`;
                    }
                    else if ("endsWith" in issue.validation) {
                        message = `Invalid input: must end with "${issue.validation.endsWith}"`;
                    }
                    else {
                        util.assertNever(issue.validation);
                    }
                }
                else if (issue.validation !== "regex") {
                    message = `Invalid ${issue.validation}`;
                }
                else {
                    message = "Invalid";
                }
                break;
            case ZodIssueCode.too_small:
                if (issue.type === "array")
                    message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
                else if (issue.type === "string")
                    message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
                else if (issue.type === "number")
                    message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
                else if (issue.type === "bigint")
                    message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
                else if (issue.type === "date")
                    message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
                else
                    message = "Invalid input";
                break;
            case ZodIssueCode.too_big:
                if (issue.type === "array")
                    message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
                else if (issue.type === "string")
                    message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
                else if (issue.type === "number")
                    message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
                else if (issue.type === "bigint")
                    message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
                else if (issue.type === "date")
                    message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
                else
                    message = "Invalid input";
                break;
            case ZodIssueCode.custom:
                message = `Invalid input`;
                break;
            case ZodIssueCode.invalid_intersection_types:
                message = `Intersection results could not be merged`;
                break;
            case ZodIssueCode.not_multiple_of:
                message = `Number must be a multiple of ${issue.multipleOf}`;
                break;
            case ZodIssueCode.not_finite:
                message = "Number must be finite";
                break;
            default:
                message = _ctx.defaultError;
                util.assertNever(issue);
        }
        return { message };
    };

    let overrideErrorMap = errorMap;
    function getErrorMap() {
        return overrideErrorMap;
    }

    const makeIssue = (params) => {
        const { data, path, errorMaps, issueData } = params;
        const fullPath = [...path, ...(issueData.path || [])];
        const fullIssue = {
            ...issueData,
            path: fullPath,
        };
        if (issueData.message !== undefined) {
            return {
                ...issueData,
                path: fullPath,
                message: issueData.message,
            };
        }
        let errorMessage = "";
        const maps = errorMaps
            .filter((m) => !!m)
            .slice()
            .reverse();
        for (const map of maps) {
            errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
        }
        return {
            ...issueData,
            path: fullPath,
            message: errorMessage,
        };
    };
    function addIssueToContext(ctx, issueData) {
        const overrideMap = getErrorMap();
        const issue = makeIssue({
            issueData: issueData,
            data: ctx.data,
            path: ctx.path,
            errorMaps: [
                ctx.common.contextualErrorMap, // contextual error map is first priority
                ctx.schemaErrorMap, // then schema-bound map if available
                overrideMap, // then global override map
                overrideMap === errorMap ? undefined : errorMap, // then global default map
            ].filter((x) => !!x),
        });
        ctx.common.issues.push(issue);
    }
    class ParseStatus {
        constructor() {
            this.value = "valid";
        }
        dirty() {
            if (this.value === "valid")
                this.value = "dirty";
        }
        abort() {
            if (this.value !== "aborted")
                this.value = "aborted";
        }
        static mergeArray(status, results) {
            const arrayValue = [];
            for (const s of results) {
                if (s.status === "aborted")
                    return INVALID;
                if (s.status === "dirty")
                    status.dirty();
                arrayValue.push(s.value);
            }
            return { status: status.value, value: arrayValue };
        }
        static async mergeObjectAsync(status, pairs) {
            const syncPairs = [];
            for (const pair of pairs) {
                const key = await pair.key;
                const value = await pair.value;
                syncPairs.push({
                    key,
                    value,
                });
            }
            return ParseStatus.mergeObjectSync(status, syncPairs);
        }
        static mergeObjectSync(status, pairs) {
            const finalObject = {};
            for (const pair of pairs) {
                const { key, value } = pair;
                if (key.status === "aborted")
                    return INVALID;
                if (value.status === "aborted")
                    return INVALID;
                if (key.status === "dirty")
                    status.dirty();
                if (value.status === "dirty")
                    status.dirty();
                if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
                    finalObject[key.value] = value.value;
                }
            }
            return { status: status.value, value: finalObject };
        }
    }
    const INVALID = Object.freeze({
        status: "aborted",
    });
    const DIRTY = (value) => ({ status: "dirty", value });
    const OK = (value) => ({ status: "valid", value });
    const isAborted = (x) => x.status === "aborted";
    const isDirty = (x) => x.status === "dirty";
    const isValid = (x) => x.status === "valid";
    const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;

    var errorUtil;
    (function (errorUtil) {
        errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
        // biome-ignore lint:
        errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
    })(errorUtil || (errorUtil = {}));

    class ParseInputLazyPath {
        constructor(parent, value, path, key) {
            this._cachedPath = [];
            this.parent = parent;
            this.data = value;
            this._path = path;
            this._key = key;
        }
        get path() {
            if (!this._cachedPath.length) {
                if (Array.isArray(this._key)) {
                    this._cachedPath.push(...this._path, ...this._key);
                }
                else {
                    this._cachedPath.push(...this._path, this._key);
                }
            }
            return this._cachedPath;
        }
    }
    const handleResult = (ctx, result) => {
        if (isValid(result)) {
            return { success: true, data: result.value };
        }
        else {
            if (!ctx.common.issues.length) {
                throw new Error("Validation failed but no issues detected.");
            }
            return {
                success: false,
                get error() {
                    if (this._error)
                        return this._error;
                    const error = new ZodError(ctx.common.issues);
                    this._error = error;
                    return this._error;
                },
            };
        }
    };
    function processCreateParams(params) {
        if (!params)
            return {};
        const { errorMap, invalid_type_error, required_error, description } = params;
        if (errorMap && (invalid_type_error || required_error)) {
            throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
        }
        if (errorMap)
            return { errorMap: errorMap, description };
        const customMap = (iss, ctx) => {
            const { message } = params;
            if (iss.code === "invalid_enum_value") {
                return { message: message ?? ctx.defaultError };
            }
            if (typeof ctx.data === "undefined") {
                return { message: message ?? required_error ?? ctx.defaultError };
            }
            if (iss.code !== "invalid_type")
                return { message: ctx.defaultError };
            return { message: message ?? invalid_type_error ?? ctx.defaultError };
        };
        return { errorMap: customMap, description };
    }
    class ZodType {
        get description() {
            return this._def.description;
        }
        _getType(input) {
            return getParsedType(input.data);
        }
        _getOrReturnCtx(input, ctx) {
            return (ctx || {
                common: input.parent.common,
                data: input.data,
                parsedType: getParsedType(input.data),
                schemaErrorMap: this._def.errorMap,
                path: input.path,
                parent: input.parent,
            });
        }
        _processInputParams(input) {
            return {
                status: new ParseStatus(),
                ctx: {
                    common: input.parent.common,
                    data: input.data,
                    parsedType: getParsedType(input.data),
                    schemaErrorMap: this._def.errorMap,
                    path: input.path,
                    parent: input.parent,
                },
            };
        }
        _parseSync(input) {
            const result = this._parse(input);
            if (isAsync(result)) {
                throw new Error("Synchronous parse encountered promise.");
            }
            return result;
        }
        _parseAsync(input) {
            const result = this._parse(input);
            return Promise.resolve(result);
        }
        parse(data, params) {
            const result = this.safeParse(data, params);
            if (result.success)
                return result.data;
            throw result.error;
        }
        safeParse(data, params) {
            const ctx = {
                common: {
                    issues: [],
                    async: params?.async ?? false,
                    contextualErrorMap: params?.errorMap,
                },
                path: params?.path || [],
                schemaErrorMap: this._def.errorMap,
                parent: null,
                data,
                parsedType: getParsedType(data),
            };
            const result = this._parseSync({ data, path: ctx.path, parent: ctx });
            return handleResult(ctx, result);
        }
        "~validate"(data) {
            const ctx = {
                common: {
                    issues: [],
                    async: !!this["~standard"].async,
                },
                path: [],
                schemaErrorMap: this._def.errorMap,
                parent: null,
                data,
                parsedType: getParsedType(data),
            };
            if (!this["~standard"].async) {
                try {
                    const result = this._parseSync({ data, path: [], parent: ctx });
                    return isValid(result)
                        ? {
                            value: result.value,
                        }
                        : {
                            issues: ctx.common.issues,
                        };
                }
                catch (err) {
                    if (err?.message?.toLowerCase()?.includes("encountered")) {
                        this["~standard"].async = true;
                    }
                    ctx.common = {
                        issues: [],
                        async: true,
                    };
                }
            }
            return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
                ? {
                    value: result.value,
                }
                : {
                    issues: ctx.common.issues,
                });
        }
        async parseAsync(data, params) {
            const result = await this.safeParseAsync(data, params);
            if (result.success)
                return result.data;
            throw result.error;
        }
        async safeParseAsync(data, params) {
            const ctx = {
                common: {
                    issues: [],
                    contextualErrorMap: params?.errorMap,
                    async: true,
                },
                path: params?.path || [],
                schemaErrorMap: this._def.errorMap,
                parent: null,
                data,
                parsedType: getParsedType(data),
            };
            const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
            const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
            return handleResult(ctx, result);
        }
        refine(check, message) {
            const getIssueProperties = (val) => {
                if (typeof message === "string" || typeof message === "undefined") {
                    return { message };
                }
                else if (typeof message === "function") {
                    return message(val);
                }
                else {
                    return message;
                }
            };
            return this._refinement((val, ctx) => {
                const result = check(val);
                const setError = () => ctx.addIssue({
                    code: ZodIssueCode.custom,
                    ...getIssueProperties(val),
                });
                if (typeof Promise !== "undefined" && result instanceof Promise) {
                    return result.then((data) => {
                        if (!data) {
                            setError();
                            return false;
                        }
                        else {
                            return true;
                        }
                    });
                }
                if (!result) {
                    setError();
                    return false;
                }
                else {
                    return true;
                }
            });
        }
        refinement(check, refinementData) {
            return this._refinement((val, ctx) => {
                if (!check(val)) {
                    ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
                    return false;
                }
                else {
                    return true;
                }
            });
        }
        _refinement(refinement) {
            return new ZodEffects({
                schema: this,
                typeName: ZodFirstPartyTypeKind.ZodEffects,
                effect: { type: "refinement", refinement },
            });
        }
        superRefine(refinement) {
            return this._refinement(refinement);
        }
        constructor(def) {
            /** Alias of safeParseAsync */
            this.spa = this.safeParseAsync;
            this._def = def;
            this.parse = this.parse.bind(this);
            this.safeParse = this.safeParse.bind(this);
            this.parseAsync = this.parseAsync.bind(this);
            this.safeParseAsync = this.safeParseAsync.bind(this);
            this.spa = this.spa.bind(this);
            this.refine = this.refine.bind(this);
            this.refinement = this.refinement.bind(this);
            this.superRefine = this.superRefine.bind(this);
            this.optional = this.optional.bind(this);
            this.nullable = this.nullable.bind(this);
            this.nullish = this.nullish.bind(this);
            this.array = this.array.bind(this);
            this.promise = this.promise.bind(this);
            this.or = this.or.bind(this);
            this.and = this.and.bind(this);
            this.transform = this.transform.bind(this);
            this.brand = this.brand.bind(this);
            this.default = this.default.bind(this);
            this.catch = this.catch.bind(this);
            this.describe = this.describe.bind(this);
            this.pipe = this.pipe.bind(this);
            this.readonly = this.readonly.bind(this);
            this.isNullable = this.isNullable.bind(this);
            this.isOptional = this.isOptional.bind(this);
            this["~standard"] = {
                version: 1,
                vendor: "zod",
                validate: (data) => this["~validate"](data),
            };
        }
        optional() {
            return ZodOptional.create(this, this._def);
        }
        nullable() {
            return ZodNullable.create(this, this._def);
        }
        nullish() {
            return this.nullable().optional();
        }
        array() {
            return ZodArray.create(this);
        }
        promise() {
            return ZodPromise.create(this, this._def);
        }
        or(option) {
            return ZodUnion.create([this, option], this._def);
        }
        and(incoming) {
            return ZodIntersection.create(this, incoming, this._def);
        }
        transform(transform) {
            return new ZodEffects({
                ...processCreateParams(this._def),
                schema: this,
                typeName: ZodFirstPartyTypeKind.ZodEffects,
                effect: { type: "transform", transform },
            });
        }
        default(def) {
            const defaultValueFunc = typeof def === "function" ? def : () => def;
            return new ZodDefault({
                ...processCreateParams(this._def),
                innerType: this,
                defaultValue: defaultValueFunc,
                typeName: ZodFirstPartyTypeKind.ZodDefault,
            });
        }
        brand() {
            return new ZodBranded({
                typeName: ZodFirstPartyTypeKind.ZodBranded,
                type: this,
                ...processCreateParams(this._def),
            });
        }
        catch(def) {
            const catchValueFunc = typeof def === "function" ? def : () => def;
            return new ZodCatch({
                ...processCreateParams(this._def),
                innerType: this,
                catchValue: catchValueFunc,
                typeName: ZodFirstPartyTypeKind.ZodCatch,
            });
        }
        describe(description) {
            const This = this.constructor;
            return new This({
                ...this._def,
                description,
            });
        }
        pipe(target) {
            return ZodPipeline.create(this, target);
        }
        readonly() {
            return ZodReadonly.create(this);
        }
        isOptional() {
            return this.safeParse(undefined).success;
        }
        isNullable() {
            return this.safeParse(null).success;
        }
    }
    const cuidRegex = /^c[^\s-]{8,}$/i;
    const cuid2Regex = /^[0-9a-z]+$/;
    const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    // const uuidRegex =
    //   /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
    const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    const nanoidRegex = /^[a-z0-9_-]{21}$/i;
    const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    // from https://stackoverflow.com/a/46181/1550155
    // old version: too slow, didn't support unicode
    // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
    //old email regex
    // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
    // eslint-disable-next-line
    // const emailRegex =
    //   /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
    // const emailRegex =
    //   /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    // const emailRegex =
    //   /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
    const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    // const emailRegex =
    //   /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
    // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
    const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    let emojiRegex;
    // faster, simpler, safer
    const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
    // const ipv6Regex =
    // /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
    const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
    const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    // https://base64.guru/standards/base64url
    const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    // simple
    // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
    // no leap year validation
    // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
    // with leap year validation
    const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
    const dateRegex = new RegExp(`^${dateRegexSource}$`);
    function timeRegexSource(args) {
        let secondsRegexSource = `[0-5]\\d`;
        if (args.precision) {
            secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
        }
        else if (args.precision == null) {
            secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
        }
        const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero
        return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
    }
    function timeRegex(args) {
        return new RegExp(`^${timeRegexSource(args)}$`);
    }
    // Adapted from https://stackoverflow.com/a/3143231
    function datetimeRegex(args) {
        let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
        const opts = [];
        opts.push(args.local ? `Z?` : `Z`);
        if (args.offset)
            opts.push(`([+-]\\d{2}:?\\d{2})`);
        regex = `${regex}(${opts.join("|")})`;
        return new RegExp(`^${regex}$`);
    }
    function isValidIP(ip, version) {
        if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
            return true;
        }
        if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
            return true;
        }
        return false;
    }
    function isValidJWT(jwt, alg) {
        if (!jwtRegex.test(jwt))
            return false;
        try {
            const [header] = jwt.split(".");
            if (!header)
                return false;
            // Convert base64url to base64
            const base64 = header
                .replace(/-/g, "+")
                .replace(/_/g, "/")
                .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
            const decoded = JSON.parse(atob(base64));
            if (typeof decoded !== "object" || decoded === null)
                return false;
            if ("typ" in decoded && decoded?.typ !== "JWT")
                return false;
            if (!decoded.alg)
                return false;
            if (alg && decoded.alg !== alg)
                return false;
            return true;
        }
        catch {
            return false;
        }
    }
    function isValidCidr(ip, version) {
        if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
            return true;
        }
        if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
            return true;
        }
        return false;
    }
    class ZodString extends ZodType {
        _parse(input) {
            if (this._def.coerce) {
                input.data = String(input.data);
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.string) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.string,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            const status = new ParseStatus();
            let ctx = undefined;
            for (const check of this._def.checks) {
                if (check.kind === "min") {
                    if (input.data.length < check.value) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_small,
                            minimum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: false,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "max") {
                    if (input.data.length > check.value) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_big,
                            maximum: check.value,
                            type: "string",
                            inclusive: true,
                            exact: false,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "length") {
                    const tooBig = input.data.length > check.value;
                    const tooSmall = input.data.length < check.value;
                    if (tooBig || tooSmall) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        if (tooBig) {
                            addIssueToContext(ctx, {
                                code: ZodIssueCode.too_big,
                                maximum: check.value,
                                type: "string",
                                inclusive: true,
                                exact: true,
                                message: check.message,
                            });
                        }
                        else if (tooSmall) {
                            addIssueToContext(ctx, {
                                code: ZodIssueCode.too_small,
                                minimum: check.value,
                                type: "string",
                                inclusive: true,
                                exact: true,
                                message: check.message,
                            });
                        }
                        status.dirty();
                    }
                }
                else if (check.kind === "email") {
                    if (!emailRegex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "email",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "emoji") {
                    if (!emojiRegex) {
                        emojiRegex = new RegExp(_emojiRegex, "u");
                    }
                    if (!emojiRegex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "emoji",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "uuid") {
                    if (!uuidRegex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "uuid",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "nanoid") {
                    if (!nanoidRegex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "nanoid",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "cuid") {
                    if (!cuidRegex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "cuid",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "cuid2") {
                    if (!cuid2Regex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "cuid2",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "ulid") {
                    if (!ulidRegex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "ulid",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "url") {
                    try {
                        new URL(input.data);
                    }
                    catch {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "url",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "regex") {
                    check.regex.lastIndex = 0;
                    const testResult = check.regex.test(input.data);
                    if (!testResult) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "regex",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "trim") {
                    input.data = input.data.trim();
                }
                else if (check.kind === "includes") {
                    if (!input.data.includes(check.value, check.position)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.invalid_string,
                            validation: { includes: check.value, position: check.position },
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "toLowerCase") {
                    input.data = input.data.toLowerCase();
                }
                else if (check.kind === "toUpperCase") {
                    input.data = input.data.toUpperCase();
                }
                else if (check.kind === "startsWith") {
                    if (!input.data.startsWith(check.value)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.invalid_string,
                            validation: { startsWith: check.value },
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "endsWith") {
                    if (!input.data.endsWith(check.value)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.invalid_string,
                            validation: { endsWith: check.value },
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "datetime") {
                    const regex = datetimeRegex(check);
                    if (!regex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.invalid_string,
                            validation: "datetime",
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "date") {
                    const regex = dateRegex;
                    if (!regex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.invalid_string,
                            validation: "date",
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "time") {
                    const regex = timeRegex(check);
                    if (!regex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.invalid_string,
                            validation: "time",
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "duration") {
                    if (!durationRegex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "duration",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "ip") {
                    if (!isValidIP(input.data, check.version)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "ip",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "jwt") {
                    if (!isValidJWT(input.data, check.alg)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "jwt",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "cidr") {
                    if (!isValidCidr(input.data, check.version)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "cidr",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "base64") {
                    if (!base64Regex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "base64",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "base64url") {
                    if (!base64urlRegex.test(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            validation: "base64url",
                            code: ZodIssueCode.invalid_string,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else {
                    util.assertNever(check);
                }
            }
            return { status: status.value, value: input.data };
        }
        _regex(regex, validation, message) {
            return this.refinement((data) => regex.test(data), {
                validation,
                code: ZodIssueCode.invalid_string,
                ...errorUtil.errToObj(message),
            });
        }
        _addCheck(check) {
            return new ZodString({
                ...this._def,
                checks: [...this._def.checks, check],
            });
        }
        email(message) {
            return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
        }
        url(message) {
            return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
        }
        emoji(message) {
            return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
        }
        uuid(message) {
            return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
        }
        nanoid(message) {
            return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
        }
        cuid(message) {
            return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
        }
        cuid2(message) {
            return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
        }
        ulid(message) {
            return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
        }
        base64(message) {
            return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
        }
        base64url(message) {
            // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
            return this._addCheck({
                kind: "base64url",
                ...errorUtil.errToObj(message),
            });
        }
        jwt(options) {
            return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
        }
        ip(options) {
            return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
        }
        cidr(options) {
            return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
        }
        datetime(options) {
            if (typeof options === "string") {
                return this._addCheck({
                    kind: "datetime",
                    precision: null,
                    offset: false,
                    local: false,
                    message: options,
                });
            }
            return this._addCheck({
                kind: "datetime",
                precision: typeof options?.precision === "undefined" ? null : options?.precision,
                offset: options?.offset ?? false,
                local: options?.local ?? false,
                ...errorUtil.errToObj(options?.message),
            });
        }
        date(message) {
            return this._addCheck({ kind: "date", message });
        }
        time(options) {
            if (typeof options === "string") {
                return this._addCheck({
                    kind: "time",
                    precision: null,
                    message: options,
                });
            }
            return this._addCheck({
                kind: "time",
                precision: typeof options?.precision === "undefined" ? null : options?.precision,
                ...errorUtil.errToObj(options?.message),
            });
        }
        duration(message) {
            return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
        }
        regex(regex, message) {
            return this._addCheck({
                kind: "regex",
                regex: regex,
                ...errorUtil.errToObj(message),
            });
        }
        includes(value, options) {
            return this._addCheck({
                kind: "includes",
                value: value,
                position: options?.position,
                ...errorUtil.errToObj(options?.message),
            });
        }
        startsWith(value, message) {
            return this._addCheck({
                kind: "startsWith",
                value: value,
                ...errorUtil.errToObj(message),
            });
        }
        endsWith(value, message) {
            return this._addCheck({
                kind: "endsWith",
                value: value,
                ...errorUtil.errToObj(message),
            });
        }
        min(minLength, message) {
            return this._addCheck({
                kind: "min",
                value: minLength,
                ...errorUtil.errToObj(message),
            });
        }
        max(maxLength, message) {
            return this._addCheck({
                kind: "max",
                value: maxLength,
                ...errorUtil.errToObj(message),
            });
        }
        length(len, message) {
            return this._addCheck({
                kind: "length",
                value: len,
                ...errorUtil.errToObj(message),
            });
        }
        /**
         * Equivalent to `.min(1)`
         */
        nonempty(message) {
            return this.min(1, errorUtil.errToObj(message));
        }
        trim() {
            return new ZodString({
                ...this._def,
                checks: [...this._def.checks, { kind: "trim" }],
            });
        }
        toLowerCase() {
            return new ZodString({
                ...this._def,
                checks: [...this._def.checks, { kind: "toLowerCase" }],
            });
        }
        toUpperCase() {
            return new ZodString({
                ...this._def,
                checks: [...this._def.checks, { kind: "toUpperCase" }],
            });
        }
        get isDatetime() {
            return !!this._def.checks.find((ch) => ch.kind === "datetime");
        }
        get isDate() {
            return !!this._def.checks.find((ch) => ch.kind === "date");
        }
        get isTime() {
            return !!this._def.checks.find((ch) => ch.kind === "time");
        }
        get isDuration() {
            return !!this._def.checks.find((ch) => ch.kind === "duration");
        }
        get isEmail() {
            return !!this._def.checks.find((ch) => ch.kind === "email");
        }
        get isURL() {
            return !!this._def.checks.find((ch) => ch.kind === "url");
        }
        get isEmoji() {
            return !!this._def.checks.find((ch) => ch.kind === "emoji");
        }
        get isUUID() {
            return !!this._def.checks.find((ch) => ch.kind === "uuid");
        }
        get isNANOID() {
            return !!this._def.checks.find((ch) => ch.kind === "nanoid");
        }
        get isCUID() {
            return !!this._def.checks.find((ch) => ch.kind === "cuid");
        }
        get isCUID2() {
            return !!this._def.checks.find((ch) => ch.kind === "cuid2");
        }
        get isULID() {
            return !!this._def.checks.find((ch) => ch.kind === "ulid");
        }
        get isIP() {
            return !!this._def.checks.find((ch) => ch.kind === "ip");
        }
        get isCIDR() {
            return !!this._def.checks.find((ch) => ch.kind === "cidr");
        }
        get isBase64() {
            return !!this._def.checks.find((ch) => ch.kind === "base64");
        }
        get isBase64url() {
            // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
            return !!this._def.checks.find((ch) => ch.kind === "base64url");
        }
        get minLength() {
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
            }
            return min;
        }
        get maxLength() {
            let max = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return max;
        }
    }
    ZodString.create = (params) => {
        return new ZodString({
            checks: [],
            typeName: ZodFirstPartyTypeKind.ZodString,
            coerce: params?.coerce ?? false,
            ...processCreateParams(params),
        });
    };
    // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
    function floatSafeRemainder(val, step) {
        const valDecCount = (val.toString().split(".")[1] || "").length;
        const stepDecCount = (step.toString().split(".")[1] || "").length;
        const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
        const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
        const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
        return (valInt % stepInt) / 10 ** decCount;
    }
    class ZodNumber extends ZodType {
        constructor() {
            super(...arguments);
            this.min = this.gte;
            this.max = this.lte;
            this.step = this.multipleOf;
        }
        _parse(input) {
            if (this._def.coerce) {
                input.data = Number(input.data);
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.number) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.number,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            let ctx = undefined;
            const status = new ParseStatus();
            for (const check of this._def.checks) {
                if (check.kind === "int") {
                    if (!util.isInteger(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.invalid_type,
                            expected: "integer",
                            received: "float",
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "min") {
                    const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
                    if (tooSmall) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_small,
                            minimum: check.value,
                            type: "number",
                            inclusive: check.inclusive,
                            exact: false,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "max") {
                    const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
                    if (tooBig) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_big,
                            maximum: check.value,
                            type: "number",
                            inclusive: check.inclusive,
                            exact: false,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "multipleOf") {
                    if (floatSafeRemainder(input.data, check.value) !== 0) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.not_multiple_of,
                            multipleOf: check.value,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "finite") {
                    if (!Number.isFinite(input.data)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.not_finite,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else {
                    util.assertNever(check);
                }
            }
            return { status: status.value, value: input.data };
        }
        gte(value, message) {
            return this.setLimit("min", value, true, errorUtil.toString(message));
        }
        gt(value, message) {
            return this.setLimit("min", value, false, errorUtil.toString(message));
        }
        lte(value, message) {
            return this.setLimit("max", value, true, errorUtil.toString(message));
        }
        lt(value, message) {
            return this.setLimit("max", value, false, errorUtil.toString(message));
        }
        setLimit(kind, value, inclusive, message) {
            return new ZodNumber({
                ...this._def,
                checks: [
                    ...this._def.checks,
                    {
                        kind,
                        value,
                        inclusive,
                        message: errorUtil.toString(message),
                    },
                ],
            });
        }
        _addCheck(check) {
            return new ZodNumber({
                ...this._def,
                checks: [...this._def.checks, check],
            });
        }
        int(message) {
            return this._addCheck({
                kind: "int",
                message: errorUtil.toString(message),
            });
        }
        positive(message) {
            return this._addCheck({
                kind: "min",
                value: 0,
                inclusive: false,
                message: errorUtil.toString(message),
            });
        }
        negative(message) {
            return this._addCheck({
                kind: "max",
                value: 0,
                inclusive: false,
                message: errorUtil.toString(message),
            });
        }
        nonpositive(message) {
            return this._addCheck({
                kind: "max",
                value: 0,
                inclusive: true,
                message: errorUtil.toString(message),
            });
        }
        nonnegative(message) {
            return this._addCheck({
                kind: "min",
                value: 0,
                inclusive: true,
                message: errorUtil.toString(message),
            });
        }
        multipleOf(value, message) {
            return this._addCheck({
                kind: "multipleOf",
                value: value,
                message: errorUtil.toString(message),
            });
        }
        finite(message) {
            return this._addCheck({
                kind: "finite",
                message: errorUtil.toString(message),
            });
        }
        safe(message) {
            return this._addCheck({
                kind: "min",
                inclusive: true,
                value: Number.MIN_SAFE_INTEGER,
                message: errorUtil.toString(message),
            })._addCheck({
                kind: "max",
                inclusive: true,
                value: Number.MAX_SAFE_INTEGER,
                message: errorUtil.toString(message),
            });
        }
        get minValue() {
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
            }
            return min;
        }
        get maxValue() {
            let max = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return max;
        }
        get isInt() {
            return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value)));
        }
        get isFinite() {
            let max = null;
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
                    return true;
                }
                else if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
                else if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return Number.isFinite(min) && Number.isFinite(max);
        }
    }
    ZodNumber.create = (params) => {
        return new ZodNumber({
            checks: [],
            typeName: ZodFirstPartyTypeKind.ZodNumber,
            coerce: params?.coerce || false,
            ...processCreateParams(params),
        });
    };
    class ZodBigInt extends ZodType {
        constructor() {
            super(...arguments);
            this.min = this.gte;
            this.max = this.lte;
        }
        _parse(input) {
            if (this._def.coerce) {
                try {
                    input.data = BigInt(input.data);
                }
                catch {
                    return this._getInvalidInput(input);
                }
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.bigint) {
                return this._getInvalidInput(input);
            }
            let ctx = undefined;
            const status = new ParseStatus();
            for (const check of this._def.checks) {
                if (check.kind === "min") {
                    const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
                    if (tooSmall) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_small,
                            type: "bigint",
                            minimum: check.value,
                            inclusive: check.inclusive,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "max") {
                    const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
                    if (tooBig) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_big,
                            type: "bigint",
                            maximum: check.value,
                            inclusive: check.inclusive,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "multipleOf") {
                    if (input.data % check.value !== BigInt(0)) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.not_multiple_of,
                            multipleOf: check.value,
                            message: check.message,
                        });
                        status.dirty();
                    }
                }
                else {
                    util.assertNever(check);
                }
            }
            return { status: status.value, value: input.data };
        }
        _getInvalidInput(input) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.bigint,
                received: ctx.parsedType,
            });
            return INVALID;
        }
        gte(value, message) {
            return this.setLimit("min", value, true, errorUtil.toString(message));
        }
        gt(value, message) {
            return this.setLimit("min", value, false, errorUtil.toString(message));
        }
        lte(value, message) {
            return this.setLimit("max", value, true, errorUtil.toString(message));
        }
        lt(value, message) {
            return this.setLimit("max", value, false, errorUtil.toString(message));
        }
        setLimit(kind, value, inclusive, message) {
            return new ZodBigInt({
                ...this._def,
                checks: [
                    ...this._def.checks,
                    {
                        kind,
                        value,
                        inclusive,
                        message: errorUtil.toString(message),
                    },
                ],
            });
        }
        _addCheck(check) {
            return new ZodBigInt({
                ...this._def,
                checks: [...this._def.checks, check],
            });
        }
        positive(message) {
            return this._addCheck({
                kind: "min",
                value: BigInt(0),
                inclusive: false,
                message: errorUtil.toString(message),
            });
        }
        negative(message) {
            return this._addCheck({
                kind: "max",
                value: BigInt(0),
                inclusive: false,
                message: errorUtil.toString(message),
            });
        }
        nonpositive(message) {
            return this._addCheck({
                kind: "max",
                value: BigInt(0),
                inclusive: true,
                message: errorUtil.toString(message),
            });
        }
        nonnegative(message) {
            return this._addCheck({
                kind: "min",
                value: BigInt(0),
                inclusive: true,
                message: errorUtil.toString(message),
            });
        }
        multipleOf(value, message) {
            return this._addCheck({
                kind: "multipleOf",
                value,
                message: errorUtil.toString(message),
            });
        }
        get minValue() {
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
            }
            return min;
        }
        get maxValue() {
            let max = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return max;
        }
    }
    ZodBigInt.create = (params) => {
        return new ZodBigInt({
            checks: [],
            typeName: ZodFirstPartyTypeKind.ZodBigInt,
            coerce: params?.coerce ?? false,
            ...processCreateParams(params),
        });
    };
    class ZodBoolean extends ZodType {
        _parse(input) {
            if (this._def.coerce) {
                input.data = Boolean(input.data);
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.boolean) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.boolean,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            return OK(input.data);
        }
    }
    ZodBoolean.create = (params) => {
        return new ZodBoolean({
            typeName: ZodFirstPartyTypeKind.ZodBoolean,
            coerce: params?.coerce || false,
            ...processCreateParams(params),
        });
    };
    class ZodDate extends ZodType {
        _parse(input) {
            if (this._def.coerce) {
                input.data = new Date(input.data);
            }
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.date) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.date,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            if (Number.isNaN(input.data.getTime())) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_date,
                });
                return INVALID;
            }
            const status = new ParseStatus();
            let ctx = undefined;
            for (const check of this._def.checks) {
                if (check.kind === "min") {
                    if (input.data.getTime() < check.value) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_small,
                            message: check.message,
                            inclusive: true,
                            exact: false,
                            minimum: check.value,
                            type: "date",
                        });
                        status.dirty();
                    }
                }
                else if (check.kind === "max") {
                    if (input.data.getTime() > check.value) {
                        ctx = this._getOrReturnCtx(input, ctx);
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.too_big,
                            message: check.message,
                            inclusive: true,
                            exact: false,
                            maximum: check.value,
                            type: "date",
                        });
                        status.dirty();
                    }
                }
                else {
                    util.assertNever(check);
                }
            }
            return {
                status: status.value,
                value: new Date(input.data.getTime()),
            };
        }
        _addCheck(check) {
            return new ZodDate({
                ...this._def,
                checks: [...this._def.checks, check],
            });
        }
        min(minDate, message) {
            return this._addCheck({
                kind: "min",
                value: minDate.getTime(),
                message: errorUtil.toString(message),
            });
        }
        max(maxDate, message) {
            return this._addCheck({
                kind: "max",
                value: maxDate.getTime(),
                message: errorUtil.toString(message),
            });
        }
        get minDate() {
            let min = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "min") {
                    if (min === null || ch.value > min)
                        min = ch.value;
                }
            }
            return min != null ? new Date(min) : null;
        }
        get maxDate() {
            let max = null;
            for (const ch of this._def.checks) {
                if (ch.kind === "max") {
                    if (max === null || ch.value < max)
                        max = ch.value;
                }
            }
            return max != null ? new Date(max) : null;
        }
    }
    ZodDate.create = (params) => {
        return new ZodDate({
            checks: [],
            coerce: params?.coerce || false,
            typeName: ZodFirstPartyTypeKind.ZodDate,
            ...processCreateParams(params),
        });
    };
    class ZodSymbol extends ZodType {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.symbol) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.symbol,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            return OK(input.data);
        }
    }
    ZodSymbol.create = (params) => {
        return new ZodSymbol({
            typeName: ZodFirstPartyTypeKind.ZodSymbol,
            ...processCreateParams(params),
        });
    };
    class ZodUndefined extends ZodType {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.undefined) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.undefined,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            return OK(input.data);
        }
    }
    ZodUndefined.create = (params) => {
        return new ZodUndefined({
            typeName: ZodFirstPartyTypeKind.ZodUndefined,
            ...processCreateParams(params),
        });
    };
    class ZodNull extends ZodType {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.null) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.null,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            return OK(input.data);
        }
    }
    ZodNull.create = (params) => {
        return new ZodNull({
            typeName: ZodFirstPartyTypeKind.ZodNull,
            ...processCreateParams(params),
        });
    };
    class ZodAny extends ZodType {
        constructor() {
            super(...arguments);
            // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
            this._any = true;
        }
        _parse(input) {
            return OK(input.data);
        }
    }
    ZodAny.create = (params) => {
        return new ZodAny({
            typeName: ZodFirstPartyTypeKind.ZodAny,
            ...processCreateParams(params),
        });
    };
    class ZodUnknown extends ZodType {
        constructor() {
            super(...arguments);
            // required
            this._unknown = true;
        }
        _parse(input) {
            return OK(input.data);
        }
    }
    ZodUnknown.create = (params) => {
        return new ZodUnknown({
            typeName: ZodFirstPartyTypeKind.ZodUnknown,
            ...processCreateParams(params),
        });
    };
    class ZodNever extends ZodType {
        _parse(input) {
            const ctx = this._getOrReturnCtx(input);
            addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: ZodParsedType.never,
                received: ctx.parsedType,
            });
            return INVALID;
        }
    }
    ZodNever.create = (params) => {
        return new ZodNever({
            typeName: ZodFirstPartyTypeKind.ZodNever,
            ...processCreateParams(params),
        });
    };
    class ZodVoid extends ZodType {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.undefined) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.void,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            return OK(input.data);
        }
    }
    ZodVoid.create = (params) => {
        return new ZodVoid({
            typeName: ZodFirstPartyTypeKind.ZodVoid,
            ...processCreateParams(params),
        });
    };
    class ZodArray extends ZodType {
        _parse(input) {
            const { ctx, status } = this._processInputParams(input);
            const def = this._def;
            if (ctx.parsedType !== ZodParsedType.array) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.array,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            if (def.exactLength !== null) {
                const tooBig = ctx.data.length > def.exactLength.value;
                const tooSmall = ctx.data.length < def.exactLength.value;
                if (tooBig || tooSmall) {
                    addIssueToContext(ctx, {
                        code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
                        minimum: (tooSmall ? def.exactLength.value : undefined),
                        maximum: (tooBig ? def.exactLength.value : undefined),
                        type: "array",
                        inclusive: true,
                        exact: true,
                        message: def.exactLength.message,
                    });
                    status.dirty();
                }
            }
            if (def.minLength !== null) {
                if (ctx.data.length < def.minLength.value) {
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        minimum: def.minLength.value,
                        type: "array",
                        inclusive: true,
                        exact: false,
                        message: def.minLength.message,
                    });
                    status.dirty();
                }
            }
            if (def.maxLength !== null) {
                if (ctx.data.length > def.maxLength.value) {
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        maximum: def.maxLength.value,
                        type: "array",
                        inclusive: true,
                        exact: false,
                        message: def.maxLength.message,
                    });
                    status.dirty();
                }
            }
            if (ctx.common.async) {
                return Promise.all([...ctx.data].map((item, i) => {
                    return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
                })).then((result) => {
                    return ParseStatus.mergeArray(status, result);
                });
            }
            const result = [...ctx.data].map((item, i) => {
                return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
            });
            return ParseStatus.mergeArray(status, result);
        }
        get element() {
            return this._def.type;
        }
        min(minLength, message) {
            return new ZodArray({
                ...this._def,
                minLength: { value: minLength, message: errorUtil.toString(message) },
            });
        }
        max(maxLength, message) {
            return new ZodArray({
                ...this._def,
                maxLength: { value: maxLength, message: errorUtil.toString(message) },
            });
        }
        length(len, message) {
            return new ZodArray({
                ...this._def,
                exactLength: { value: len, message: errorUtil.toString(message) },
            });
        }
        nonempty(message) {
            return this.min(1, message);
        }
    }
    ZodArray.create = (schema, params) => {
        return new ZodArray({
            type: schema,
            minLength: null,
            maxLength: null,
            exactLength: null,
            typeName: ZodFirstPartyTypeKind.ZodArray,
            ...processCreateParams(params),
        });
    };
    function deepPartialify(schema) {
        if (schema instanceof ZodObject) {
            const newShape = {};
            for (const key in schema.shape) {
                const fieldSchema = schema.shape[key];
                newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
            }
            return new ZodObject({
                ...schema._def,
                shape: () => newShape,
            });
        }
        else if (schema instanceof ZodArray) {
            return new ZodArray({
                ...schema._def,
                type: deepPartialify(schema.element),
            });
        }
        else if (schema instanceof ZodOptional) {
            return ZodOptional.create(deepPartialify(schema.unwrap()));
        }
        else if (schema instanceof ZodNullable) {
            return ZodNullable.create(deepPartialify(schema.unwrap()));
        }
        else if (schema instanceof ZodTuple) {
            return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
        }
        else {
            return schema;
        }
    }
    class ZodObject extends ZodType {
        constructor() {
            super(...arguments);
            this._cached = null;
            /**
             * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
             * If you want to pass through unknown properties, use `.passthrough()` instead.
             */
            this.nonstrict = this.passthrough;
            // extend<
            //   Augmentation extends ZodRawShape,
            //   NewOutput extends util.flatten<{
            //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
            //       ? Augmentation[k]["_output"]
            //       : k extends keyof Output
            //       ? Output[k]
            //       : never;
            //   }>,
            //   NewInput extends util.flatten<{
            //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
            //       ? Augmentation[k]["_input"]
            //       : k extends keyof Input
            //       ? Input[k]
            //       : never;
            //   }>
            // >(
            //   augmentation: Augmentation
            // ): ZodObject<
            //   extendShape<T, Augmentation>,
            //   UnknownKeys,
            //   Catchall,
            //   NewOutput,
            //   NewInput
            // > {
            //   return new ZodObject({
            //     ...this._def,
            //     shape: () => ({
            //       ...this._def.shape(),
            //       ...augmentation,
            //     }),
            //   }) as any;
            // }
            /**
             * @deprecated Use `.extend` instead
             *  */
            this.augment = this.extend;
        }
        _getCached() {
            if (this._cached !== null)
                return this._cached;
            const shape = this._def.shape();
            const keys = util.objectKeys(shape);
            this._cached = { shape, keys };
            return this._cached;
        }
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.object) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.object,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            const { status, ctx } = this._processInputParams(input);
            const { shape, keys: shapeKeys } = this._getCached();
            const extraKeys = [];
            if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
                for (const key in ctx.data) {
                    if (!shapeKeys.includes(key)) {
                        extraKeys.push(key);
                    }
                }
            }
            const pairs = [];
            for (const key of shapeKeys) {
                const keyValidator = shape[key];
                const value = ctx.data[key];
                pairs.push({
                    key: { status: "valid", value: key },
                    value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
                    alwaysSet: key in ctx.data,
                });
            }
            if (this._def.catchall instanceof ZodNever) {
                const unknownKeys = this._def.unknownKeys;
                if (unknownKeys === "passthrough") {
                    for (const key of extraKeys) {
                        pairs.push({
                            key: { status: "valid", value: key },
                            value: { status: "valid", value: ctx.data[key] },
                        });
                    }
                }
                else if (unknownKeys === "strict") {
                    if (extraKeys.length > 0) {
                        addIssueToContext(ctx, {
                            code: ZodIssueCode.unrecognized_keys,
                            keys: extraKeys,
                        });
                        status.dirty();
                    }
                }
                else if (unknownKeys === "strip") ;
                else {
                    throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
                }
            }
            else {
                // run catchall validation
                const catchall = this._def.catchall;
                for (const key of extraKeys) {
                    const value = ctx.data[key];
                    pairs.push({
                        key: { status: "valid", value: key },
                        value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
                        ),
                        alwaysSet: key in ctx.data,
                    });
                }
            }
            if (ctx.common.async) {
                return Promise.resolve()
                    .then(async () => {
                    const syncPairs = [];
                    for (const pair of pairs) {
                        const key = await pair.key;
                        const value = await pair.value;
                        syncPairs.push({
                            key,
                            value,
                            alwaysSet: pair.alwaysSet,
                        });
                    }
                    return syncPairs;
                })
                    .then((syncPairs) => {
                    return ParseStatus.mergeObjectSync(status, syncPairs);
                });
            }
            else {
                return ParseStatus.mergeObjectSync(status, pairs);
            }
        }
        get shape() {
            return this._def.shape();
        }
        strict(message) {
            errorUtil.errToObj;
            return new ZodObject({
                ...this._def,
                unknownKeys: "strict",
                ...(message !== undefined
                    ? {
                        errorMap: (issue, ctx) => {
                            const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
                            if (issue.code === "unrecognized_keys")
                                return {
                                    message: errorUtil.errToObj(message).message ?? defaultError,
                                };
                            return {
                                message: defaultError,
                            };
                        },
                    }
                    : {}),
            });
        }
        strip() {
            return new ZodObject({
                ...this._def,
                unknownKeys: "strip",
            });
        }
        passthrough() {
            return new ZodObject({
                ...this._def,
                unknownKeys: "passthrough",
            });
        }
        // const AugmentFactory =
        //   <Def extends ZodObjectDef>(def: Def) =>
        //   <Augmentation extends ZodRawShape>(
        //     augmentation: Augmentation
        //   ): ZodObject<
        //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
        //     Def["unknownKeys"],
        //     Def["catchall"]
        //   > => {
        //     return new ZodObject({
        //       ...def,
        //       shape: () => ({
        //         ...def.shape(),
        //         ...augmentation,
        //       }),
        //     }) as any;
        //   };
        extend(augmentation) {
            return new ZodObject({
                ...this._def,
                shape: () => ({
                    ...this._def.shape(),
                    ...augmentation,
                }),
            });
        }
        /**
         * Prior to zod@1.0.12 there was a bug in the
         * inferred type of merged objects. Please
         * upgrade if you are experiencing issues.
         */
        merge(merging) {
            const merged = new ZodObject({
                unknownKeys: merging._def.unknownKeys,
                catchall: merging._def.catchall,
                shape: () => ({
                    ...this._def.shape(),
                    ...merging._def.shape(),
                }),
                typeName: ZodFirstPartyTypeKind.ZodObject,
            });
            return merged;
        }
        // merge<
        //   Incoming extends AnyZodObject,
        //   Augmentation extends Incoming["shape"],
        //   NewOutput extends {
        //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
        //       ? Augmentation[k]["_output"]
        //       : k extends keyof Output
        //       ? Output[k]
        //       : never;
        //   },
        //   NewInput extends {
        //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
        //       ? Augmentation[k]["_input"]
        //       : k extends keyof Input
        //       ? Input[k]
        //       : never;
        //   }
        // >(
        //   merging: Incoming
        // ): ZodObject<
        //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
        //   Incoming["_def"]["unknownKeys"],
        //   Incoming["_def"]["catchall"],
        //   NewOutput,
        //   NewInput
        // > {
        //   const merged: any = new ZodObject({
        //     unknownKeys: merging._def.unknownKeys,
        //     catchall: merging._def.catchall,
        //     shape: () =>
        //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
        //     typeName: ZodFirstPartyTypeKind.ZodObject,
        //   }) as any;
        //   return merged;
        // }
        setKey(key, schema) {
            return this.augment({ [key]: schema });
        }
        // merge<Incoming extends AnyZodObject>(
        //   merging: Incoming
        // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
        // ZodObject<
        //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
        //   Incoming["_def"]["unknownKeys"],
        //   Incoming["_def"]["catchall"]
        // > {
        //   // const mergedShape = objectUtil.mergeShapes(
        //   //   this._def.shape(),
        //   //   merging._def.shape()
        //   // );
        //   const merged: any = new ZodObject({
        //     unknownKeys: merging._def.unknownKeys,
        //     catchall: merging._def.catchall,
        //     shape: () =>
        //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
        //     typeName: ZodFirstPartyTypeKind.ZodObject,
        //   }) as any;
        //   return merged;
        // }
        catchall(index) {
            return new ZodObject({
                ...this._def,
                catchall: index,
            });
        }
        pick(mask) {
            const shape = {};
            for (const key of util.objectKeys(mask)) {
                if (mask[key] && this.shape[key]) {
                    shape[key] = this.shape[key];
                }
            }
            return new ZodObject({
                ...this._def,
                shape: () => shape,
            });
        }
        omit(mask) {
            const shape = {};
            for (const key of util.objectKeys(this.shape)) {
                if (!mask[key]) {
                    shape[key] = this.shape[key];
                }
            }
            return new ZodObject({
                ...this._def,
                shape: () => shape,
            });
        }
        /**
         * @deprecated
         */
        deepPartial() {
            return deepPartialify(this);
        }
        partial(mask) {
            const newShape = {};
            for (const key of util.objectKeys(this.shape)) {
                const fieldSchema = this.shape[key];
                if (mask && !mask[key]) {
                    newShape[key] = fieldSchema;
                }
                else {
                    newShape[key] = fieldSchema.optional();
                }
            }
            return new ZodObject({
                ...this._def,
                shape: () => newShape,
            });
        }
        required(mask) {
            const newShape = {};
            for (const key of util.objectKeys(this.shape)) {
                if (mask && !mask[key]) {
                    newShape[key] = this.shape[key];
                }
                else {
                    const fieldSchema = this.shape[key];
                    let newField = fieldSchema;
                    while (newField instanceof ZodOptional) {
                        newField = newField._def.innerType;
                    }
                    newShape[key] = newField;
                }
            }
            return new ZodObject({
                ...this._def,
                shape: () => newShape,
            });
        }
        keyof() {
            return createZodEnum(util.objectKeys(this.shape));
        }
    }
    ZodObject.create = (shape, params) => {
        return new ZodObject({
            shape: () => shape,
            unknownKeys: "strip",
            catchall: ZodNever.create(),
            typeName: ZodFirstPartyTypeKind.ZodObject,
            ...processCreateParams(params),
        });
    };
    ZodObject.strictCreate = (shape, params) => {
        return new ZodObject({
            shape: () => shape,
            unknownKeys: "strict",
            catchall: ZodNever.create(),
            typeName: ZodFirstPartyTypeKind.ZodObject,
            ...processCreateParams(params),
        });
    };
    ZodObject.lazycreate = (shape, params) => {
        return new ZodObject({
            shape,
            unknownKeys: "strip",
            catchall: ZodNever.create(),
            typeName: ZodFirstPartyTypeKind.ZodObject,
            ...processCreateParams(params),
        });
    };
    class ZodUnion extends ZodType {
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            const options = this._def.options;
            function handleResults(results) {
                // return first issue-free validation if it exists
                for (const result of results) {
                    if (result.result.status === "valid") {
                        return result.result;
                    }
                }
                for (const result of results) {
                    if (result.result.status === "dirty") {
                        // add issues from dirty option
                        ctx.common.issues.push(...result.ctx.common.issues);
                        return result.result;
                    }
                }
                // return invalid
                const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_union,
                    unionErrors,
                });
                return INVALID;
            }
            if (ctx.common.async) {
                return Promise.all(options.map(async (option) => {
                    const childCtx = {
                        ...ctx,
                        common: {
                            ...ctx.common,
                            issues: [],
                        },
                        parent: null,
                    };
                    return {
                        result: await option._parseAsync({
                            data: ctx.data,
                            path: ctx.path,
                            parent: childCtx,
                        }),
                        ctx: childCtx,
                    };
                })).then(handleResults);
            }
            else {
                let dirty = undefined;
                const issues = [];
                for (const option of options) {
                    const childCtx = {
                        ...ctx,
                        common: {
                            ...ctx.common,
                            issues: [],
                        },
                        parent: null,
                    };
                    const result = option._parseSync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: childCtx,
                    });
                    if (result.status === "valid") {
                        return result;
                    }
                    else if (result.status === "dirty" && !dirty) {
                        dirty = { result, ctx: childCtx };
                    }
                    if (childCtx.common.issues.length) {
                        issues.push(childCtx.common.issues);
                    }
                }
                if (dirty) {
                    ctx.common.issues.push(...dirty.ctx.common.issues);
                    return dirty.result;
                }
                const unionErrors = issues.map((issues) => new ZodError(issues));
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_union,
                    unionErrors,
                });
                return INVALID;
            }
        }
        get options() {
            return this._def.options;
        }
    }
    ZodUnion.create = (types, params) => {
        return new ZodUnion({
            options: types,
            typeName: ZodFirstPartyTypeKind.ZodUnion,
            ...processCreateParams(params),
        });
    };
    function mergeValues(a, b) {
        const aType = getParsedType(a);
        const bType = getParsedType(b);
        if (a === b) {
            return { valid: true, data: a };
        }
        else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
            const bKeys = util.objectKeys(b);
            const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
            const newObj = { ...a, ...b };
            for (const key of sharedKeys) {
                const sharedValue = mergeValues(a[key], b[key]);
                if (!sharedValue.valid) {
                    return { valid: false };
                }
                newObj[key] = sharedValue.data;
            }
            return { valid: true, data: newObj };
        }
        else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
            if (a.length !== b.length) {
                return { valid: false };
            }
            const newArray = [];
            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 };
                }
                newArray.push(sharedValue.data);
            }
            return { valid: true, data: newArray };
        }
        else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
            return { valid: true, data: a };
        }
        else {
            return { valid: false };
        }
    }
    class ZodIntersection extends ZodType {
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            const handleParsed = (parsedLeft, parsedRight) => {
                if (isAborted(parsedLeft) || isAborted(parsedRight)) {
                    return INVALID;
                }
                const merged = mergeValues(parsedLeft.value, parsedRight.value);
                if (!merged.valid) {
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.invalid_intersection_types,
                    });
                    return INVALID;
                }
                if (isDirty(parsedLeft) || isDirty(parsedRight)) {
                    status.dirty();
                }
                return { status: status.value, value: merged.data };
            };
            if (ctx.common.async) {
                return Promise.all([
                    this._def.left._parseAsync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    }),
                    this._def.right._parseAsync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    }),
                ]).then(([left, right]) => handleParsed(left, right));
            }
            else {
                return handleParsed(this._def.left._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }), this._def.right._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                }));
            }
        }
    }
    ZodIntersection.create = (left, right, params) => {
        return new ZodIntersection({
            left: left,
            right: right,
            typeName: ZodFirstPartyTypeKind.ZodIntersection,
            ...processCreateParams(params),
        });
    };
    // type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];
    class ZodTuple extends ZodType {
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            if (ctx.parsedType !== ZodParsedType.array) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.array,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            if (ctx.data.length < this._def.items.length) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_small,
                    minimum: this._def.items.length,
                    inclusive: true,
                    exact: false,
                    type: "array",
                });
                return INVALID;
            }
            const rest = this._def.rest;
            if (!rest && ctx.data.length > this._def.items.length) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.too_big,
                    maximum: this._def.items.length,
                    inclusive: true,
                    exact: false,
                    type: "array",
                });
                status.dirty();
            }
            const items = [...ctx.data]
                .map((item, itemIndex) => {
                const schema = this._def.items[itemIndex] || this._def.rest;
                if (!schema)
                    return null;
                return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
            })
                .filter((x) => !!x); // filter nulls
            if (ctx.common.async) {
                return Promise.all(items).then((results) => {
                    return ParseStatus.mergeArray(status, results);
                });
            }
            else {
                return ParseStatus.mergeArray(status, items);
            }
        }
        get items() {
            return this._def.items;
        }
        rest(rest) {
            return new ZodTuple({
                ...this._def,
                rest,
            });
        }
    }
    ZodTuple.create = (schemas, params) => {
        if (!Array.isArray(schemas)) {
            throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
        }
        return new ZodTuple({
            items: schemas,
            typeName: ZodFirstPartyTypeKind.ZodTuple,
            rest: null,
            ...processCreateParams(params),
        });
    };
    class ZodMap extends ZodType {
        get keySchema() {
            return this._def.keyType;
        }
        get valueSchema() {
            return this._def.valueType;
        }
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            if (ctx.parsedType !== ZodParsedType.map) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.map,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            const keyType = this._def.keyType;
            const valueType = this._def.valueType;
            const pairs = [...ctx.data.entries()].map(([key, value], index) => {
                return {
                    key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
                    value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
                };
            });
            if (ctx.common.async) {
                const finalMap = new Map();
                return Promise.resolve().then(async () => {
                    for (const pair of pairs) {
                        const key = await pair.key;
                        const value = await pair.value;
                        if (key.status === "aborted" || value.status === "aborted") {
                            return INVALID;
                        }
                        if (key.status === "dirty" || value.status === "dirty") {
                            status.dirty();
                        }
                        finalMap.set(key.value, value.value);
                    }
                    return { status: status.value, value: finalMap };
                });
            }
            else {
                const finalMap = new Map();
                for (const pair of pairs) {
                    const key = pair.key;
                    const value = pair.value;
                    if (key.status === "aborted" || value.status === "aborted") {
                        return INVALID;
                    }
                    if (key.status === "dirty" || value.status === "dirty") {
                        status.dirty();
                    }
                    finalMap.set(key.value, value.value);
                }
                return { status: status.value, value: finalMap };
            }
        }
    }
    ZodMap.create = (keyType, valueType, params) => {
        return new ZodMap({
            valueType,
            keyType,
            typeName: ZodFirstPartyTypeKind.ZodMap,
            ...processCreateParams(params),
        });
    };
    class ZodSet extends ZodType {
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            if (ctx.parsedType !== ZodParsedType.set) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.set,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            const def = this._def;
            if (def.minSize !== null) {
                if (ctx.data.size < def.minSize.value) {
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_small,
                        minimum: def.minSize.value,
                        type: "set",
                        inclusive: true,
                        exact: false,
                        message: def.minSize.message,
                    });
                    status.dirty();
                }
            }
            if (def.maxSize !== null) {
                if (ctx.data.size > def.maxSize.value) {
                    addIssueToContext(ctx, {
                        code: ZodIssueCode.too_big,
                        maximum: def.maxSize.value,
                        type: "set",
                        inclusive: true,
                        exact: false,
                        message: def.maxSize.message,
                    });
                    status.dirty();
                }
            }
            const valueType = this._def.valueType;
            function finalizeSet(elements) {
                const parsedSet = new Set();
                for (const element of elements) {
                    if (element.status === "aborted")
                        return INVALID;
                    if (element.status === "dirty")
                        status.dirty();
                    parsedSet.add(element.value);
                }
                return { status: status.value, value: parsedSet };
            }
            const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
            if (ctx.common.async) {
                return Promise.all(elements).then((elements) => finalizeSet(elements));
            }
            else {
                return finalizeSet(elements);
            }
        }
        min(minSize, message) {
            return new ZodSet({
                ...this._def,
                minSize: { value: minSize, message: errorUtil.toString(message) },
            });
        }
        max(maxSize, message) {
            return new ZodSet({
                ...this._def,
                maxSize: { value: maxSize, message: errorUtil.toString(message) },
            });
        }
        size(size, message) {
            return this.min(size, message).max(size, message);
        }
        nonempty(message) {
            return this.min(1, message);
        }
    }
    ZodSet.create = (valueType, params) => {
        return new ZodSet({
            valueType,
            minSize: null,
            maxSize: null,
            typeName: ZodFirstPartyTypeKind.ZodSet,
            ...processCreateParams(params),
        });
    };
    class ZodLazy extends ZodType {
        get schema() {
            return this._def.getter();
        }
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            const lazySchema = this._def.getter();
            return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
        }
    }
    ZodLazy.create = (getter, params) => {
        return new ZodLazy({
            getter: getter,
            typeName: ZodFirstPartyTypeKind.ZodLazy,
            ...processCreateParams(params),
        });
    };
    class ZodLiteral extends ZodType {
        _parse(input) {
            if (input.data !== this._def.value) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    received: ctx.data,
                    code: ZodIssueCode.invalid_literal,
                    expected: this._def.value,
                });
                return INVALID;
            }
            return { status: "valid", value: input.data };
        }
        get value() {
            return this._def.value;
        }
    }
    ZodLiteral.create = (value, params) => {
        return new ZodLiteral({
            value: value,
            typeName: ZodFirstPartyTypeKind.ZodLiteral,
            ...processCreateParams(params),
        });
    };
    function createZodEnum(values, params) {
        return new ZodEnum({
            values,
            typeName: ZodFirstPartyTypeKind.ZodEnum,
            ...processCreateParams(params),
        });
    }
    class ZodEnum extends ZodType {
        _parse(input) {
            if (typeof input.data !== "string") {
                const ctx = this._getOrReturnCtx(input);
                const expectedValues = this._def.values;
                addIssueToContext(ctx, {
                    expected: util.joinValues(expectedValues),
                    received: ctx.parsedType,
                    code: ZodIssueCode.invalid_type,
                });
                return INVALID;
            }
            if (!this._cache) {
                this._cache = new Set(this._def.values);
            }
            if (!this._cache.has(input.data)) {
                const ctx = this._getOrReturnCtx(input);
                const expectedValues = this._def.values;
                addIssueToContext(ctx, {
                    received: ctx.data,
                    code: ZodIssueCode.invalid_enum_value,
                    options: expectedValues,
                });
                return INVALID;
            }
            return OK(input.data);
        }
        get options() {
            return this._def.values;
        }
        get enum() {
            const enumValues = {};
            for (const val of this._def.values) {
                enumValues[val] = val;
            }
            return enumValues;
        }
        get Values() {
            const enumValues = {};
            for (const val of this._def.values) {
                enumValues[val] = val;
            }
            return enumValues;
        }
        get Enum() {
            const enumValues = {};
            for (const val of this._def.values) {
                enumValues[val] = val;
            }
            return enumValues;
        }
        extract(values, newDef = this._def) {
            return ZodEnum.create(values, {
                ...this._def,
                ...newDef,
            });
        }
        exclude(values, newDef = this._def) {
            return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
                ...this._def,
                ...newDef,
            });
        }
    }
    ZodEnum.create = createZodEnum;
    class ZodNativeEnum extends ZodType {
        _parse(input) {
            const nativeEnumValues = util.getValidEnumValues(this._def.values);
            const ctx = this._getOrReturnCtx(input);
            if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
                const expectedValues = util.objectValues(nativeEnumValues);
                addIssueToContext(ctx, {
                    expected: util.joinValues(expectedValues),
                    received: ctx.parsedType,
                    code: ZodIssueCode.invalid_type,
                });
                return INVALID;
            }
            if (!this._cache) {
                this._cache = new Set(util.getValidEnumValues(this._def.values));
            }
            if (!this._cache.has(input.data)) {
                const expectedValues = util.objectValues(nativeEnumValues);
                addIssueToContext(ctx, {
                    received: ctx.data,
                    code: ZodIssueCode.invalid_enum_value,
                    options: expectedValues,
                });
                return INVALID;
            }
            return OK(input.data);
        }
        get enum() {
            return this._def.values;
        }
    }
    ZodNativeEnum.create = (values, params) => {
        return new ZodNativeEnum({
            values: values,
            typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
            ...processCreateParams(params),
        });
    };
    class ZodPromise extends ZodType {
        unwrap() {
            return this._def.type;
        }
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.promise,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
            return OK(promisified.then((data) => {
                return this._def.type.parseAsync(data, {
                    path: ctx.path,
                    errorMap: ctx.common.contextualErrorMap,
                });
            }));
        }
    }
    ZodPromise.create = (schema, params) => {
        return new ZodPromise({
            type: schema,
            typeName: ZodFirstPartyTypeKind.ZodPromise,
            ...processCreateParams(params),
        });
    };
    class ZodEffects extends ZodType {
        innerType() {
            return this._def.schema;
        }
        sourceType() {
            return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
                ? this._def.schema.sourceType()
                : this._def.schema;
        }
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            const effect = this._def.effect || null;
            const checkCtx = {
                addIssue: (arg) => {
                    addIssueToContext(ctx, arg);
                    if (arg.fatal) {
                        status.abort();
                    }
                    else {
                        status.dirty();
                    }
                },
                get path() {
                    return ctx.path;
                },
            };
            checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
            if (effect.type === "preprocess") {
                const processed = effect.transform(ctx.data, checkCtx);
                if (ctx.common.async) {
                    return Promise.resolve(processed).then(async (processed) => {
                        if (status.value === "aborted")
                            return INVALID;
                        const result = await this._def.schema._parseAsync({
                            data: processed,
                            path: ctx.path,
                            parent: ctx,
                        });
                        if (result.status === "aborted")
                            return INVALID;
                        if (result.status === "dirty")
                            return DIRTY(result.value);
                        if (status.value === "dirty")
                            return DIRTY(result.value);
                        return result;
                    });
                }
                else {
                    if (status.value === "aborted")
                        return INVALID;
                    const result = this._def.schema._parseSync({
                        data: processed,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (result.status === "aborted")
                        return INVALID;
                    if (result.status === "dirty")
                        return DIRTY(result.value);
                    if (status.value === "dirty")
                        return DIRTY(result.value);
                    return result;
                }
            }
            if (effect.type === "refinement") {
                const executeRefinement = (acc) => {
                    const result = effect.refinement(acc, checkCtx);
                    if (ctx.common.async) {
                        return Promise.resolve(result);
                    }
                    if (result instanceof Promise) {
                        throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
                    }
                    return acc;
                };
                if (ctx.common.async === false) {
                    const inner = this._def.schema._parseSync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (inner.status === "aborted")
                        return INVALID;
                    if (inner.status === "dirty")
                        status.dirty();
                    // return value is ignored
                    executeRefinement(inner.value);
                    return { status: status.value, value: inner.value };
                }
                else {
                    return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
                        if (inner.status === "aborted")
                            return INVALID;
                        if (inner.status === "dirty")
                            status.dirty();
                        return executeRefinement(inner.value).then(() => {
                            return { status: status.value, value: inner.value };
                        });
                    });
                }
            }
            if (effect.type === "transform") {
                if (ctx.common.async === false) {
                    const base = this._def.schema._parseSync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (!isValid(base))
                        return INVALID;
                    const result = effect.transform(base.value, checkCtx);
                    if (result instanceof Promise) {
                        throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
                    }
                    return { status: status.value, value: result };
                }
                else {
                    return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
                        if (!isValid(base))
                            return INVALID;
                        return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
                            status: status.value,
                            value: result,
                        }));
                    });
                }
            }
            util.assertNever(effect);
        }
    }
    ZodEffects.create = (schema, effect, params) => {
        return new ZodEffects({
            schema,
            typeName: ZodFirstPartyTypeKind.ZodEffects,
            effect,
            ...processCreateParams(params),
        });
    };
    ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
        return new ZodEffects({
            schema,
            effect: { type: "preprocess", transform: preprocess },
            typeName: ZodFirstPartyTypeKind.ZodEffects,
            ...processCreateParams(params),
        });
    };
    class ZodOptional extends ZodType {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType === ZodParsedType.undefined) {
                return OK(undefined);
            }
            return this._def.innerType._parse(input);
        }
        unwrap() {
            return this._def.innerType;
        }
    }
    ZodOptional.create = (type, params) => {
        return new ZodOptional({
            innerType: type,
            typeName: ZodFirstPartyTypeKind.ZodOptional,
            ...processCreateParams(params),
        });
    };
    class ZodNullable extends ZodType {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType === ZodParsedType.null) {
                return OK(null);
            }
            return this._def.innerType._parse(input);
        }
        unwrap() {
            return this._def.innerType;
        }
    }
    ZodNullable.create = (type, params) => {
        return new ZodNullable({
            innerType: type,
            typeName: ZodFirstPartyTypeKind.ZodNullable,
            ...processCreateParams(params),
        });
    };
    class ZodDefault extends ZodType {
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            let data = ctx.data;
            if (ctx.parsedType === ZodParsedType.undefined) {
                data = this._def.defaultValue();
            }
            return this._def.innerType._parse({
                data,
                path: ctx.path,
                parent: ctx,
            });
        }
        removeDefault() {
            return this._def.innerType;
        }
    }
    ZodDefault.create = (type, params) => {
        return new ZodDefault({
            innerType: type,
            typeName: ZodFirstPartyTypeKind.ZodDefault,
            defaultValue: typeof params.default === "function" ? params.default : () => params.default,
            ...processCreateParams(params),
        });
    };
    class ZodCatch extends ZodType {
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            // newCtx is used to not collect issues from inner types in ctx
            const newCtx = {
                ...ctx,
                common: {
                    ...ctx.common,
                    issues: [],
                },
            };
            const result = this._def.innerType._parse({
                data: newCtx.data,
                path: newCtx.path,
                parent: {
                    ...newCtx,
                },
            });
            if (isAsync(result)) {
                return result.then((result) => {
                    return {
                        status: "valid",
                        value: result.status === "valid"
                            ? result.value
                            : this._def.catchValue({
                                get error() {
                                    return new ZodError(newCtx.common.issues);
                                },
                                input: newCtx.data,
                            }),
                    };
                });
            }
            else {
                return {
                    status: "valid",
                    value: result.status === "valid"
                        ? result.value
                        : this._def.catchValue({
                            get error() {
                                return new ZodError(newCtx.common.issues);
                            },
                            input: newCtx.data,
                        }),
                };
            }
        }
        removeCatch() {
            return this._def.innerType;
        }
    }
    ZodCatch.create = (type, params) => {
        return new ZodCatch({
            innerType: type,
            typeName: ZodFirstPartyTypeKind.ZodCatch,
            catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
            ...processCreateParams(params),
        });
    };
    class ZodNaN extends ZodType {
        _parse(input) {
            const parsedType = this._getType(input);
            if (parsedType !== ZodParsedType.nan) {
                const ctx = this._getOrReturnCtx(input);
                addIssueToContext(ctx, {
                    code: ZodIssueCode.invalid_type,
                    expected: ZodParsedType.nan,
                    received: ctx.parsedType,
                });
                return INVALID;
            }
            return { status: "valid", value: input.data };
        }
    }
    ZodNaN.create = (params) => {
        return new ZodNaN({
            typeName: ZodFirstPartyTypeKind.ZodNaN,
            ...processCreateParams(params),
        });
    };
    class ZodBranded extends ZodType {
        _parse(input) {
            const { ctx } = this._processInputParams(input);
            const data = ctx.data;
            return this._def.type._parse({
                data,
                path: ctx.path,
                parent: ctx,
            });
        }
        unwrap() {
            return this._def.type;
        }
    }
    class ZodPipeline extends ZodType {
        _parse(input) {
            const { status, ctx } = this._processInputParams(input);
            if (ctx.common.async) {
                const handleAsync = async () => {
                    const inResult = await this._def.in._parseAsync({
                        data: ctx.data,
                        path: ctx.path,
                        parent: ctx,
                    });
                    if (inResult.status === "aborted")
                        return INVALID;
                    if (inResult.status === "dirty") {
                        status.dirty();
                        return DIRTY(inResult.value);
                    }
                    else {
                        return this._def.out._parseAsync({
                            data: inResult.value,
                            path: ctx.path,
                            parent: ctx,
                        });
                    }
                };
                return handleAsync();
            }
            else {
                const inResult = this._def.in._parseSync({
                    data: ctx.data,
                    path: ctx.path,
                    parent: ctx,
                });
                if (inResult.status === "aborted")
                    return INVALID;
                if (inResult.status === "dirty") {
                    status.dirty();
                    return {
                        status: "dirty",
                        value: inResult.value,
                    };
                }
                else {
                    return this._def.out._parseSync({
                        data: inResult.value,
                        path: ctx.path,
                        parent: ctx,
                    });
                }
            }
        }
        static create(a, b) {
            return new ZodPipeline({
                in: a,
                out: b,
                typeName: ZodFirstPartyTypeKind.ZodPipeline,
            });
        }
    }
    class ZodReadonly extends ZodType {
        _parse(input) {
            const result = this._def.innerType._parse(input);
            const freeze = (data) => {
                if (isValid(data)) {
                    data.value = Object.freeze(data.value);
                }
                return data;
            };
            return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
        }
        unwrap() {
            return this._def.innerType;
        }
    }
    ZodReadonly.create = (type, params) => {
        return new ZodReadonly({
            innerType: type,
            typeName: ZodFirstPartyTypeKind.ZodReadonly,
            ...processCreateParams(params),
        });
    };
    var ZodFirstPartyTypeKind;
    (function (ZodFirstPartyTypeKind) {
        ZodFirstPartyTypeKind["ZodString"] = "ZodString";
        ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
        ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
        ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
        ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
        ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
        ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
        ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
        ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
        ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
        ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
        ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
        ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
        ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
        ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
        ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
        ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
        ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
        ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
        ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
        ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
        ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
        ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
        ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
        ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
        ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
        ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
        ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
        ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
        ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
        ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
        ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
        ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
        ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
        ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
        ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
    const stringType = ZodString.create;
    const numberType = ZodNumber.create;
    const booleanType = ZodBoolean.create;
    ZodNever.create;
    const arrayType = ZodArray.create;
    const objectType = ZodObject.create;
    const unionType = ZodUnion.create;
    ZodIntersection.create;
    ZodTuple.create;
    const literalType = ZodLiteral.create;
    const enumType = ZodEnum.create;
    ZodPromise.create;
    ZodOptional.create;
    ZodNullable.create;

    const PlanCodeSchema = enumType(["single_box", "premium", "family"]);
    const FeatureFlagsSchema = objectType({
        baseAiScoring: booleanType(),
        deepScan: booleanType(),
        highLevelAiEscalation: booleanType(),
        autoUnsubscribe: booleanType()
    });
    const AccountAccessCodeSchema = enumType([
        "subscription_required",
        "trialing",
        "past_due_warning",
        "subscription_inactive",
        "plan_upgrade_required",
        "mailbox_limit_reached",
        "downgrade_selection_required",
        "feature_not_in_plan"
    ]);
    const AccountAccessActionSchema = enumType([
        "invite_creation",
        "mailbox_connection",
        "add_mailbox",
        "email_scanning",
        "verdict_polling",
        "feed_api",
        "message_api",
        "deep_scan",
        "high_level_ai_escalation",
        "auto_unsubscribe",
        "premium_report"
    ]);
    const AccountAccessGateSchema = objectType({
        code: AccountAccessCodeSchema,
        action: AccountAccessActionSchema,
        mode: enumType(["off", "shadow", "enforce"]),
        accountId: stringType(),
        planCode: PlanCodeSchema.nullable(),
        subscriptionStatus: enumType([
            "no_subscription",
            "trialing",
            "active",
            "past_due",
            "canceled",
            "incomplete",
            "incomplete_expired",
            "unpaid",
            "inactive",
            "blocked"
        ]),
        billingWarningLevel: enumType(["none", "warning", "hard_stop"]),
        allowedMailboxCount: numberType().int().nonnegative(),
        activeMailboxCount: numberType().int().nonnegative(),
        featureFlags: FeatureFlagsSchema,
        recommendedPlanCode: PlanCodeSchema.nullable()
    });
    const AccountAccessErrorResponseSchema = objectType({
        error: stringType(),
        billingGate: AccountAccessGateSchema
    });
    function planLabel(planCode) {
        switch (planCode) {
            case "single_box":
                return "Single Box";
            case "premium":
                return "Premium";
            case "family":
                return "Family";
            default:
                return "a compatible plan";
        }
    }
    function describeAccountAccessGate(gate) {
        switch (gate.code) {
            case "subscription_required":
            case "subscription_inactive":
                return "This ArcWardyn account is not currently authorized for that action. Open the ArcWardyn account website to review access.";
            case "past_due_warning":
                return "This ArcWardyn account needs attention before that action is available. Open the ArcWardyn account website.";
            case "mailbox_limit_reached":
                return "This account has reached its mailbox limit. Open the ArcWardyn account website before adding another mailbox.";
            case "plan_upgrade_required":
            case "feature_not_in_plan":
                return gate.recommendedPlanCode
                    ? `That feature requires ${planLabel(gate.recommendedPlanCode)}. Open the ArcWardyn account website to review access.`
                    : "That feature is not available for this account. Open the ArcWardyn account website to review access.";
            case "downgrade_selection_required":
                return "The account owner must choose which mailboxes remain active on the ArcWardyn account website.";
            case "trialing":
                return "Account access is active.";
        }
    }

    const DATABASE_NAME = "arcwardyn-feed-cache";
    const DATABASE_VERSION = 1;
    const FEED_ITEMS_STORE = "feedItems";
    const FEED_METADATA_STORE = "feedMetadata";
    function transactionDone(transaction) {
        return new Promise((resolve, reject) => {
            transaction.addEventListener("complete", () => resolve(), { once: true });
            transaction.addEventListener("abort", () => reject(transaction.error ?? new Error("IndexedDB transaction aborted")), { once: true });
            transaction.addEventListener("error", () => reject(transaction.error ?? new Error("IndexedDB transaction failed")), { once: true });
        });
    }
    let databasePromise;
    function openDatabase() {
        databasePromise ??= new Promise((resolve, reject) => {
            const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
            request.addEventListener("upgradeneeded", () => {
                const database = request.result;
                if (!database.objectStoreNames.contains(FEED_ITEMS_STORE)) {
                    const store = database.createObjectStore(FEED_ITEMS_STORE, { keyPath: "key" });
                    store.createIndex("provider", "provider", { unique: false });
                    store.createIndex("receivedAt", "receivedAt", { unique: false });
                }
                if (!database.objectStoreNames.contains(FEED_METADATA_STORE)) {
                    database.createObjectStore(FEED_METADATA_STORE, { keyPath: "provider" });
                }
            });
            request.addEventListener("success", () => resolve(request.result), { once: true });
            request.addEventListener("error", () => reject(request.error ?? new Error("Could not open feed cache")), {
                once: true
            });
            request.addEventListener("blocked", () => reject(new Error("Feed cache upgrade was blocked")), {
                once: true
            });
        });
        return databasePromise;
    }
    async function clearCachedFeeds() {
        const database = await openDatabase();
        const transaction = database.transaction([FEED_ITEMS_STORE, FEED_METADATA_STORE], "readwrite");
        const completion = transactionDone(transaction);
        transaction.objectStore(FEED_ITEMS_STORE).clear();
        transaction.objectStore(FEED_METADATA_STORE).clear();
        await completion;
    }

    const LEGACY_RESOLVED_ROW_ALIAS_PREFIX = "resolvedRowAlias.v1:";
    const RESOLVED_ROW_ALIAS_PREFIX = "resolvedRowAlias.v2:";
    let feedCacheMutationQueue = Promise.resolve();
    const DEFAULT_SETTINGS = {
        serverBaseUrl: "https://api.arcwardyn.ai",
        debugMode: false
    };
    async function getSettings() {
        const { settings } = await chrome.storage.local.get("settings");
        return { ...DEFAULT_SETTINGS, ...settings };
    }
    async function clearPairingBoundState() {
        await queueFeedCacheMutation(clearCachedFeeds);
        await chrome.storage.local.remove([
            "acknowledgedVerdicts",
            "activeMessage",
            "connectedAccounts",
            "lastBillingStatus",
            "lastServerSettings",
            "mailboxPolicies",
            "cachedFeeds"
        ]);
        await clearResolvedRowAliases();
    }
    async function setSettings(settings) {
        const current = await getSettings();
        const next = { ...current, ...settings };
        if (next.serverBaseUrl) {
            next.serverBaseUrl = normalizeServerBaseUrl(next.serverBaseUrl);
        }
        const hasOwnSetting = (key) => Object.prototype.hasOwnProperty.call(settings, key);
        const pairingIdentityChanged = Boolean((hasOwnSetting("deviceId") && next.deviceId !== current.deviceId) ||
            (hasOwnSetting("deviceToken") && next.deviceToken !== current.deviceToken) ||
            next.serverBaseUrl !== current.serverBaseUrl);
        if (pairingIdentityChanged) {
            next.selectedAccountId = undefined;
        }
        if (pairingIdentityChanged) {
            await clearPairingBoundState();
        }
        await chrome.storage.local.set({ settings: next });
        if (pairingIdentityChanged) {
            // The second pass closes the narrow race where a response authorized under
            // the previous pairing finished while the new settings were being committed.
            await clearPairingBoundState();
        }
        return next;
    }
    function queueFeedCacheMutation(mutation) {
        const result = feedCacheMutationQueue.then(mutation, mutation);
        feedCacheMutationQueue = result.then(() => undefined, () => undefined);
        return result;
    }
    function isResolvedRowAliasStorageKey(key) {
        return (key.startsWith(RESOLVED_ROW_ALIAS_PREFIX) ||
            key.startsWith(LEGACY_RESOLVED_ROW_ALIAS_PREFIX));
    }
    async function clearResolvedRowAliases() {
        const stored = await chrome.storage.local.get(null);
        const keys = Object.keys(stored).filter(isResolvedRowAliasStorageKey);
        if (keys.length > 0) {
            await chrome.storage.local.remove(keys);
        }
    }
    async function getConnectedAccounts() {
        const settings = await getSettings();
        const { connectedAccounts } = await chrome.storage.local.get("connectedAccounts");
        const cached = connectedAccounts;
        if (!cached)
            return [];
        if (!settings.deviceId ||
            Array.isArray(cached) ||
            cached.deviceId !== settings.deviceId ||
            !Array.isArray(cached.accounts)) {
            // Older extension versions cached the server-global account list without an
            // owner key. It cannot be safely displayed after account scoping is enabled.
            await chrome.storage.local.remove("connectedAccounts");
            await chrome.storage.local.remove("mailboxPolicies");
            return [];
        }
        return cached.accounts;
    }
    async function getLastServerSettings() {
        const { lastServerSettings } = await chrome.storage.local.get("lastServerSettings");
        return lastServerSettings;
    }
    async function setLastServerSettings(lastServerSettings) {
        if (!lastServerSettings) {
            await chrome.storage.local.remove("lastServerSettings");
            return;
        }
        await chrome.storage.local.set({ lastServerSettings });
    }
    async function setConnectedAccounts(connectedAccounts) {
        const settings = await getSettings();
        if (!settings.deviceId) {
            await chrome.storage.local.remove("connectedAccounts");
            await chrome.storage.local.remove("mailboxPolicies");
            return;
        }
        const mailboxPolicies = await getMailboxPolicies();
        const allowedAccountIds = new Set(connectedAccounts.map((account) => account.id));
        const scopedPolicies = Object.fromEntries(Object.entries(mailboxPolicies).filter(([accountId]) => allowedAccountIds.has(accountId)));
        await chrome.storage.local.set({
            connectedAccounts: {
                deviceId: settings.deviceId,
                accounts: connectedAccounts
            },
            mailboxPolicies: scopedPolicies
        });
    }
    async function getActiveSetupSession() {
        const { activeSetupSession } = await chrome.storage.local.get("activeSetupSession");
        return activeSetupSession;
    }
    async function setActiveSetupSession(activeSetupSession) {
        await chrome.storage.local.set({ activeSetupSession });
    }
    async function getMailboxPolicies() {
        const { mailboxPolicies } = await chrome.storage.local.get("mailboxPolicies");
        return mailboxPolicies ?? {};
    }
    async function setMailboxPolicy(accountId, policy) {
        const mailboxPolicies = await getMailboxPolicies();
        mailboxPolicies[accountId] = policy;
        await chrome.storage.local.set({ mailboxPolicies });
    }
    async function getProtectionCatalog() {
        const { protectionCatalog } = await chrome.storage.local.get("protectionCatalog");
        return protectionCatalog;
    }
    async function setProtectionCatalog(protectionCatalog) {
        await chrome.storage.local.set({ protectionCatalog });
    }
    async function getImapPresets() {
        const { imapPresets } = await chrome.storage.local.get("imapPresets");
        return imapPresets ?? [];
    }
    async function setImapPresets(imapPresets) {
        await chrome.storage.local.set({ imapPresets });
    }

    const EXTENSION_BUILD_MODE = "production" ;
    const IS_DEVELOPMENT_EXTENSION_BUILD = EXTENSION_BUILD_MODE === "development";
    const PRODUCTION_BACKEND_ORIGIN = "https://api.arcwardyn.ai";

    const FEED_LOOKBACK_DAYS = 14;
    const FEED_PAGE_SIZE = 250;
    const INCOMPATIBLE_RESPONSE_MESSAGE = "ArcWardyn returned an incompatible response. Update ArcWardyn and try again.";
    const FeedPageResponseSchema = FeedResponseSchema.extend({
        nextCursor: stringType().min(1).optional(),
        hasMore: booleanType().optional()
    });
    const AnalysisPollResponseSchema = objectType({
        job: AnalysisJobSchema,
        verdict: MessageVerdictResponseSchema.shape.verdict.optional()
    });
    const RenderedResponseSchema = unionType([
        OpenAttemptResponseSchema,
        objectType({
            status: literalType("ok")
        })
    ]);
    const ImapPresetListSchema = arrayType(ImapProviderPresetSchema);
    const OkResponseSchema = objectType({
        ok: literalType(true)
    });
    const CustomerUnpairResponseSchema = objectType({ revoked: literalType(true) }).strict();
    function currentClientDescriptor(displayName) {
        const manifest = chrome.runtime.getManifest();
        return {
            clientType: "browser_extension",
            platform: "safari",
            applicationId: chrome.runtime.id,
            applicationVersion: manifest.version,
            capabilities: ["mailbox.feed", "verdicts.read", "setup"],
            displayName
        };
    }
    class AccountAccessClientError extends Error {
        billingGate;
        constructor(billingGate) {
            super("This ArcWardyn account is not authorized for that action.");
            this.name = "AccountAccessClientError";
            this.billingGate = billingGate;
        }
    }
    function baseUrlVariants(serverBaseUrl) {
        const normalized = normalizeServerBaseUrl(serverBaseUrl);
        const primary = new URL(normalized);
        if (primary.origin !== PRODUCTION_BACKEND_ORIGIN) {
            throw new Error("The production extension accepts only the ArcWardyn backend.");
        }
        const variants = [primary.toString().replace(/\/$/, "")];
        return Array.from(new Set(variants));
    }
    async function request(path, schema, init, options) {
        const settings = await getSettings();
        const serverBaseUrl = options?.serverBaseUrl?.trim() ?? settings.serverBaseUrl?.trim();
        if (!serverBaseUrl) {
            throw new Error("Enter your ArcWardyn backend URL in the extension options first.");
        }
        const headers = new Headers(init?.headers);
        const hasBody = init?.body !== undefined && init?.body !== null;
        if (hasBody && typeof init?.body === "string") {
            headers.set("content-type", "application/json");
        }
        else {
            headers.delete("content-type");
        }
        if (options?.requiresDeviceToken === false) {
            // Pairing requests establish a new trust relationship and must never inherit
            // a token from a previous server or installation state.
            headers.delete("x-device-token");
            headers.delete("x-client-credential");
        }
        else if (settings.deviceToken) {
            headers.set("x-client-credential", settings.deviceToken);
        }
        else if (options?.optionalDeviceToken) {
            headers.delete("x-device-token");
            headers.delete("x-client-credential");
        }
        else {
            throw new Error("Pair this extension to your ArcWardyn account before checking email.");
        }
        let response = null;
        let lastError = null;
        const timeoutMs = options?.timeoutMs ?? 12_000;
        const baseUrls = baseUrlVariants(serverBaseUrl);
        for (const baseUrl of baseUrls) {
            try {
                response = await fetch(`${baseUrl}${path}`, {
                    ...init,
                    headers,
                    signal: init?.signal ?? AbortSignal.timeout(timeoutMs)
                });
                lastError = null;
                break;
            }
            catch (error) {
                lastError = error;
            }
        }
        if (!response) {
            throw new Error(lastError instanceof Error && lastError.name === "TimeoutError"
                ? "The hosted ArcWardyn backend is taking longer than expected to respond."
                : "Could not reach the hosted ArcWardyn backend. Check the backend URL and network connection.");
        }
        if (!response.ok) {
            const bodyText = await response.text();
            let body = { error: `Request failed: ${response.status}` };
            if (bodyText) {
                try {
                    body = JSON.parse(bodyText);
                }
                catch {
                    body = { error: bodyText };
                }
            }
            if (response.status === 402) {
                const accessGate = AccountAccessErrorResponseSchema.safeParse(body);
                if (accessGate.success) {
                    throw new AccountAccessClientError(accessGate.data.billingGate);
                }
            }
            const parsed = ApiErrorSchema.safeParse(body);
            if (response.status === 401) {
                throw new Error("This extension is not paired to the ArcWardyn account anymore. Pair it again.");
            }
            if (parsed.success) {
                throw new Error(parsed.data.details ? `${parsed.data.error} ${parsed.data.details}` : parsed.data.error);
            }
            throw new Error(`Request failed: ${response.status}`);
        }
        const body = await response.json();
        try {
            return schema.parse(body);
        }
        catch (error) {
            if (options?.repairResponse) {
                try {
                    return schema.parse(options.repairResponse(body));
                }
                catch (repairError) {
                    if (repairError instanceof ZodError) {
                        throw new Error(INCOMPATIBLE_RESPONSE_MESSAGE);
                    }
                    throw repairError;
                }
            }
            if (error instanceof ZodError) {
                throw new Error(INCOMPATIBLE_RESPONSE_MESSAGE);
            }
            throw error;
        }
    }
    const api = {
        async startInviteSession(input) {
            return request("/v1/setup/invite/session", SetupInviteSessionResponseSchema, {
                method: "POST",
                body: JSON.stringify({
                    ...input,
                    client: currentClientDescriptor(input.deviceName)
                })
            }, {
                requiresDeviceToken: false,
                serverBaseUrl: input.serverBaseUrl
            });
        },
        async revokeCurrentCustomerDevice() {
            return request("/v1/pair/customer-handoff/unpair", CustomerUnpairResponseSchema, { method: "POST" });
        },
        async getSetupSession(sessionId) {
            return request(`/v1/setup/sessions/${encodeURIComponent(sessionId)}`, SetupSessionResponseSchema);
        },
        async listAccounts() {
            return request("/v1/accounts", AccountListResponseSchema);
        },
        async getImapPresets() {
            return request("/v1/accounts/imap/presets", ImapPresetListSchema);
        },
        async startGoogleOAuth(payload) {
            return request("/v1/accounts/oauth/google/start", AccountOAuthStartResponseSchema, {
                method: "POST",
                body: JSON.stringify(payload)
            });
        },
        async startMicrosoftOAuth(payload) {
            return request("/v1/accounts/oauth/microsoft/start", AccountOAuthStartResponseSchema, {
                method: "POST",
                body: JSON.stringify(payload)
            });
        },
        async sendImapVerification(payload) {
            return request("/v1/accounts/imap/verification/send", ImapVerificationSendResponseSchema, {
                method: "POST",
                body: JSON.stringify(payload)
            });
        },
        async verifyImapCode(payload) {
            return request("/v1/accounts/imap/verification/verify", ImapVerificationVerifyResponseSchema, {
                method: "POST",
                body: JSON.stringify(payload)
            });
        },
        async connectImap(payload) {
            return request("/v1/accounts/imap/connect", AccountConnectResponseSchema, {
                method: "POST",
                body: JSON.stringify(payload)
            });
        },
        async getProtectionCatalog() {
            return request("/v1/accounts/policy/catalog", ProtectionCatalogResponseSchema);
        },
        async getMailboxPolicy(accountId) {
            return request(`/v1/accounts/${encodeURIComponent(accountId)}/policy`, MailboxPolicyResponseSchema);
        },
        async saveMailboxPolicy(accountId, payload) {
            const body = DeterministicSettingsUpdateSchema.parse(payload);
            return request(`/v1/accounts/${encodeURIComponent(accountId)}/policy`, MailboxPolicyResponseSchema, {
                method: "POST",
                body: JSON.stringify(body)
            });
        },
        async refreshFeed(provider) {
            const items = [];
            let cursor;
            let generatedAt = new Date().toISOString();
            for (let pageNumber = 0; pageNumber < 200; pageNumber += 1) {
                const params = new URLSearchParams({
                    provider,
                    days: String(FEED_LOOKBACK_DAYS),
                    limit: String(FEED_PAGE_SIZE),
                    view: "badge"
                });
                if (cursor)
                    params.set("cursor", cursor);
                const page = await request(`/v1/feed?${params.toString()}`, FeedPageResponseSchema, undefined, {
                    repairResponse: sanitizeFeedResponseBody,
                    timeoutMs: 45_000
                });
                generatedAt = page.generatedAt;
                items.push(...page.items);
                if (!page.hasMore || !page.nextCursor) {
                    return {
                        provider,
                        days: FEED_LOOKBACK_DAYS,
                        generatedAt,
                        items
                    };
                }
                cursor = page.nextCursor;
            }
            throw new Error("ArcWardyn feed pagination did not terminate safely");
        },
        async resolveRow(hints, options) {
            return request("/v1/dom/resolve-row", ResolveRowResponseSchema, {
                method: "POST",
                body: JSON.stringify({
                    hints,
                    ...(options?.skipClientSyncWait ? { skipClientSyncWait: true } : {})
                })
            });
        },
        async getVerdict(messageKey) {
            return request(`/v1/messages/${encodeURIComponent(messageKey)}/verdict`, MessageVerdictResponseSchema, undefined, {
                timeoutMs: 30_000
            });
        },
        async getUnsubscribePreview(messageKey) {
            return request(`/v1/messages/${encodeURIComponent(messageKey)}/unsubscribe-preview`, MessageUnsubscribePreviewResponseSchema, undefined, {
                repairResponse: (body) => {
                    if (body &&
                        typeof body === "object" &&
                        "preview" in body &&
                        body.preview &&
                        typeof body.preview === "object" &&
                        !("canOverride" in body.preview)) {
                        return {
                            ...body,
                            preview: {
                                ...body.preview,
                                canOverride: false
                            }
                        };
                    }
                    return body;
                },
                timeoutMs: 30_000
            });
        },
        async recheckMessage(messageKey) {
            return request(`/v1/messages/${encodeURIComponent(messageKey)}/recheck`, MessageRecheckResponseSchema, {
                method: "POST",
                body: JSON.stringify({})
            });
        },
        async deepScanMessage(messageKey) {
            return request(`/v1/messages/${encodeURIComponent(messageKey)}/deep-scan`, MessageDeepScanResponseSchema, {
                method: "POST",
                body: JSON.stringify({})
            });
        },
        async openAttempt(payload) {
            return request("/v1/messages/open-attempt", OpenAttemptResponseSchema, {
                method: "POST",
                body: JSON.stringify(payload)
            }, {
                timeoutMs: 45_000
            });
        },
        async pollAnalysis(jobId) {
            return request(`/v1/analysis/${jobId}`, AnalysisPollResponseSchema, undefined, {
                timeoutMs: 30_000
            });
        },
        async rendered(payload) {
            return request("/v1/messages/rendered", RenderedResponseSchema, {
                method: "POST",
                body: JSON.stringify(payload)
            });
        },
        async acknowledge(messageKey) {
            return request(`/v1/messages/${encodeURIComponent(messageKey)}/acknowledge`, OkResponseSchema, {
                method: "POST",
                body: JSON.stringify({})
            });
        },
        async linkPreflight(payload) {
            return request("/v1/links/preflight", LinkDecisionSchema, {
                method: "POST",
                body: JSON.stringify(payload)
            });
        },
        async action(messageKey, action, options) {
            MessageActionSchema.parse(action);
            return request(`/v1/messages/${encodeURIComponent(messageKey)}/actions/${action}`, OkResponseSchema, {
                method: "POST",
                body: JSON.stringify({
                    ...(options?.overrideManualReview ? { overrideManualReview: true } : {})
                })
            });
        },
        async getSettings() {
            return request("/v1/settings", SettingsSchema);
        },
        async saveSettings(payload) {
            return request("/v1/settings", SettingsSchema, {
                method: "POST",
                body: JSON.stringify(payload)
            });
        }
    };

    const V1_IMAP_PROVIDER_IDS = new Set([
        "yahoo",
        "aol",
        "icloud",
        "spectrum",
        "att",
        "comcast",
        "cox",
        "frontier",
        "optimum",
        "mediacom",
        "windstream",
        "tds",
        "astound"
    ]);
    const V1_IMAP_FALLBACK_PRESETS = [
        {
            id: "yahoo",
            name: "Yahoo Mail",
            host: "imap.mail.yahoo.com",
            port: 993,
            secure: true,
            note: "Usually requires a Yahoo app password for third-party IMAP access.",
            domains: ["yahoo.com", "ymail.com", "rocketmail.com"],
            setupGuidance: "Create a Yahoo app password and use it instead of the primary mailbox password.",
            requiresAppPassword: true,
            extensionSurface: "tested-webmail",
            status: "supported"
        },
        {
            id: "aol",
            name: "AOL Mail",
            host: "imap.aol.com",
            port: 993,
            secure: true,
            note: "AOL commonly uses Yahoo/AOL app-password style IMAP setup.",
            domains: ["aol.com", "aim.com", "netscape.net"],
            setupGuidance: "Create an AOL/Yahoo app password and use it as the mailbox credential.",
            requiresAppPassword: true,
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "icloud",
            name: "iCloud Mail",
            host: "imap.mail.me.com",
            port: 993,
            secure: true,
            note: "Use an Apple app-specific password when two-factor authentication is enabled.",
            domains: ["icloud.com", "me.com", "mac.com"],
            setupGuidance: "Use an Apple app-specific password. Do not enter the Apple ID primary password.",
            requiresAppPassword: true,
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "spectrum",
            name: "Spectrum / Charter / Roadrunner",
            host: "",
            port: 993,
            secure: true,
            note: "Enter the provider-published SSL IMAP host for the mailbox.",
            domains: ["spectrum.net", "charter.net", "twc.com", "rr.com"],
            setupGuidance: "Use provider SSL IMAP settings and a scoped/app-password style credential if supported.",
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "att",
            name: "AT&T / Currently",
            host: "imap.mail.att.net",
            port: 993,
            secure: true,
            note: "AT&T legacy mail typically requires a secure mail key.",
            domains: [
                "att.net",
                "currently.com",
                "sbcglobal.net",
                "bellsouth.net",
                "ameritech.net",
                "pacbell.net",
                "prodigy.net",
                "swbell.net",
                "nvbell.net",
                "snet.net",
                "flash.net",
                "wans.net"
            ],
            setupGuidance: "Create an AT&T secure mail key where applicable and use it as the IMAP credential.",
            requiresSecureMailKey: true,
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "comcast",
            name: "Comcast / Xfinity legacy",
            host: "imap.comcast.net",
            port: 993,
            secure: true,
            note: "Some migrated accounts may require Yahoo-backed handling.",
            domains: ["comcast.net"],
            setupGuidance: "Use Comcast-published SSL IMAP settings and a scoped mailbox credential where available.",
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "cox",
            name: "Cox legacy",
            host: "imap.cox.net",
            port: 993,
            secure: true,
            note: "Cox legacy mail may be Yahoo-backed for migrated accounts.",
            domains: ["cox.net"],
            setupGuidance: "Use provider-published SSL IMAP settings and any Cox/Yahoo migration guidance.",
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "frontier",
            name: "Frontier legacy",
            host: "",
            port: 993,
            secure: true,
            note: "Enter the provider-published SSL IMAP host.",
            domains: ["frontier.com", "frontiernet.net", "citlink.net", "epix.net", "newnorth.net", "gvni.com"],
            setupGuidance: "Use provider-published Frontier or Yahoo-backed IMAP setup guidance.",
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "optimum",
            name: "Optimum / OptOnline",
            host: "",
            port: 993,
            secure: true,
            note: "Enter the provider-published SSL IMAP host.",
            domains: ["optimum.net", "optonline.net"],
            setupGuidance: "Use provider-published SSL IMAP settings and a scoped mailbox credential where available.",
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "mediacom",
            name: "Mediacom / Xtream",
            host: "",
            port: 993,
            secure: true,
            note: "Enter the provider-published SSL IMAP host.",
            domains: ["mediacombb.net", "mchsi.com", "mediacomtoday.com"],
            setupGuidance: "Use provider-published SSL IMAP settings and a scoped mailbox credential where available.",
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "windstream",
            name: "Windstream / Kinetic",
            host: "",
            port: 993,
            secure: true,
            note: "Enter the provider-published SSL IMAP host.",
            domains: ["windstream.net"],
            setupGuidance: "Use provider-published SSL IMAP settings and a scoped mailbox credential where available.",
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "tds",
            name: "TDS",
            host: "",
            port: 993,
            secure: true,
            note: "Enter the provider-published SSL IMAP host.",
            domains: ["tds.net"],
            setupGuidance: "Use provider-published SSL IMAP settings and a scoped mailbox credential where available.",
            extensionSurface: "server-scan-only",
            status: "supported"
        },
        {
            id: "astound",
            name: "Astound / RCN / WOW legacy",
            host: "",
            port: 993,
            secure: true,
            note: "Enter the provider-published SSL IMAP host.",
            domains: ["astound.net", "rcn.com", "wowway.com"],
            setupGuidance: "Use provider-published SSL IMAP settings and a scoped mailbox credential where available.",
            extensionSurface: "server-scan-only",
            status: "supported"
        }
    ];
    function visibleImapPresets(presets) {
        return presets.filter((entry) => V1_IMAP_PROVIDER_IDS.has(entry.id) &&
            entry.status === "supported" &&
            Array.isArray(entry.domains) &&
            entry.domains.length > 0);
    }
    function v1ImapDropdownPresets(presets) {
        const sourceById = new Map(visibleImapPresets(presets).map((entry) => [entry.id, entry]));
        return V1_IMAP_FALLBACK_PRESETS.map((fallbackPreset) => {
            const sourcePreset = sourceById.get(fallbackPreset.id);
            return {
                ...fallbackPreset,
                ...sourcePreset,
                id: fallbackPreset.id,
                name: fallbackPreset.name,
                domains: fallbackPreset.domains,
                status: "supported"
            };
        });
    }
    function imapPresetOptionLabel(preset) {
        return `${preset.name} - ${preset.domains?.join(", ") ?? ""}`;
    }
    function imapPresetDomainSummary(preset) {
        return preset.domains?.length ? `Supported domains: ${preset.domains.join(", ")}.` : "";
    }

    const DEFAULT_PERMISSION_POLICY = {
        development: IS_DEVELOPMENT_EXTENSION_BUILD,
        productionBackendOrigin: PRODUCTION_BACKEND_ORIGIN
    };
    function toPermissionPattern(value) {
        const hostname = value.hostname.includes(":") && !value.hostname.startsWith("[")
            ? `[${value.hostname}]`
            : value.hostname;
        return `${value.protocol}//${hostname}/*`;
    }
    function serverPermissionOrigins(serverBaseUrl, policy = DEFAULT_PERMISSION_POLICY) {
        const url = new URL(normalizeServerBaseUrl(serverBaseUrl));
        if (!policy.development && url.origin !== policy.productionBackendOrigin) {
            return null;
        }
        const originPatterns = new Set([toPermissionPattern(url)]);
        if (policy.development && url.hostname === "localhost") {
            const fallback = new URL(url.toString());
            fallback.hostname = "127.0.0.1";
            originPatterns.add(toPermissionPattern(fallback));
        }
        return Array.from(originPatterns);
    }
    function requestServerPermission(serverBaseUrl) {
        const origins = serverPermissionOrigins(serverBaseUrl);
        if (!origins)
            return Promise.resolve(false);
        // Safari requires permissions.request() to run in the synchronous portion of
        // the click handler. Do not await permissions.contains() before this call.
        return chrome.permissions.request({ origins });
    }

    function parseRuntimeResult(value) {
        if (!value || typeof value !== "object" || Array.isArray(value)) {
            return { ok: false, error: undefined };
        }
        const record = value;
        return {
            ok: record.ok === true,
            error: typeof record.error === "string" ? record.error : undefined
        };
    }
    const inviteInput = document.getElementById("invite-input");
    const deviceNameInput = document.getElementById("device-name");
    const connectInviteButton = document.getElementById("connect-invite-button");
    const customerAccountLink = document.getElementById("customer-account-link");
    const disconnectSection = document.getElementById("disconnect-section");
    const disconnectCustomerButton = document.getElementById("disconnect-customer-button");
    const setupStatusEl = document.getElementById("setup-status");
    const deepScanStatusHeadlineEl = document.getElementById("deep-scan-status-headline");
    const deepScanStatusDetailEl = document.getElementById("deep-scan-status-detail");
    const deepScanStatusBehaviorEl = document.getElementById("deep-scan-status-behavior");
    const deepScanStatusBudgetEl = document.getElementById("deep-scan-status-budget");
    const mailboxSection = document.getElementById("mailbox-section");
    const accountsSection = document.getElementById("accounts-section");
    const policySection = document.getElementById("policy-section");
    const connectionPill = document.getElementById("connection-pill");
    const globalStatusText = document.getElementById("global-status-text");
    const globalStatusCard = document.getElementById("global-status");
    const gmailLabelInput = document.getElementById("gmail-label");
    const microsoftLabelInput = document.getElementById("microsoft-label");
    const connectGmailButton = document.getElementById("connect-gmail-button");
    const connectMicrosoftButton = document.getElementById("connect-microsoft-button");
    const mailboxStatusEl = document.getElementById("mailbox-status");
    const imapPresetSelect = document.getElementById("imap-preset");
    const imapDisplayNameInput = document.getElementById("imap-display-name");
    const imapEmailInput = document.getElementById("imap-email");
    const imapUsernameInput = document.getElementById("imap-username");
    const imapHostInput = document.getElementById("imap-host");
    const imapPortInput = document.getElementById("imap-port");
    const imapSecureInput = document.getElementById("imap-secure");
    const imapPasswordInput = document.getElementById("imap-password");
    const imapPasswordLabelEl = document.getElementById("imap-password-label");
    const imapCodeInput = document.getElementById("imap-code");
    const imapNoteEl = document.getElementById("imap-note");
    const imapSendCodeButton = document.getElementById("imap-send-code-button");
    const imapVerifyButton = document.getElementById("imap-verify-button");
    const imapConnectButton = document.getElementById("imap-connect-button");
    const refreshAccountsButton = document.getElementById("refresh-accounts-button");
    const accountsListEl = document.getElementById("accounts-list");
    const policySubtitleEl = document.getElementById("policy-subtitle");
    const basePresetSelect = document.getElementById("base-preset");
    const protectedContactsInput = document.getElementById("protected-contacts");
    const protectedDomainsInput = document.getElementById("protected-domains");
    const trustedSendersInput = document.getElementById("trusted-senders");
    const trustedDomainsInput = document.getElementById("trusted-domains");
    const optionGroupsEl = document.getElementById("option-groups");
    const savePolicyButton = document.getElementById("save-policy-button");
    const resetPolicyButton = document.getElementById("reset-policy-button");
    const policyStatusEl = document.getElementById("policy-status");
    let currentAccounts = [];
    let currentCatalog = null;
    let currentImapPresets = [];
    let currentPolicyAccountId = null;
    let activePollSessionId = null;
    const optionInputs = new Map();
    const UNSUPPORTED_IMAP_PROVIDER_MESSAGE = "This email provider is not supported in ArcWardyn V1. ArcWardyn currently supports Gmail, Microsoft Outlook/Microsoft 365, Yahoo, AOL, iCloud, and selected major ISP email providers.";
    const GOOGLE_OAUTH_DOMAINS = new Set(["gmail.com", "googlemail.com"]);
    const MICROSOFT_OAUTH_DOMAINS = new Set(["outlook.com", "hotmail.com", "live.com", "msn.com"]);
    function setStatus(element, message, tone = "neutral") {
        element.textContent = message;
        element.dataset.tone = tone === "neutral" ? "" : tone;
    }
    function setGlobalStatus(message, tone = "neutral") {
        setStatus(globalStatusText, message, tone);
        globalStatusCard.dataset.tone = tone === "neutral" ? "" : tone;
    }
    function renderDeepScanStatus(settings) {
        const summary = summarizeDeepScanSettings(settings);
        deepScanStatusHeadlineEl.textContent = summary.headline;
        deepScanStatusDetailEl.textContent = summary.detail;
        deepScanStatusBehaviorEl.textContent = summary.behavior;
        deepScanStatusBudgetEl.textContent = summary.budget;
    }
    function accountAccessAwareErrorMessage(error, fallback) {
        if (error instanceof AccountAccessClientError) {
            const message = describeAccountAccessGate(error.billingGate);
            setGlobalStatus(message, "error");
            return message;
        }
        return error instanceof Error ? error.message : fallback;
    }
    function listToTextarea(values) {
        return (values ?? []).join("\n");
    }
    function textareaToList(value) {
        return Array.from(new Set(value
            .split(/[\n,]/)
            .map((entry) => entry.trim())
            .filter(Boolean)));
    }
    function decodeInviteToken(rawValue) {
        const trimmed = rawValue.trim();
        if (!trimmed)
            return null;
        const token = trimmed.replace(/^FES1\./i, "");
        const normalized = token.replace(/-/g, "+").replace(/_/g, "/");
        const padded = normalized.length % 4 === 0
            ? normalized
            : normalized.padEnd(normalized.length + (4 - (normalized.length % 4)), "=");
        try {
            const parsed = JSON.parse(atob(padded));
            if (!parsed.serverBaseUrl || !parsed.pairingCode)
                return null;
            return {
                serverBaseUrl: normalizeServerBaseUrl(parsed.serverBaseUrl),
                pairingCode: parsed.pairingCode.trim()
            };
        }
        catch {
            return null;
        }
    }
    function parseInviteInput(value) {
        const trimmed = value.trim();
        if (!trimmed)
            return null;
        try {
            const url = new URL(trimmed);
            if (url.protocol !== "https:" && url.hostname !== "localhost" && url.hostname !== "127.0.0.1") {
                return null;
            }
            if (url.pathname !== "/setup") {
                return null;
            }
            const token = url.searchParams.get("invite");
            if (token)
                return decodeInviteToken(token);
        }
        catch {
            return null;
        }
        return null;
    }
    function setBusy(button, busy, label) {
        button.dataset.busy = busy ? "true" : "false";
        button.disabled = busy;
        if (busy) {
            if (!label)
                return;
            button.dataset.label ||= button.textContent ?? "";
            button.textContent = label;
            return;
        }
        if (button.dataset.label) {
            button.textContent = button.dataset.label;
        }
    }
    function updateConnectionPill(input) {
        if (!input.paired) {
            connectionPill.textContent = "Not connected";
            return;
        }
        const origin = input.serverBaseUrl ? new URL(input.serverBaseUrl).host : "server";
        connectionPill.textContent =
            input.accountCount > 0
                ? `${input.accountCount} mailbox${input.accountCount === 1 ? "" : "es"} on ${origin}`
                : `Browser paired to ${origin}`;
    }
    function updateSectionVisibility(input) {
        mailboxSection.hidden = !input.paired;
        accountsSection.hidden = !input.paired;
        policySection.hidden = !input.selectedAccountId;
    }
    function renderImapPresets(presets) {
        imapPresetSelect.innerHTML = "";
        const visiblePresets = v1ImapDropdownPresets(presets);
        for (const preset of visiblePresets) {
            const option = document.createElement("option");
            option.value = preset.id;
            option.textContent = imapPresetOptionLabel(preset);
            imapPresetSelect.append(option);
        }
    }
    function imapPasswordLabelText(preset) {
        switch (preset?.security?.authType) {
            case "app_password":
                return "App-specific password";
            case "local_bridge":
                return "Local bridge credential";
            default:
                return preset?.requiresSecureMailKey
                    ? "Secure mail key"
                    : "App-specific password or scoped mailbox credential";
        }
    }
    function emailDomain(value) {
        const normalized = value.trim().toLowerCase().replace(/\.+$/, "");
        const at = normalized.lastIndexOf("@");
        return at >= 0 ? normalized.slice(at + 1).replace(/\.+$/, "") : undefined;
    }
    function oauthProviderForDomain(domain) {
        if (!domain)
            return undefined;
        if (GOOGLE_OAUTH_DOMAINS.has(domain))
            return "gmail";
        if (MICROSOFT_OAUTH_DOMAINS.has(domain))
            return "outlook";
        return undefined;
    }
    function selectedImapPreset() {
        return currentImapPresets.find((entry) => entry.id === imapPresetSelect.value);
    }
    function applyImapPreset(presetId) {
        const preset = currentImapPresets.find((entry) => entry.id === presetId);
        if (!preset)
            return;
        imapHostInput.value = preset.host;
        imapPortInput.value = String(preset.port);
        imapSecureInput.checked = preset.secure;
        imapNoteEl.textContent = [
            preset.security?.securitySummary,
            imapPresetDomainSummary(preset),
            preset.setupGuidance,
            preset.legacyMigrationNotes,
            preset.extensionSurface === "server-scan-only"
                ? "This provider is server-scan-only in V1; the browser extension will not render mailbox UI on its webmail pages."
                : undefined,
            preset.note
        ]
            .filter((entry, index, items) => Boolean(entry) && items.indexOf(entry) === index)
            .join(" ");
        imapPasswordLabelEl.textContent = imapPasswordLabelText(preset);
        imapUsernameInput.placeholder = preset.usernameHint ?? "Leave blank to use the email address";
    }
    async function refreshServerSettingsSnapshot(options) {
        const extensionSettings = await getSettings();
        const cached = await getLastServerSettings();
        if (cached && !options?.force) {
            renderDeepScanStatus(cached);
        }
        else if (!cached) {
            renderDeepScanStatus(undefined);
        }
        if (!extensionSettings.deviceToken) {
            if (!cached) {
                renderDeepScanStatus(undefined);
            }
            return cached;
        }
        try {
            const serverSettings = await api.getSettings();
            await setLastServerSettings(serverSettings);
            renderDeepScanStatus(serverSettings);
            return serverSettings;
        }
        catch {
            renderDeepScanStatus(cached);
            return cached;
        }
    }
    async function loadProtectionCatalog() {
        const settings = await getSettings();
        const cached = await getProtectionCatalog();
        if (cached) {
            currentCatalog = cached;
            renderOptionGroups(cached, null);
        }
        if (!settings.deviceToken)
            return;
        const catalog = await api.getProtectionCatalog();
        currentCatalog = catalog;
        await setProtectionCatalog(catalog);
        renderOptionGroups(catalog, null);
    }
    async function loadImapPresetCatalog() {
        const settings = await getSettings();
        currentImapPresets = v1ImapDropdownPresets(V1_IMAP_FALLBACK_PRESETS);
        renderImapPresets(currentImapPresets);
        applyImapPreset(imapPresetSelect.value || currentImapPresets[0]?.id || "");
        const cached = await getImapPresets();
        currentImapPresets = v1ImapDropdownPresets(cached);
        renderImapPresets(currentImapPresets);
        applyImapPreset(imapPresetSelect.value || currentImapPresets[0]?.id || "");
        if (!settings.deviceToken)
            return;
        const presets = await api.getImapPresets();
        currentImapPresets = v1ImapDropdownPresets(presets);
        await setImapPresets(currentImapPresets);
        renderImapPresets(currentImapPresets);
        applyImapPreset(imapPresetSelect.value || currentImapPresets[0]?.id || "");
    }
    function renderOptionGroups(catalog, policy) {
        optionInputs.clear();
        optionGroupsEl.replaceChildren();
        const grouped = new Map();
        for (const option of catalog.options) {
            const bucket = grouped.get(option.category) ?? [];
            bucket.push(option);
            grouped.set(option.category, bucket);
        }
        for (const [category, options] of grouped.entries()) {
            const group = document.createElement("section");
            group.className = "option-group";
            const heading = document.createElement("h3");
            heading.textContent = category;
            group.append(heading);
            for (const option of options) {
                const row = document.createElement("div");
                row.className = "option-row";
                const copy = document.createElement("div");
                const label = document.createElement("strong");
                label.textContent = option.label;
                copy.append(label);
                const help = document.createElement("div");
                help.className = "help";
                help.textContent = option.help;
                copy.append(help);
                if (option.locked) {
                    const locked = document.createElement("div");
                    locked.className = "locked";
                    locked.textContent = "Locked by the protection engine";
                    copy.append(locked);
                }
                const select = document.createElement("select");
                for (const value of ["inherit", "off", "warn", "block"]) {
                    const optionEl = document.createElement("option");
                    optionEl.value = value;
                    optionEl.textContent = value === "inherit" ? "Preset default" : value;
                    select.append(optionEl);
                }
                select.value = policy?.settings.options[option.key] ?? "inherit";
                select.disabled = option.locked;
                optionInputs.set(option.key, select);
                row.append(copy, select);
                group.append(row);
            }
            optionGroupsEl.append(group);
        }
    }
    function applyPolicyToForm(response) {
        basePresetSelect.value = response.settings.basePreset;
        protectedContactsInput.value = listToTextarea(response.settings.protectedContacts);
        protectedDomainsInput.value = listToTextarea(response.settings.protectedDomains);
        trustedSendersInput.value = listToTextarea(response.settings.trustedSenders);
        trustedDomainsInput.value = listToTextarea(response.settings.trustedDomains);
        for (const [key, select] of optionInputs.entries()) {
            const configuredValue = response.settings.options[key];
            select.value = configuredValue ?? "inherit";
        }
    }
    async function loadMailboxPolicy(accountId) {
        if (!currentCatalog) {
            await loadProtectionCatalog();
        }
        const response = await api.getMailboxPolicy(accountId);
        currentPolicyAccountId = accountId;
        await setMailboxPolicy(accountId, response.policy);
        await setSettings({ selectedAccountId: accountId });
        policySubtitleEl.textContent = `Editing ${response.account.displayName} (${response.account.provider})`;
        renderOptionGroups(currentCatalog, response.policy);
        applyPolicyToForm(response.policy);
        updateSectionVisibility({ paired: true, selectedAccountId: accountId });
    }
    function renderAccounts() {
        accountsListEl.replaceChildren();
        if (currentAccounts.length === 0) {
            const empty = document.createElement("p");
            empty.className = "muted";
            empty.textContent =
                "No mailbox is connected yet. Finish Gmail, Microsoft, or IMAP setup above.";
            accountsListEl.append(empty);
            return;
        }
        for (const account of currentAccounts) {
            const row = document.createElement("div");
            row.className = "account-row";
            row.dataset.selected = String(account.id === currentPolicyAccountId);
            const copy = document.createElement("div");
            const title = document.createElement("strong");
            title.textContent = account.displayName;
            const meta = document.createElement("div");
            meta.className = "meta";
            meta.textContent = [
                account.provider.toUpperCase(),
                account.accountId,
                account.status === "connected" ? "Connected" : "Needs attention",
                account.lastSyncAt ? `Last sync ${new Date(account.lastSyncAt).toLocaleString()}` : ""
            ]
                .filter(Boolean)
                .join(" • ");
            copy.append(title, meta);
            const manageButton = document.createElement("button");
            manageButton.type = "button";
            manageButton.className = account.id === currentPolicyAccountId ? "secondary" : "ghost";
            manageButton.textContent = "Manage protection";
            manageButton.addEventListener("click", () => {
                void loadMailboxPolicy(account.id).catch((error) => {
                    setStatus(policyStatusEl, accountAccessAwareErrorMessage(error, "Could not load mailbox protection."), "error");
                });
            });
            const actions = document.createElement("div");
            actions.className = "inline";
            actions.append(manageButton);
            row.append(copy, actions);
            accountsListEl.append(row);
        }
    }
    async function refreshAccounts(options) {
        const settings = await getSettings();
        if (!settings.deviceToken) {
            currentAccounts = [];
            renderAccounts();
            updateConnectionPill({ paired: false, accountCount: 0 });
            updateSectionVisibility({ paired: false });
            return;
        }
        const response = await api.listAccounts();
        currentAccounts = response.accounts;
        await setConnectedAccounts(response.accounts);
        updateConnectionPill({
            paired: true,
            accountCount: response.accounts.length,
            serverBaseUrl: settings.serverBaseUrl
        });
        const requestedAccountId = (options?.keepSelection ? currentPolicyAccountId : null) ??
            settings.selectedAccountId;
        const selectedAccountId = response.accounts.some((account) => account.id === requestedAccountId)
            ? requestedAccountId
            : response.accounts[0]?.id;
        currentPolicyAccountId = selectedAccountId ?? null;
        await setSettings({ selectedAccountId });
        renderAccounts();
        updateSectionVisibility({
            paired: true,
            selectedAccountId: selectedAccountId ?? undefined
        });
        if (selectedAccountId) {
            await loadMailboxPolicy(selectedAccountId);
        }
    }
    function sessionStatusMessage(session) {
        switch (session.status) {
            case "paired":
                return "Browser paired. Choose a mailbox provider to continue.";
            case "oauth_pending":
                return "Finish the provider sign-in in the opened browser tab.";
            case "imap_code_sent":
                return `Verification code sent to ${session.maskedDestination ?? session.email ?? "your mailbox"}.`;
            case "imap_ready":
                return "Verification email is unavailable right now. Finish the IMAP connection with the app-specific password or scoped mailbox credential.";
            case "imap_verified":
                return "Mailbox code accepted. Finish the IMAP connection with the password or app password.";
            case "connected":
                return session.account
                    ? `${session.account.displayName} is connected and ready.`
                    : "Mailbox connected successfully.";
            case "error":
                return session.errorMessage ?? "The setup flow needs attention.";
        }
    }
    async function rememberSession(session) {
        await setActiveSetupSession(session);
        await setSettings({ setupSessionId: session.sessionId });
        setGlobalStatus(sessionStatusMessage(session), session.status === "error" ? "error" : "success");
    }
    async function pollSetupSession(sessionId) {
        activePollSessionId = sessionId;
        const run = async () => {
            if (activePollSessionId !== sessionId)
                return;
            try {
                const { session } = await api.getSetupSession(sessionId);
                await rememberSession(session);
                if (session.status === "connected") {
                    activePollSessionId = null;
                    await refreshAccounts({ keepSelection: false });
                    setStatus(mailboxStatusEl, sessionStatusMessage(session), "success");
                    return;
                }
                if (session.status === "imap_code_sent" ||
                    session.status === "imap_ready" ||
                    session.status === "imap_verified" ||
                    session.status === "error") {
                    activePollSessionId = null;
                    setStatus(mailboxStatusEl, sessionStatusMessage(session), session.status === "error" ? "error" : "success");
                    return;
                }
                window.setTimeout(() => void run(), 2000);
            }
            catch (error) {
                activePollSessionId = null;
                setStatus(mailboxStatusEl, accountAccessAwareErrorMessage(error, "Could not check setup progress."), "error");
            }
        };
        await run();
    }
    async function saveServerSettings(input) {
        let permissionGranted = false;
        try {
            permissionGranted = await requestServerPermission(input.serverBaseUrl);
        }
        catch (error) {
            throw new Error(`Could not request extension permission for that server URL. ${error instanceof Error ? error.message : String(error)}`);
        }
        if (!permissionGranted) {
            throw new Error("Safari did not grant permission for the extension to reach that server URL.");
        }
        await setSettings({
            serverBaseUrl: input.serverBaseUrl,
            debugMode: input.debugMode
        });
    }
    async function connectUsingInvite(invite) {
        const deviceName = deviceNameInput.value.trim() || "ArcWardyn";
        const existingSettings = await getSettings();
        await saveServerSettings({
            serverBaseUrl: invite.serverBaseUrl,
            debugMode: Boolean(existingSettings.debugMode)
        });
        const response = await api.startInviteSession({
            serverBaseUrl: invite.serverBaseUrl,
            pairingCode: invite.pairingCode,
            deviceName
        });
        await setSettings({
            serverBaseUrl: invite.serverBaseUrl,
            deviceToken: response.deviceToken,
            deviceId: response.deviceId,
            debugMode: Boolean(existingSettings.debugMode),
            setupSessionId: response.session.sessionId
        });
        await rememberSession(response.session);
        setStatus(setupStatusEl, "Browser connected successfully.", "success");
        await refreshServerSettingsSnapshot({ force: true });
        await refreshAccounts({ keepSelection: false });
        await loadProtectionCatalog();
        await loadImapPresetCatalog();
    }
    function collectImapForm() {
        const email = imapEmailInput.value.trim();
        const domain = emailDomain(email);
        const oauthProvider = oauthProviderForDomain(domain);
        if (oauthProvider === "gmail") {
            throw new Error("Use the Gmail / Google Workspace OAuth setup for this mailbox. Gmail is not offered as a normal IMAP setup path.");
        }
        if (oauthProvider === "outlook") {
            throw new Error("Use the Microsoft Outlook / Microsoft 365 OAuth setup for this mailbox. Microsoft mailboxes are not offered as a normal IMAP setup path.");
        }
        const preset = selectedImapPreset();
        if (!preset || (preset.status ?? "supported") !== "supported") {
            throw new Error(UNSUPPORTED_IMAP_PROVIDER_MESSAGE);
        }
        if (!domain || !preset.domains?.includes(domain)) {
            throw new Error(UNSUPPORTED_IMAP_PROVIDER_MESSAGE);
        }
        if (!imapHostInput.value.trim()) {
            throw new Error(`${preset.name} is supported for server scanning, but this V1 preset does not include verified IMAP host settings. Enter the provider-published SSL IMAP host before connecting.`);
        }
        return {
            presetId: preset.id,
            displayName: imapDisplayNameInput.value.trim() || email,
            email,
            username: imapUsernameInput.value.trim() || undefined,
            host: imapHostInput.value.trim(),
            port: Number(imapPortInput.value),
            secure: imapSecureInput.checked,
            password: imapPasswordInput.value
        };
    }
    function reusableImapSetupSessionId(session, email) {
        if (!session)
            return undefined;
        if (session.provider && session.provider !== "imap")
            return undefined;
        if (session.email && session.email !== email)
            return undefined;
        return session.sessionId;
    }
    async function startOAuth(provider) {
        const label = provider === "gmail"
            ? gmailLabelInput.value.trim() || undefined
            : microsoftLabelInput.value.trim() || undefined;
        const response = provider === "gmail"
            ? await api.startGoogleOAuth({ label })
            : await api.startMicrosoftOAuth({ label });
        await setSettings({ setupSessionId: response.setupSessionId });
        setStatus(mailboxStatusEl, [
            `Opening ${provider === "gmail" ? "Google" : "Microsoft"} sign-in...`,
            response.security?.securitySummary
        ]
            .filter(Boolean)
            .join(" "), "success");
        window.open(response.authUrl, "_blank", "noopener,noreferrer");
        await pollSetupSession(response.setupSessionId);
    }
    async function sendImapVerification() {
        const payload = collectImapForm();
        const activeSession = await getActiveSetupSession();
        const response = await api.sendImapVerification({
            setupSessionId: reusableImapSetupSessionId(activeSession, payload.email),
            presetId: payload.presetId,
            displayName: payload.displayName,
            email: payload.email,
            username: payload.username,
            host: payload.host,
            port: payload.port,
            secure: payload.secure
        });
        await setSettings({ setupSessionId: response.setupSessionId });
        const { session } = await api.getSetupSession(response.setupSessionId);
        await rememberSession(session);
        setStatus(mailboxStatusEl, response.verificationRequired
            ? `Verification code sent to ${response.maskedDestination}.`
            : "Verification email is unavailable right now. Finish the IMAP connection with the app-specific password or scoped mailbox credential.", "success");
    }
    async function verifyImapCode() {
        const settings = await getSettings();
        if (!settings.setupSessionId) {
            throw new Error("Start IMAP verification first.");
        }
        await api.verifyImapCode({
            setupSessionId: settings.setupSessionId,
            code: imapCodeInput.value.trim().toUpperCase()
        });
        const { session } = await api.getSetupSession(settings.setupSessionId);
        await rememberSession(session);
        setStatus(mailboxStatusEl, "Mailbox verified. Finish the IMAP connection now.", "success");
    }
    async function finishImapConnection() {
        const activeSession = await getActiveSetupSession();
        const payload = collectImapForm();
        const response = await api.connectImap({
            setupSessionId: reusableImapSetupSessionId(activeSession, payload.email),
            ...payload
        });
        if (response.session) {
            await rememberSession(response.session);
        }
        setStatus(mailboxStatusEl, `${response.account.displayName} is connected.`, "success");
        await refreshAccounts({ keepSelection: false });
    }
    function readPolicyPayload() {
        const options = Object.fromEntries(Array.from(optionInputs.entries()).map(([key, select]) => [key, select.value]));
        return {
            basePreset: basePresetSelect.value,
            protectedContacts: textareaToList(protectedContactsInput.value),
            protectedDomains: textareaToList(protectedDomainsInput.value),
            trustedSenders: textareaToList(trustedSendersInput.value),
            trustedDomains: textareaToList(trustedDomainsInput.value),
            options
        };
    }
    async function loadInitialState() {
        const settings = await getSettings();
        customerAccountLink.href = "https://arcwardyn.ai/account";
        const cachedAccounts = await getConnectedAccounts();
        const cachedSession = await getActiveSetupSession();
        const cachedPolicies = await getMailboxPolicies();
        const cachedServerSettings = await getLastServerSettings();
        deviceNameInput.value = deviceNameInput.value || "ArcWardyn";
        renderDeepScanStatus(cachedServerSettings);
        if (cachedSession) {
            setGlobalStatus(sessionStatusMessage(cachedSession), cachedSession.status === "error" ? "error" : "success");
        }
        currentAccounts = cachedAccounts;
        currentPolicyAccountId =
            cachedAccounts.find((account) => account.id === settings.selectedAccountId)?.id ??
                cachedAccounts[0]?.id ??
                null;
        renderAccounts();
        await loadImapPresetCatalog();
        await loadProtectionCatalog();
        const cachedPolicy = currentPolicyAccountId ? cachedPolicies[currentPolicyAccountId] : undefined;
        if (cachedPolicy && currentCatalog) {
            renderOptionGroups(currentCatalog, cachedPolicy);
            applyPolicyToForm(cachedPolicy);
        }
        updateConnectionPill({
            paired: Boolean(settings.deviceToken),
            accountCount: currentAccounts.length,
            serverBaseUrl: settings.serverBaseUrl
        });
        updateSectionVisibility({
            paired: Boolean(settings.deviceToken),
            selectedAccountId: currentPolicyAccountId ?? undefined
        });
        disconnectSection.hidden = !settings.deviceToken;
        if (settings.deviceToken) {
            await refreshServerSettingsSnapshot();
            await refreshAccounts({ keepSelection: true });
        }
        else {
            void refreshServerSettingsSnapshot();
        }
        if (settings.setupSessionId) {
            await pollSetupSession(settings.setupSessionId);
        }
        else {
            setGlobalStatus(settings.deviceToken
                ? "This browser is paired. Connect a mailbox or adjust mailbox protection below."
                : "Create a client invite on the ArcWardyn account website, then paste its full setup link here.");
        }
    }
    disconnectCustomerButton.addEventListener("click", () => {
        void (async () => {
            const confirmed = window.confirm("Disconnect this extension? This removes this browser connection, but does not delete your ArcWardyn account, mailboxes, or other clients.");
            if (!confirmed)
                return;
            setBusy(disconnectCustomerButton, true, "Disconnecting...");
            try {
                const rawResponse = await chrome.runtime.sendMessage({
                    type: "disconnect-customer"
                });
                const response = parseRuntimeResult(rawResponse);
                if (!response?.ok) {
                    throw new Error(response?.error || "The device could not be revoked.");
                }
                setStatus(setupStatusEl, "This extension is disconnected.", "success");
                setGlobalStatus("Open your ArcWardyn account website to connect this browser.", "success");
                await loadInitialState();
            }
            catch (error) {
                setStatus(setupStatusEl, accountAccessAwareErrorMessage(error, "Could not disconnect this extension. Try again while the backend is available."), "error");
            }
            finally {
                setBusy(disconnectCustomerButton, false);
            }
        })();
    });
    connectInviteButton.addEventListener("click", () => {
        void (async () => {
            setBusy(connectInviteButton, true, "Connecting...");
            setStatus(setupStatusEl, "Resolving invite...");
            try {
                const invite = parseInviteInput(inviteInput.value);
                if (!invite) {
                    throw new Error("Paste the complete client invite link created by your ArcWardyn account website.");
                }
                await connectUsingInvite(invite);
                inviteInput.value = "";
            }
            catch (error) {
                const message = accountAccessAwareErrorMessage(error, "Could not connect with that invite.");
                setStatus(setupStatusEl, message, "error");
                setGlobalStatus(message, "error");
            }
            finally {
                setBusy(connectInviteButton, false);
            }
        })();
    });
    connectGmailButton.addEventListener("click", () => {
        void (async () => {
            setBusy(connectGmailButton, true, "Opening...");
            try {
                await startOAuth("gmail");
            }
            catch (error) {
                setStatus(mailboxStatusEl, accountAccessAwareErrorMessage(error, "Could not start Gmail OAuth."), "error");
            }
            finally {
                setBusy(connectGmailButton, false);
            }
        })();
    });
    connectMicrosoftButton.addEventListener("click", () => {
        void (async () => {
            setBusy(connectMicrosoftButton, true, "Opening...");
            try {
                await startOAuth("outlook");
            }
            catch (error) {
                setStatus(mailboxStatusEl, accountAccessAwareErrorMessage(error, "Could not start Microsoft OAuth."), "error");
            }
            finally {
                setBusy(connectMicrosoftButton, false);
            }
        })();
    });
    imapPresetSelect.addEventListener("change", () => {
        applyImapPreset(imapPresetSelect.value);
    });
    imapSendCodeButton.addEventListener("click", () => {
        void (async () => {
            setBusy(imapSendCodeButton, true, "Sending...");
            try {
                await sendImapVerification();
            }
            catch (error) {
                setStatus(mailboxStatusEl, accountAccessAwareErrorMessage(error, "Could not send the IMAP verification code."), "error");
            }
            finally {
                setBusy(imapSendCodeButton, false);
            }
        })();
    });
    imapVerifyButton.addEventListener("click", () => {
        void (async () => {
            setBusy(imapVerifyButton, true, "Verifying...");
            try {
                await verifyImapCode();
            }
            catch (error) {
                setStatus(mailboxStatusEl, accountAccessAwareErrorMessage(error, "Could not verify that IMAP code."), "error");
            }
            finally {
                setBusy(imapVerifyButton, false);
            }
        })();
    });
    imapConnectButton.addEventListener("click", () => {
        void (async () => {
            setBusy(imapConnectButton, true, "Connecting...");
            try {
                await finishImapConnection();
            }
            catch (error) {
                setStatus(mailboxStatusEl, accountAccessAwareErrorMessage(error, "Could not connect that IMAP mailbox."), "error");
            }
            finally {
                setBusy(imapConnectButton, false);
            }
        })();
    });
    refreshAccountsButton.addEventListener("click", () => {
        void (async () => {
            setBusy(refreshAccountsButton, true, "Refreshing...");
            try {
                await refreshAccounts({ keepSelection: true });
            }
            catch (error) {
                setStatus(policyStatusEl, accountAccessAwareErrorMessage(error, "Could not refresh the connected accounts."), "error");
            }
            finally {
                setBusy(refreshAccountsButton, false);
            }
        })();
    });
    savePolicyButton.addEventListener("click", () => {
        void (async () => {
            setBusy(savePolicyButton, true, "Saving...");
            try {
                if (!currentPolicyAccountId) {
                    throw new Error("Select a mailbox first.");
                }
                const response = await api.saveMailboxPolicy(currentPolicyAccountId, readPolicyPayload());
                await setMailboxPolicy(currentPolicyAccountId, response.policy);
                applyPolicyToForm(response.policy);
                setStatus(policyStatusEl, `Saved protection for ${response.account.displayName}. Recent eligible mail will be rechecked with the new mailbox rules.`, "success");
            }
            catch (error) {
                setStatus(policyStatusEl, accountAccessAwareErrorMessage(error, "Could not save mailbox protection."), "error");
            }
            finally {
                setBusy(savePolicyButton, false);
            }
        })();
    });
    resetPolicyButton.addEventListener("click", () => {
        void (async () => {
            setBusy(resetPolicyButton, true, "Resetting...");
            try {
                if (!currentPolicyAccountId) {
                    throw new Error("Select a mailbox first.");
                }
                const response = await api.saveMailboxPolicy(currentPolicyAccountId, {
                    basePreset: basePresetSelect.value,
                    protectedContacts: textareaToList(protectedContactsInput.value),
                    protectedDomains: textareaToList(protectedDomainsInput.value),
                    trustedSenders: textareaToList(trustedSendersInput.value),
                    trustedDomains: textareaToList(trustedDomainsInput.value),
                    restorePresetDefaults: true
                });
                await setMailboxPolicy(currentPolicyAccountId, response.policy);
                applyPolicyToForm(response.policy);
                setStatus(policyStatusEl, "Preset defaults restored for this mailbox.", "success");
            }
            catch (error) {
                setStatus(policyStatusEl, accountAccessAwareErrorMessage(error, "Could not reset mailbox protection."), "error");
            }
            finally {
                setBusy(resetPolicyButton, false);
            }
        })();
    });
    chrome.storage.onChanged.addListener((changes, areaName) => {
        if (areaName !== "local") {
            return;
        }
        if (changes.lastServerSettings) {
            renderDeepScanStatus(changes.lastServerSettings.newValue);
        }
    });
    void loadInitialState().catch((error) => {
        setGlobalStatus(accountAccessAwareErrorMessage(error, "Could not load the setup dashboard."), "error");
    });

})();
//# sourceMappingURL=options.js.map
