diff --git a/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4-mini/index.ts b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4-mini/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..87b293a4f15e3f68f506e98c2abdde6f7b0e2dc9 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4-mini/index.ts @@ -0,0 +1 @@ +export * from "../v4/mini/index.js"; diff --git a/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/errors.ts b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..699c81f31beb0655d26c6cc863807e3cf7740a66 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/errors.ts @@ -0,0 +1,424 @@ +import type { $ZodCheck, $ZodStringFormats } from "./checks.js"; +import { $constructor } from "./core.js"; +import type { $ZodType } from "./schemas.js"; +import * as util from "./util.js"; + +/////////////////////////// +//// base type //// +/////////////////////////// +export interface $ZodIssueBase { + readonly code?: string; + readonly input?: unknown; + readonly path: PropertyKey[]; + readonly message: string; + // [k: string]: unknown; +} + +//////////////////////////////// +//// issue subtypes //// +//////////////////////////////// +export interface $ZodIssueInvalidType extends $ZodIssueBase { + readonly code: "invalid_type"; + readonly expected: $ZodType["_zod"]["def"]["type"]; + readonly input: Input; +} + +export interface $ZodIssueTooBig extends $ZodIssueBase { + readonly code: "too_big"; + readonly origin: "number" | "int" | "bigint" | "date" | "string" | "array" | "set" | "file" | (string & {}); + readonly maximum: number | bigint; + readonly inclusive?: boolean; + readonly exact?: boolean; + readonly input: Input; +} + +export interface $ZodIssueTooSmall extends $ZodIssueBase { + readonly code: "too_small"; + readonly origin: "number" | "int" | "bigint" | "date" | "string" | "array" | "set" | "file" | (string & {}); + readonly minimum: number | bigint; + /** True if the allowable range includes the minimum */ + readonly inclusive?: boolean; + /** True if the allowed value is fixed (e.g.` z.length(5)`), not a range (`z.minLength(5)`) */ + readonly exact?: boolean; + readonly input: Input; +} + +export interface $ZodIssueInvalidStringFormat extends $ZodIssueBase { + readonly code: "invalid_format"; + readonly format: $ZodStringFormats | (string & {}); + readonly pattern?: string; + readonly input: string; +} + +export interface $ZodIssueNotMultipleOf extends $ZodIssueBase { + readonly code: "not_multiple_of"; + readonly divisor: number; + readonly input: Input; +} + +export interface $ZodIssueUnrecognizedKeys extends $ZodIssueBase { + readonly code: "unrecognized_keys"; + readonly keys: string[]; + readonly input: Record; +} + +export interface $ZodIssueInvalidUnion extends $ZodIssueBase { + readonly code: "invalid_union"; + readonly errors: $ZodIssue[][]; + readonly input: unknown; +} + +export interface $ZodIssueInvalidKey extends $ZodIssueBase { + readonly code: "invalid_key"; + readonly origin: "map" | "record"; + readonly issues: $ZodIssue[]; + readonly input: Input; +} + +export interface $ZodIssueInvalidElement extends $ZodIssueBase { + readonly code: "invalid_element"; + readonly origin: "map" | "set"; + readonly key: unknown; + readonly issues: $ZodIssue[]; + readonly input: Input; +} + +export interface $ZodIssueInvalidValue extends $ZodIssueBase { + readonly code: "invalid_value"; + readonly values: util.Primitive[]; + readonly input: Input; +} + +export interface $ZodIssueCustom extends $ZodIssueBase { + readonly code: "custom"; + readonly params?: Record | undefined; + readonly input: unknown; +} + +//////////////////////////////////////////// +//// first-party string formats //// +//////////////////////////////////////////// + +export interface $ZodIssueStringCommonFormats extends $ZodIssueInvalidStringFormat { + format: Exclude<$ZodStringFormats, "regex" | "jwt" | "starts_with" | "ends_with" | "includes">; +} + +export interface $ZodIssueStringInvalidRegex extends $ZodIssueInvalidStringFormat { + format: "regex"; + pattern: string; +} + +export interface $ZodIssueStringInvalidJWT extends $ZodIssueInvalidStringFormat { + format: "jwt"; + algorithm?: string; +} + +export interface $ZodIssueStringStartsWith extends $ZodIssueInvalidStringFormat { + format: "starts_with"; + prefix: string; +} + +export interface $ZodIssueStringEndsWith extends $ZodIssueInvalidStringFormat { + format: "ends_with"; + suffix: string; +} + +export interface $ZodIssueStringIncludes extends $ZodIssueInvalidStringFormat { + format: "includes"; + includes: string; +} + +export type $ZodStringFormatIssues = + | $ZodIssueStringCommonFormats + | $ZodIssueStringInvalidRegex + | $ZodIssueStringInvalidJWT + | $ZodIssueStringStartsWith + | $ZodIssueStringEndsWith + | $ZodIssueStringIncludes; + +//////////////////////// +//// utils ///// +//////////////////////// + +export type $ZodIssue = + | $ZodIssueInvalidType + | $ZodIssueTooBig + | $ZodIssueTooSmall + | $ZodIssueInvalidStringFormat + | $ZodIssueNotMultipleOf + | $ZodIssueUnrecognizedKeys + | $ZodIssueInvalidUnion + | $ZodIssueInvalidKey + | $ZodIssueInvalidElement + | $ZodIssueInvalidValue + | $ZodIssueCustom; + +export type $ZodIssueCode = $ZodIssue["code"]; + +export type $ZodRawIssue = T extends any ? RawIssue : never; +type RawIssue = util.Flatten< + util.MakePartial & { + /** The input data */ + readonly input?: unknown; + /** The schema or check that originated this issue. */ + readonly inst?: $ZodType | $ZodCheck; + /** @deprecated Internal use only. If `true`, Zod will continue executing validation despite this issue. */ + readonly continue?: boolean | undefined; + } & Record +>; + +export interface $ZodErrorMap { + // biome-ignore lint: + (issue: $ZodRawIssue): { message: string } | string | undefined | null; +} + +//////////////////////// ERROR CLASS //////////////////////// + +// const ZOD_ERROR: symbol = Symbol.for("{{zod.error}}"); +export interface $ZodError extends Error { + type: T; + issues: $ZodIssue[]; + _zod: { + output: T; + def: $ZodIssue[]; + }; + stack?: string; + name: string; +} + +const initializer = (inst: $ZodError, def: $ZodIssue[]): void => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false, + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false, + }); + Object.defineProperty(inst, "message", { + get() { + return JSON.stringify(def, util.jsonStringifyReplacer, 2); + }, + enumerable: true, + // configurable: false, + }); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false, + }); +}; + +export const $ZodError: $constructor<$ZodError> = $constructor("$ZodError", initializer); +interface $ZodRealError extends $ZodError {} +export const $ZodRealError: $constructor<$ZodRealError> = $constructor("$ZodError", initializer, { Parent: Error }); + +/////////////////// ERROR UTILITIES //////////////////////// + +// flatten +export type $ZodFlattenedError = _FlattenedError; +type _FlattenedError = { + formErrors: U[]; + fieldErrors: { + [P in keyof T]?: U[]; + }; +}; + +export function flattenError(error: $ZodError): _FlattenedError; +export function flattenError(error: $ZodError, mapper?: (issue: $ZodIssue) => U): _FlattenedError; +export function flattenError(error: $ZodError, mapper = (issue: $ZodIssue) => issue.message): any { + const fieldErrors: any = {}; + const formErrors: any[] = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]!] = fieldErrors[sub.path[0]!] || []; + fieldErrors[sub.path[0]!].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} + +type _ZodFormattedError = T extends [any, ...any[]] + ? { [K in keyof T]?: $ZodFormattedError } + : T extends any[] + ? { [k: number]: $ZodFormattedError } + : T extends object + ? util.Flatten<{ [K in keyof T]?: $ZodFormattedError }> + : any; + +export type $ZodFormattedError = { + _errors: U[]; +} & util.Flatten<_ZodFormattedError>; + +export function formatError(error: $ZodError): $ZodFormattedError; +export function formatError(error: $ZodError, mapper?: (issue: $ZodIssue) => U): $ZodFormattedError; +export function formatError(error: $ZodError, _mapper?: any) { + const mapper: (issue: $ZodIssue) => any = + _mapper || + function (issue: $ZodIssue) { + return issue.message; + }; + const fieldErrors: $ZodFormattedError = { _errors: [] } as any; + const processError = (error: { issues: $ZodIssue[] }) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues })); + } else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }); + } else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }); + } else if (issue.path.length === 0) { + (fieldErrors as any)._errors.push(mapper(issue)); + } else { + let curr: any = 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: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + + curr = curr[el]; + i++; + } + } + } + }; + processError(error); + return fieldErrors; +} + +export type $ZodErrorTree = T extends [any, ...any[]] + ? { errors: U[]; items?: { [K in keyof T]?: $ZodErrorTree } } + : T extends any[] + ? { errors: U[]; items?: Array<$ZodErrorTree> } + : T extends object + ? { errors: U[]; properties?: { [K in keyof T]?: $ZodErrorTree } } + : { errors: U[] }; + +export function treeifyError(error: $ZodError): $ZodErrorTree; +export function treeifyError(error: $ZodError, mapper?: (issue: $ZodIssue) => U): $ZodErrorTree; +export function treeifyError(error: $ZodError, _mapper?: any) { + const mapper: (issue: $ZodIssue) => any = + _mapper || + function (issue: $ZodIssue) { + return issue.message; + }; + const result: $ZodErrorTree = { errors: [] } as any; + const processError = (error: { issues: $ZodIssue[] }, path: PropertyKey[] = []) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, issue.path)); + } else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, issue.path); + } else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, issue.path); + } else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + + let curr: any = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]!; + + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ??= {}; + curr.properties[el] ??= { errors: [] }; + curr = curr.properties[el]; + } else { + curr.items ??= []; + curr.items[el] ??= { errors: [] }; + curr = curr.items[el]; + } + + if (terminal) { + curr.errors.push(mapper(issue)); + } + + i++; + } + } + } + }; + processError(error); + return result; +} + +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +export function toDotPath(path: (string | number | symbol)[]): string { + const segs: string[] = []; + for (const seg of path) { + if (typeof seg === "number") segs.push(`[${seg}]`); + else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) segs.push("."); + segs.push(seg); + } + } + + return segs.join(""); +} + +interface BaseError { + issues: $ZodIssueBase[]; +} + +export function prettifyError(error: BaseError): string { + const lines: string[] = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => a.path.length - b.path.length); + + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) lines.push(` → at ${toDotPath(issue.path)}`); + } + + // Convert Map to formatted string + return lines.join("\n"); +} diff --git a/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/function.ts b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/function.ts new file mode 100644 index 0000000000000000000000000000000000000000..79fd2caad61548f1357b6ced87e180a42effb950 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/function.ts @@ -0,0 +1,176 @@ +import { _array, _tuple, _unknown } from "./api.js"; +import type * as core from "./core.js"; +import { parse, parseAsync } from "./parse.js"; +import * as schemas from "./schemas.js"; +import { $ZodTuple } from "./schemas.js"; +import type * as util from "./util.js"; + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// $ZodFunction ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface $ZodFunctionDef< + In extends $ZodFunctionIn = $ZodFunctionIn, + Out extends $ZodFunctionOut = $ZodFunctionOut, +> { + type: "function"; + input: In; + output: Out; +} + +export type $ZodFunctionArgs = schemas.$ZodType; +export type $ZodFunctionIn = $ZodFunctionArgs; +export type $ZodFunctionOut = schemas.$ZodType; + +export type $InferInnerFunctionType = ( + ...args: $ZodFunctionIn extends Args ? never[] : core.output +) => core.input; + +export type $InferInnerFunctionTypeAsync = ( + ...args: $ZodFunctionIn extends Args ? never[] : core.output +) => util.MaybeAsync>; + +export type $InferOuterFunctionType = ( + ...args: $ZodFunctionIn extends Args ? never[] : core.input +) => core.output; + +export type $InferOuterFunctionTypeAsync = ( + ...args: $ZodFunctionIn extends Args ? never[] : core.input +) => util.MaybeAsync>; + +export class $ZodFunction< + Args extends $ZodFunctionIn = $ZodFunctionIn, + Returns extends $ZodFunctionOut = $ZodFunctionOut, +> { + def: $ZodFunctionDef; + + /** @deprecated */ + _def!: $ZodFunctionDef; + _input!: $InferInnerFunctionType; + _output!: $InferOuterFunctionType; + + constructor(def: $ZodFunctionDef) { + this._def = def; + this.def = def; + } + + implement>( + func: F + ): // allow for return type inference + ( + ...args: Parameters + ) => ReturnType extends ReturnType ? ReturnType : ReturnType { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + const impl = ((...args: any[]) => { + const parsedArgs = this._def.input ? parse(this._def.input, args, undefined, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = func(...(parsedArgs as any)); + return this._def.output ? parse(this._def.output, output, undefined, { callee: impl }) : output; + }) as any; + return impl; + } + + implementAsync>( + func: F + ): F extends $InferOuterFunctionTypeAsync ? F : $InferOuterFunctionTypeAsync { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + + const impl = (async (...args: any[]) => { + const parsedArgs = this._def.input ? await parseAsync(this._def.input, args, undefined, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = await func(...(parsedArgs as any)); + return this._def.output ? parseAsync(this._def.output, output, undefined, { callee: impl }) : output; + }) as any; + return impl; + } + + input( + args: Items, + rest?: Rest + ): $ZodFunction, Returns>; + input(args: NewArgs): $ZodFunction; + input(...args: any[]): $ZodFunction { + const F: any = this.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: this._def.output, + }); + } + + return new F({ + type: "function", + input: args[0], + output: this._def.output, + }); + } + + output(output: NewReturns): $ZodFunction { + const F: any = this.constructor; + return new F({ + type: "function", + input: this._def.input, + output, + }); + } +} + +export interface $ZodFunctionParams { + input?: I; + output?: O; +} + +function _function(): $ZodFunction; +function _function = Array>(params: { + input: In; +}): $ZodFunction<$ZodTuple, $ZodFunctionOut>; +function _function< + const In extends Array = Array, + const Out extends $ZodFunctionOut = $ZodFunctionOut, +>(params: { + input: In; + output: Out; +}): $ZodFunction<$ZodTuple, Out>; +function _function(params: { + input: In; +}): $ZodFunction; +function _function(params: { + output: Out; +}): $ZodFunction<$ZodFunctionIn, Out>; +function _function< + In extends $ZodFunctionIn = $ZodFunctionIn, + Out extends schemas.$ZodType = schemas.$ZodType, +>(params?: { + input: In; + output: Out; +}): $ZodFunction; +function _function(params?: { + output?: schemas.$ZodType; + input?: $ZodFunctionArgs | Array; +}): any { + return new $ZodFunction({ + type: "function", + input: Array.isArray(params?.input) + ? _tuple(schemas.$ZodTuple, params?.input as any) + : (params?.input ?? _array(schemas.$ZodArray, _unknown(schemas.$ZodUnknown))), + output: params?.output ?? _unknown(schemas.$ZodUnknown), + }); +} + +export { _function as function }; diff --git a/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/index.ts b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6887877a45610d7f498aeeeaa369c70742ff188 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/index.ts @@ -0,0 +1,15 @@ +export * from "./core.js"; +export * from "./parse.js"; +export * from "./errors.js"; +export * from "./schemas.js"; +export * from "./checks.js"; +export * from "./versions.js"; +export * as util from "./util.js"; +export * as regexes from "./regexes.js"; +export * as locales from "../locales/index.js"; +export * from "./registries.js"; +export * from "./doc.js"; +export * from "./function.js"; +export * from "./api.js"; +export * from "./to-json-schema.js"; +export * as JSONSchema from "./json-schema.js"; diff --git a/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/json-schema.ts b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/json-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b3abfbe02e824f677a35a3a966ade0e81572025 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/json-schema.ts @@ -0,0 +1,143 @@ +export type Schema = + | ObjectSchema + | ArraySchema + | StringSchema + | NumberSchema + | IntegerSchema + | BooleanSchema + | NullSchema; + +// export type JsonType = "object" | "array" | "string" | "number" | "boolean" | "null" | "integer"; + +// export interface JSONSchema { +// type?: string ; +// $id?: string ; +// id?: string ; +// $schema?: string ; +// $ref?: string ; +// $anchor?: string ; +// $defs?: { [key: string]: JSONSchema } ; +// definitions?: { [key: string]: JSONSchema } ; +// $comment?: string ; +// title?: string ; +// description?: string ; +// default?: unknown ; +// examples?: unknown[] ; +// readOnly?: boolean ; +// writeOnly?: boolean ; +// deprecated?: boolean ; +// allOf?: JSONSchema[] ; +// anyOf?: JSONSchema[] ; +// oneOf?: JSONSchema[] ; +// not?: JSONSchema ; +// if?: JSONSchema ; +// then?: JSONSchema ; +// else?: JSONSchema ; +// enum?: Array ; +// const?: string | number | boolean | null ; +// [k: string]: unknown; + +// /** A special key used as an intermediate representation of extends-style relationships. Omitted as a $ref with additional properties. */ +// // _ref?: JSONSchema; +// _prefault?: unknown ; +// } + +export type _JSONSchema = boolean | JSONSchema; +export type JSONSchema = { + [k: string]: unknown; + $schema?: "https://json-schema.org/draft/2020-12/schema" | "http://json-schema.org/draft-07/schema#"; + $id?: string; + $anchor?: string; + $ref?: string; + $dynamicRef?: string; + $dynamicAnchor?: string; + $vocabulary?: Record; + $comment?: string; + $defs?: Record; + type?: "object" | "array" | "string" | "number" | "boolean" | "null" | "integer"; + additionalItems?: _JSONSchema; + unevaluatedItems?: _JSONSchema; + prefixItems?: _JSONSchema[]; + items?: _JSONSchema | _JSONSchema[]; + contains?: _JSONSchema; + additionalProperties?: _JSONSchema; + unevaluatedProperties?: _JSONSchema; + properties?: Record; + patternProperties?: Record; + dependentSchemas?: Record; + propertyNames?: _JSONSchema; + if?: _JSONSchema; + then?: _JSONSchema; + else?: _JSONSchema; + allOf?: JSONSchema[]; + anyOf?: JSONSchema[]; + oneOf?: JSONSchema[]; + not?: _JSONSchema; + multipleOf?: number; + maximum?: number; + exclusiveMaximum?: number; + minimum?: number; + exclusiveMinimum?: number; + maxLength?: number; + minLength?: number; + pattern?: string; + maxItems?: number; + minItems?: number; + uniqueItems?: boolean; + maxContains?: number; + minContains?: number; + maxProperties?: number; + minProperties?: number; + required?: string[]; + dependentRequired?: Record; + enum?: Array; + const?: string | number | boolean | null; + + // metadata + id?: string; + title?: string; + description?: string; + default?: unknown; + deprecated?: boolean; + readOnly?: boolean; + writeOnly?: boolean; + examples?: unknown[]; + format?: string; + contentMediaType?: string; + contentEncoding?: string; + contentSchema?: JSONSchema; + + // internal + _prefault?: unknown; +}; + +// for backwards compatibility +export type BaseSchema = JSONSchema; + +export interface ObjectSchema extends JSONSchema { + type: "object"; +} + +export interface ArraySchema extends JSONSchema { + type: "array"; +} + +export interface StringSchema extends JSONSchema { + type: "string"; +} + +export interface NumberSchema extends JSONSchema { + type: "number"; +} + +export interface IntegerSchema extends JSONSchema { + type: "integer"; +} + +export interface BooleanSchema extends JSONSchema { + type: "boolean"; +} + +export interface NullSchema extends JSONSchema { + type: "null"; +} diff --git a/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/parse.ts b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/parse.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec046dfe914ab42e33f964955470d161125229d9 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/parse.ts @@ -0,0 +1,94 @@ +import * as core from "./core.js"; +import * as errors from "./errors.js"; +import type * as schemas from "./schemas.js"; +import * as util from "./util.js"; + +export type $ZodErrorClass = { new (issues: errors.$ZodIssue[]): errors.$ZodError }; + +/////////// METHODS /////////// +export type $Parse = ( + schema: T, + value: unknown, + _ctx?: schemas.ParseContext, + _params?: { callee?: util.AnyFunc; Err?: $ZodErrorClass } +) => core.output; + +export const _parse: (_Err: $ZodErrorClass) => $Parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx: schemas.ParseContextInternal = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new core.$ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))); + util.captureStackTrace(e, _params?.callee); + throw e; + } + return result.value as core.output; +}; + +export const parse: $Parse = /* @__PURE__*/ _parse(errors.$ZodRealError); + +export type $ParseAsync = ( + schema: T, + value: unknown, + _ctx?: schemas.ParseContext, + _params?: { callee?: util.AnyFunc; Err?: $ZodErrorClass } +) => Promise>; + +export const _parseAsync: (_Err: $ZodErrorClass) => $ParseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx: schemas.ParseContextInternal = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))); + util.captureStackTrace(e, params?.callee); + throw e; + } + return result.value as core.output; +}; + +export const parseAsync: $ParseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError); + +export type $SafeParse = ( + schema: T, + value: unknown, + _ctx?: schemas.ParseContext +) => util.SafeParseResult>; + +export const _safeParse: (_Err: $ZodErrorClass) => $SafeParse = (_Err) => (schema, value, _ctx) => { + const ctx: schemas.ParseContextInternal = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new core.$ZodAsyncError(); + } + + return result.issues.length + ? { + success: false, + error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + } + : ({ success: true, data: result.value } as any); +}; +export const safeParse: $SafeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError); + +export type $SafeParseAsync = ( + schema: T, + value: unknown, + _ctx?: schemas.ParseContext +) => Promise>>; + +export const _safeParseAsync: (_Err: $ZodErrorClass) => $SafeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx: schemas.ParseContextInternal = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) result = await result; + + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + } + : ({ success: true, data: result.value } as any); +}; + +export const safeParseAsync: $SafeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError); diff --git a/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/regexes.ts b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/regexes.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfcb6a0e1661157a561d5016344bf8dfde0d5fe1 --- /dev/null +++ b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/regexes.ts @@ -0,0 +1,135 @@ +export const cuid: RegExp = /^[cC][^\s-]{8,}$/; +export const cuid2: RegExp = /^[0-9a-z]+$/; +export const ulid: RegExp = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +export const xid: RegExp = /^[0-9a-vA-V]{20}$/; +export const ksuid: RegExp = /^[A-Za-z0-9]{27}$/; +export const nanoid: RegExp = /^[a-zA-Z0-9_-]{21}$/; + +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +export const duration: RegExp = + /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; + +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +export const extendedDuration: RegExp = + /^[-+]?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)?)??$/; + +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +export const guid: RegExp = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; + +/** Returns a regex for validating an RFC 4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +export const uuid = (version?: number | undefined): RegExp => { + if (!version) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; + return new RegExp( + `^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$` + ); +}; +export const uuid4: RegExp = /*@__PURE__*/ uuid(4); +export const uuid6: RegExp = /*@__PURE__*/ uuid(6); +export const uuid7: RegExp = /*@__PURE__*/ uuid(7); + +/** Practical email validation */ +export const email: RegExp = + /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; + +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +export const html5Email: RegExp = + /^[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])?)*$/; + +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +export const rfc5322Email = + /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +export const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; + +export const browserEmail: RegExp = + /^[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])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression + +export const _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +export function emoji(): RegExp { + return new RegExp(_emoji, "u"); +} + +export const ipv4: RegExp = + /^(?:(?: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])$/; +export const ipv6: RegExp = + /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; + +export const cidrv4: RegExp = + /^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/; +export const cidrv6: RegExp = + /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +export const base64: RegExp = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +export const base64url: RegExp = /^[A-Za-z0-9_-]*$/; + +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = +// /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/; +export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +export const domain: RegExp = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; + +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) +export const e164: RegExp = /^\+(?:[0-9]){6,14}[0-9]$/; + +// const dateSource = `((\\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 dateSource = `(?:(?:\\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])))`; +export const date: RegExp = /*@__PURE__*/ new RegExp(`^${dateSource}$`); + +function timeSource(args: { precision?: number | null | undefined }) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = + typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +export function time(args: { + precision?: number | null; + // local?: boolean; +}): RegExp { + return new RegExp(`^${timeSource(args)}$`); +} + +// Adapted from https://stackoverflow.com/a/3143231 +export function datetime(args: { + precision?: number | null; + offset?: boolean; + local?: boolean; +}): RegExp { + const time = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) opts.push(""); + if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); + const timeRegex = `${time}(?:${opts.join("|")})`; + + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} + +export const string = (params?: { minimum?: number | undefined; maximum?: number | undefined }): RegExp => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; + +export const bigint: RegExp = /^\d+n?$/; +export const integer: RegExp = /^\d+$/; +export const number: RegExp = /^-?\d+(?:\.\d+)?/i; +export const boolean: RegExp = /true|false/i; +const _null: RegExp = /null/i; +export { _null as null }; +const _undefined: RegExp = /undefined/i; +export { _undefined as undefined }; + +// regex for string with no uppercase letters +export const lowercase: RegExp = /^[^A-Z]*$/; +// regex for string with no lowercase letters +export const uppercase: RegExp = /^[^a-z]*$/; diff --git a/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/registries.ts b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/registries.ts new file mode 100644 index 0000000000000000000000000000000000000000..14652be8ef041a10431c4e0b374a543827baa73f --- /dev/null +++ b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/registries.ts @@ -0,0 +1,96 @@ +import type * as core from "./core.js"; +import type { $ZodType } from "./schemas.js"; + +export const $output: unique symbol = Symbol("ZodOutput"); +export type $output = typeof $output; +export const $input: unique symbol = Symbol("ZodInput"); +export type $input = typeof $input; + +export type $replace = Meta extends $output + ? core.output + : Meta extends $input + ? core.input + : Meta extends (infer M)[] + ? $replace[] + : Meta extends (...args: infer P) => infer R + ? ( + ...args: { + [K in keyof P]: $replace; // tuple + } + ) => $replace + : // handle objects + Meta extends object + ? { [K in keyof Meta]: $replace } + : Meta; + +type MetadataType = Record | undefined; +export class $ZodRegistry { + _meta!: Meta; + _schema!: Schema; + _map: Map> = new Map(); + _idmap: Map = new Map(); + + add( + schema: S, + ..._meta: undefined extends Meta ? [$replace?] : [$replace] + ): this { + const meta: any = _meta[0]; + this._map.set(schema, meta!); + if (meta && typeof meta === "object" && "id" in meta) { + if (this._idmap.has(meta.id!)) { + throw new Error(`ID ${meta.id} already exists in the registry`); + } + this._idmap.set(meta.id!, schema); + } + return this as any; + } + + clear(): this { + this._map = new Map(); + this._idmap = new Map(); + return this; + } + + remove(schema: Schema): this { + const meta: any = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id!); + } + this._map.delete(schema); + return this; + } + + get(schema: S): $replace | undefined { + // return this._map.get(schema) as any; + + // inherit metadata + const p = schema._zod.parent as Schema; + if (p) { + const pm: any = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + return { ...pm, ...this._map.get(schema) } as any; + } + return this._map.get(schema) as any; + } + + has(schema: Schema): boolean { + return this._map.has(schema); + } +} + +export interface JSONSchemaMeta { + id?: string | undefined; + title?: string | undefined; + description?: string | undefined; + deprecated?: boolean | undefined; + [k: string]: unknown; +} + +export interface GlobalMeta extends JSONSchemaMeta {} + +// registries +export function registry(): $ZodRegistry { + return new $ZodRegistry(); +} + +export const globalRegistry: $ZodRegistry = /*@__PURE__*/ registry(); diff --git a/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/schemas.ts b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce16838549a39ff2522a1b6eea2b8994265f1b0f --- /dev/null +++ b/node_modules/@jimp/plugin-circle/node_modules/zod/src/v4/core/schemas.ts @@ -0,0 +1,3842 @@ +import type { $ZodTypeDiscriminable } from "./api.js"; +import * as checks from "./checks.js"; +import * as core from "./core.js"; +import { Doc } from "./doc.js"; +import type * as errors from "./errors.js"; +import { safeParse, safeParseAsync } from "./parse.js"; +import * as regexes from "./regexes.js"; +import type { StandardSchemaV1 } from "./standard-schema.js"; +import * as util from "./util.js"; +import { version } from "./versions.js"; + +///////////////////////////// PARSE ////////////////////////////// + +export interface ParseContext { + /** Customize error messages. */ + readonly error?: errors.$ZodErrorMap; + /** Include the `input` field in issue objects. Default `false`. */ + readonly reportInput?: boolean; + /** Skip eval-based fast path. Default `false`. */ + readonly jitless?: boolean; + /** Abort validation after the first error. Default `false`. */ + // readonly abortEarly?: boolean; +} + +/** @internal */ +export interface ParseContextInternal extends ParseContext { + readonly async?: boolean | undefined; +} + +export interface ParsePayload { + value: T; + issues: errors.$ZodRawIssue[]; +} + +export type CheckFn = (input: ParsePayload) => util.MaybeAsync; + +///////////////////////////// SCHEMAS ////////////////////////////// + +export interface $ZodTypeDef { + type: + | "string" + | "number" + | "int" + | "boolean" + | "bigint" + | "symbol" + | "null" + | "undefined" + | "void" // merge with undefined? + | "never" + | "any" + | "unknown" + | "date" + | "object" + | "record" + | "file" + | "array" + | "tuple" + | "union" + | "intersection" + | "map" + | "set" + | "enum" + | "literal" + | "nullable" + | "optional" + | "nonoptional" + | "success" + | "transform" + | "default" + | "prefault" + | "catch" + | "nan" + | "pipe" + | "readonly" + | "template_literal" + | "promise" + | "lazy" + | "custom"; + error?: errors.$ZodErrorMap | undefined; + checks?: checks.$ZodCheck[]; +} + +export interface _$ZodTypeInternals { + /** The `@zod/core` version of this schema */ + version: typeof version; + + /** Schema definition. */ + def: $ZodTypeDef; + // types: Types; + + /** @internal Randomly generated ID for this schema. */ + // id: string; + + /** @internal List of deferred initializers. */ + deferred: util.AnyFunc[] | undefined; + + /** @internal Parses input and runs all checks (refinements). */ + run(payload: ParsePayload, ctx: ParseContextInternal): util.MaybeAsync; + + /** @internal Parses input, doesn't run checks. */ + parse(payload: ParsePayload, ctx: ParseContextInternal): util.MaybeAsync; + + /** @internal Stores identifiers for the set of traits implemented by this schema. */ + traits: Set; + + /** @internal Indicates that a schema output type should be considered optional inside objects. + * @default Required + */ + + /** @internal */ + optin?: "optional" | undefined; + /** @internal */ + optout?: "optional" | undefined; + + /** @internal The set of literal values that will pass validation. Must be an exhaustive set. Used to determine optionality in z.record(). + * + * Defined on: enum, const, literal, null, undefined + * Passthrough: optional, nullable, branded, default, catch, pipe + * Todo: unions? + */ + values?: util.PrimitiveSet | undefined; + + /** @internal A set of literal discriminators used for the fast path in discriminated unions. */ + propValues?: util.PropValues | undefined; + + /** @internal This flag indicates that a schema validation can be represented with a regular expression. Used to determine allowable schemas in z.templateLiteral(). */ + pattern: RegExp | undefined; + + /** @internal The constructor function of this schema. */ + constr: new ( + def: any + ) => $ZodType; + + /** @internal A catchall object for bag metadata related to this schema. Commonly modified by checks using `onattach`. */ + bag: Record; + + /** @internal The set of issues this schema might throw during type checking. */ + isst: errors.$ZodIssueBase; + + /** An optional method used to override `toJSONSchema` logic. */ + toJSONSchema?: () => unknown; + + /** @internal The parent of this schema. Only set during certain clone operations. */ + parent?: $ZodType | undefined; +} +/** @internal */ +export interface $ZodTypeInternals extends _$ZodTypeInternals { + /** @internal The inferred output type */ + output: O; //extends { $out: infer O } ? O : Out; + /** @internal The inferred input type */ + input: I; //extends { $in: infer I } ? I : In; +} + +export type $ZodStandardSchema = StandardSchemaV1.Props, core.output>; + +export type SomeType = { _zod: _$ZodTypeInternals }; + +export interface $ZodType< + O = unknown, + I = unknown, + Internals extends $ZodTypeInternals = $ZodTypeInternals, +> { + _zod: Internals; + "~standard": $ZodStandardSchema; +} +export interface _$ZodType + extends $ZodType { + // _zod: T; +} + +export const $ZodType: core.$constructor<$ZodType> = /*@__PURE__*/ core.$constructor("$ZodType", (inst, def) => { + inst ??= {} as any; + + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = version; + + const checks = [...(inst._zod.def.checks ?? [])]; + + // if inst is itself a checks.$ZodCheck, run it as a check + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst as any); + } + // + + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + + if (checks.length === 0) { + // deferred initializer + // inst._zod.parse is not yet defined + inst._zod.deferred ??= []; + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = ( + payload: ParsePayload, + checks: checks.$ZodCheck[], + ctx?: ParseContextInternal | undefined + ): util.MaybeAsync => { + let isAborted = util.aborted(payload); + + let asyncResult!: Promise | undefined; + for (const ch of checks) { + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) continue; + } else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload as any) as any as ParsePayload; + + if (_ instanceof Promise && ctx?.async === false) { + throw new core.$ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) return; + if (!isAborted) isAborted = util.aborted(payload, currLen); + }); + } else { + const nextLen = payload.issues.length; + if (nextLen === currLen) continue; + if (!isAborted) isAborted = util.aborted(payload, currLen); + } + } + + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + + inst._zod.run = (payload, ctx) => { + const result = inst._zod.parse(payload, ctx); + + if (result instanceof Promise) { + if (ctx.async === false) throw new core.$ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + + return runChecks(result, checks, ctx); + }; + } + + inst["~standard"] = { + validate: (value: unknown) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_) { + return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues })); + } + }, + vendor: "zod", + version: 1 as const, + }; +}); + +export { clone } from "./util.js"; + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// $ZodString ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// +export interface $ZodStringDef extends $ZodTypeDef { + type: "string"; + coerce?: boolean; + checks?: checks.$ZodCheck[]; +} + +export interface $ZodStringInternals extends $ZodTypeInternals { + def: $ZodStringDef; + /** @deprecated Internal API, use with caution (not deprecated) */ + pattern: RegExp; + + /** @deprecated Internal API, use with caution (not deprecated) */ + isst: errors.$ZodIssueInvalidType; + bag: util.LoosePartial<{ + minimum: number; + maximum: number; + patterns: Set; + format: string; + contentEncoding: string; + }>; +} + +export interface $ZodString extends _$ZodType<$ZodStringInternals> { + // _zod: $ZodStringInternals; +} + +export const $ZodString: core.$constructor<$ZodString> = /*@__PURE__*/ core.$constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } catch (_) {} + + if (typeof payload.value === "string") return payload; + + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); + +////////////////////////////// ZodStringFormat ////////////////////////////// + +export interface $ZodStringFormatDef + extends $ZodStringDef, + checks.$ZodCheckStringFormatDef {} + +export interface $ZodStringFormatInternals + extends $ZodStringInternals, + checks.$ZodCheckStringFormatInternals { + def: $ZodStringFormatDef; +} +export interface $ZodStringFormat extends $ZodType { + _zod: $ZodStringFormatInternals; +} + +export const $ZodStringFormat: core.$constructor<$ZodStringFormat> = /*@__PURE__*/ core.$constructor( + "$ZodStringFormat", + (inst, def): void => { + // check initialization must come first + checks.$ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); + } +); + +////////////////////////////// ZodGUID ////////////////////////////// +export interface $ZodGUIDDef extends $ZodStringFormatDef<"guid"> {} +export interface $ZodGUIDInternals extends $ZodStringFormatInternals<"guid"> {} + +export interface $ZodGUID extends $ZodType { + _zod: $ZodGUIDInternals; +} + +export const $ZodGUID: core.$constructor<$ZodGUID> = /*@__PURE__*/ core.$constructor("$ZodGUID", (inst, def): void => { + def.pattern ??= regexes.guid; + $ZodStringFormat.init(inst, def); +}); + +////////////////////////////// ZodUUID ////////////////////////////// + +export interface $ZodUUIDDef extends $ZodStringFormatDef<"uuid"> { + version?: "v1" | "v2" | "v3" | "v4" | "v5" | "v6" | "v7" | "v8"; +} + +export interface $ZodUUIDInternals extends $ZodStringFormatInternals<"uuid"> { + def: $ZodUUIDDef; +} + +export interface $ZodUUID extends $ZodType { + _zod: $ZodUUIDInternals; +} + +export const $ZodUUID: core.$constructor<$ZodUUID> = /*@__PURE__*/ core.$constructor("$ZodUUID", (inst, def): void => { + if (def.version) { + const versionMap: Record = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ??= regexes.uuid(v); + } else def.pattern ??= regexes.uuid(); + $ZodStringFormat.init(inst, def); +}); + +////////////////////////////// ZodEmail ////////////////////////////// + +export interface $ZodEmailDef extends $ZodStringFormatDef<"email"> {} +export interface $ZodEmailInternals extends $ZodStringFormatInternals<"email"> {} +export interface $ZodEmail extends $ZodType { + _zod: $ZodEmailInternals; +} + +export const $ZodEmail: core.$constructor<$ZodEmail> = /*@__PURE__*/ core.$constructor( + "$ZodEmail", + (inst, def): void => { + def.pattern ??= regexes.email; + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodURL ////////////////////////////// + +export interface $ZodURLDef extends $ZodStringFormatDef<"url"> { + hostname?: RegExp | undefined; + protocol?: RegExp | undefined; +} +export interface $ZodURLInternals extends $ZodStringFormatInternals<"url"> { + def: $ZodURLDef; +} + +export interface $ZodURL extends $ZodType { + _zod: $ZodURLInternals; +} + +export const $ZodURL: core.$constructor<$ZodURL> = /*@__PURE__*/ core.$constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const orig = payload.value; + const url = new URL(orig); + const href = url.href; + + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: regexes.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + } + + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + } + + // payload.value = url.href; + if (!orig.endsWith("/") && href.endsWith("/")) { + payload.value = href.slice(0, -1); + } else { + payload.value = href; + } + + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); + +////////////////////////////// ZodEmoji ////////////////////////////// + +export interface $ZodEmojiDef extends $ZodStringFormatDef<"emoji"> {} +export interface $ZodEmojiInternals extends $ZodStringFormatInternals<"emoji"> {} + +export interface $ZodEmoji extends $ZodType { + _zod: $ZodEmojiInternals; +} + +export const $ZodEmoji: core.$constructor<$ZodEmoji> = /*@__PURE__*/ core.$constructor( + "$ZodEmoji", + (inst, def): void => { + def.pattern ??= regexes.emoji(); + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodNanoID ////////////////////////////// + +export interface $ZodNanoIDDef extends $ZodStringFormatDef<"nanoid"> {} +export interface $ZodNanoIDInternals extends $ZodStringFormatInternals<"nanoid"> {} + +export interface $ZodNanoID extends $ZodType { + _zod: $ZodNanoIDInternals; +} + +export const $ZodNanoID: core.$constructor<$ZodNanoID> = /*@__PURE__*/ core.$constructor( + "$ZodNanoID", + (inst, def): void => { + def.pattern ??= regexes.nanoid; + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodCUID ////////////////////////////// + +export interface $ZodCUIDDef extends $ZodStringFormatDef<"cuid"> {} +export interface $ZodCUIDInternals extends $ZodStringFormatInternals<"cuid"> {} + +export interface $ZodCUID extends $ZodType { + _zod: $ZodCUIDInternals; +} + +export const $ZodCUID: core.$constructor<$ZodCUID> = /*@__PURE__*/ core.$constructor("$ZodCUID", (inst, def): void => { + def.pattern ??= regexes.cuid; + $ZodStringFormat.init(inst, def); +}); + +////////////////////////////// ZodCUID2 ////////////////////////////// + +export interface $ZodCUID2Def extends $ZodStringFormatDef<"cuid2"> {} +export interface $ZodCUID2Internals extends $ZodStringFormatInternals<"cuid2"> {} + +export interface $ZodCUID2 extends $ZodType { + _zod: $ZodCUID2Internals; +} + +export const $ZodCUID2: core.$constructor<$ZodCUID2> = /*@__PURE__*/ core.$constructor( + "$ZodCUID2", + (inst, def): void => { + def.pattern ??= regexes.cuid2; + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodULID ////////////////////////////// + +export interface $ZodULIDDef extends $ZodStringFormatDef<"ulid"> {} +export interface $ZodULIDInternals extends $ZodStringFormatInternals<"ulid"> {} + +export interface $ZodULID extends $ZodType { + _zod: $ZodULIDInternals; +} + +export const $ZodULID: core.$constructor<$ZodULID> = /*@__PURE__*/ core.$constructor("$ZodULID", (inst, def): void => { + def.pattern ??= regexes.ulid; + $ZodStringFormat.init(inst, def); +}); + +////////////////////////////// ZodXID ////////////////////////////// + +export interface $ZodXIDDef extends $ZodStringFormatDef<"xid"> {} +export interface $ZodXIDInternals extends $ZodStringFormatInternals<"xid"> {} + +export interface $ZodXID extends $ZodType { + _zod: $ZodXIDInternals; +} + +export const $ZodXID: core.$constructor<$ZodXID> = /*@__PURE__*/ core.$constructor("$ZodXID", (inst, def): void => { + def.pattern ??= regexes.xid; + $ZodStringFormat.init(inst, def); +}); + +////////////////////////////// ZodKSUID ////////////////////////////// + +export interface $ZodKSUIDDef extends $ZodStringFormatDef<"ksuid"> {} +export interface $ZodKSUIDInternals extends $ZodStringFormatInternals<"ksuid"> {} + +export interface $ZodKSUID extends $ZodType { + _zod: $ZodKSUIDInternals; +} + +export const $ZodKSUID: core.$constructor<$ZodKSUID> = /*@__PURE__*/ core.$constructor( + "$ZodKSUID", + (inst, def): void => { + def.pattern ??= regexes.ksuid; + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodISODateTime ////////////////////////////// + +export interface $ZodISODateTimeDef extends $ZodStringFormatDef<"datetime"> { + precision: number | null; + offset: boolean; + local: boolean; +} + +export interface $ZodISODateTimeInternals extends $ZodStringFormatInternals { + def: $ZodISODateTimeDef; +} + +export interface $ZodISODateTime extends $ZodType { + _zod: $ZodISODateTimeInternals; +} + +export const $ZodISODateTime: core.$constructor<$ZodISODateTime> = /*@__PURE__*/ core.$constructor( + "$ZodISODateTime", + (inst, def): void => { + def.pattern ??= regexes.datetime(def); + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodISODate ////////////////////////////// + +export interface $ZodISODateDef extends $ZodStringFormatDef<"date"> {} +export interface $ZodISODateInternals extends $ZodStringFormatInternals<"date"> {} + +export interface $ZodISODate extends $ZodType { + _zod: $ZodISODateInternals; +} + +export const $ZodISODate: core.$constructor<$ZodISODate> = /*@__PURE__*/ core.$constructor( + "$ZodISODate", + (inst, def): void => { + def.pattern ??= regexes.date; + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodISOTime ////////////////////////////// + +export interface $ZodISOTimeDef extends $ZodStringFormatDef<"time"> { + precision?: number | null; +} + +export interface $ZodISOTimeInternals extends $ZodStringFormatInternals<"time"> { + def: $ZodISOTimeDef; +} + +export interface $ZodISOTime extends $ZodType { + _zod: $ZodISOTimeInternals; +} + +export const $ZodISOTime: core.$constructor<$ZodISOTime> = /*@__PURE__*/ core.$constructor( + "$ZodISOTime", + (inst, def): void => { + def.pattern ??= regexes.time(def); + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodISODuration ////////////////////////////// + +export interface $ZodISODurationDef extends $ZodStringFormatDef<"duration"> {} +export interface $ZodISODurationInternals extends $ZodStringFormatInternals<"duration"> {} + +export interface $ZodISODuration extends $ZodType { + _zod: $ZodISODurationInternals; +} + +export const $ZodISODuration: core.$constructor<$ZodISODuration> = /*@__PURE__*/ core.$constructor( + "$ZodISODuration", + (inst, def): void => { + def.pattern ??= regexes.duration; + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodIPv4 ////////////////////////////// + +export interface $ZodIPv4Def extends $ZodStringFormatDef<"ipv4"> { + version?: "v4"; +} + +export interface $ZodIPv4Internals extends $ZodStringFormatInternals<"ipv4"> { + def: $ZodIPv4Def; +} + +export interface $ZodIPv4 extends $ZodType { + _zod: $ZodIPv4Internals; +} + +export const $ZodIPv4: core.$constructor<$ZodIPv4> = /*@__PURE__*/ core.$constructor("$ZodIPv4", (inst, def): void => { + def.pattern ??= regexes.ipv4; + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag as $ZodStringInternals["bag"]; + bag.format = `ipv4`; + }); +}); + +////////////////////////////// ZodIPv6 ////////////////////////////// + +export interface $ZodIPv6Def extends $ZodStringFormatDef<"ipv6"> { + version?: "v6"; +} + +export interface $ZodIPv6Internals extends $ZodStringFormatInternals<"ipv6"> { + def: $ZodIPv6Def; +} + +export interface $ZodIPv6 extends $ZodType { + _zod: $ZodIPv6Internals; +} + +export const $ZodIPv6: core.$constructor<$ZodIPv6> = /*@__PURE__*/ core.$constructor("$ZodIPv6", (inst, def): void => { + def.pattern ??= regexes.ipv6; + $ZodStringFormat.init(inst, def); + + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag as $ZodStringInternals["bag"]; + bag.format = `ipv6`; + }); + + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + // return; + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); + +////////////////////////////// ZodCIDRv4 ////////////////////////////// + +export interface $ZodCIDRv4Def extends $ZodStringFormatDef<"cidrv4"> { + version?: "v4"; +} + +export interface $ZodCIDRv4Internals extends $ZodStringFormatInternals<"cidrv4"> { + def: $ZodCIDRv4Def; +} + +export interface $ZodCIDRv4 extends $ZodType { + _zod: $ZodCIDRv4Internals; +} + +export const $ZodCIDRv4: core.$constructor<$ZodCIDRv4> = /*@__PURE__*/ core.$constructor( + "$ZodCIDRv4", + (inst, def): void => { + def.pattern ??= regexes.cidrv4; + $ZodStringFormat.init(inst, def); + } +); + +////////////////////////////// ZodCIDRv6 ////////////////////////////// + +export interface $ZodCIDRv6Def extends $ZodStringFormatDef<"cidrv6"> { + version?: "v6"; +} + +export interface $ZodCIDRv6Internals extends $ZodStringFormatInternals<"cidrv6"> { + def: $ZodCIDRv6Def; +} + +export interface $ZodCIDRv6 extends $ZodType { + _zod: $ZodCIDRv6Internals; +} + +export const $ZodCIDRv6: core.$constructor<$ZodCIDRv6> = /*@__PURE__*/ core.$constructor( + "$ZodCIDRv6", + (inst, def): void => { + def.pattern ??= regexes.cidrv6; // not used for validation + $ZodStringFormat.init(inst, def); + + inst._zod.check = (payload) => { + const [address, prefix] = payload.value.split("/"); + try { + if (!prefix) throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) throw new Error(); + if (prefixNum < 0 || prefixNum > 128) throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; + } +); + +////////////////////////////// ZodBase64 ////////////////////////////// +export function isValidBase64(data: string): boolean { + if (data === "") return true; + if (data.length % 4 !== 0) return false; + try { + atob(data); + return true; + } catch { + return false; + } +} + +export interface $ZodBase64Def extends $ZodStringFormatDef<"base64"> {} +export interface $ZodBase64Internals extends $ZodStringFormatInternals<"base64"> {} + +export interface $ZodBase64 extends $ZodType { + _zod: $ZodBase64Internals; +} + +export const $ZodBase64: core.$constructor<$ZodBase64> = /*@__PURE__*/ core.$constructor( + "$ZodBase64", + (inst, def): void => { + def.pattern ??= regexes.base64; + $ZodStringFormat.init(inst, def); + + inst._zod.onattach.push((inst) => { + inst._zod.bag.contentEncoding = "base64"; + }); + + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) return; + + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; + } +); + +////////////////////////////// ZodBase64 ////////////////////////////// +export function isValidBase64URL(data: string): boolean { + if (!regexes.base64url.test(data)) return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} + +export interface $ZodBase64URLDef extends $ZodStringFormatDef<"base64url"> {} +export interface $ZodBase64URLInternals extends $ZodStringFormatInternals<"base64url"> {} + +export interface $ZodBase64URL extends $ZodType { + _zod: $ZodBase64URLInternals; +} + +export const $ZodBase64URL: core.$constructor<$ZodBase64URL> = /*@__PURE__*/ core.$constructor( + "$ZodBase64URL", + (inst, def): void => { + def.pattern ??= regexes.base64url; + $ZodStringFormat.init(inst, def); + + inst._zod.onattach.push((inst) => { + inst._zod.bag.contentEncoding = "base64url"; + }); + + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) return; + + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; + } +); + +////////////////////////////// ZodE164 ////////////////////////////// + +export interface $ZodE164Def extends $ZodStringFormatDef<"e164"> {} +export interface $ZodE164Internals extends $ZodStringFormatInternals<"e164"> {} + +export interface $ZodE164 extends $ZodType { + _zod: $ZodE164Internals; +} + +export const $ZodE164: core.$constructor<$ZodE164> = /*@__PURE__*/ core.$constructor("$ZodE164", (inst, def): void => { + def.pattern ??= regexes.e164; + $ZodStringFormat.init(inst, def); +}); + +////////////////////////////// ZodJWT ////////////////////////////// + +export function isValidJWT(token: string, algorithm: util.JWTAlgorithm | null = null): boolean { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) return false; + const [header] = tokensParts; + if (!header) return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; + if (!parsedHeader.alg) return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; + return true; + } catch { + return false; + } +} + +export interface $ZodJWTDef extends $ZodStringFormatDef<"jwt"> { + alg?: util.JWTAlgorithm | undefined; +} + +export interface $ZodJWTInternals extends $ZodStringFormatInternals<"jwt"> { + def: $ZodJWTDef; +} + +export interface $ZodJWT extends $ZodType { + _zod: $ZodJWTInternals; +} + +export const $ZodJWT: core.$constructor<$ZodJWT> = /*@__PURE__*/ core.$constructor("$ZodJWT", (inst, def): void => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) return; + + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); + +////////////////////////////// ZodCustomStringFormat ////////////////////////////// + +export interface $ZodCustomStringFormatDef extends $ZodStringFormatDef { + fn: (val: string) => unknown; +} + +export interface $ZodCustomStringFormatInternals + extends $ZodStringFormatInternals { + def: $ZodCustomStringFormatDef; +} + +export interface $ZodCustomStringFormat extends $ZodStringFormat { + _zod: $ZodCustomStringFormatInternals; +} + +export const $ZodCustomStringFormat: core.$constructor<$ZodCustomStringFormat> = /*@__PURE__*/ core.$constructor( + "$ZodCustomStringFormat", + (inst, def): void => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) return; + + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort, + }); + }; + } +); + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodNumber ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// + +export interface $ZodNumberDef extends $ZodTypeDef { + type: "number"; + coerce?: boolean; + // checks: checks.$ZodCheck[]; +} + +export interface $ZodNumberInternals extends $ZodTypeInternals { + def: $ZodNumberDef; + /** @deprecated Internal API, use with caution (not deprecated) */ + pattern: RegExp; + /** @deprecated Internal API, use with caution (not deprecated) */ + isst: errors.$ZodIssueInvalidType; + bag: util.LoosePartial<{ + minimum: number; + maximum: number; + exclusiveMinimum: number; + exclusiveMaximum: number; + format: string; + pattern: RegExp; + }>; +} + +export interface $ZodNumber extends $ZodType { + _zod: $ZodNumberInternals; +} + +export const $ZodNumber: core.$constructor<$ZodNumber> = /*@__PURE__*/ core.$constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number; + + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } catch (_) {} + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + + const received = + typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? "Infinity" + : undefined + : undefined; + + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), + }); + return payload; + }; +}); + +/////////////////////////////////////////////// +////////// ZodNumberFormat ////////// +/////////////////////////////////////////////// +export interface $ZodNumberFormatDef extends $ZodNumberDef, checks.$ZodCheckNumberFormatDef {} + +export interface $ZodNumberFormatInternals extends $ZodNumberInternals, checks.$ZodCheckNumberFormatInternals { + def: $ZodNumberFormatDef; + isst: errors.$ZodIssueInvalidType; +} + +export interface $ZodNumberFormat extends $ZodType { + _zod: $ZodNumberFormatInternals; +} + +export const $ZodNumberFormat: core.$constructor<$ZodNumberFormat> = /*@__PURE__*/ core.$constructor( + "$ZodNumber", + (inst, def) => { + checks.$ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checksp + } +); + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// /////////// +////////// $ZodBoolean ////////// +////////// /////////// +/////////////////////////////////////////// +/////////////////////////////////////////// + +export interface $ZodBooleanDef extends $ZodTypeDef { + type: "boolean"; + coerce?: boolean; + checks?: checks.$ZodCheck[]; +} + +export interface $ZodBooleanInternals extends $ZodTypeInternals { + pattern: RegExp; + def: $ZodBooleanDef; + isst: errors.$ZodIssueInvalidType; +} + +export interface $ZodBoolean extends $ZodType { + _zod: $ZodBooleanInternals; +} + +export const $ZodBoolean: core.$constructor<$ZodBoolean> = /*@__PURE__*/ core.$constructor( + "$ZodBoolean", + (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.boolean; + + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } catch (_) {} + const input = payload.value; + if (typeof input === "boolean") return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, + }); + return payload; + }; + } +); + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// $ZodBigInt ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface $ZodBigIntDef extends $ZodTypeDef { + type: "bigint"; + coerce?: boolean; + // checks: checks.$ZodCheck[]; +} + +export interface $ZodBigIntInternals extends $ZodTypeInternals { + pattern: RegExp; + /** @internal Internal API, use with caution */ + def: $ZodBigIntDef; + isst: errors.$ZodIssueInvalidType; + bag: util.LoosePartial<{ + minimum: bigint; + maximum: bigint; + format: string; + }>; +} + +export interface $ZodBigInt extends $ZodType { + _zod: $ZodBigIntInternals; +} + +export const $ZodBigInt: core.$constructor<$ZodBigInt> = /*@__PURE__*/ core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } catch (_) {} + + if (typeof payload.value === "bigint") return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); + +/////////////////////////////////////////////// +////////// ZodBigIntFormat ////////// +/////////////////////////////////////////////// +export interface $ZodBigIntFormatDef extends $ZodBigIntDef, checks.$ZodCheckBigIntFormatDef { + check: "bigint_format"; +} + +export interface $ZodBigIntFormatInternals extends $ZodBigIntInternals, checks.$ZodCheckBigIntFormatInternals { + def: $ZodBigIntFormatDef; +} + +export interface $ZodBigIntFormat extends $ZodType { + _zod: $ZodBigIntFormatInternals; +} + +export const $ZodBigIntFormat: core.$constructor<$ZodBigIntFormat> = /*@__PURE__*/ core.$constructor( + "$ZodBigInt", + (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks + } +); + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodSymbol ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface $ZodSymbolDef extends $ZodTypeDef { + type: "symbol"; +} + +export interface $ZodSymbolInternals extends $ZodTypeInternals { + def: $ZodSymbolDef; + isst: errors.$ZodIssueInvalidType; +} + +export interface $ZodSymbol extends $ZodType { + _zod: $ZodSymbolInternals; +} + +export const $ZodSymbol: core.$constructor<$ZodSymbol> = /*@__PURE__*/ core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodUndefined ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface $ZodUndefinedDef extends $ZodTypeDef { + type: "undefined"; +} + +export interface $ZodUndefinedInternals extends $ZodTypeInternals { + pattern: RegExp; + def: $ZodUndefinedDef; + values: util.PrimitiveSet; + isst: errors.$ZodIssueInvalidType; +} + +export interface $ZodUndefined extends $ZodType { + _zod: $ZodUndefinedInternals; +} + +export const $ZodUndefined: core.$constructor<$ZodUndefined> = /*@__PURE__*/ core.$constructor( + "$ZodUndefined", + (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, + }); + return payload; + }; + } +); + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// $ZodNull ///////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// + +export interface $ZodNullDef extends $ZodTypeDef { + type: "null"; +} + +export interface $ZodNullInternals extends $ZodTypeInternals { + pattern: RegExp; + def: $ZodNullDef; + values: util.PrimitiveSet; + isst: errors.$ZodIssueInvalidType; +} + +export interface $ZodNull extends $ZodType { + _zod: $ZodNullInternals; +} + +export const $ZodNull: core.$constructor<$ZodNull> = /*@__PURE__*/ core.$constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.null; + inst._zod.values = new Set([null]); + + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); + +////////////////////////////////////// +////////////////////////////////////// +////////// ////////// +////////// $ZodAny ////////// +////////// ////////// +////////////////////////////////////// +////////////////////////////////////// + +export interface $ZodAnyDef extends $ZodTypeDef { + type: "any"; +} + +export interface $ZodAnyInternals extends $ZodTypeInternals { + def: $ZodAnyDef; + isst: never; +} + +export interface $ZodAny extends $ZodType { + _zod: $ZodAnyInternals; +} + +export const $ZodAny: core.$constructor<$ZodAny> = /*@__PURE__*/ core.$constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload) => payload; +}); + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// $ZodUnknown ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface $ZodUnknownDef extends $ZodTypeDef { + type: "unknown"; +} + +export interface $ZodUnknownInternals extends $ZodTypeInternals { + def: $ZodUnknownDef; + isst: never; +} + +export interface $ZodUnknown extends $ZodType { + _zod: $ZodUnknownInternals; +} + +export const $ZodUnknown: core.$constructor<$ZodUnknown> = /*@__PURE__*/ core.$constructor( + "$ZodUnknown", + (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload) => payload; + } +); + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// $ZodNever ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// + +export interface $ZodNeverDef extends $ZodTypeDef { + type: "never"; +} + +export interface $ZodNeverInternals extends $ZodTypeInternals { + def: $ZodNeverDef; + isst: errors.$ZodIssueInvalidType; +} + +export interface $ZodNever extends $ZodType { + _zod: $ZodNeverInternals; +} + +export const $ZodNever: core.$constructor<$ZodNever> = /*@__PURE__*/ core.$constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// $ZodVoid ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// + +export interface $ZodVoidDef extends $ZodTypeDef { + type: "void"; +} + +export interface $ZodVoidInternals extends $ZodTypeInternals { + def: $ZodVoidDef; + isst: errors.$ZodIssueInvalidType; +} + +export interface $ZodVoid extends $ZodType { + _zod: $ZodVoidInternals; +} + +export const $ZodVoid: core.$constructor<$ZodVoid> = /*@__PURE__*/ core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); + +/////////////////////////////////////// +/////////////////////////////////////// +////////// //////// +////////// $ZodDate //////// +////////// //////// +/////////////////////////////////////// +/////////////////////////////////////// +export interface $ZodDateDef extends $ZodTypeDef { + type: "date"; + coerce?: boolean; +} + +export interface $ZodDateInternals extends $ZodTypeInternals { + def: $ZodDateDef; + isst: errors.$ZodIssueInvalidType; // | errors.$ZodIssueInvalidDate; + bag: util.LoosePartial<{ + minimum: Date; + maximum: Date; + format: string; + }>; +} + +export interface $ZodDate extends $ZodType { + _zod: $ZodDateInternals; +} + +export const $ZodDate: core.$constructor<$ZodDate> = /*@__PURE__*/ core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value as string | number | Date); + } catch (_err: any) {} + } + const input = payload.value; + + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + + return payload; + }; +}); + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// $ZodArray ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// + +export interface $ZodArrayDef extends $ZodTypeDef { + type: "array"; + element: T; +} + +export interface $ZodArrayInternals extends _$ZodTypeInternals { + //$ZodTypeInternals[], core.input[]> { + def: $ZodArrayDef; + isst: errors.$ZodIssueInvalidType; + output: core.output[]; + input: core.input[]; +} + +export interface $ZodArray extends $ZodType> {} + +function handleArrayResult(result: ParsePayload, final: ParsePayload, index: number) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} + +export const $ZodArray: core.$constructor<$ZodArray> = /*@__PURE__*/ core.$constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + + payload.value = Array(input.length); + const proms: Promise[] = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run( + { + value: item, + issues: [], + }, + ctx + ); + + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } else { + handleArrayResult(result, payload, i); + } + } + + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}); + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// $ZodObject ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +type OptionalOutSchema = { _zod: { optout: "optional" } }; +type OptionalInSchema = { _zod: { optin: "optional" } }; + +export type $InferObjectOutput> = string extends keyof T + ? util.IsAny extends true + ? Record + : Record> + : keyof (T & Extra) extends never + ? Record + : util.Prettify< + { + -readonly [k in keyof T as T[k] extends OptionalOutSchema ? never : k]: T[k]["_zod"]["output"]; + } & { + -readonly [k in keyof T as T[k] extends OptionalOutSchema ? k : never]?: T[k]["_zod"]["output"]; + } & Extra + >; + +export type $InferObjectInput> = string extends keyof T + ? util.IsAny extends true + ? Record + : Record> + : keyof (T & Extra) extends never + ? Record + : util.Prettify< + { + -readonly [k in keyof T as T[k] extends OptionalInSchema ? never : k]: T[k]["_zod"]["input"]; + } & { + -readonly [k in keyof T as T[k] extends OptionalInSchema ? k : never]?: T[k]["_zod"]["input"]; + } & Extra + >; + +function handleObjectResult(result: ParsePayload, final: ParsePayload, key: PropertyKey) { + // if(isOptional) + if (result.issues.length) { + final.issues.push(...util.prefixIssues(key, result.issues)); + } + + (final.value as any)[key] = result.value; +} + +function handleOptionalObjectResult(result: ParsePayload, final: ParsePayload, key: PropertyKey, input: any) { + if (result.issues.length) { + // validation failed against value schema + if (input[key] === undefined) { + // if input was undefined, ignore the error + if (key in input) { + (final.value as any)[key] = undefined; + } else { + (final.value as any)[key] = result.value; + } + } else { + final.issues.push(...util.prefixIssues(key, result.issues)); + } + } else if (result.value === undefined) { + // validation returned `undefined` + if (key in input) (final.value as any)[key] = undefined; + } else { + // non-undefined value + (final.value as any)[key] = result.value; + } +} + +export type $ZodObjectConfig = { out: Record; in: Record }; + +export type $loose = { + out: Record; + in: Record; +}; +export type $strict = { + out: {}; + in: {}; +}; +export type $strip = { + out: {}; + in: {}; +}; + +export type $catchall = { + out: { [k: string]: core.output }; + in: { [k: string]: core.input }; +}; + +export type $ZodShape = Readonly<{ [k: string]: $ZodType }>; + +export interface $ZodObjectDef extends $ZodTypeDef { + type: "object"; + shape: Shape; + catchall?: $ZodType | undefined; +} + +export interface $ZodObjectInternals< + /** @ts-ignore Cast variance */ + out Shape extends Readonly<$ZodShape> = Readonly<$ZodShape>, + out Config extends $ZodObjectConfig = $ZodObjectConfig, +> extends _$ZodTypeInternals { + def: $ZodObjectDef; + config: Config; + isst: errors.$ZodIssueInvalidType | errors.$ZodIssueUnrecognizedKeys; + propValues: util.PropValues; + output: $InferObjectOutput; + input: $InferObjectInput; +} +export type $ZodLooseShape = Record; + +export interface $ZodObject< + /** @ts-ignore Cast variance */ + out Shape extends Readonly<$ZodShape> = Readonly<$ZodShape>, + out Params extends $ZodObjectConfig = $ZodObjectConfig, +> extends $ZodType> { + "~standard": $ZodStandardSchema; +} + +export const $ZodObject: core.$constructor<$ZodObject> = /*@__PURE__*/ core.$constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + + const _normalized = util.cached(() => { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!(def.shape[k] instanceof $ZodType)) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + } + } + const okeys = util.optionalKeys(def.shape); + + return { + shape: def.shape, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; + }); + + util.defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues: util.PropValues = {}; + for (const key in shape) { + const field = shape[key]!._zod; + if (field.values) { + propValues[key] ??= new Set(); + for (const v of field.values) propValues[key].add(v); + } + } + return propValues; + }); + + const generateFastpass = (shape: any) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + + const parseStr = (key: string) => { + const k = util.esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + + doc.write(`const input = payload.value;`); + + const ids: any = Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + + // A: preserve key order { + doc.write(`const newResult = {}`); + for (const key of normalized.keys) { + if (normalized.optionalKeys.has(key)) { + const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + const k = util.esc(key); + doc.write(` + if (${id}.issues.length) { + if (input[${k}] === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${id}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}], + })) + ); + } + } else if (${id}.value === undefined) { + if (${k} in input) newResult[${k}] = undefined; + } else { + newResult[${k}] = ${id}.value; + } + `); + } else { + const id = ids[key]; + // const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(` + if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${util.esc(key)}, ...iss.path] : [${util.esc(key)}] + })));`); + doc.write(`newResult[${util.esc(key)}] = ${id}.value`); + } + } + + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload: any, ctx: any) => fn(shape, payload, ctx); + }; + + let fastpass!: ReturnType; + + const isObject = util.isObject; + const jit = !core.globalConfig.jitless; + const allowsEval = util.allowsEval; + + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const catchall = def.catchall; + + let value!: typeof _normalized.value; + + inst._zod.parse = (payload, ctx) => { + value ??= _normalized.value; + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + + const proms: Promise[] = []; + + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + } else { + payload.value = {}; + + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]!; + + // do not add omitted optional keys + // if (!(key in input)) { + // if (optionalKeys.has(key)) continue; + // payload.issues.push({ + // code: "invalid_type", + // path: [key], + // expected: "nonoptional", + // note: `Missing required key: "${key}"`, + // input, + // inst, + // }); + // } + + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; + + if (r instanceof Promise) { + proms.push( + r.then((r) => + isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key) + ) + ); + } else if (isOptional) { + handleOptionalObjectResult(r, payload, key, input); + } else { + handleObjectResult(r, payload, key); + } + } + } + + if (!catchall) { + // return payload; + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + const unrecognized: string[] = []; + // iterate over input keys + const keySet = value.keySet; + const _catchall = catchall._zod; + const t = _catchall.def.type; + for (const key of Object.keys(input)) { + if (keySet.has(key)) continue; + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + + if (r instanceof Promise) { + proms.push(r.then((r) => handleObjectResult(r, payload, key))); + } else { + handleObjectResult(r, payload, key); + } + } + + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + }); + } + + if (!proms.length) return payload; + return Promise.all(proms).then(() => { + return payload; + }); + }; +}); + +///////////////////////////////////////// +///////////////////////////////////////// +////////// /////////// +////////// $ZodUnion ////////// +////////// /////////// +///////////////////////////////////////// +///////////////////////////////////////// +// use generic to distribute union types +export type $InferUnionOutput = T extends any ? core.output : never; +export type $InferUnionInput = T extends any ? core.input : never; +export interface $ZodUnionDef extends $ZodTypeDef { + type: "union"; + options: Options; +} + +type IsOptionalIn = T extends OptionalInSchema ? true : false; +type IsOptionalOut = T extends OptionalOutSchema ? true : false; + +export interface $ZodUnionInternals extends _$ZodTypeInternals { + def: $ZodUnionDef; + isst: errors.$ZodIssueInvalidUnion; + pattern: T[number]["_zod"]["pattern"]; + values: T[number]["_zod"]["values"]; //GetValues; + output: $InferUnionOutput; + input: $InferUnionInput; + // if any element in the union is optional, then the union is optional + optin: IsOptionalIn extends false ? "optional" | undefined : "optional"; + optout: IsOptionalOut extends false ? "optional" | undefined : "optional"; +} + +export interface $ZodUnion + extends $ZodType> { + _zod: $ZodUnionInternals; +} + +function handleUnionResults(results: ParsePayload[], final: ParsePayload, inst: $ZodUnion, ctx?: ParseContext) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + + return final; +} + +export const $ZodUnion: core.$constructor<$ZodUnion> = /*@__PURE__*/ core.$constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + + util.defineLazy(inst._zod, "optin", () => + def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined + ); + + util.defineLazy(inst._zod, "optout", () => + def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined + ); + + util.defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values!))); + } + return undefined; + }); + + util.defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p!.source)).join("|")})$`); + } + return undefined; + }); + + inst._zod.parse = (payload, ctx) => { + let async = false; + + const results: util.MaybeAsync[] = []; + for (const option of def.options) { + const result = option._zod.run( + { + value: payload.value, + issues: [], + }, + ctx + ); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) return result; + results.push(result); + } + } + + if (!async) return handleUnionResults(results as ParsePayload[], payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results as ParsePayload[], payload, inst, ctx); + }); + }; +}); + +////////////////////////////////////////////////////// +////////////////////////////////////////////////////// +////////// ////////// +////////// $ZodDiscriminatedUnion ////////// +////////// ////////// +////////////////////////////////////////////////////// +////////////////////////////////////////////////////// + +export interface $ZodDiscriminatedUnionDef + extends $ZodUnionDef { + discriminator: string; + unionFallback?: boolean; +} + +export interface $ZodDiscriminatedUnionInternals + extends $ZodUnionInternals { + def: $ZodDiscriminatedUnionDef; + propValues: util.PropValues; +} + +export interface $ZodDiscriminatedUnion extends $ZodType { + _zod: $ZodDiscriminatedUnionInternals; +} + +export const $ZodDiscriminatedUnion: core.$constructor<$ZodDiscriminatedUnion> = + /*@__PURE__*/ + core.$constructor("$ZodDiscriminatedUnion", (inst, def) => { + $ZodUnion.init(inst, def); + + const _super = inst._zod.parse; + util.defineLazy(inst._zod, "propValues", () => { + const propValues: util.PropValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv!)) { + if (!propValues[k]) propValues[k] = new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + + const disc = util.cached(() => { + const opts = def.options as $ZodTypeDiscriminable[]; + const map: Map = new Map(); + for (const o of opts) { + const values = o._zod.propValues[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map.set(v, o); + } + } + return map; + }); + + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util.isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; + } + + const opt = disc.value.get(input?.[def.discriminator] as any); + if (opt) { + return opt._zod.run(payload, ctx) as any; + } + + if (def.unionFallback) { + return _super(payload, ctx); + } + + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + input, + path: [def.discriminator], + inst, + }); + + return payload; + }; + }); + +//////////////////////////////////////////////// +//////////////////////////////////////////////// +////////// ////////// +////////// $ZodIntersection ////////// +////////// ////////// +//////////////////////////////////////////////// +//////////////////////////////////////////////// + +export interface $ZodIntersectionDef + extends $ZodTypeDef { + type: "intersection"; + left: Left; + right: Right; +} + +export interface $ZodIntersectionInternals + extends $ZodTypeInternals & core.output, core.input & core.input> { + def: $ZodIntersectionDef; + isst: never; + optin: A["_zod"]["optin"] | B["_zod"]["optin"]; + optout: A["_zod"]["optout"] | B["_zod"]["optout"]; +} + +export interface $ZodIntersection extends $ZodType { + _zod: $ZodIntersectionInternals; +} + +export const $ZodIntersection: core.$constructor<$ZodIntersection> = /*@__PURE__*/ core.$constructor( + "$ZodIntersection", + (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + } + + return handleIntersectionResults(payload, left, right); + }; + } +); + +function mergeValues( + a: any, + b: any +): { valid: true; data: any } | { valid: false; mergeErrorPath: (string | number)[] } { + // const aType = parse.t(a); + // const bType = parse.t(b); + + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (util.isPlainObject(a) && util.isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + + const newObj: any = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; + } + + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + + const newArray: unknown[] = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + + newArray.push(sharedValue.data); + } + + return { valid: true, data: newArray }; + } + + return { valid: false, mergeErrorPath: [] }; +} + +function handleIntersectionResults(result: ParsePayload, left: ParsePayload, right: ParsePayload): ParsePayload { + if (left.issues.length) { + result.issues.push(...left.issues); + } + if (right.issues.length) { + result.issues.push(...right.issues); + } + if (util.aborted(result)) return result; + + const merged = mergeValues(left.value, right.value); + + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + + result.value = merged.data; + return result; +} + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// $ZodTuple ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// + +export interface $ZodTupleDef< + T extends util.TupleItems = readonly $ZodType[], + Rest extends SomeType | null = $ZodType | null, +> extends $ZodTypeDef { + type: "tuple"; + items: T; + rest: Rest; +} + +export type $InferTupleInputType = [ + ...TupleInputTypeWithOptionals, + ...(Rest extends SomeType ? core.input[] : []), +]; +type TupleInputTypeNoOptionals = { + [k in keyof T]: core.input; +}; +type TupleInputTypeWithOptionals = T extends readonly [ + ...infer Prefix extends SomeType[], + infer Tail extends SomeType, +] + ? Tail["_zod"]["optin"] extends "optional" + ? [...TupleInputTypeWithOptionals, core.input?] + : TupleInputTypeNoOptionals + : []; + +export type $InferTupleOutputType = [ + ...TupleOutputTypeWithOptionals, + ...(Rest extends SomeType ? core.output[] : []), +]; +type TupleOutputTypeNoOptionals = { + [k in keyof T]: core.output; +}; +type TupleOutputTypeWithOptionals = T extends readonly [ + ...infer Prefix extends SomeType[], + infer Tail extends SomeType, +] + ? Tail["_zod"]["optout"] extends "optional" + ? [...TupleOutputTypeWithOptionals, core.output?] + : TupleOutputTypeNoOptionals + : []; + +export interface $ZodTupleInternals< + T extends util.TupleItems = readonly $ZodType[], + Rest extends SomeType | null = $ZodType | null, +> extends $ZodTypeInternals<$InferTupleOutputType, $InferTupleInputType> { + def: $ZodTupleDef; + isst: errors.$ZodIssueInvalidType | errors.$ZodIssueTooBig | errors.$ZodIssueTooSmall; +} + +export interface $ZodTuple< + T extends util.TupleItems = readonly $ZodType[], + Rest extends SomeType | null = $ZodType | null, +> extends $ZodType { + _zod: $ZodTupleInternals; +} + +export const $ZodTuple: core.$constructor<$ZodTuple> = /*@__PURE__*/ core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + + payload.value = []; + const proms: Promise[] = []; + + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload.issues.push({ + input, + inst, + origin: "array" as const, + ...(tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }), + }); + return payload; + } + } + + let i = -1; + for (const item of items) { + i++; + if (i >= input.length) if (i >= optStart) continue; + const result = item._zod.run( + { + value: input[i], + issues: [], + }, + ctx + ); + + if (result instanceof Promise) { + proms.push(result.then((result) => handleTupleResult(result, payload, i))); + } else { + handleTupleResult(result, payload, i); + } + } + + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run( + { + value: el, + issues: [], + }, + ctx + ); + + if (result instanceof Promise) { + proms.push(result.then((result) => handleTupleResult(result, payload, i))); + } else { + handleTupleResult(result, payload, i); + } + } + } + + if (proms.length) return Promise.all(proms).then(() => payload); + return payload; + }; +}); + +function handleTupleResult(result: ParsePayload, final: ParsePayload, index: number) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// $ZodRecord ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export type $ZodRecordKey = $ZodType; // $HasValues | $HasPattern; +export interface $ZodRecordDef + extends $ZodTypeDef { + type: "record"; + keyType: Key; + valueType: Value; +} + +// export type $InferZodRecordOutput< +// Key extends $ZodRecordKey = $ZodRecordKey, +// Value extends SomeType = $ZodType, +// > = undefined extends Key["_zod"]["values"] +// ? string extends core.output +// ? Record, core.output> +// : number extends core.output +// ? Record, core.output> +// : symbol extends core.output +// ? Record, core.output> +// : Record, core.output> +// : Record, core.output>; +export type $InferZodRecordOutput< + Key extends $ZodRecordKey = $ZodRecordKey, + Value extends SomeType = $ZodType, +> = Key extends $partial + ? Partial, core.output>> + : Record, core.output>; + +// export type $InferZodRecordInput< +// Key extends $ZodRecordKey = $ZodRecordKey, +// Value extends SomeType = $ZodType, +// > = undefined extends Key["_zod"]["values"] +// ? string extends core.input +// ? Record, core.input> +// : number extends core.input +// ? Record, core.input> +// : symbol extends core.input +// ? Record, core.input> +// : Record, core.input> +// : Record, core.input>; +export type $InferZodRecordInput< + Key extends $ZodRecordKey = $ZodRecordKey, + Value extends SomeType = $ZodType, +> = Key extends $partial + ? Partial, core.input>> + : Record, core.input>; + +export interface $ZodRecordInternals + extends $ZodTypeInternals<$InferZodRecordOutput, $InferZodRecordInput> { + def: $ZodRecordDef; + isst: errors.$ZodIssueInvalidType | errors.$ZodIssueInvalidKey>; + optin?: "optional" | undefined; + optout?: "optional" | undefined; +} + +export type $partial = { "~~partial": true }; +export interface $ZodRecord + extends $ZodType { + _zod: $ZodRecordInternals; +} + +export const $ZodRecord: core.$constructor<$ZodRecord> = /*@__PURE__*/ core.$constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + + if (!util.isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + + const proms: Promise[] = []; + + if (def.keyType._zod.values) { + const values = def.keyType._zod.values!; + payload.value = {}; + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + + if (result instanceof Promise) { + proms.push( + result.then((result) => { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + }) + ); + } else { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + } + } + } + + let unrecognized!: string[]; + for (const key in input) { + if (!values.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + }); + } + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + + if (keyResult.issues.length) { + payload.issues.push({ + origin: "record", + code: "invalid_key", + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + input: key, + path: [key], + inst, + }); + payload.value[keyResult.value as PropertyKey] = keyResult.value; + continue; + } + + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + + if (result instanceof Promise) { + proms.push( + result.then((result) => { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[keyResult.value as PropertyKey] = result.value; + }) + ); + } else { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[keyResult.value as PropertyKey] = result.value; + } + } + } + + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// $ZodMap ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export interface $ZodMapDef extends $ZodTypeDef { + type: "map"; + keyType: Key; + valueType: Value; +} + +export interface $ZodMapInternals + extends $ZodTypeInternals, core.output>, Map, core.input>> { + def: $ZodMapDef; + isst: errors.$ZodIssueInvalidType | errors.$ZodIssueInvalidKey | errors.$ZodIssueInvalidElement; + optin?: "optional" | undefined; + optout?: "optional" | undefined; +} + +export interface $ZodMap extends $ZodType { + _zod: $ZodMapInternals; +} + +export const $ZodMap: core.$constructor<$ZodMap> = /*@__PURE__*/ core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + + const proms: Promise[] = []; + payload.value = new Map(); + + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push( + Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + }) + ); + } else { + handleMapResult(keyResult as ParsePayload, valueResult as ParsePayload, payload, key, input, inst, ctx); + } + } + + if (proms.length) return Promise.all(proms).then(() => payload); + return payload; + }; +}); + +function handleMapResult( + keyResult: ParsePayload, + valueResult: ParsePayload, + final: ParsePayload>, + key: unknown, + input: Map, + inst: $ZodMap, + ctx?: ParseContext | undefined +): void { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key as PropertyKey, keyResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_key", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key as PropertyKey, valueResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// $ZodSet ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// +export interface $ZodSetDef extends $ZodTypeDef { + type: "set"; + valueType: T; +} + +export interface $ZodSetInternals + extends $ZodTypeInternals>, Set>> { + def: $ZodSetDef; + isst: errors.$ZodIssueInvalidType; + optin?: "optional" | undefined; + optout?: "optional" | undefined; +} + +export interface $ZodSet extends $ZodType { + _zod: $ZodSetInternals; +} + +export const $ZodSet: core.$constructor<$ZodSet> = /*@__PURE__*/ core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + + const proms: Promise[] = []; + payload.value = new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } else handleSetResult(result, payload); + } + + if (proms.length) return Promise.all(proms).then(() => payload); + return payload; + }; +}); + +function handleSetResult(result: ParsePayload, final: ParsePayload>) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// $ZodEnum ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +export type $InferEnumOutput = T[keyof T] & {}; +export type $InferEnumInput = T[keyof T] & {}; + +export interface $ZodEnumDef extends $ZodTypeDef { + type: "enum"; + entries: T; +} + +export interface $ZodEnumInternals< + /** @ts-ignore Cast variance */ + out T extends util.EnumLike = util.EnumLike, +> extends $ZodTypeInternals<$InferEnumOutput, $InferEnumInput> { + // enum: T; + + def: $ZodEnumDef; + /** @deprecated Internal API, use with caution (not deprecated) */ + values: util.PrimitiveSet; + /** @deprecated Internal API, use with caution (not deprecated) */ + pattern: RegExp; + isst: errors.$ZodIssueInvalidValue; +} + +export interface $ZodEnum extends $ZodType { + _zod: $ZodEnumInternals; +} + +export const $ZodEnum: core.$constructor<$ZodEnum> = /*@__PURE__*/ core.$constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + + const values = util.getEnumValues(def.entries); + + inst._zod.values = new Set(values); + + inst._zod.pattern = new RegExp( + `^(${values + .filter((k) => util.propertyKeyTypes.has(typeof k)) + .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o.toString())) + .join("|")})$` + ); + + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}); + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// $ZodLiteral ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// + +export interface $ZodLiteralDef extends $ZodTypeDef { + type: "literal"; + values: T[]; +} + +export interface $ZodLiteralInternals extends $ZodTypeInternals { + def: $ZodLiteralDef; + values: Set; + pattern: RegExp; + isst: errors.$ZodIssueInvalidValue; +} + +export interface $ZodLiteral extends $ZodType { + _zod: $ZodLiteralInternals; +} + +export const $ZodLiteral: core.$constructor<$ZodLiteral> = /*@__PURE__*/ core.$constructor( + "$ZodLiteral", + (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.values = new Set(def.values); + inst._zod.pattern = new RegExp( + `^(${def.values + + .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o ? o.toString() : String(o))) + .join("|")})$` + ); + + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; + } +); + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// $ZodConst ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// + +// export interface $ZodConstDef extends $ZodTypeDef { +// type: "const"; +// value: unknown; +// } + +// export _interface $ZodConstInternals extends $ZodTypeInternals { +// _def: $ZodConstDef; +// _values: util.PrimitiveSet; +// _pattern: RegExp; +// _isst: errors.$ZodIssueInvalidValue; +// } + +// export const $ZodConst: core.$constructor<{_zod: $ZodConstInternals}> = /*@__PURE__*/ core.$constructor("$ZodConst", (inst, def) => { +// $ZodType.init(inst, def); + +// if (util.primitiveTypes.has(typeof def.value) || def.value === null) { +// inst._zod.values = new Set(def.value as any); +// } + +// if (util.propertyKeyTypes.has(typeof def.value)) { +// inst._zod.pattern = new RegExp( +// `^(${typeof def.value === "string" ? util.escapeRegex(def.value) : (def.value as any).toString()})$` +// ); +// } else { +// throw new Error("Const value cannot be converted to regex"); +// } + +// inst._zod.parse = (payload, _ctx) => { +// payload.value = def.value; // always override +// return payload; +// }; +// }); + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// $ZodFile ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +// provide a fallback in case the File interface isn't provided in the environment +declare global { + interface File {} +} + +export interface $ZodFileDef extends $ZodTypeDef { + type: "file"; +} + +export interface $ZodFileInternals extends $ZodTypeInternals { + def: $ZodFileDef; + isst: errors.$ZodIssueInvalidType; + bag: util.LoosePartial<{ + minimum: number; + maximum: number; + mime: util.MimeTypes[]; + }>; +} + +export interface $ZodFile extends $ZodType { + _zod: $ZodFileInternals; +} + +export const $ZodFile: core.$constructor<$ZodFile> = /*@__PURE__*/ core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); + +////////////////////////////////////////////// +////////////////////////////////////////////// +////////// ////////// +////////// $ZodTransform ////////// +////////// ////////// +////////////////////////////////////////////// +////////////////////////////////////////////// +export interface $ZodTransformDef extends $ZodTypeDef { + type: "transform"; + transform: (input: unknown, payload: ParsePayload) => util.MaybeAsync; +} +export interface $ZodTransformInternals extends $ZodTypeInternals { + def: $ZodTransformDef; + isst: never; +} + +export interface $ZodTransform extends $ZodType { + _zod: $ZodTransformInternals; +} + +export const $ZodTransform: core.$constructor<$ZodTransform> = /*@__PURE__*/ core.$constructor( + "$ZodTransform", + (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const _out = def.transform(payload.value, payload); + if (_ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + + if (_out instanceof Promise) { + throw new core.$ZodAsyncError(); + } + + payload.value = _out; + return payload; + }; + } +); + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodOptional ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface $ZodOptionalDef extends $ZodTypeDef { + type: "optional"; + innerType: T; +} + +export interface $ZodOptionalInternals + extends $ZodTypeInternals | undefined, core.input | undefined> { + def: $ZodOptionalDef; + optin: "optional"; + optout: "optional"; + isst: never; + values: T["_zod"]["values"]; + pattern: T["_zod"]["pattern"]; +} + +export interface $ZodOptional extends $ZodType { + _zod: $ZodOptionalInternals; +} + +export const $ZodOptional: core.$constructor<$ZodOptional> = /*@__PURE__*/ core.$constructor( + "$ZodOptional", + (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + + util.defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; + }); + util.defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined; + }); + + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === undefined) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; + } +); + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodNullable ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface $ZodNullableDef extends $ZodTypeDef { + type: "nullable"; + innerType: T; +} + +export interface $ZodNullableInternals + extends $ZodTypeInternals | null, core.input | null> { + def: $ZodNullableDef; + optin: T["_zod"]["optin"]; + optout: T["_zod"]["optout"]; + isst: never; + values: T["_zod"]["values"]; + pattern: T["_zod"]["pattern"]; +} + +export interface $ZodNullable extends $ZodType { + _zod: $ZodNullableInternals; +} + +export const $ZodNullable: core.$constructor<$ZodNullable> = /*@__PURE__*/ core.$constructor( + "$ZodNullable", + (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + + util.defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined; + }); + + util.defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; + }); + + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) return payload; + return def.innerType._zod.run(payload, ctx); + }; + } +); +// ); + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodDefault ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface $ZodDefaultDef extends $ZodTypeDef { + type: "default"; + innerType: T; + /** The default value. May be a getter. */ + defaultValue: util.NoUndefined>; +} + +export interface $ZodDefaultInternals + extends $ZodTypeInternals>, core.input | undefined> { + def: $ZodDefaultDef; + optin: "optional"; + optout?: "optional" | undefined; // required + isst: never; + values: T["_zod"]["values"]; +} + +export interface $ZodDefault extends $ZodType { + _zod: $ZodDefaultInternals; +} + +export const $ZodDefault: core.$constructor<$ZodDefault> = /*@__PURE__*/ core.$constructor( + "$ZodDefault", + (inst, def) => { + $ZodType.init(inst, def); + + // inst._zod.qin = "true"; + inst._zod.optin = "optional"; + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault always returns the default value immediately. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; + } +); + +function handleDefaultResult(payload: ParsePayload, def: $ZodDefaultDef) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodPrefault ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// + +export interface $ZodPrefaultDef extends $ZodTypeDef { + type: "prefault"; + innerType: T; + /** The default value. May be a getter. */ + defaultValue: core.input; +} + +export interface $ZodPrefaultInternals + extends $ZodTypeInternals>, core.input | undefined> { + def: $ZodPrefaultDef; + optin: "optional"; + optout?: "optional" | undefined; + isst: never; + values: T["_zod"]["values"]; +} + +export interface $ZodPrefault extends $ZodType { + _zod: $ZodPrefaultInternals; +} + +export const $ZodPrefault: core.$constructor<$ZodPrefault> = /*@__PURE__*/ core.$constructor( + "$ZodPrefault", + (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.optin = "optional"; + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; + } +); + +/////////////////////////////////////////////// +/////////////////////////////////////////////// +////////// ////////// +////////// $ZodNonOptional ////////// +////////// ////////// +/////////////////////////////////////////////// +/////////////////////////////////////////////// +export interface $ZodNonOptionalDef extends $ZodTypeDef { + type: "nonoptional"; + innerType: T; +} + +export interface $ZodNonOptionalInternals + extends $ZodTypeInternals>, util.NoUndefined>> { + def: $ZodNonOptionalDef; + isst: errors.$ZodIssueInvalidType; + values: T["_zod"]["values"]; + optin: "optional" | undefined; + optout: "optional" | undefined; +} + +export interface $ZodNonOptional extends $ZodType { + _zod: $ZodNonOptionalInternals; +} + +export const $ZodNonOptional: core.$constructor<$ZodNonOptional> = /*@__PURE__*/ core.$constructor( + "$ZodNonOptional", + (inst, def) => { + $ZodType.init(inst, def); + + util.defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; + } +); + +function handleNonOptionalResult(payload: ParsePayload, inst: $ZodNonOptional) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodCoalesce ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +// export interface $ZodCoalesceDef extends $ZodTypeDef { +// type: "coalesce"; +// innerType: T; +// defaultValue: () => NonNullable; +// } + +// export _interface $ZodCoalesceInternals +// extends $ZodTypeInternals, T['_zod']["input"] | undefined | null> { +// _def: $ZodCoalesceDef; +// _isst: errors.$ZodIssueInvalidType; +// _qin: "true"; +// } + +// function handleCoalesceResult(payload: ParsePayload, def: $ZodCoalesceDef) { +// payload.value ??= def.defaultValue(); +// return payload; +// } + +// export const $ZodCoalesce: core.$constructor<{_zod: $ZodCoalesceInternals}> = /*@__PURE__*/ core.$constructor( +// "$ZodCoalesce", +// (inst, def) => { +// $ZodType.init(inst, def); +// inst._zod.qin = "true"; +// inst._zod.parse = (payload, ctx) => { +// const result = def.innerType._zod.run(payload, ctx); +// if (result instanceof Promise) { +// return result.then((result) => handleCoalesceResult(result, def)); +// } +// return handleCoalesceResult(result, def); +// }; +// } +// ); + +///////////////////////////////////////////// +///////////////////////////////////////////// +////////// ////////// +////////// $ZodSuccess ////////// +////////// ////////// +///////////////////////////////////////////// +///////////////////////////////////////////// +export interface $ZodSuccessDef extends $ZodTypeDef { + type: "success"; + innerType: T; +} + +export interface $ZodSuccessInternals extends $ZodTypeInternals> { + def: $ZodSuccessDef; + isst: never; + optin: T["_zod"]["optin"]; + optout: "optional" | undefined; +} + +export interface $ZodSuccess extends $ZodType { + _zod: $ZodSuccessInternals; +} + +export const $ZodSuccess: core.$constructor<$ZodSuccess> = /*@__PURE__*/ core.$constructor( + "$ZodSuccess", + (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; + } +); + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodCatch ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface $ZodCatchCtx extends ParsePayload { + /** @deprecated Use `ctx.issues` */ + error: { issues: errors.$ZodIssue[] }; + /** @deprecated Use `ctx.value` */ + input: unknown; +} +export interface $ZodCatchDef extends $ZodTypeDef { + type: "catch"; + innerType: T; + catchValue: (ctx: $ZodCatchCtx) => unknown; +} + +export interface $ZodCatchInternals + extends $ZodTypeInternals, core.input | util.Whatever> { + def: $ZodCatchDef; + // qin: T["_zod"]["qin"]; + // qout: T["_zod"]["qout"]; + + optin: T["_zod"]["optin"]; + optout: T["_zod"]["optout"]; + isst: never; + values: T["_zod"]["values"]; +} + +export interface $ZodCatch extends $ZodType { + _zod: $ZodCatchInternals; +} + +export const $ZodCatch: core.$constructor<$ZodCatch> = /*@__PURE__*/ core.$constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }, + input: payload.value, + }); + payload.issues = []; + } + + return payload; + }); + } + + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }, + input: payload.value, + }); + payload.issues = []; + } + + return payload; + }; +}); + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodNaN ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface $ZodNaNDef extends $ZodTypeDef { + type: "nan"; +} + +export interface $ZodNaNInternals extends $ZodTypeInternals { + def: $ZodNaNDef; + isst: errors.$ZodIssueInvalidType; +} + +export interface $ZodNaN extends $ZodType { + _zod: $ZodNaNInternals; +} + +export const $ZodNaN: core.$constructor<$ZodNaN> = /*@__PURE__*/ core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}); + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodPipe ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// +export interface $ZodPipeDef extends $ZodTypeDef { + type: "pipe"; + in: A; + out: B; +} + +export interface $ZodPipeInternals + extends $ZodTypeInternals, core.input> { + def: $ZodPipeDef; + isst: never; + values: A["_zod"]["values"]; + optin: A["_zod"]["optin"]; + optout: B["_zod"]["optout"]; +} + +export interface $ZodPipe extends $ZodType { + _zod: $ZodPipeInternals; +} + +export const $ZodPipe: core.$constructor<$ZodPipe> = /*@__PURE__*/ core.$constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "values", () => def.in._zod.values); + util.defineLazy(inst._zod, "optin", () => def.in._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.out._zod.optout); + + inst._zod.parse = (payload, ctx) => { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def, ctx)); + } + return handlePipeResult(left, def, ctx); + }; +}); + +function handlePipeResult(left: ParsePayload, def: $ZodPipeDef, ctx: ParseContext) { + if (util.aborted(left)) { + return left; + } + return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); +} + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// $ZodReadonly ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// + +export interface $ZodReadonlyDef extends $ZodTypeDef { + type: "readonly"; + innerType: T; +} + +export interface $ZodReadonlyInternals + extends $ZodTypeInternals>, util.MakeReadonly>> { + def: $ZodReadonlyDef; + optin: T["_zod"]["optin"]; + optout: T["_zod"]["optout"]; + isst: never; + propValues: T["_zod"]["propValues"]; + values: T["_zod"]["values"]; +} + +export interface $ZodReadonly extends $ZodType { + _zod: $ZodReadonlyInternals; +} + +export const $ZodReadonly: core.$constructor<$ZodReadonly> = /*@__PURE__*/ core.$constructor( + "$ZodReadonly", + (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; + } +); + +function handleReadonlyResult(payload: ParsePayload): ParsePayload { + payload.value = Object.freeze(payload.value); + return payload; +} + +///////////////////////////////////////////// +///////////////////////////////////////////// +////////// ////////// +////////// $ZodTemplateLiteral ////////// +////////// ////////// +///////////////////////////////////////////// +///////////////////////////////////////////// + +export interface $ZodTemplateLiteralDef extends $ZodTypeDef { + type: "template_literal"; + parts: $ZodTemplateLiteralPart[]; +} +export interface $ZodTemplateLiteralInternals