diff --git a/.gitattributes b/.gitattributes index 14cfc8fd4afeb08b31f2d094984b5c0262ee2773..ace3d0d2cf3cd8c4183741f2bc6a0e7d6f860528 100644 --- a/.gitattributes +++ b/.gitattributes @@ -36,3 +36,4 @@ node_modules/@jimp/plugin-print/dist/fonts/open-sans/open-sans-128-black/open-sa node_modules/@jimp/plugin-print/dist/fonts/open-sans/open-sans-128-white/open-sans-128-white.png filter=lfs diff=lfs merge=lfs -text node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-black/open-sans-128-black.png filter=lfs diff=lfs merge=lfs -text node_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-white/open-sans-128-white.png filter=lfs diff=lfs merge=lfs -text +node_modules/@jimp/plugin-threshold/src/__image_snapshots__/index-test-ts-src-index-test-ts-threshold-defines-default-threshold-for-lighter-backgrounds-1-snap.png filter=lfs diff=lfs merge=lfs -text diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4-mini/index.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4-mini/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..87b293a4f15e3f68f506e98c2abdde6f7b0e2dc9 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4-mini/index.ts @@ -0,0 +1 @@ +export * from "../v4/mini/index.js"; diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/array.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/array.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..57cf9e340659851f5871450c48d535f783eaa872 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/array.test.ts @@ -0,0 +1,264 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("type inference", () => { + const schema = z.string().array(); + expectTypeOf>().toEqualTypeOf(); +}); + +test("array min/max", async () => { + const schema = z.array(z.string()).min(2).max(2); + const r1 = await schema.safeParse(["asdf"]); + expect(r1.success).toEqual(false); + expect(r1.error!.issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "inclusive": true, + "message": "Too small: expected array to have >=2 items", + "minimum": 2, + "origin": "array", + "path": [], + }, + ] + `); + + const r2 = await schema.safeParse(["asdf", "asdf", "asdf"]); + expect(r2.success).toEqual(false); + expect(r2.error!.issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "inclusive": true, + "maximum": 2, + "message": "Too big: expected array to have <=2 items", + "origin": "array", + "path": [], + }, + ] + `); +}); + +test("array length", async () => { + const schema = z.array(z.string()).length(2); + schema.parse(["asdf", "asdf"]); + + const r1 = await schema.safeParse(["asdf"]); + expect(r1.success).toEqual(false); + expect(r1.error!.issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "exact": true, + "inclusive": true, + "message": "Too small: expected array to have >=2 items", + "minimum": 2, + "origin": "array", + "path": [], + }, + ] + `); + + const r2 = await schema.safeParse(["asdf", "asdf", "asdf"]); + expect(r2.success).toEqual(false); + expect(r2.error!.issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "exact": true, + "inclusive": true, + "maximum": 2, + "message": "Too big: expected array to have <=2 items", + "origin": "array", + "path": [], + }, + ] + `); +}); + +test("array.nonempty()", () => { + const schema = z.string().array().nonempty(); + schema.parse(["a"]); + expect(() => schema.parse([])).toThrow(); +}); + +test("array.nonempty().max()", () => { + const schema = z.string().array().nonempty().max(2); + schema.parse(["a"]); + expect(() => schema.parse([])).toThrow(); + expect(() => schema.parse(["a", "a", "a"])).toThrow(); +}); + +test("parse empty array in nonempty", () => { + expect(() => + z + .array(z.string()) + .nonempty() + .parse([] as any) + ).toThrow(); +}); + +test("get element", () => { + const schema = z.string().array(); + schema.element.parse("asdf"); + expect(() => schema.element.parse(12)).toThrow(); +}); + +test("continue parsing despite array size error", () => { + const schema = z.object({ + people: z.string().array().min(2), + }); + + const result = schema.safeParse({ + people: [123], + }); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + "people", + 0 + ], + "message": "Invalid input: expected string, received number" + }, + { + "origin": "array", + "code": "too_small", + "minimum": 2, + "inclusive": true, + "path": [ + "people" + ], + "message": "Too small: expected array to have >=2 items" + } + ]], + "success": false, + } + `); +}); + +test("parse should fail given sparse array", () => { + const schema = z.array(z.string()).nonempty().min(1).max(3); + const result = schema.safeParse(new Array(3)); + expect(result.success).toEqual(false); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + 0 + ], + "message": "Invalid input: expected string, received undefined" + }, + { + "expected": "string", + "code": "invalid_type", + "path": [ + 1 + ], + "message": "Invalid input: expected string, received undefined" + }, + { + "expected": "string", + "code": "invalid_type", + "path": [ + 2 + ], + "message": "Invalid input: expected string, received undefined" + } + ]], + "success": false, + } + `); +}); + +// const unique = z.string().array().unique(); +// const uniqueArrayOfObjects = z.array(z.object({ name: z.string() })).unique({ identifier: (item) => item.name }); + +// test("passing unique validation", () => { +// unique.parse(["a", "b", "c"]); +// uniqueArrayOfObjects.parse([{ name: "Leo" }, { name: "Joe" }]); +// }); + +// test("failing unique validation", () => { +// expect(() => unique.parse(["a", "a", "b"])).toThrow(); +// expect(() => uniqueArrayOfObjects.parse([{ name: "Leo" }, { name: "Leo" }])).toThrow(); +// }); + +// test("continue parsing despite array of primitives uniqueness error", () => { +// const schema = z.number().array().unique(); + +// const result = schema.safeParse([1, 1, 2, 2, 3]); + +// expect(result.success).toEqual(false); +// if (!result.success) { +// const issue = result.error.issues.find(({ code }) => code === "not_unique"); +// expect(issue?.message).toEqual("Values must be unique"); +// } +// }); + +// test("continue parsing despite array of objects not_unique error", () => { +// const schema = z.array(z.object({ name: z.string() })).unique({ +// identifier: (item) => item.name, +// showDuplicates: true, +// }); + +// const result = schema.safeParse([ +// { name: "Leo" }, +// { name: "Joe" }, +// { name: "Leo" }, +// ]); + +// expect(result.success).toEqual(false); +// if (!result.success) { +// const issue = result.error.issues.find(({ code }) => code === "not_unique"); +// expect(issue?.message).toEqual("Element(s): 'Leo' not unique"); +// } +// }); + +// test("returns custom error message without duplicate elements", () => { +// const schema = z.number().array().unique({ message: "Custom message" }); + +// const result = schema.safeParse([1, 1, 2, 2, 3]); + +// expect(result.success).toEqual(false); +// if (!result.success) { +// const issue = result.error.issues.find(({ code }) => code === "not_unique"); +// expect(issue?.message).toEqual("Custom message"); +// } +// }); + +// test("returns error message with duplicate elements", () => { +// const schema = z.number().array().unique({ showDuplicates: true }); + +// const result = schema.safeParse([1, 1, 2, 2, 3]); + +// expect(result.success).toEqual(false); +// if (!result.success) { +// const issue = result.error.issues.find(({ code }) => code === "not_unique"); +// expect(issue?.message).toEqual("Element(s): '1,2' not unique"); +// } +// }); + +// test("returns custom error message with duplicate elements", () => { +// const schema = z +// .number() +// .array() +// .unique({ +// message: (item) => `Custom message: '${item}' are not unique`, +// showDuplicates: true, +// }); + +// const result = schema.safeParse([1, 1, 2, 2, 3]); + +// expect(result.success).toEqual(false); +// if (!result.success) { +// const issue = result.error.issues.find(({ code }) => code === "not_unique"); +// expect(issue?.message).toEqual("Custom message: '1,2' are not unique"); +// } +// }); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/assignability.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/assignability.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..603ff6c1a1228b377d05673e36681ff64f28d2e1 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/assignability.test.ts @@ -0,0 +1,210 @@ +import { expectTypeOf, test } from "vitest"; + +import * as z from "zod/v4"; + +test("assignability", () => { + // $ZodString + z.string() satisfies z.core.$ZodString; + z.string() satisfies z.ZodString; + + // $ZodNumber + z.number() satisfies z.core.$ZodNumber; + z.number() satisfies z.ZodNumber; + + // $ZodBigInt + z.bigint() satisfies z.core.$ZodBigInt; + z.bigint() satisfies z.ZodBigInt; + + // $ZodBoolean + z.boolean() satisfies z.core.$ZodBoolean; + z.boolean() satisfies z.ZodBoolean; + + // $ZodDate + z.date() satisfies z.core.$ZodDate; + z.date() satisfies z.ZodDate; + + // $ZodSymbol + z.symbol() satisfies z.core.$ZodSymbol; + z.symbol() satisfies z.ZodSymbol; + + // $ZodUndefined + z.undefined() satisfies z.core.$ZodUndefined; + z.undefined() satisfies z.ZodUndefined; + + // $ZodNullable + z.string().nullable() satisfies z.core.$ZodNullable; + z.string().nullable() satisfies z.ZodNullable; + + // $ZodNull + z.null() satisfies z.core.$ZodNull; + z.null() satisfies z.ZodNull; + + // $ZodAny + z.any() satisfies z.core.$ZodAny; + z.any() satisfies z.ZodAny; + + // $ZodUnknown + z.unknown() satisfies z.core.$ZodUnknown; + z.unknown() satisfies z.ZodUnknown; + + // $ZodNever + z.never() satisfies z.core.$ZodNever; + z.never() satisfies z.ZodNever; + + // $ZodVoid + z.void() satisfies z.core.$ZodVoid; + z.void() satisfies z.ZodVoid; + + // $ZodArray + z.array(z.string()) satisfies z.core.$ZodArray; + z.array(z.string()) satisfies z.ZodArray; + z.array(z.string()) satisfies z.ZodType>; + + // $ZodObject + z.object({ key: z.string() }) satisfies z.core.$ZodObject; + z.object({ key: z.string() }) satisfies z.ZodObject<{ key: z.ZodType }>; + z.object({ key: z.string() }) satisfies z.ZodType<{ key: string }>; + + // $ZodUnion + z.union([z.string(), z.number()]) satisfies z.core.$ZodUnion; + z.union([z.string(), z.number()]) satisfies z.ZodUnion; + z.union([z.string(), z.number()]) satisfies z.ZodType; + + // $ZodIntersection + z.intersection(z.string(), z.number()) satisfies z.core.$ZodIntersection; + z.intersection(z.string(), z.number()) satisfies z.ZodIntersection; + + // $ZodTuple + z.tuple([z.string(), z.number()]) satisfies z.core.$ZodTuple; + z.tuple([z.string(), z.number()]) satisfies z.ZodTuple; + + // $ZodRecord + z.record(z.string(), z.number()) satisfies z.core.$ZodRecord; + z.record(z.string(), z.number()) satisfies z.ZodRecord; + + // $ZodMap + z.map(z.string(), z.number()) satisfies z.core.$ZodMap; + z.map(z.string(), z.number()) satisfies z.ZodMap; + + // $ZodSet + z.set(z.string()) satisfies z.core.$ZodSet; + z.set(z.string()) satisfies z.ZodSet; + + // $ZodLiteral + z.literal("example") satisfies z.core.$ZodLiteral; + z.literal("example") satisfies z.ZodLiteral; + + // $ZodEnum + z.enum(["a", "b", "c"]) satisfies z.core.$ZodEnum; + z.enum(["a", "b", "c"]) satisfies z.ZodEnum; + + // $ZodPromise + z.promise(z.string()) satisfies z.core.$ZodPromise; + z.promise(z.string()) satisfies z.ZodPromise; + + // $ZodLazy + const lazySchema = z.lazy(() => z.string()); + lazySchema satisfies z.core.$ZodLazy; + lazySchema satisfies z.ZodLazy; + + // $ZodOptional + z.string().optional() satisfies z.core.$ZodOptional; + z.string().optional() satisfies z.ZodOptional; + + // $ZodDefault + z.string().default("default") satisfies z.core.$ZodDefault; + z.string().default("default") satisfies z.ZodDefault; + + // $ZodTemplateLiteral + z.templateLiteral([z.literal("a"), z.literal("b")]) satisfies z.core.$ZodTemplateLiteral; + z.templateLiteral([z.literal("a"), z.literal("b")]) satisfies z.ZodTemplateLiteral; + + // $ZodCustom + z.custom((val) => typeof val === "string") satisfies z.core.$ZodCustom; + z.custom((val) => typeof val === "string") satisfies z.ZodCustom; + + // $ZodTransform + z.transform((val) => val as string) satisfies z.core.$ZodTransform; + z.transform((val) => val as string) satisfies z.ZodTransform; + + // $ZodNonOptional + z.string().optional().nonoptional() satisfies z.core.$ZodNonOptional; + z.string().optional().nonoptional() satisfies z.ZodNonOptional; + + // $ZodReadonly + z.object({ key: z.string() }).readonly() satisfies z.core.$ZodReadonly; + z.object({ key: z.string() }).readonly() satisfies z.ZodReadonly; + + // $ZodNaN + z.nan() satisfies z.core.$ZodNaN; + z.nan() satisfies z.ZodNaN; + + // $ZodPipe + z.unknown().pipe(z.number()) satisfies z.core.$ZodPipe; + z.unknown().pipe(z.number()) satisfies z.ZodPipe; + + // $ZodSuccess + z.success(z.string()) satisfies z.core.$ZodSuccess; + z.success(z.string()) satisfies z.ZodSuccess; + + // $ZodCatch + z.string().catch("fallback") satisfies z.core.$ZodCatch; + z.string().catch("fallback") satisfies z.ZodCatch; + + // $ZodFile + z.file() satisfies z.core.$ZodFile; + z.file() satisfies z.ZodFile; +}); + +test("checks", () => { + const _a: z.core.$ZodCheck = {} as any as z.core.$ZodChecks; + const _b: z.core.$ZodCheck = {} as any as z.core.$ZodStringFormatChecks; + const _c: z.core.$ZodType = {} as any as z.core.$ZodTypes; + const _d: z.core.$ZodType = {} as any as z.core.$ZodStringFormatTypes; +}); + +test("assignability to $ZodType", () => { + z.string() satisfies z.ZodType; + z.number() satisfies z.ZodType; + z.boolean() satisfies z.ZodType; + z.object({ key: z.string() }) satisfies z.ZodType; + z.object({ key: z.string() }) satisfies z.ZodType<{ key: string }>; + z.array(z.string()) satisfies z.ZodType; + z.union([z.string(), z.number()]) satisfies z.ZodType; + z.intersection(z.string(), z.number()) satisfies z.ZodType; + z.tuple([z.string(), z.number()]) satisfies z.ZodType; + z.record(z.string(), z.number()) satisfies z.ZodType; + z.map(z.string(), z.number()) satisfies z.ZodType; + z.set(z.string()) satisfies z.ZodType; + z.literal("example") satisfies z.ZodType; + + expectTypeOf().toEqualTypeOf(); +}); + +test("assignability with narrowing", () => { + type _RefinedSchema | z.ZodUnion> = T extends z.ZodUnion + ? RefinedUnionSchema // <-- Type instantiation is excessively deep and possibly infinite. + : T extends z.ZodType + ? RefinedTypeSchema> // <-- Type instantiation is excessively deep and possibly infinite. + : never; + + type RefinedTypeSchema = T; + + type RefinedUnionSchema = T; +}); + +test("generic assignability in objects", () => { + interface SortItem { + key: T; + order: string; + } + + const createSortItemSchema = >(sortKeySchema: T) => + z.object({ + key: sortKeySchema, + order: z.string(), + }); + + >(sortKeySchema: T, defaultSortBy: SortItem>[] = []) => + createSortItemSchema(sortKeySchema).array().default(defaultSortBy); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..310976355d8e18dabefc1f65157dd954f3962be6 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts @@ -0,0 +1,381 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +/// string +const stringSchema = z.string(); + +test("string async parse", async () => { + const goodData = "XXX"; + const badData = 12; + + const goodResult = await stringSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await stringSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// number +const numberSchema = z.number(); +test("number async parse", async () => { + const goodData = 1234.2353; + const badData = "1234"; + + const goodResult = await numberSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await numberSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// bigInt +const bigIntSchema = z.bigint(); +test("bigInt async parse", async () => { + const goodData = BigInt(145); + const badData = 134; + + const goodResult = await bigIntSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await bigIntSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// boolean +const booleanSchema = z.boolean(); +test("boolean async parse", async () => { + const goodData = true; + const badData = 1; + + const goodResult = await booleanSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await booleanSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// date +const dateSchema = z.date(); +test("date async parse", async () => { + const goodData = new Date(); + const badData = new Date().toISOString(); + + const goodResult = await dateSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await dateSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// undefined +const undefinedSchema = z.undefined(); +test("undefined async parse", async () => { + const goodData = undefined; + const badData = "XXX"; + + const goodResult = await undefinedSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(undefined); + + const badResult = await undefinedSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// null +const nullSchema = z.null(); +test("null async parse", async () => { + const goodData = null; + const badData = undefined; + + const goodResult = await nullSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await nullSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// any +const anySchema = z.any(); +test("any async parse", async () => { + const goodData = [{}]; + // const badData = 'XXX'; + + const goodResult = await anySchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + // const badResult = await anySchema.safeParseAsync(badData); + // expect(badResult.success).toBe(false); + // if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// unknown +const unknownSchema = z.unknown(); +test("unknown async parse", async () => { + const goodData = ["asdf", 124, () => {}]; + // const badData = 'XXX'; + + const goodResult = await unknownSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + // const badResult = await unknownSchema.safeParseAsync(badData); + // expect(badResult.success).toBe(false); + // if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// void +const voidSchema = z.void(); +test("void async parse", async () => { + const goodData = undefined; + const badData = 0; + + const goodResult = await voidSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await voidSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// array +const arraySchema = z.array(z.string()); +test("array async parse", async () => { + const goodData = ["XXX"]; + const badData = "XXX"; + + const goodResult = await arraySchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await arraySchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// object +const objectSchema = z.object({ string: z.string() }); +test("object async parse", async () => { + const goodData = { string: "XXX" }; + const badData = { string: 12 }; + + const goodResult = await objectSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await objectSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// union +const unionSchema = z.union([z.string(), z.undefined()]); +test("union async parse", async () => { + const goodData = undefined; + const badData = null; + + const goodResult = await unionSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await unionSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// record +const recordSchema = z.record(z.string(), z.object({})); +test("record async parse", async () => { + const goodData = { adsf: {}, asdf: {} }; + const badData = [{}]; + + const goodResult = await recordSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await recordSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// function +// const functionSchema = z.function(); +// test("function async parse", async () => { +// const goodData = () => {}; +// const badData = "XXX"; + +// const goodResult = await functionSchema.safeParseAsync(goodData); +// expect(goodResult.success).toBe(true); +// if (goodResult.success) expect(typeof goodResult.data).toEqual("function"); + +// const badResult = await functionSchema.safeParseAsync(badData); +// expect(badResult.success).toBe(false); +// if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +// }); + +/// literal +const literalSchema = z.literal("asdf"); +test("literal async parse", async () => { + const goodData = "asdf"; + const badData = "asdff"; + + const goodResult = await literalSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await literalSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// enum +const enumSchema = z.enum(["fish", "whale"]); +test("enum async parse", async () => { + const goodData = "whale"; + const badData = "leopard"; + + const goodResult = await enumSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await enumSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// nativeEnum +enum nativeEnumTest { + asdf = "qwer", +} +// @ts-ignore +const nativeEnumSchema = z.nativeEnum(nativeEnumTest); +test("nativeEnum async parse", async () => { + const goodData = nativeEnumTest.asdf; + const badData = "asdf"; + + const goodResult = await nativeEnumSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + if (goodResult.success) expect(goodResult.data).toEqual(goodData); + + const badResult = await nativeEnumSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +/// promise +const promiseSchema = z.promise(z.number()); +test("promise async parse good", async () => { + const goodData = Promise.resolve(123); + + const goodResult = await promiseSchema.safeParseAsync(goodData); + expect(goodResult.success).toBe(true); + expect(typeof goodResult.data).toEqual("number"); + expect(goodResult.data).toEqual(123); +}); + +test("promise async parse bad", async () => { + const badData = Promise.resolve("XXX"); + const badResult = await promiseSchema.safeParseAsync(badData); + expect(badResult.success).toBe(false); + expect(badResult.error).toBeInstanceOf(z.ZodError); +}); + +test("async validation non-empty strings", async () => { + const base = z.object({ + hello: z.string().refine((x) => x && x.length > 0), + foo: z.string().refine((x) => x && x.length > 0), + }); + + const testval = { hello: "", foo: "" }; + const result1 = base.safeParse(testval); + const result2 = base.safeParseAsync(testval); + + const r1 = result1; + await result2.then((r2) => { + expect(r1.error!.issues.length).toBe(r2.error!.issues.length); + }); +}); + +test("async validation multiple errors 1", async () => { + const base = z.object({ + hello: z.string(), + foo: z.number(), + }); + + const testval = { hello: 3, foo: "hello" }; + const result1 = base.safeParse(testval); + const result2 = base.safeParseAsync(testval); + + await result2.then((result2) => { + expect(result2.error!.issues.length).toBe(result1.error!.issues.length); + }); +}); + +test("async validation multiple errors 2", async () => { + const base = (is_async?: boolean) => + z.object({ + hello: z.string(), + foo: z.object({ + bar: z.number().refine( + is_async + ? async () => + new Promise((resolve) => { + setTimeout(() => resolve(false), 500); + }) + : () => false + ), + }), + }); + + const testval = { hello: 3, foo: { bar: 4 } }; + const result1 = base().safeParse(testval); + const result2 = base(true).safeParseAsync(testval); + + await result2.then((result2) => { + expect(result1.error!.issues.length).toBe(result2.error!.issues.length); + }); +}); + +test("ensure early async failure prevents follow-up refinement checks", async () => { + let count = 0; + const base = z.object({ + hello: z.string(), + foo: z + .number() + .refine(async () => { + count++; + return true; + }) + .refine(async () => { + count++; + return true; + }, "Good"), + }); + + const testval = { hello: "bye", foo: 3 }; + const result = await base.safeParseAsync(testval); + if (result.success === false) { + expect(result.error.issues.length).toBe(1); + expect(count).toBe(1); + } + + // await result.then((r) => { + // if (r.success === false) expect(r.error.issues.length).toBe(1); + // expect(count).toBe(2); + // }); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ebb577ecb4c938b10452cb07eaed3603e3db4232 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts @@ -0,0 +1,68 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +test("async refine .parse()", async () => { + // throws ZodAsyncError + const s1 = z.string().refine(async (_val) => true); + expect(() => s1.safeParse("asdf")).toThrow(); +}); + +test("async refine", async () => { + const s1 = z.string().refine(async (_val) => true); + const r1 = await s1.parseAsync("asdf"); + expect(r1).toEqual("asdf"); + + const s2 = z.string().refine(async (_val) => false); + const r2 = await s2.safeParseAsync("asdf"); + expect(r2.success).toBe(false); + expect(r2).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "path": [], + "message": "Invalid input" + } + ]], + "success": false, + } + `); +}); + +test("async refine with Promises", async () => { + // expect.assertions(2); + + const schema1 = z.string().refine((_val) => Promise.resolve(true)); + const v1 = await schema1.parseAsync("asdf"); + expect(v1).toEqual("asdf"); + + const schema2 = z.string().refine((_val) => Promise.resolve(false)); + await expect(schema2.parseAsync("asdf")).rejects.toBeDefined(); + + const schema3 = z.string().refine((_val) => Promise.resolve(true)); + await expect(schema3.parseAsync("asdf")).resolves.toEqual("asdf"); + return await expect(schema3.parseAsync("qwer")).resolves.toEqual("qwer"); +}); + +test("async refine that uses value", async () => { + const schema1 = z.string().refine(async (val) => { + return val.length > 5; + }); + + const r1 = await schema1.safeParseAsync("asdf"); + expect(r1.success).toBe(false); + expect(r1.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "message": "Invalid input" + } + ]] + `); + + const r2 = await schema1.safeParseAsync("asdf123"); + expect(r2.success).toBe(true); + expect(r2.data).toEqual("asdf123"); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/base.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/base.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e33470a1812635c6c5e00722a4f56c3df28e37a9 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/base.test.ts @@ -0,0 +1,7 @@ +import { expect, test } from "vitest"; +import * as z from "zod/v4"; + +test("test this binding", () => { + const parse = z.string().parse; + expect(parse("asdf")).toBe("asdf"); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/bigint.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/bigint.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ea022430d8cbd3ec6b3773e03d146346dacb134 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/bigint.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +const gtFive = z.bigint().gt(BigInt(5)); +const gteFive = z.bigint().gte(BigInt(5)); +const ltFive = z.bigint().lt(BigInt(5)); +const lteFive = z.bigint().lte(BigInt(5)); +const positive = z.bigint().positive(); +const negative = z.bigint().negative(); +const nonnegative = z.bigint().nonnegative(); +const nonpositive = z.bigint().nonpositive(); +const multipleOfFive = z.bigint().multipleOf(BigInt(5)); + +test("passing validations", () => { + z.bigint().parse(BigInt(1)); + z.bigint().parse(BigInt(0)); + z.bigint().parse(BigInt(-1)); + gtFive.parse(BigInt(6)); + gteFive.parse(BigInt(5)); + gteFive.parse(BigInt(6)); + ltFive.parse(BigInt(4)); + lteFive.parse(BigInt(5)); + lteFive.parse(BigInt(4)); + positive.parse(BigInt(3)); + negative.parse(BigInt(-2)); + nonnegative.parse(BigInt(0)); + nonnegative.parse(BigInt(7)); + nonpositive.parse(BigInt(0)); + nonpositive.parse(BigInt(-12)); + multipleOfFive.parse(BigInt(15)); +}); + +test("failing validations", () => { + expect(() => gtFive.parse(BigInt(5))).toThrow(); + expect(() => gteFive.parse(BigInt(4))).toThrow(); + expect(() => ltFive.parse(BigInt(5))).toThrow(); + expect(() => lteFive.parse(BigInt(6))).toThrow(); + expect(() => positive.parse(BigInt(0))).toThrow(); + expect(() => positive.parse(BigInt(-2))).toThrow(); + expect(() => negative.parse(BigInt(0))).toThrow(); + expect(() => negative.parse(BigInt(3))).toThrow(); + expect(() => nonnegative.parse(BigInt(-1))).toThrow(); + expect(() => nonpositive.parse(BigInt(1))).toThrow(); + expect(() => multipleOfFive.parse(BigInt(13))).toThrow(); +}); + +test("min max getters", () => { + expect(z.bigint().min(BigInt(5)).minValue).toEqual(BigInt(5)); + expect(z.bigint().min(BigInt(5)).min(BigInt(10)).minValue).toEqual(BigInt(10)); + + expect(z.bigint().max(BigInt(5)).maxValue).toEqual(BigInt(5)); + expect(z.bigint().max(BigInt(5)).max(BigInt(1)).maxValue).toEqual(BigInt(1)); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/brand.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/brand.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0f8c47ceaa1ba38241c0c61c65c8cd0a2034dfa4 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/brand.test.ts @@ -0,0 +1,63 @@ +import { expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("branded types", () => { + const mySchema = z + .object({ + name: z.string(), + }) + .brand<"superschema">(); + + // simple branding + type MySchema = z.infer; + + expectTypeOf().toEqualTypeOf<{ name: string } & z.$brand<"superschema">>(); + + const doStuff = (arg: MySchema) => arg; + doStuff(mySchema.parse({ name: "hello there" })); + + // inheritance + const extendedSchema = mySchema.brand<"subschema">(); + type ExtendedSchema = z.infer; + expectTypeOf().toEqualTypeOf<{ name: string } & z.BRAND<"superschema"> & z.BRAND<"subschema">>(); + + doStuff(extendedSchema.parse({ name: "hello again" })); + + // number branding + const numberSchema = z.number().brand<42>(); + type NumberSchema = z.infer; + expectTypeOf().toEqualTypeOf(); + + // symbol branding + const MyBrand: unique symbol = Symbol("hello"); + type MyBrand = typeof MyBrand; + const symbolBrand = z.number().brand<"sup">().brand(); + type SymbolBrand = z.infer; + // number & { [z.BRAND]: { sup: true, [MyBrand]: true } } + expectTypeOf().toEqualTypeOf & z.BRAND>(); + + // keeping brands out of input types + const age = z.number().brand<"age">(); + + type Age = z.infer; + type AgeInput = z.input; + + expectTypeOf().not.toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + + // @ts-expect-error + doStuff({ name: "hello there!" }); +}); + +test("$branded", () => { + const a = z.string().brand<"a">(); + + expectTypeOf().toEqualTypeOf>(); +}); + +test("branded record", () => { + const recordWithBrandedNumberKeys = z.record(z.string().brand("SomeBrand"), z.number()); + type recordWithBrandedNumberKeys = z.infer; + expectTypeOf().toEqualTypeOf, number>>(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/catch.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/catch.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8ad85a6f77c191ed2adf295d4a0175c415cdacc --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/catch.test.ts @@ -0,0 +1,252 @@ +import { expect, expectTypeOf, test } from "vitest"; +import { z } from "zod/v4"; +import type { util } from "zod/v4/core"; + +test("basic catch", () => { + expect(z.string().catch("default").parse(undefined)).toBe("default"); +}); + +test("catch fn does not run when parsing succeeds", () => { + let isCalled = false; + const cb = () => { + isCalled = true; + return "asdf"; + }; + expect(z.string().catch(cb).parse("test")).toBe("test"); + expect(isCalled).toEqual(false); +}); + +test("basic catch async", async () => { + const result = await z.string().catch("default").parseAsync(1243); + expect(result).toBe("default"); +}); + +test("catch replace wrong types", () => { + expect(z.string().catch("default").parse(true)).toBe("default"); + expect(z.string().catch("default").parse(true)).toBe("default"); + expect(z.string().catch("default").parse(15)).toBe("default"); + expect(z.string().catch("default").parse([])).toBe("default"); + expect(z.string().catch("default").parse(new Map())).toBe("default"); + expect(z.string().catch("default").parse(new Set())).toBe("default"); + expect(z.string().catch("default").parse({})).toBe("default"); +}); + +test("catch with transform", () => { + const stringWithDefault = z + .string() + .transform((val) => val.toUpperCase()) + .catch("default"); + + expect(stringWithDefault.parse(undefined)).toBe("default"); + expect(stringWithDefault.parse(15)).toBe("default"); + expect(stringWithDefault).toBeInstanceOf(z.ZodCatch); + expect(stringWithDefault.unwrap()).toBeInstanceOf(z.ZodPipe); + expect(stringWithDefault.unwrap().in).toBeInstanceOf(z.ZodString); + expect(stringWithDefault.unwrap().out).toBeInstanceOf(z.ZodTransform); + + type inp = z.input; + expectTypeOf().toEqualTypeOf(); + type out = z.output; + expectTypeOf().toEqualTypeOf(); +}); + +test("catch on existing optional", () => { + const stringWithDefault = z.string().optional().catch("asdf"); + expect(stringWithDefault.parse(undefined)).toBe(undefined); + expect(stringWithDefault.parse(15)).toBe("asdf"); + expect(stringWithDefault).toBeInstanceOf(z.ZodCatch); + expect(stringWithDefault.unwrap()).toBeInstanceOf(z.ZodOptional); + expect(stringWithDefault.unwrap().unwrap()).toBeInstanceOf(z.ZodString); + + type inp = z.input; + expectTypeOf().toEqualTypeOf(); + type out = z.output; + expectTypeOf().toEqualTypeOf(); +}); + +test("optional on catch", () => { + const stringWithDefault = z.string().catch("asdf").optional(); + + type inp = z.input; + expectTypeOf().toEqualTypeOf(); + type out = z.output; + expectTypeOf().toEqualTypeOf(); +}); + +test("complex chain example", () => { + const complex = z + .string() + .catch("asdf") + .transform((val) => `${val}!`) + .transform((val) => val.toUpperCase()) + .catch("qwer") + .unwrap() + .optional() + .catch("asdfasdf"); + + expect(complex.parse("qwer")).toBe("QWER!"); + expect(complex.parse(15)).toBe("ASDF!"); + expect(complex.parse(true)).toBe("ASDF!"); +}); + +test("removeCatch", () => { + const stringWithRemovedDefault = z.string().catch("asdf").unwrap(); + + type out = z.output; + expectTypeOf().toEqualTypeOf(); +}); + +test("nested", () => { + const inner = z.string().catch("asdf"); + const outer = z.object({ inner }).catch({ + inner: "asdf", + }); + type input = z.input; + expectTypeOf().toEqualTypeOf<{ inner: string | util.Whatever } | util.Whatever>(); + type out = z.output; + + expectTypeOf().toEqualTypeOf<{ inner: string }>(); + expect(outer.parse(undefined)).toEqual({ inner: "asdf" }); + expect(outer.parse({})).toEqual({ inner: "asdf" }); + expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" }); +}); + +test("chained catch", () => { + const stringWithDefault = z.string().catch("inner").catch("outer"); + const result = stringWithDefault.parse(undefined); + expect(result).toEqual("inner"); + const resultDiff = stringWithDefault.parse(5); + expect(resultDiff).toEqual("inner"); +}); + +test("native enum", () => { + enum Fruits { + apple = "apple", + orange = "orange", + } + + const schema = z.object({ + fruit: z.nativeEnum(Fruits).catch(Fruits.apple), + }); + + expect(schema.parse({})).toEqual({ fruit: Fruits.apple }); + expect(schema.parse({ fruit: 15 })).toEqual({ fruit: Fruits.apple }); +}); + +test("enum", () => { + const schema = z.object({ + fruit: z.enum(["apple", "orange"]).catch("apple"), + }); + + expect(schema.parse({})).toEqual({ fruit: "apple" }); + expect(schema.parse({ fruit: true })).toEqual({ fruit: "apple" }); + expect(schema.parse({ fruit: 15 })).toEqual({ fruit: "apple" }); +}); + +test("reported issues with nested usage", () => { + const schema = z.object({ + string: z.string(), + obj: z.object({ + sub: z.object({ + lit: z.literal("a"), + subCatch: z.number().catch(23), + }), + midCatch: z.number().catch(42), + }), + number: z.number().catch(0), + bool: z.boolean(), + }); + + try { + schema.parse({ + string: {}, + obj: { + sub: { + lit: "b", + subCatch: "24", + }, + midCatch: 444, + }, + number: "", + bool: "yes", + }); + } catch (error) { + const issues = (error as z.ZodError).issues; + + expect(issues.length).toEqual(3); + expect(issues).toMatchInlineSnapshot(` + [ + { + "code": "invalid_type", + "expected": "string", + "message": "Invalid input: expected string, received object", + "path": [ + "string", + ], + }, + { + "code": "invalid_value", + "message": "Invalid input: expected "a"", + "path": [ + "obj", + "sub", + "lit", + ], + "values": [ + "a", + ], + }, + { + "code": "invalid_type", + "expected": "boolean", + "message": "Invalid input: expected boolean, received string", + "path": [ + "bool", + ], + }, + ] + `); + // expect(issues[0].message).toMatch("string"); + // expect(issues[1].message).toMatch("literal"); + // expect(issues[2].message).toMatch("boolean"); + } +}); + +test("catch error", () => { + const schema = z.object({ + age: z.number(), + name: z.string().catch((ctx) => { + ctx.issues; + // issues = ctx.issues; + + return "John Doe"; + }), + }); + + const result = schema.safeParse({ + age: null, + name: null, + }); + + expect(result.success).toEqual(false); + expect(result.error!).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "number", + "code": "invalid_type", + "path": [ + "age" + ], + "message": "Invalid input: expected number, received null" + } + ]] + `); +}); + +test("ctx.input", () => { + const schema = z.string().catch((ctx) => { + return String(ctx.input); + }); + + expect(schema.parse(123)).toEqual("123"); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/coalesce.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/coalesce.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..beca25d802ce796195b3a154948b0f576f0cd265 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/coalesce.test.ts @@ -0,0 +1,20 @@ +import { expect, test } from "vitest"; + +test("coalesce", () => { + expect(true).toBe(true); +}); + +// test("nonoptional with default", () => { +// const schema = z.string().optional().coalesce("hi"); +// expectTypeOf().toEqualTypeOf(); +// expectTypeOf().toEqualTypeOf(); +// expect(schema.parse(undefined)).toBe("hi"); +// }); + +// test("nonoptional in object", () => { +// const schema = z.object({ hi: z.string().optional().nonoptional("hi") }); + +// expectTypeOf().toEqualTypeOf<{ hi: string | undefined }>(); +// expectTypeOf().toEqualTypeOf<{ hi: string }>(); +// expect(schema.parse(undefined)).toBe("hi"); +// }); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/coerce.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/coerce.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..136a3827d1b81d6626f1013837ce089f13db915c --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/coerce.test.ts @@ -0,0 +1,160 @@ +import { expect, expectTypeOf, test } from "vitest"; + +import * as z from "zod/v4"; + +test("string coercion", () => { + const schema = z.coerce.string(); + expect(schema.parse("sup")).toEqual("sup"); + expect(schema.parse("")).toEqual(""); + expect(schema.parse(12)).toEqual("12"); + expect(schema.parse(0)).toEqual("0"); + expect(schema.parse(-12)).toEqual("-12"); + expect(schema.parse(3.14)).toEqual("3.14"); + expect(schema.parse(BigInt(15))).toEqual("15"); + expect(schema.parse(Number.NaN)).toEqual("NaN"); + expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual("Infinity"); + expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual("-Infinity"); + expect(schema.parse(true)).toEqual("true"); + expect(schema.parse(false)).toEqual("false"); + expect(schema.parse(null)).toEqual("null"); + expect(schema.parse(undefined)).toEqual("undefined"); + expect(schema.parse({ hello: "world!" })).toEqual("[object Object]"); + expect(schema.parse(["item", "another_item"])).toEqual("item,another_item"); + expect(schema.parse([])).toEqual(""); + expect(schema.parse(new Date("2022-01-01T00:00:00.000Z"))).toEqual(new Date("2022-01-01T00:00:00.000Z").toString()); +}); + +test("number coercion", () => { + const schema = z.coerce.number(); + expect(schema.parse("12")).toEqual(12); + expect(schema.parse("0")).toEqual(0); + expect(schema.parse("-12")).toEqual(-12); + expect(schema.parse("3.14")).toEqual(3.14); + expect(schema.parse("")).toEqual(0); + expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // z.ZodError + expect(schema.parse(12)).toEqual(12); + expect(schema.parse(0)).toEqual(0); + expect(schema.parse(-12)).toEqual(-12); + expect(schema.parse(3.14)).toEqual(3.14); + expect(schema.parse(BigInt(15))).toEqual(15); + expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError + // expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(Number.POSITIVE_INFINITY); + // expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(Number.NEGATIVE_INFINITY); + expect(schema.parse(true)).toEqual(1); + expect(schema.parse(false)).toEqual(0); + expect(schema.parse(null)).toEqual(0); + expect(() => schema.parse(undefined)).toThrow(); // z.ZodError + expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError + expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError + expect(schema.parse([])).toEqual(0); + expect(schema.parse(new Date(1670139203496))).toEqual(1670139203496); +}); + +test("boolean coercion", () => { + const schema = z.coerce.boolean(); + expect(schema.parse("true")).toEqual(true); + expect(schema.parse("false")).toEqual(true); + expect(schema.parse("0")).toEqual(true); + expect(schema.parse("1")).toEqual(true); + expect(schema.parse("")).toEqual(false); + expect(schema.parse(1)).toEqual(true); + expect(schema.parse(0)).toEqual(false); + expect(schema.parse(-1)).toEqual(true); + expect(schema.parse(3.14)).toEqual(true); + expect(schema.parse(BigInt(15))).toEqual(true); + expect(schema.parse(Number.NaN)).toEqual(false); + expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(true); + expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(true); + expect(schema.parse(true)).toEqual(true); + expect(schema.parse(false)).toEqual(false); + expect(schema.parse(null)).toEqual(false); + expect(schema.parse(undefined)).toEqual(false); + expect(schema.parse({ hello: "world!" })).toEqual(true); + expect(schema.parse(["item", "another_item"])).toEqual(true); + expect(schema.parse([])).toEqual(true); + expect(schema.parse(new Date(1670139203496))).toEqual(true); +}); + +test("bigint coercion", () => { + const schema = z.coerce.bigint(); + expect(schema.parse("5")).toEqual(BigInt(5)); + expect(schema.parse("0")).toEqual(BigInt(0)); + expect(schema.parse("-5")).toEqual(BigInt(-5)); + expect(() => schema.parse("3.14")).toThrow(); // not a z.ZodError! + expect(schema.parse("")).toEqual(BigInt(0)); + expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // not a z.ZodError! + expect(schema.parse(5)).toEqual(BigInt(5)); + expect(schema.parse(0)).toEqual(BigInt(0)); + expect(schema.parse(-5)).toEqual(BigInt(-5)); + expect(() => schema.parse(3.14)).toThrow(); // not a z.ZodError! + expect(schema.parse(BigInt(5))).toEqual(BigInt(5)); + expect(() => schema.parse(Number.NaN)).toThrow(); // not a z.ZodError! + expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // not a z.ZodError! + expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // not a z.ZodError! + expect(schema.parse(true)).toEqual(BigInt(1)); + expect(schema.parse(false)).toEqual(BigInt(0)); + expect(() => schema.parse(null)).toThrow(); // not a z.ZodError! + expect(() => schema.parse(undefined)).toThrow(); // not a z.ZodError! + expect(() => schema.parse({ hello: "world!" })).toThrow(); // not a z.ZodError! + expect(() => schema.parse(["item", "another_item"])).toThrow(); // not a z.ZodError! + expect(schema.parse([])).toEqual(BigInt(0)); + expect(schema.parse(new Date(1670139203496))).toEqual(BigInt(1670139203496)); +}); + +test("date coercion", () => { + const schema = z.coerce.date(); + expect(schema.parse(new Date().toDateString())).toBeInstanceOf(Date); + expect(schema.parse(new Date().toISOString())).toBeInstanceOf(Date); + expect(schema.parse(new Date().toUTCString())).toBeInstanceOf(Date); + expect(schema.parse("5")).toBeInstanceOf(Date); + expect(schema.parse("2000-01-01")).toBeInstanceOf(Date); + // expect(schema.parse("0")).toBeInstanceOf(Date); + // expect(schema.parse("-5")).toBeInstanceOf(Date); + // expect(schema.parse("3.14")).toBeInstanceOf(Date); + expect(() => schema.parse("")).toThrow(); // z.ZodError + expect(() => schema.parse("NOT_A_DATE")).toThrow(); // z.ZodError + expect(schema.parse(5)).toBeInstanceOf(Date); + expect(schema.parse(0)).toBeInstanceOf(Date); + expect(schema.parse(-5)).toBeInstanceOf(Date); + expect(schema.parse(3.14)).toBeInstanceOf(Date); + expect(() => schema.parse(BigInt(5))).toThrow(); // not a z.ZodError! + expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError + expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // z.ZodError + expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // z.ZodError + expect(schema.parse(true)).toBeInstanceOf(Date); + expect(schema.parse(false)).toBeInstanceOf(Date); + expect(schema.parse(null)).toBeInstanceOf(Date); + expect(() => schema.parse(undefined)).toThrow(); // z.ZodError + expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError + expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError + expect(() => schema.parse([])).toThrow(); // z.ZodError + expect(schema.parse(new Date())).toBeInstanceOf(Date); +}); + +// test("template literal coercion", () => { +// const schema = z.coerce +// .templateLiteral() +// .interpolated(z.number().finite()) +// .interpolated( +// z.enum(["px", "em", "rem", "vh", "vw", "vmin", "vmax"]).optional() +// ); +// expect(schema.parse(300)).toEqual("300"); +// expect(schema.parse(BigInt(300))).toEqual("300"); +// expect(schema.parse("300")).toEqual("300"); +// expect(schema.parse("300px")).toEqual("300px"); +// expect(schema.parse("300em")).toEqual("300em"); +// expect(schema.parse("300rem")).toEqual("300rem"); +// expect(schema.parse("300vh")).toEqual("300vh"); +// expect(schema.parse("300vw")).toEqual("300vw"); +// expect(schema.parse("300vmin")).toEqual("300vmin"); +// expect(schema.parse("300vmax")).toEqual("300vmax"); +// expect(schema.parse(["300px"])).toEqual("300px"); +// }); + +test("override input type", () => { + const a = z.coerce.string(); + type input = z.input; + expectTypeOf().toEqualTypeOf(); + type output = z.infer; + expectTypeOf().toEqualTypeOf(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/continuability.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/continuability.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f85ecd077d99274b4cdcdc6354762bf746b9d589 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/continuability.test.ts @@ -0,0 +1,352 @@ +import { expect, test } from "vitest"; +import * as z from "zod/v4"; + +test("continuability", () => { + /** + * | $ZodGUID + | $ZodUUID + | $ZodEmail + | $ZodURL + | $ZodEmoji + | $ZodNanoID + | $ZodCUID + | $ZodCUID2 + | $ZodULID + | $ZodXID + | $ZodKSUID + | $ZodISODateTime + | $ZodISODate + | $ZodISOTime + | $ZodISODuration + | $ZodIPv4 + | $ZodIPv6 + | $ZodCIDRv4 + | $ZodCIDRv6 + | $ZodBase64 + | $ZodBase64URL + | $ZodE164 + | $ZodJWT; + */ + expect( + z + .email() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "email", + "message": "Invalid email address", + "origin": "string", + "path": [], + "pattern": "/^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .uuid() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "uuid", + "message": "Invalid UUID", + "origin": "string", + "path": [], + "pattern": "/^([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)$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .url() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "url", + "message": "Invalid URL", + "path": [], + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .jwt() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "jwt", + "message": "Invalid JWT", + "path": [], + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .cidrv4() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "cidrv4", + "message": "Invalid IPv4 range", + "origin": "string", + "path": [], + "pattern": "/^((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])$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .cidrv6() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "cidrv6", + "message": "Invalid IPv6 range", + "path": [], + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .ipv4() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "ipv4", + "message": "Invalid IPv4 address", + "origin": "string", + "path": [], + "pattern": "/^(?:(?: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])$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .ipv6() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "ipv6", + "message": "Invalid IPv6 address", + "path": [], + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .emoji() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "emoji", + "message": "Invalid emoji", + "origin": "string", + "path": [], + "pattern": "/^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$/u", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .nanoid() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "nanoid", + "message": "Invalid nanoid", + "origin": "string", + "path": [], + "pattern": "/^[a-zA-Z0-9_-]{21}$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .cuid() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "cuid", + "message": "Invalid cuid", + "origin": "string", + "path": [], + "pattern": "/^[cC][^\\s-]{8,}$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .cuid2() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "cuid2", + "message": "Invalid cuid2", + "origin": "string", + "path": [], + "pattern": "/^[0-9a-z]+$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .ulid() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "ulid", + "message": "Invalid ULID", + "origin": "string", + "path": [], + "pattern": "/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .xid() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "xid", + "message": "Invalid XID", + "origin": "string", + "path": [], + "pattern": "/^[0-9a-vA-V]{20}$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); + expect( + z + .ksuid() + .refine(() => false) + .safeParse("invalid_value").error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "ksuid", + "message": "Invalid KSUID", + "origin": "string", + "path": [], + "pattern": "/^[A-Za-z0-9]{27}$/", + }, + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ] + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/custom.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/custom.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b77f81158495d667cd1d54fd65c6eb40548f7cbc --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/custom.test.ts @@ -0,0 +1,40 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +test("passing validations", () => { + const example1 = z.custom((x) => typeof x === "number"); + example1.parse(1234); + expect(() => example1.parse({})).toThrow(); +}); + +test("string params", () => { + const example1 = z.custom((x) => typeof x !== "number", "customerr"); + const result = example1.safeParse(1234); + expect(result.success).toEqual(false); + expect(JSON.stringify(result.error).includes("customerr")).toEqual(true); +}); + +test("instanceof", () => { + const fn = (value: string) => Uint8Array.from(Buffer.from(value, "base64")); + + // Argument of type 'ZodCustom, unknown>' is not assignable to parameter of type '$ZodType>'. + z.string().transform(fn).pipe(z.instanceof(Uint8Array)); +}); + +test("non-continuable by default", () => { + const A = z + .custom((val) => typeof val === "string") + .transform((_) => { + throw new Error("Invalid input"); + }); + expect(A.safeParse(123).error!).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "message": "Invalid input" + } + ]] + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/date.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/date.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e63302da4eef8a14696670d4fd1fe7c3eef645f6 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/date.test.ts @@ -0,0 +1,31 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +const beforeBenchmarkDate = new Date(2022, 10, 4); +const benchmarkDate = new Date(2022, 10, 5); +const afterBenchmarkDate = new Date(2022, 10, 6); + +const minCheck = z.date().min(benchmarkDate); +const maxCheck = z.date().max(benchmarkDate); + +test("passing validations", () => { + minCheck.parse(benchmarkDate); + minCheck.parse(afterBenchmarkDate); + + maxCheck.parse(benchmarkDate); + maxCheck.parse(beforeBenchmarkDate); +}); + +test("failing validations", () => { + expect(() => minCheck.parse(beforeBenchmarkDate)).toThrow(); + expect(() => maxCheck.parse(afterBenchmarkDate)).toThrow(); +}); + +test("min max getters", () => { + expect(minCheck.minDate).toEqual(benchmarkDate); + expect(minCheck.min(afterBenchmarkDate).minDate).toEqual(afterBenchmarkDate); + + expect(maxCheck.maxDate).toEqual(benchmarkDate); + expect(maxCheck.max(beforeBenchmarkDate).maxDate).toEqual(beforeBenchmarkDate); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/datetime.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/datetime.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f78d48d46c486c6dd0f70f687756bda84b083bd5 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/datetime.test.ts @@ -0,0 +1,296 @@ +import { checkSync } from "recheck"; +import { expect, test } from "vitest"; +import * as z from "zod/v4"; + +test("basic datetime parsing", () => { + const datetime = z.string().datetime(); + datetime.parse("1970-01-01T00:00:00.000Z"); + datetime.parse("2022-10-13T09:52:31.816Z"); + datetime.parse("2022-10-13T09:52:31.8162314Z"); + datetime.parse("1970-01-01T00:00:00Z"); + datetime.parse("2022-10-13T09:52:31Z"); + expect(() => datetime.parse("")).toThrow(); + expect(() => datetime.parse("foo")).toThrow(); + expect(() => datetime.parse("2020-10-14")).toThrow(); + expect(() => datetime.parse("T18:45:12.123")).toThrow(); + expect(() => datetime.parse("2020-10-14T17:42:29+00:00")).toThrow(); +}); + +test("datetime parsing with precision -1", () => { + const datetimeNoMs = z.string().datetime({ precision: -1, offset: true, local: true }); + datetimeNoMs.parse("1970-01-01T00:00Z"); + datetimeNoMs.parse("2022-10-13T09:52Z"); + datetimeNoMs.parse("2022-10-13T09:52+02:00"); + + datetimeNoMs.parse("2022-10-13T09:52"); + expect(() => datetimeNoMs.parse("tuna")).toThrow(); + expect(() => datetimeNoMs.parse("2022-10-13T09:52+02")).toThrow(); + expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.000Z")).toThrow(); + expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.Z")).toThrow(); + expect(() => datetimeNoMs.parse("2022-10-13T09:52:31.816Z")).toThrow(); +}); + +test("datetime parsing with precision 0", () => { + const datetimeNoMs = z.string().datetime({ precision: 0 }); + datetimeNoMs.parse("1970-01-01T00:00:00Z"); + datetimeNoMs.parse("2022-10-13T09:52:31Z"); + expect(() => datetimeNoMs.parse("tuna")).toThrow(); + expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.000Z")).toThrow(); + expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.Z")).toThrow(); + expect(() => datetimeNoMs.parse("2022-10-13T09:52:31.816Z")).toThrow(); +}); + +test("datetime parsing with precision 3", () => { + const datetime3Ms = z.string().datetime({ precision: 3 }); + datetime3Ms.parse("1970-01-01T00:00:00.000Z"); + datetime3Ms.parse("2022-10-13T09:52:31.123Z"); + expect(() => datetime3Ms.parse("tuna")).toThrow(); + expect(() => datetime3Ms.parse("1970-01-01T00:00:00.1Z")).toThrow(); + expect(() => datetime3Ms.parse("1970-01-01T00:00:00.12Z")).toThrow(); + expect(() => datetime3Ms.parse("2022-10-13T09:52:31Z")).toThrow(); +}); + +test("datetime parsing with offset", () => { + const datetimeOffset = z.string().datetime({ offset: true }); + datetimeOffset.parse("1970-01-01T00:00:00.000Z"); + datetimeOffset.parse("2022-10-13T09:52:31.816234134Z"); + datetimeOffset.parse("1970-01-01T00:00:00Z"); + datetimeOffset.parse("2022-10-13T09:52:31.4Z"); + datetimeOffset.parse("2020-10-14T17:42:29+00:00"); + datetimeOffset.parse("2020-10-14T17:42:29+03:15"); + expect(() => datetimeOffset.parse("2020-10-14T17:42:29+0315")).toThrow(); + expect(() => datetimeOffset.parse("2020-10-14T17:42:29+03")).toThrow(); + expect(() => datetimeOffset.parse("tuna")).toThrow(); + expect(() => datetimeOffset.parse("2022-10-13T09:52:31.Z")).toThrow(); +}); + +test("datetime parsing with offset and precision 0", () => { + const datetimeOffsetNoMs = z.string().datetime({ offset: true, precision: 0 }); + datetimeOffsetNoMs.parse("1970-01-01T00:00:00Z"); + datetimeOffsetNoMs.parse("2022-10-13T09:52:31Z"); + datetimeOffsetNoMs.parse("2020-10-14T17:42:29+00:00"); + expect(() => datetimeOffsetNoMs.parse("2020-10-14T17:42:29+0000")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("2020-10-14T17:42:29+00")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("tuna")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("1970-01-01T00:00:00.000Z")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("1970-01-01T00:00:00.Z")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("2022-10-13T09:52:31.816Z")).toThrow(); + expect(() => datetimeOffsetNoMs.parse("2020-10-14T17:42:29.124+00:00")).toThrow(); +}); + +test("datetime parsing with offset and precision 4", () => { + const datetimeOffset4Ms = z.string().datetime({ offset: true, precision: 4 }); + datetimeOffset4Ms.parse("1970-01-01T00:00:00.1234Z"); + datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+00:00"); + expect(() => datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+0000")).toThrow(); + expect(() => datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+00")).toThrow(); + expect(() => datetimeOffset4Ms.parse("tuna")).toThrow(); + expect(() => datetimeOffset4Ms.parse("1970-01-01T00:00:00.123Z")).toThrow(); + expect(() => datetimeOffset4Ms.parse("2020-10-14T17:42:29.124+00:00")).toThrow(); +}); + +test("datetime offset normalization", () => { + const a = z.iso.datetime({ offset: true }); + + expect(a.safeParse("2020-10-14T17:42:29+02")).toMatchObject({ success: false }); + expect(a.safeParse("2020-10-14T17:42:29+0200")).toMatchObject({ success: false }); + a.safeParse("2020-10-14T17:42:29+02:00"); +}); + +test("datetime parsing with local option", () => { + const a = z.string().datetime({ local: true }); + + expect(a.safeParse("1970-01-01T00:00")).toMatchObject({ success: true }); + expect(a.safeParse("1970-01-01T00:00:00")).toMatchObject({ success: true }); + expect(a.safeParse("2022-10-13T09:52:31.816")).toMatchObject({ success: true }); + expect(a.safeParse("1970-01-01T00:00:00.000")).toMatchObject({ success: true }); + expect(a.safeParse("1970-01-01T00")).toMatchObject({ success: false }); + + // Should reject timezone indicators and invalid formats + + expect(() => a.parse("2022-10-13T09:52:31+00:00")).toThrow(); + expect(() => a.parse("2022-10-13 09:52:31")).toThrow(); + expect(() => a.parse("2022-10-13T24:52:31")).toThrow(); + expect(() => a.parse("2022-10-13T24:52")).toThrow(); + expect(() => a.parse("2022-10-13T24:52Z")).toThrow(); +}); + +test("datetime parsing with local and offset", () => { + const a = z.string().datetime({ local: true, offset: true }); + + // expect(a.parse("2022-10-13T12:52")).toEqual("2022-10-13T12:52:00"); + a.parse("2022-10-13T12:52:00"); + a.parse("2022-10-13T12:52:00Z"); + a.parse("2022-10-13T12:52Z"); + a.parse("2022-10-13T12:52"); + a.parse("2022-10-13T12:52+02:00"); + expect(() => a.parse("2022-10-13T12:52:00+02")).toThrow(); + // expect(() => a.parse("2022-10-13T12:52Z")).toThrow(); + // expect(() => a.parse("2022-10-13T12:52+02:00")).toThrow(); +}); + +test("date parsing", () => { + const date = z.string().date(); + date.parse("1970-01-01"); + date.parse("2022-01-31"); + date.parse("2022-03-31"); + date.parse("2022-04-30"); + date.parse("2022-05-31"); + date.parse("2022-06-30"); + date.parse("2022-07-31"); + date.parse("2022-08-31"); + date.parse("2022-09-30"); + date.parse("2022-10-31"); + date.parse("2022-11-30"); + date.parse("2022-12-31"); + + date.parse("2000-02-29"); + date.parse("2400-02-29"); + expect(() => date.parse("2022-02-29")).toThrow(); + expect(() => date.parse("2100-02-29")).toThrow(); + expect(() => date.parse("2200-02-29")).toThrow(); + expect(() => date.parse("2300-02-29")).toThrow(); + expect(() => date.parse("2500-02-29")).toThrow(); + + expect(() => date.parse("")).toThrow(); + expect(() => date.parse("foo")).toThrow(); + expect(() => date.parse("200-01-01")).toThrow(); + expect(() => date.parse("20000-01-01")).toThrow(); + expect(() => date.parse("2000-0-01")).toThrow(); + expect(() => date.parse("2000-011-01")).toThrow(); + expect(() => date.parse("2000-01-0")).toThrow(); + expect(() => date.parse("2000-01-011")).toThrow(); + expect(() => date.parse("2000/01/01")).toThrow(); + expect(() => date.parse("01-01-2022")).toThrow(); + expect(() => date.parse("01/01/2022")).toThrow(); + expect(() => date.parse("2000-01-01 00:00:00Z")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29+00:00")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29Z")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29")).toThrow(); + expect(() => date.parse("2020-10-14T17:42:29.123Z")).toThrow(); + + expect(() => date.parse("2000-00-12")).toThrow(); + expect(() => date.parse("2000-12-00")).toThrow(); + expect(() => date.parse("2000-01-32")).toThrow(); + expect(() => date.parse("2000-13-01")).toThrow(); + expect(() => date.parse("2000-21-01")).toThrow(); + + expect(() => date.parse("2000-02-30")).toThrow(); + expect(() => date.parse("2000-02-31")).toThrow(); + expect(() => date.parse("2000-04-31")).toThrow(); + expect(() => date.parse("2000-06-31")).toThrow(); + expect(() => date.parse("2000-09-31")).toThrow(); + expect(() => date.parse("2000-11-31")).toThrow(); +}); + +test("time parsing", () => { + const time = z.string().time(); + time.parse("00:00:00"); + time.parse("23:00:00"); + time.parse("00:59:00"); + time.parse("00:00:59"); + time.parse("23:59:59"); + time.parse("09:52:31"); + time.parse("23:59:59.9999999"); + time.parse("00:00"); + expect(() => time.parse("")).toThrow(); + expect(() => time.parse("foo")).toThrow(); + expect(() => time.parse("00:00:00Z")).toThrow(); + expect(() => time.parse("0:00:00")).toThrow(); + expect(() => time.parse("00:0:00")).toThrow(); + expect(() => time.parse("00:00:0")).toThrow(); + expect(() => time.parse("00:00:00.000+00:00")).toThrow(); + expect(() => time.parse("24:00:00")).toThrow(); + expect(() => time.parse("00:60:00")).toThrow(); + expect(() => time.parse("00:00:60")).toThrow(); + expect(() => time.parse("24:60:60")).toThrow(); + + const time2 = z.string().time({ precision: 2 }); + time2.parse("00:00:00.00"); + time2.parse("09:52:31.12"); + time2.parse("23:59:59.99"); + expect(() => time2.parse("")).toThrow(); + expect(() => time2.parse("foo")).toThrow(); + expect(() => time2.parse("00:00:00")).toThrow(); + expect(() => time2.parse("00:00:00.00Z")).toThrow(); + expect(() => time2.parse("00:00:00.0")).toThrow(); + expect(() => time2.parse("00:00:00.000")).toThrow(); + expect(() => time2.parse("00:00:00.00+00:00")).toThrow(); + + const time3 = z.string().time({ precision: z.TimePrecision.Minute }); + time3.parse("00:00"); + expect(() => time3.parse("00:00:00")).toThrow(); +}); + +test("duration", () => { + const duration = z.string().duration(); + + const validDurations = [ + "P3Y6M4DT12H30M5S", + "P2Y9M3DT12H31M8.001S", + // "+P3Y6M4DT12H30M5S", + // "-PT0.001S", + // "+PT0.001S", + "PT0,001S", + "PT12H30M5S", + // "-P2M1D", + // "P-2M-1D", + // "-P5DT10H", + // "P-5DT-10H", + "P1Y", + "P2MT30M", + "PT6H", + "P5W", + // "P0.5Y", + // "P0,5Y", + // "P42YT7.004M", + ]; + + const invalidDurations = [ + "foo bar", + "", + " ", + "P", + "PT", + "P1Y2MT", + "T1H", + "P0.5Y1D", + "P0,5Y6M", + "P1YT", + "P-2M-1D", + "P-5DT-10H", + "P1W2D", + "-P1D", + ]; + + for (const val of validDurations) { + const result = duration.safeParse(val); + if (!result.success) { + throw Error(`Valid duration could not be parsed: ${val}`); + } + } + + for (const val of invalidDurations) { + const result = duration.safeParse(val); + + if (result.success) { + throw Error(`Invalid duration was successful parsed: ${val}`); + } + + expect(result.error.issues[0].message).toEqual("Invalid ISO duration"); + } +}); + +test("redos checker", () => { + const a = z.iso.datetime(); + const b = z.string().datetime({ offset: true }); + const c = z.string().datetime({ local: true }); + const d = z.string().datetime({ local: true, offset: true, precision: 3 }); + const e = z.string().date(); + const f = z.string().time(); + const g = z.string().duration(); + for (const schema of [a, b, c, d, e, f, g]) { + const result = checkSync(schema._zod.pattern.source, ""); + if (result.status !== "safe") throw Error("ReDoS issue"); + } +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/default.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/default.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..895f51a1661c7f3e8904eab8a8dd9c9561c99026 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/default.test.ts @@ -0,0 +1,313 @@ +import { expect, expectTypeOf, test } from "vitest"; +import { z } from "zod/v4"; + +test("basic defaults", () => { + expect(z.string().default("default").parse(undefined)).toBe("default"); +}); + +test("default with optional", () => { + const schema = z.string().optional().default("default"); + expect(schema.parse(undefined)).toBe("default"); + expect(schema.unwrap().parse(undefined)).toBe(undefined); +}); + +test("default with transform", () => { + const stringWithDefault = z + .string() + .transform((val) => val.toUpperCase()) + .default("default"); + expect(stringWithDefault.parse(undefined)).toBe("default"); + expect(stringWithDefault).toBeInstanceOf(z.ZodDefault); + expect(stringWithDefault.unwrap()).toBeInstanceOf(z.ZodPipe); + expect(stringWithDefault.unwrap().in).toBeInstanceOf(z.ZodString); + expect(stringWithDefault.unwrap().out).toBeInstanceOf(z.ZodTransform); + + type inp = z.input; + expectTypeOf().toEqualTypeOf(); + type out = z.output; + expectTypeOf().toEqualTypeOf(); +}); + +test("default on existing optional", () => { + const stringWithDefault = z.string().optional().default("asdf"); + expect(stringWithDefault.parse(undefined)).toBe("asdf"); + expect(stringWithDefault).toBeInstanceOf(z.ZodDefault); + expect(stringWithDefault.unwrap()).toBeInstanceOf(z.ZodOptional); + expect(stringWithDefault.unwrap().unwrap()).toBeInstanceOf(z.ZodString); + + type inp = z.input; + expectTypeOf().toEqualTypeOf(); + type out = z.output; + expectTypeOf().toEqualTypeOf(); +}); + +test("optional on default", () => { + const stringWithDefault = z.string().default("asdf").optional(); + + type inp = z.input; + expectTypeOf().toEqualTypeOf(); + type out = z.output; + expectTypeOf().toEqualTypeOf(); + + expect(stringWithDefault.parse(undefined)).toBe("asdf"); +}); + +// test("complex chain example", () => { +// const complex = z +// .string() +// .default("asdf") +// .transform((val) => val.toUpperCase()) +// .default("qwer") +// .unwrap() +// .optional() +// .default("asdfasdf"); + +// expect(complex.parse(undefined)).toBe("asdfasdf"); +// }); + +test("removeDefault", () => { + const stringWithRemovedDefault = z.string().default("asdf").removeDefault(); + + type out = z.output; + expectTypeOf().toEqualTypeOf(); +}); + +test("apply default at output", () => { + const schema = z + .string() + .transform((_) => (Math.random() > 0 ? undefined : _)) + .default("asdf"); + expect(schema.parse("")).toEqual("asdf"); +}); + +test("nested", () => { + const inner = z.string().default("asdf"); + const outer = z.object({ inner }).default({ + inner: "qwer", + }); + type input = z.input; + expectTypeOf().toEqualTypeOf<{ inner?: string | undefined } | undefined>(); + type out = z.output; + expectTypeOf().toEqualTypeOf<{ inner: string }>(); + expect(outer.parse(undefined)).toEqual({ inner: "qwer" }); + expect(outer.parse({})).toEqual({ inner: "asdf" }); + expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" }); +}); + +test("chained defaults", () => { + const stringWithDefault = z.string().default("inner").default("outer"); + const result = stringWithDefault.parse(undefined); + expect(result).toEqual("outer"); +}); + +test("object optionality", () => { + const schema = z.object({ + hi: z.string().default("hi"), + }); + type schemaInput = z.input; + type schemaOutput = z.output; + expectTypeOf().toEqualTypeOf<{ hi?: string | undefined }>(); + expectTypeOf().toEqualTypeOf<{ hi: string }>(); + expect(schema.parse({})).toEqual({ + hi: "hi", + }); +}); + +test("nested prefault/default", () => { + const a = z + .string() + .default("a") + .refine((val) => val.startsWith("a")); + const b = z + .string() + .refine((val) => val.startsWith("b")) + .default("b"); + const c = z + .string() + .prefault("c") + .refine((val) => val.startsWith("c")); + const d = z + .string() + .refine((val) => val.startsWith("d")) + .prefault("d"); + + const obj = z.object({ + a, + b, + c, + d, + }); + + expect(obj.safeParse({ a: "a1", b: "b1", c: "c1", d: "d1" })).toMatchInlineSnapshot(` + { + "data": { + "a": "a1", + "b": "b1", + "c": "c1", + "d": "d1", + }, + "success": true, + } + `); + + expect(obj.safeParse({ a: "f", b: "f", c: "f", d: "f" })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "path": [ + "a" + ], + "message": "Invalid input" + }, + { + "code": "custom", + "path": [ + "b" + ], + "message": "Invalid input" + }, + { + "code": "custom", + "path": [ + "c" + ], + "message": "Invalid input" + }, + { + "code": "custom", + "path": [ + "d" + ], + "message": "Invalid input" + } + ]], + "success": false, + } + `); + + expect(obj.safeParse({})).toMatchInlineSnapshot(` + { + "data": { + "a": "a", + "b": "b", + "c": "c", + "d": "d", + }, + "success": true, + } + `); + + expect(obj.safeParse({ a: undefined, b: undefined, c: undefined, d: undefined })).toMatchInlineSnapshot(` + { + "data": { + "a": "a", + "b": "b", + "c": "c", + "d": "d", + }, + "success": true, + } + `); + + const obj2 = z.object({ + a: a.optional(), + b: b.optional(), + c: c.optional(), + d: d.optional(), + }); + expect(obj2.safeParse({ a: undefined, b: undefined, c: undefined, d: undefined })).toMatchInlineSnapshot(` + { + "data": { + "a": "a", + "b": "b", + "c": "c", + "d": "d", + }, + "success": true, + } + `); + + expect(a.parse(undefined)).toBe("a"); + expect(b.parse(undefined)).toBe("b"); + expect(c.parse(undefined)).toBe("c"); + expect(d.parse(undefined)).toBe("d"); +}); + +test("failing default", () => { + const a = z + .string() + .default("z") + .refine((val) => val.startsWith("a")); + const b = z + .string() + .refine((val) => val.startsWith("b")) + .default("z"); + const c = z + .string() + .prefault("z") + .refine((val) => val.startsWith("c")); + const d = z + .string() + .refine((val) => val.startsWith("d")) + .prefault("z"); + + const obj = z.object({ + a, + b, + c, + d, + }); + + expect( + obj.safeParse({ + a: undefined, + b: undefined, + c: undefined, + d: undefined, + }).error!.issues + ).toMatchInlineSnapshot(` + [ + { + "code": "custom", + "message": "Invalid input", + "path": [ + "a", + ], + }, + { + "code": "custom", + "message": "Invalid input", + "path": [ + "c", + ], + }, + { + "code": "custom", + "message": "Invalid input", + "path": [ + "d", + ], + }, + ] + `); +}); + +test("partial should not clobber defaults", () => { + const objWithDefaults = z.object({ + a: z.string().default("defaultA"), + b: z.string().default("defaultB"), + c: z.string().default("defaultC"), + }); + + const objPartialWithOneRequired = objWithDefaults.partial(); //.required({ a: true }); + + const test = objPartialWithOneRequired.parse({}); + expect(test).toMatchInlineSnapshot(` + { + "a": "defaultA", + "b": "defaultB", + "c": "defaultC", + } + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/description.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/description.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a3dd1b26b1bb80fc4489dd31d30438c8ed5fda4 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/description.test.ts @@ -0,0 +1,32 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +const description = "a description"; + +// test("passing `description` to schema should add a description", () => { +// expect(z.string({ description }).description).toEqual(description); +// expect(z.number({ description }).description).toEqual(description); +// expect(z.boolean({ description }).description).toEqual(description); +// }); + +test(".describe", () => { + expect(z.string().describe(description).description).toEqual(description); + expect(z.number().describe(description).description).toEqual(description); + expect(z.boolean().describe(description).description).toEqual(description); +}); + +test("adding description with z.globalRegistry", () => { + const schema = z.string(); + z.core.globalRegistry.add(schema, { description }); + z.core.globalRegistry.get(schema); + expect(schema.description).toEqual(description); +}); + +// in Zod 4 descriptions are not inherited +// test("description should carry over to chained schemas", () => { +// const schema = z.string().describe(description); +// expect(schema.description).toEqual(description); +// expect(schema.optional().description).toEqual(description); +// expect(schema.optional().nullable().default("default").description).toEqual(description); +// }); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9aba3df8098289bdc232c9c214018314155c9ded --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts @@ -0,0 +1,619 @@ +import { expect, expectTypeOf, test } from "vitest"; + +import * as z from "zod/v4"; + +test("_values", () => { + expect(z.string()._zod.values).toEqual(undefined); + expect(z.enum(["a", "b"])._zod.values).toEqual(new Set(["a", "b"])); + expect(z.nativeEnum({ a: "A", b: "B" })._zod.values).toEqual(new Set(["A", "B"])); + expect(z.literal("test")._zod.values).toEqual(new Set(["test"])); + expect(z.literal(123)._zod.values).toEqual(new Set([123])); + expect(z.literal(true)._zod.values).toEqual(new Set([true])); + expect(z.literal(BigInt(123))._zod.values).toEqual(new Set([BigInt(123)])); + expect(z.undefined()._zod.values).toEqual(new Set([undefined])); + expect(z.null()._zod.values).toEqual(new Set([null])); + + const t = z.literal("test"); + expect(t.optional()._zod.values).toEqual(new Set(["test", undefined])); + expect(t.nullable()._zod.values).toEqual(new Set(["test", null])); + expect(t.default("test")._zod.values).toEqual(new Set(["test"])); + expect(t.catch("test")._zod.values).toEqual(new Set(["test"])); + + const pre = z.preprocess((val) => String(val), z.string()).pipe(z.literal("test")); + expect(pre._zod.values).toEqual(undefined); + + const post = z.literal("test").transform((_) => Math.random()); + expect(post._zod.values).toEqual(new Set(["test"])); + + // Test that readonly literals pass through their values property + expect(z.literal("test").readonly()._zod.values).toEqual(new Set(["test"])); +}); + +test("valid parse - object", () => { + expect( + z + .discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]) + .parse({ type: "a", a: "abc" }) + ).toEqual({ type: "a", a: "abc" }); +}); + +test("valid - include discriminator key (deprecated)", () => { + expect( + z + .discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]) + .parse({ type: "a", a: "abc" }) + ).toEqual({ type: "a", a: "abc" }); +}); + +test("valid - optional discriminator (object)", () => { + const schema = z.discriminatedUnion("type", [ + z.object({ type: z.literal("a").optional(), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]); + expect(schema.parse({ type: "a", a: "abc" })).toEqual({ type: "a", a: "abc" }); + expect(schema.parse({ a: "abc" })).toEqual({ a: "abc" }); +}); + +test("valid - discriminator value of various primitive types", () => { + const schema = z.discriminatedUnion("type", [ + z.object({ type: z.literal("1"), val: z.string() }), + z.object({ type: z.literal(1), val: z.string() }), + z.object({ type: z.literal(BigInt(1)), val: z.string() }), + z.object({ type: z.literal("true"), val: z.string() }), + z.object({ type: z.literal(true), val: z.string() }), + z.object({ type: z.literal("null"), val: z.string() }), + z.object({ type: z.null(), val: z.string() }), + z.object({ type: z.literal("undefined"), val: z.string() }), + z.object({ type: z.undefined(), val: z.string() }), + ]); + + expect(schema.parse({ type: "1", val: "val" })).toEqual({ type: "1", val: "val" }); + expect(schema.parse({ type: 1, val: "val" })).toEqual({ type: 1, val: "val" }); + expect(schema.parse({ type: BigInt(1), val: "val" })).toEqual({ + type: BigInt(1), + val: "val", + }); + expect(schema.parse({ type: "true", val: "val" })).toEqual({ + type: "true", + val: "val", + }); + expect(schema.parse({ type: true, val: "val" })).toEqual({ + type: true, + val: "val", + }); + expect(schema.parse({ type: "null", val: "val" })).toEqual({ + type: "null", + val: "val", + }); + expect(schema.parse({ type: null, val: "val" })).toEqual({ + type: null, + val: "val", + }); + expect(schema.parse({ type: "undefined", val: "val" })).toEqual({ + type: "undefined", + val: "val", + }); + expect(schema.parse({ type: undefined, val: "val" })).toEqual({ + type: undefined, + val: "val", + }); + + const fail = schema.safeParse({ + type: "not_a_key", + val: "val", + }); + expect(fail.error).toBeInstanceOf(z.ZodError); +}); + +test("invalid - null", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]).parse(null); + throw new Error(); + } catch (e: any) { + // [ + // { + // code: z.ZodIssueCode.invalid_type, + // expected: z.ZodParsedType.object, + // input: null, + // message: "Expected object, received null", + // received: z.ZodParsedType.null, + // path: [], + // }, + // ]; + expect(e.issues).toMatchInlineSnapshot(` + [ + { + "code": "invalid_type", + "expected": "object", + "message": "Invalid input: expected object, received null", + "path": [], + }, + ] + `); + } +}); + +test("invalid discriminator value", () => { + const result = z + .discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]) + .safeParse({ type: "x", a: "abc" }); + + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_union", + "errors": [], + "note": "No matching discriminator", + "path": [ + "type" + ], + "message": "Invalid input" + } + ]], + "success": false, + } + `); +}); + +test("invalid discriminator value - unionFallback", () => { + const result = z + .discriminatedUnion( + "type", + [z.object({ type: z.literal("a"), a: z.string() }), z.object({ type: z.literal("b"), b: z.string() })], + { unionFallback: true } + ) + .safeParse({ type: "x", a: "abc" }); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_union", + "errors": [ + [ + { + "code": "invalid_value", + "values": [ + "a" + ], + "path": [ + "type" + ], + "message": "Invalid input: expected \\"a\\"" + } + ], + [ + { + "code": "invalid_value", + "values": [ + "b" + ], + "path": [ + "type" + ], + "message": "Invalid input: expected \\"b\\"" + }, + { + "expected": "string", + "code": "invalid_type", + "path": [ + "b" + ], + "message": "Invalid input: expected string, received undefined" + } + ] + ], + "path": [], + "message": "Invalid input" + } + ]], + "success": false, + } + `); +}); + +test("valid discriminator value, invalid data", () => { + const result = z + .discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ type: z.literal("b"), b: z.string() }), + ]) + .safeParse({ type: "a", b: "abc" }); + + // [ + // { + // code: z.ZodIssueCode.invalid_type, + // expected: z.ZodParsedType.string, + // message: "Required", + // path: ["a"], + // received: z.ZodParsedType.undefined, + // }, + // ]; + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + "a" + ], + "message": "Invalid input: expected string, received undefined" + } + ]], + "success": false, + } + `); +}); + +test("wrong schema - missing discriminator", () => { + try { + z.discriminatedUnion("type", [ + z.object({ type: z.literal("a"), a: z.string() }), + z.object({ b: z.string() }) as any, + ])._zod.propValues; + throw new Error(); + } catch (e: any) { + expect(e.message.includes("Invalid discriminated union option")).toBe(true); + } +}); + +// removed to account for unions of unions +// test("wrong schema - duplicate discriminator values", () => { +// try { +// z.discriminatedUnion("type",[ +// z.object({ type: z.literal("a"), a: z.string() }), +// z.object({ type: z.literal("a"), b: z.string() }), +// ]); +// throw new Error(); +// } catch (e: any) { +// expect(e.message.includes("Duplicate discriminator value")).toEqual(true); +// } +// }); + +test("async - valid", async () => { + const schema = await z.discriminatedUnion("type", [ + z.object({ + type: z.literal("a"), + a: z + .string() + .refine(async () => true) + .transform(async (val) => Number(val)), + }), + z.object({ + type: z.literal("b"), + b: z.string(), + }), + ]); + const data = { type: "a", a: "1" }; + const result = await schema.safeParseAsync(data); + expect(result.data).toEqual({ type: "a", a: 1 }); +}); + +test("async - invalid", async () => { + // try { + const a = z.discriminatedUnion("type", [ + z.object({ + type: z.literal("a"), + a: z + .string() + .refine(async () => true) + .transform(async (val) => val), + }), + z.object({ + type: z.literal("b"), + b: z.string(), + }), + ]); + const result = await a.safeParseAsync({ type: "a", a: 1 }); + + // expect(JSON.parse(e.message)).toEqual([ + // { + // code: "invalid_type", + // expected: "string", + // input: 1, + // received: "number", + // path: ["a"], + // message: "Expected string, received number", + // }, + // ]); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + "a" + ], + "message": "Invalid input: expected string, received number" + } + ]] + `); +}); + +test("valid - literals with .default or .pipe", () => { + const schema = z.discriminatedUnion("type", [ + z.object({ + type: z.literal("foo").default("foo"), + a: z.string(), + }), + z.object({ + type: z.literal("custom"), + method: z.string(), + }), + z.object({ + type: z.literal("bar").transform((val) => val), + c: z.string(), + }), + ]); + expect(schema.parse({ type: "foo", a: "foo" })).toEqual({ + type: "foo", + a: "foo", + }); +}); + +test("enum and nativeEnum", () => { + enum MyEnum { + d = 0, + e = "e", + } + + const schema = z.discriminatedUnion("key", [ + z.object({ + key: z.literal("a"), + // Add other properties specific to this option + }), + z.object({ + key: z.enum(["b", "c"]), + // Add other properties specific to this option + }), + z.object({ + key: z.nativeEnum(MyEnum), + // Add other properties specific to this option + }), + ]); + + type schema = z.infer; + expectTypeOf().toEqualTypeOf<{ key: "a" } | { key: "b" | "c" } | { key: MyEnum.d | MyEnum.e }>(); + + schema.parse({ key: "a" }); + schema.parse({ key: "b" }); + schema.parse({ key: "c" }); + schema.parse({ key: MyEnum.d }); + schema.parse({ key: MyEnum.e }); + schema.parse({ key: "e" }); +}); + +test("branded", () => { + const schema = z.discriminatedUnion("key", [ + z.object({ + key: z.literal("a"), + // Add other properties specific to this option + }), + z.object({ + key: z.literal("b").brand<"asdfasdf">(), + // Add other properties specific to this option + }), + ]); + + type schema = z.infer; + expectTypeOf().toEqualTypeOf<{ key: "a" } | { key: "b" & z.core.$brand<"asdfasdf"> }>(); + + schema.parse({ key: "a" }); + schema.parse({ key: "b" }); + expect(() => { + schema.parse({ key: "c" }); + }).toThrow(); +}); + +test("optional and nullable", () => { + const schema = z.discriminatedUnion("key", [ + z.object({ + key: z.literal("a").optional(), + a: z.literal(true), + }), + z.object({ + key: z.literal("b").nullable(), + b: z.literal(true), + // Add other properties specific to this option + }), + ]); + + type schema = z.infer; + expectTypeOf().toEqualTypeOf<{ key?: "a" | undefined; a: true } | { key: "b" | null; b: true }>(); + + schema.parse({ key: "a", a: true }); + schema.parse({ key: undefined, a: true }); + schema.parse({ key: "b", b: true }); + schema.parse({ key: null, b: true }); + expect(() => { + schema.parse({ key: null, a: true }); + }).toThrow(); + expect(() => { + schema.parse({ key: "b", a: true }); + }).toThrow(); + + const value = schema.parse({ key: null, b: true }); + + if (!("key" in value)) value.a; + if (value.key === undefined) value.a; + if (value.key === "a") value.a; + if (value.key === "b") value.b; + if (value.key === null) value.b; +}); + +test("multiple discriminators", () => { + const FreeConfig = z.object({ + type: z.literal("free"), + min_cents: z.null(), + }); + + // console.log(FreeConfig.shape.type); + const PricedConfig = z.object({ + type: z.literal("fiat-price"), + // min_cents: z.int().nullable(), + min_cents: z.null(), + }); + + const Config = z.discriminatedUnion("type", [FreeConfig, PricedConfig]); + + Config.parse({ + min_cents: null, + type: "fiat-price", + name: "Standard", + }); + + expect(() => { + Config.parse({ + min_cents: null, + type: "not real", + name: "Standard", + }); + }).toThrow(); +}); + +test("single element union", () => { + const schema = z.object({ + a: z.literal("discKey"), + b: z.enum(["apple", "banana"]), + c: z.object({ id: z.string() }), + }); + + const input = { + a: "discKey", + b: "apple", + c: {}, // Invalid, as schema requires `id` property + }; + + // Validation must fail here, but it doesn't + + const u = z.discriminatedUnion("a", [schema]); + const result = u.safeParse(input); + expect(result).toMatchObject({ success: false }); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + "c", + "id" + ], + "message": "Invalid input: expected string, received undefined" + } + ]], + "success": false, + } + `); + + expect(u.options.length).toEqual(1); +}); + +test("nested discriminated unions", () => { + const BaseError = z.object({ status: z.literal("failed"), message: z.string() }); + const MyErrors = z.discriminatedUnion("code", [ + BaseError.extend({ code: z.literal(400) }), + BaseError.extend({ code: z.literal(401) }), + BaseError.extend({ code: z.literal(500) }), + ]); + + const MyResult = z.discriminatedUnion("status", [ + z.object({ status: z.literal("success"), data: z.string() }), + MyErrors, + ]); + + expect(MyErrors._zod.propValues).toMatchInlineSnapshot(` + { + "code": Set { + 400, + 401, + 500, + }, + "status": Set { + "failed", + }, + } + `); + expect(MyResult._zod.propValues).toMatchInlineSnapshot(` + { + "code": Set { + 400, + 401, + 500, + }, + "status": Set { + "success", + "failed", + }, + } + `); + + const result = MyResult.parse({ status: "success", data: "hello" }); + expect(result).toMatchInlineSnapshot(` + { + "data": "hello", + "status": "success", + } + `); + const result2 = MyResult.parse({ status: "failed", code: 400, message: "bad request" }); + expect(result2).toMatchInlineSnapshot(` + { + "code": 400, + "message": "bad request", + "status": "failed", + } + `); + const result3 = MyResult.parse({ status: "failed", code: 401, message: "unauthorized" }); + expect(result3).toMatchInlineSnapshot(` + { + "code": 401, + "message": "unauthorized", + "status": "failed", + } + `); + const result4 = MyResult.parse({ status: "failed", code: 500, message: "internal server error" }); + expect(result4).toMatchInlineSnapshot(` + { + "code": 500, + "message": "internal server error", + "status": "failed", + } + `); +}); + +test("readonly literal discriminator", () => { + const discUnion = z.discriminatedUnion("type", [ + z.object({ type: z.literal("a").readonly(), a: z.string() }), + z.object({ type: z.literal("b"), b: z.number() }), + ]); + + // Test that both discriminator values are correctly included in propValues + const propValues = discUnion._zod.propValues; + expect(propValues?.type?.has("a")).toBe(true); + expect(propValues?.type?.has("b")).toBe(true); + + // Test that the discriminated union works correctly + const result1 = discUnion.parse({ type: "a", a: "hello" }); + expect(result1).toEqual({ type: "a", a: "hello" }); + + const result2 = discUnion.parse({ type: "b", b: 42 }); + expect(result2).toEqual({ type: "b", b: 42 }); + + // Test that invalid discriminator values are rejected + expect(() => { + discUnion.parse({ type: "c", a: "hello" }); + }).toThrow(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/enum.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/enum.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..144ae977a372501bb67d8c992234b60501e63062 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/enum.test.ts @@ -0,0 +1,285 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("enum from string array", () => { + const MyEnum = z.enum(["Red", "Green", "Blue"]); + expect(MyEnum.enum.Red).toEqual("Red"); + + type MyEnum = z.infer; + expectTypeOf().toEqualTypeOf<"Red" | "Green" | "Blue">(); +}); + +test("enum from const object", () => { + const Fruits: { Apple: "apple"; Banana: "banana" } = { + Apple: "apple", + Banana: "banana", + }; + const fruitEnum = z.nativeEnum(Fruits); + type fruitEnum = z.infer; + fruitEnum.parse("apple"); + fruitEnum.parse("banana"); + fruitEnum.parse(Fruits.Apple); + fruitEnum.parse(Fruits.Banana); + expectTypeOf().toEqualTypeOf<"apple" | "banana">(); +}); + +test("enum from native enum", () => { + enum Fruits { + Apple = "apple", + Banana = "banana", + Orange = 3, + } + // @ts-ignore + const fruitEnum = z.nativeEnum(Fruits); + type fruitEnum = z.infer; + fruitEnum.parse("apple"); + fruitEnum.parse("banana"); + fruitEnum.parse(Fruits.Apple); + fruitEnum.parse(Fruits.Banana); + + expect(fruitEnum.safeParse("Apple").success).toEqual(false); + expect(fruitEnum.safeParse("Cantaloupe").success).toEqual(false); + + expectTypeOf().toMatchTypeOf(); + expectTypeOf().toMatchTypeOf(); +}); + +test("enum from native enum with numeric keys", () => { + const FruitValues = { + Apple: 10, + Banana: 20, + // @ts-ignore + } as const; + const fruitEnum = z.nativeEnum(FruitValues); + type fruitEnum = z.infer; + fruitEnum.parse(10); + fruitEnum.parse(20); + fruitEnum.parse(FruitValues.Apple); + fruitEnum.parse(FruitValues.Banana); + expectTypeOf().toEqualTypeOf<10 | 20>(); +}); + +test("issue metadata", () => { + const schema = z.enum(["Red", "Green", "Blue"]); + const result = schema.safeParse("Yellow"); + expect(result.error!.issues[0]).toMatchInlineSnapshot(` + { + "code": "invalid_value", + "message": "Invalid option: expected one of "Red"|"Green"|"Blue"", + "path": [], + "values": [ + "Red", + "Green", + "Blue", + ], + } + `); +}); + +test("enum from non-const inputs", () => { + const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"]; + const FoodEnum = z.enum(foods); + + expectTypeOf>().toEqualTypeOf(); + expect(FoodEnum.safeParse("Pasta").success).toEqual(true); + expect(FoodEnum.safeParse("Cucumbers").success).toEqual(false); +}); + +test("get options", () => { + expect(z.enum(["tuna", "trout"]).options).toEqual(["tuna", "trout"]); +}); + +test("readonly enum", () => { + const HTTP_SUCCESS = ["200", "201"] as const; + const arg = z.enum(HTTP_SUCCESS); + type arg = z.infer; + expectTypeOf().toEqualTypeOf<"200" | "201">(); + + arg.parse("201"); + expect(() => arg.parse("202")).toThrow(); +}); + +test("error map", () => { + const result = z + .enum(["test"], { error: (iss) => (iss.input === undefined ? "REQUIRED" : undefined) }) + .safeParse(undefined); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("REQUIRED"); + } +}); + +test("type signatures", () => { + const a = z.enum(["a", "b", "c"]); + const b = z.enum(a.options); + expectTypeOf(a).toEqualTypeOf(b); + + const c = z.enum({ a: 1, b: 2 } as const); + expectTypeOf(c.enum).toEqualTypeOf<{ + readonly a: 1; + readonly b: 2; + }>(); + + enum Fruit { + Apple = "apple", + Banana = "banana", + Orange = "orange", + } + const d = z.enum(Fruit); + expectTypeOf(d.enum).toEqualTypeOf(Fruit); + + const e = z.enum({ a: 1, b: 2 }); + expectTypeOf(e.enum).toEqualTypeOf<{ + readonly a: 1; + readonly b: 2; + }>(); +}); + +test("extract", () => { + const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const; + const FoodEnum = z.enum(foods); + const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]); + + expect(ItalianEnum.safeParse("Pasta").success).toEqual(true); + expect(ItalianEnum.safeParse("Tacos").success).toEqual(false); + + expectTypeOf>().toEqualTypeOf<"Pasta" | "Pizza">(); +}); + +test("exclude", () => { + const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const; + const FoodEnum = z.enum(foods); + const UnhealthyEnum = FoodEnum.exclude(["Salad"]); + + expect(UnhealthyEnum.safeParse("Pasta").success).toEqual(true); + expect(UnhealthyEnum.safeParse("Salad").success).toEqual(false); + expectTypeOf>().toEqualTypeOf<"Pasta" | "Pizza" | "Tacos" | "Burgers">(); + + const EmptyFoodEnum = FoodEnum.exclude(foods); + expectTypeOf().toEqualTypeOf>(); + expectTypeOf>().toEqualTypeOf(); +}); + +test("error map inheritance", () => { + const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const; + const FoodEnum = z.enum(foods, { error: () => "This is not food!" }); + const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]); + + const foodsError = FoodEnum.safeParse("Cucumbers"); + const italianError = ItalianEnum.safeParse("Tacos"); + + expect(foodsError.error!.issues[0].message).toEqual(italianError.error!.issues[0].message); + + const UnhealthyEnum = FoodEnum.exclude(["Salad"], { + error: () => ({ message: "This is not healthy food!" }), + }); + const unhealthyError = UnhealthyEnum.safeParse("Salad"); + if (!unhealthyError.success) { + expect(unhealthyError.error.issues[0].message).toEqual("This is not healthy food!"); + } +}); + +test("readonly in ZodEnumDef", () => { + type _a = z.ZodEnum<{ readonly a: "a"; readonly b: "b" }>; + type _b = z.ZodEnum<{ a: "a"; b: "b" }>; +}); + +test("enum error message, invalid enum elementstring", () => { + const result = z.enum(["Tuna", "Trout"]).safeParse("Salmon"); + expect(result.success).toEqual(false); + expect(result.error!.issues.length).toEqual(1); + + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "invalid_value", + "values": [ + "Tuna", + "Trout" + ], + "path": [], + "message": "Invalid option: expected one of \\"Tuna\\"|\\"Trout\\"" + } + ]] + `); +}); + +test("enum error message, invalid type", () => { + const result = z.enum(["Tuna", "Trout"]).safeParse(12); + expect(result.success).toEqual(false); + expect(result.error!.issues.length).toEqual(1); + // expect(result.error!.issues[0].message).toEqual('Invalid input: expected one of "Tuna"|"Trout"'); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "invalid_value", + "values": [ + "Tuna", + "Trout" + ], + "path": [], + "message": "Invalid option: expected one of \\"Tuna\\"|\\"Trout\\"" + } + ]] + `); +}); + +test("nativeEnum default error message", () => { + enum Fish { + Tuna = "Tuna", + Trout = "Trout", + } + const result = z.nativeEnum(Fish).safeParse("Salmon"); + expect(result.success).toEqual(false); + expect(result.error!.issues.length).toEqual(1); + // expect(result.error!.issues[0].message).toEqual('Invalid input: expected one of "Tuna"|"Trout"'); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "invalid_value", + "values": [ + "Tuna", + "Trout" + ], + "path": [], + "message": "Invalid option: expected one of \\"Tuna\\"|\\"Trout\\"" + } + ]] + `); +}); + +test("enum with message returns the custom error message", () => { + const schema = z.enum(["apple", "banana"], { + message: "the value provided is invalid", + }); + + const result1 = schema.safeParse("berries"); + expect(result1.success).toEqual(false); + if (!result1.success) { + expect(result1.error.issues[0].message).toEqual("the value provided is invalid"); + } + + const result2 = schema.safeParse(undefined); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].message).toEqual("the value provided is invalid"); + } + + const result3 = schema.safeParse("banana"); + expect(result3.success).toEqual(true); + + const result4 = schema.safeParse(null); + expect(result4.success).toEqual(false); + if (!result4.success) { + expect(result4.error.issues[0].message).toEqual("the value provided is invalid"); + } +}); + +test("enum with diagonal keys", () => { + const schema_02 = z.enum({ + A: 1, + B: "A", + }); + + expect(schema_02.safeParse("A")).toMatchObject({ success: true }); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/error-utils.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/error-utils.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6b2d3e39be097a5ab07f3f5780fe90591ac8e6d --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/error-utils.test.ts @@ -0,0 +1,527 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +declare const iss: z.core.$ZodIssueCode; + +const Test = z.object({ + f1: z.number(), + f2: z.string().optional(), + f3: z.string().nullable(), + f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })), +}); +// type TestFlattenedErrors = core.inferFlattenedErrors; +// type TestFormErrors = core.inferFlattenedErrors; +const parsed = Test.safeParse({}); + +test("regular error", () => { + expect(parsed).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "number", + "code": "invalid_type", + "path": [ + "f1" + ], + "message": "Invalid input: expected number, received undefined" + }, + { + "expected": "string", + "code": "invalid_type", + "path": [ + "f3" + ], + "message": "Invalid input: expected string, received undefined" + }, + { + "expected": "array", + "code": "invalid_type", + "path": [ + "f4" + ], + "message": "Invalid input: expected array, received undefined" + } + ]], + "success": false, + } + `); +}); + +test(".flatten()", () => { + const flattened = parsed.error!.flatten(); + // flattened. + expectTypeOf(flattened).toMatchTypeOf<{ + formErrors: string[]; + fieldErrors: { + f2?: string[]; + f1?: string[]; + f3?: string[]; + f4?: string[]; + }; + }>(); + + expect(flattened).toMatchInlineSnapshot(` + { + "fieldErrors": { + "f1": [ + "Invalid input: expected number, received undefined", + ], + "f3": [ + "Invalid input: expected string, received undefined", + ], + "f4": [ + "Invalid input: expected array, received undefined", + ], + }, + "formErrors": [], + } + `); +}); + +test("custom .flatten()", () => { + type ErrorType = { message: string; code: number }; + const flattened = parsed.error!.flatten((iss) => ({ message: iss.message, code: 1234 })); + expectTypeOf(flattened).toMatchTypeOf<{ + formErrors: ErrorType[]; + fieldErrors: { + f2?: ErrorType[]; + f1?: ErrorType[]; + f3?: ErrorType[]; + f4?: ErrorType[]; + }; + }>(); + + expect(flattened).toMatchInlineSnapshot(` + { + "fieldErrors": { + "f1": [ + { + "code": 1234, + "message": "Invalid input: expected number, received undefined", + }, + ], + "f3": [ + { + "code": 1234, + "message": "Invalid input: expected string, received undefined", + }, + ], + "f4": [ + { + "code": 1234, + "message": "Invalid input: expected array, received undefined", + }, + ], + }, + "formErrors": [], + } + `); +}); + +test(".format()", () => { + const formatted = parsed.error!.format(); + expectTypeOf(formatted).toMatchTypeOf<{ + _errors: string[]; + f2?: { _errors: string[] }; + f1?: { _errors: string[] }; + f3?: { _errors: string[] }; + f4?: { + [x: number]: { + _errors: string[]; + t?: { + _errors: string[]; + }; + }; + _errors: string[]; + }; + }>(); + + expect(formatted).toMatchInlineSnapshot(` + { + "_errors": [], + "f1": { + "_errors": [ + "Invalid input: expected number, received undefined", + ], + }, + "f3": { + "_errors": [ + "Invalid input: expected string, received undefined", + ], + }, + "f4": { + "_errors": [ + "Invalid input: expected array, received undefined", + ], + }, + } + `); +}); + +test("custom .format()", () => { + type ErrorType = { message: string; code: number }; + const formatted = parsed.error!.format((iss) => ({ message: iss.message, code: 1234 })); + expectTypeOf(formatted).toMatchTypeOf<{ + _errors: ErrorType[]; + f2?: { _errors: ErrorType[] }; + f1?: { _errors: ErrorType[] }; + f3?: { _errors: ErrorType[] }; + f4?: { + [x: number]: { + _errors: ErrorType[]; + t?: { + _errors: ErrorType[]; + }; + }; + _errors: ErrorType[]; + }; + }>(); + + expect(formatted).toMatchInlineSnapshot(` + { + "_errors": [], + "f1": { + "_errors": [ + { + "code": 1234, + "message": "Invalid input: expected number, received undefined", + }, + ], + }, + "f3": { + "_errors": [ + { + "code": 1234, + "message": "Invalid input: expected string, received undefined", + }, + ], + }, + "f4": { + "_errors": [ + { + "code": 1234, + "message": "Invalid input: expected array, received undefined", + }, + ], + }, + } + `); +}); + +test("all errors", () => { + const propertySchema = z.string(); + const schema = z + .object({ + a: propertySchema, + b: propertySchema, + }) + .refine( + (val) => { + return val.a === val.b; + }, + { message: "Must be equal" } + ); + + const r1 = schema.safeParse({ + a: "asdf", + b: "qwer", + }); + + expect(z.core.flattenError(r1.error!)).toEqual({ + formErrors: ["Must be equal"], + fieldErrors: {}, + }); + + const r2 = schema.safeParse({ + a: null, + b: null, + }); + + // const error = _error as z.ZodError; + expect(z.core.flattenError(r2.error!)).toMatchInlineSnapshot(` + { + "fieldErrors": { + "a": [ + "Invalid input: expected string, received null", + ], + "b": [ + "Invalid input: expected string, received null", + ], + }, + "formErrors": [], + } + `); + + expect(z.core.flattenError(r2.error!, (iss) => iss.message.toUpperCase())).toMatchInlineSnapshot(` + { + "fieldErrors": { + "a": [ + "INVALID INPUT: EXPECTED STRING, RECEIVED NULL", + ], + "b": [ + "INVALID INPUT: EXPECTED STRING, RECEIVED NULL", + ], + }, + "formErrors": [], + } + `); + // Test identity + + expect(z.core.flattenError(r2.error!, (i: z.ZodIssue) => i)).toMatchInlineSnapshot(` + { + "fieldErrors": { + "a": [ + { + "code": "invalid_type", + "expected": "string", + "message": "Invalid input: expected string, received null", + "path": [ + "a", + ], + }, + ], + "b": [ + { + "code": "invalid_type", + "expected": "string", + "message": "Invalid input: expected string, received null", + "path": [ + "b", + ], + }, + ], + }, + "formErrors": [], + } + `); + + // Test mapping + const f1 = z.core.flattenError(r2.error!, (i: z.ZodIssue) => i.message.length); + expect(f1).toMatchInlineSnapshot(` + { + "fieldErrors": { + "a": [ + 45, + ], + "b": [ + 45, + ], + }, + "formErrors": [], + } + `); + // expect(f1.fieldErrors.a![0]).toEqual("Invalid input: expected string".length); + // expect(f1).toMatchObject({ + // formErrors: [], + // fieldErrors: { + // a: ["Invalid input: expected string".length], + // b: ["Invalid input: expected string".length], + // }, + // }); +}); + +const schema = z.strictObject({ + username: z.string(), + favoriteNumbers: z.array(z.number()), + nesting: z.object({ + a: z.string(), + }), +}); +const result = schema.safeParse({ + username: 1234, + favoriteNumbers: [1234, "4567"], + nesting: { + a: 123, + }, + extra: 1234, +}); + +test("z.treeifyError", () => { + expect(z.treeifyError(result.error!)).toMatchInlineSnapshot(` + { + "errors": [ + "Unrecognized key: "extra"", + ], + "properties": { + "favoriteNumbers": { + "errors": [], + "items": [ + , + { + "errors": [ + "Invalid input: expected number, received string", + ], + }, + ], + }, + "nesting": { + "errors": [], + "properties": { + "a": { + "errors": [ + "Invalid input: expected string, received number", + ], + }, + }, + }, + "username": { + "errors": [ + "Invalid input: expected string, received number", + ], + }, + }, + } + `); +}); + +test("z.treeifyError 2", () => { + const schema = z.strictObject({ + name: z.string(), + logLevel: z.union([z.string(), z.number()]), + env: z.literal(["production", "development"]), + }); + + const data = { + name: 1000, + logLevel: false, + extra: 1000, + }; + + const result = schema.safeParse(data); + const err = z.treeifyError(result.error!); + expect(err).toMatchInlineSnapshot(` + { + "errors": [ + "Unrecognized key: "extra"", + ], + "properties": { + "env": { + "errors": [ + "Invalid option: expected one of "production"|"development"", + ], + }, + "logLevel": { + "errors": [ + "Invalid input: expected string, received boolean", + "Invalid input: expected number, received boolean", + ], + }, + "name": { + "errors": [ + "Invalid input: expected string, received number", + ], + }, + }, + } + `); +}); + +test("z.prettifyError", () => { + expect(z.prettifyError(result.error!)).toMatchInlineSnapshot(` + "✖ Unrecognized key: "extra" + ✖ Invalid input: expected string, received number + → at username + ✖ Invalid input: expected number, received string + → at favoriteNumbers[1] + ✖ Invalid input: expected string, received number + → at nesting.a" + `); +}); + +test("z.toDotPath", () => { + expect(z.core.toDotPath(["a", "b", 0, "c"])).toMatchInlineSnapshot(`"a.b[0].c"`); + + expect(z.core.toDotPath(["a", Symbol("b"), 0, "c"])).toMatchInlineSnapshot(`"a["Symbol(b)"][0].c"`); + + // Test with periods in keys + expect(z.core.toDotPath(["user.name", "first.last"])).toMatchInlineSnapshot(`"["user.name"]["first.last"]"`); + + // Test with special characters + expect(z.core.toDotPath(["user", "$special", Symbol("#symbol")])).toMatchInlineSnapshot( + `"user.$special["Symbol(#symbol)"]"` + ); + + // Test with dots and quotes + expect(z.core.toDotPath(["search", `query("foo.bar"="abc")`])).toMatchInlineSnapshot( + `"search["query(\\"foo.bar\\"=\\"abc\\")"]"` + ); + + // Test with newlines + expect(z.core.toDotPath(["search", `foo\nbar`])).toMatchInlineSnapshot(`"search["foo\\nbar"]"`); + + // Test with empty strings + expect(z.core.toDotPath(["", "empty"])).toMatchInlineSnapshot(`".empty"`); + + // Test with array indices + expect(z.core.toDotPath(["items", 0, 1, 2])).toMatchInlineSnapshot(`"items[0][1][2]"`); + + // Test with mixed path elements + expect(z.core.toDotPath(["users", "user.config", 0, "settings.theme"])).toMatchInlineSnapshot( + `"users["user.config"][0]["settings.theme"]"` + ); + + // Test with square brackets in keys + expect(z.core.toDotPath(["data[0]", "value"])).toMatchInlineSnapshot(`"["data[0]"].value"`); + + // Test with empty path + expect(z.core.toDotPath([])).toMatchInlineSnapshot(`""`); +}); + +test("inheritance", () => { + const e1 = new z.ZodError([]); + expect(e1).toBeInstanceOf(z.core.$ZodError); + expect(e1).toBeInstanceOf(z.ZodError); + // expect(e1).not.toBeInstanceOf(Error); + + const e2 = new z.ZodRealError([]); + expect(e2).toBeInstanceOf(z.ZodError); + expect(e2).toBeInstanceOf(z.ZodRealError); + expect(e2).toBeInstanceOf(Error); +}); + +test("disc union treeify/format", () => { + const schema = z.discriminatedUnion( + "foo", + [ + z.object({ + foo: z.literal("x"), + x: z.string(), + }), + z.object({ + foo: z.literal("y"), + y: z.string(), + }), + ], + { + error: "Invalid discriminator", + } + ); + + const error = schema.safeParse({ foo: "invalid" }).error; + expect(z.treeifyError(error!)).toMatchInlineSnapshot(` + { + "errors": [], + "properties": { + "foo": { + "errors": [ + "Invalid discriminator", + ], + }, + }, + } + `); + expect(z.prettifyError(error!)).toMatchInlineSnapshot(` + "✖ Invalid discriminator + → at foo" + `); + expect(z.formatError(error!)).toMatchInlineSnapshot(` + { + "_errors": [], + "foo": { + "_errors": [ + "Invalid discriminator", + ], + }, + } + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/error.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/error.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d884b7e46b4ee3f03a5920a11f412d9c8d8a3a3b --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/error.test.ts @@ -0,0 +1,711 @@ +import { inspect } from "node:util"; +import { expect, test } from "vitest"; +import * as z from "zod/v4"; + +test("error creation", () => { + const err1 = new z.ZodError([]); + + err1.issues.push({ + code: "invalid_type", + expected: "object", + path: [], + message: "", + input: "adf", + }); + err1.isEmpty; + + const err2 = new z.ZodError(err1.issues); + const err3 = new z.ZodError([]); + err3.addIssues(err1.issues); + err3.addIssue(err1.issues[0]); + err1.message; + err2.message; + err3.message; +}); + +test("do not allow error and message together", () => { + expect(() => + z.string().refine((_) => true, { + message: "override", + error: (iss) => (iss.input === undefined ? "asdf" : null), + }) + ).toThrow(); +}); + +const errorMap: z.ZodErrorMap = (issue) => { + if (issue.code === "invalid_type") { + if (issue.expected === "string") { + return { message: "bad type!" }; + } + } + if (issue.code === "custom") { + return { message: `less-than-${issue.params?.minimum}` }; + } + return undefined; +}; + +test("type error with custom error map", () => { + const result = z.string().safeParse(234, { error: errorMap }); + expect(result.success).toBe(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [], + "message": "bad type!" + } + ]] + `); +}); + +test("refinement fail with params", () => { + const result = z + .number() + .refine((val) => val >= 3, { + params: { minimum: 3 }, + }) + .safeParse(2, { error: errorMap }); + expect(result.success).toBe(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "params": { + "minimum": 3 + }, + "message": "less-than-3" + } + ]] + `); +}); + +test("hard coded error with custom errormap", () => { + const result = z + .string() + .refine((val) => val.length > 12, { + params: { minimum: 13 }, + message: "override", + }) + .safeParse("asdf", { error: () => "contextual" }); + + expect(result.success).toBe(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "params": { + "minimum": 13 + }, + "message": "override" + } + ]] + `); +}); + +test("default error message", () => { + const result = z + .number() + .refine((x) => x > 3) + .safeParse(2); + + expect(result.success).toBe(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "message": "Invalid input" + } + ]] + `); +}); + +test("override error in refine", () => { + const result = z + .number() + .refine((x) => x > 3, "override") + .safeParse(2); + expect(result.success).toBe(false); + expect(result.error!.issues.length).toEqual(1); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "message": "override" + } + ]] + `); +}); + +test("override error in refinement", () => { + const result = z + .number() + .refine((x) => x > 3, { + message: "override", + }) + .safeParse(2); + expect(result.success).toBe(false); + expect(result.error!.issues.length).toEqual(1); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "message": "override" + } + ]] + `); +}); + +test("array minimum", () => { + let result = z.array(z.string()).min(3, "tooshort").safeParse(["asdf", "qwer"]); + expect(result.success).toBe(false); + expect(result.error!.issues[0].code).toEqual("too_small"); + expect(result.error!.issues[0].message).toEqual("tooshort"); + + result = z.array(z.string()).min(3).safeParse(["asdf", "qwer"]); + expect(result.success).toBe(false); + expect(result.error!.issues[0].code).toEqual("too_small"); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "array", + "code": "too_small", + "minimum": 3, + "inclusive": true, + "path": [], + "message": "Too small: expected array to have >=3 items" + } + ]] + `); +}); + +test("literal bigint default error message", () => { + const result = z.literal(BigInt(12)).safeParse(BigInt(13)); + expect(result.success).toBe(false); + expect(result.error!.issues.length).toEqual(1); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "invalid_value", + "values": [ + "12" + ], + "path": [], + "message": "Invalid input: expected 12n" + } + ]] + `); +}); + +test("custom path in custom error map", () => { + const schema = z.object({ + items: z.array(z.string()).refine((data) => data.length > 3, { + path: ["items-too-few"], + }), + }); + + const errorMap: z.ZodErrorMap = (issue) => { + expect((issue.path ?? []).length).toBe(2); + return { message: "doesnt matter" }; + }; + const result = schema.safeParse({ items: ["first"] }, { error: errorMap }); + expect(result.success).toBe(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [ + "items", + "items-too-few" + ], + "message": "doesnt matter" + } + ]] + `); +}); + +// test("error metadata from value", () => { +// const dynamicRefine = z.string().refine( +// (val) => val === val.toUpperCase(), +// (val) => ({ params: { val } }) +// ); + +// const result = dynamicRefine.safeParse("asdf"); +// expect(result.success).toEqual(false); +// if (!result.success) { +// const sub = result.error.issues[0]; +// expect(result.error.issues[0].code).toEqual("custom"); +// if (sub.code === "custom") { +// expect(sub.params?.val).toEqual("asdf"); +// } +// } +// }); + +// test("don't call refine after validation failed", () => { +// const asdf = z +// .union([ +// z.number(), +// z.string().transform(z.number(), (val) => { +// return parseFloat(val); +// }), +// ]) +// .refine((v) => v >= 1); + +// expect(() => asdf.safeParse("foo")).not.toThrow(); +// }); + +test("root level formatting", () => { + const schema = z.string().email(); + const result = schema.safeParse("asdfsdf"); + expect(result.success).toBe(false); + + expect(result.error!.format()).toMatchInlineSnapshot(` + { + "_errors": [ + "Invalid email address", + ], + } + `); +}); + +test("custom path", () => { + const schema = z + .object({ + password: z.string(), + confirm: z.string(), + }) + .refine((val) => val.confirm === val.password, { path: ["confirm"] }); + + const result = schema.safeParse({ + password: "peanuts", + confirm: "qeanuts", + }); + + expect(result.success).toBe(false); + const error = result.error!.format(); + expect(error._errors).toEqual([]); + expect(error.password?._errors).toEqual(undefined); + expect(error.confirm?._errors).toEqual(["Invalid input"]); +}); + +test("custom path", () => { + const schema = z + .object({ + password: z.string().min(6), + confirm: z.string().min(6), + }) + .refine((val) => val.confirm === val.password); + + const result = schema.safeParse({ + password: "qwer", + confirm: "asdf", + }); + + expect(result.success).toBe(false); + expect(result.error!.issues.length).toEqual(3); +}); + +const schema = z.object({ + inner: z.object({ + name: z + .string() + .refine((val) => val.length > 5) + .array() + .refine((val) => val.length <= 1), + }), +}); + +test("no abort early on refinements", () => { + const invalidItem = { + inner: { name: ["aasd", "asdfasdfasfd"] }, + }; + + const result1 = schema.safeParse(invalidItem); + expect(result1.success).toBe(false); + expect(result1.error!.issues.length).toEqual(2); +}); + +test("detect issue with input fallback", () => { + const schema = z + .string() + .transform((val) => val.length) + .refine(() => false, { message: "always fails" }) + .refine( + (val) => { + if (typeof val !== "number") throw new Error(); + return (val ^ 2) > 10; + } // should be number but it's a string + ); + expect(() => schema.parse("hello")).toThrow(z.ZodError); +}); + +test("formatting", () => { + const invalidItem = { + inner: { name: ["aasd", "asdfasdfasfd"] }, + }; + const invalidArray = { + inner: { name: ["asdfasdf", "asdfasdfasfd"] }, + }; + const result1 = schema.safeParse(invalidItem); + const result2 = schema.safeParse(invalidArray); + + expect(result1.success).toBe(false); + expect(result2.success).toBe(false); + const error1 = result1.error!.format(); + expect(error1._errors).toEqual([]); + expect(error1.inner?._errors).toEqual([]); + expect(error1.inner?.name?.[1]).toEqual(undefined); + + type FormattedError = z.inferFormattedError; + const error2: FormattedError = result2.error!.format(); + expect(error2._errors).toEqual([]); + expect(error2.inner?._errors).toEqual([]); + expect(error2.inner?.name?._errors).toEqual(["Invalid input"]); + expect(error2.inner?.name?.[0]).toEqual(undefined); + expect(error2.inner?.name?.[1]).toEqual(undefined); + expect(error2.inner?.name?.[2]).toEqual(undefined); + + // test custom mapper + type FormattedErrorWithNumber = z.inferFormattedError; + const errorWithNumber: FormattedErrorWithNumber = result2.error!.format(() => 5); + expect(errorWithNumber._errors).toEqual([]); + expect(errorWithNumber.inner?._errors).toEqual([]); + expect(errorWithNumber.inner?.name?._errors).toEqual([5]); +}); + +test("formatting with nullable and optional fields", () => { + const nameSchema = z.string().refine((val) => val.length > 5); + const schema = z.object({ + nullableObject: z.object({ name: nameSchema }).nullable(), + nullableArray: z.array(nameSchema).nullable(), + nullableTuple: z.tuple([nameSchema, nameSchema, z.number()]).nullable(), + optionalObject: z.object({ name: nameSchema }).optional(), + optionalArray: z.array(nameSchema).optional(), + optionalTuple: z.tuple([nameSchema, nameSchema, z.number()]).optional(), + }); + const invalidItem = { + nullableObject: { name: "abcd" }, + nullableArray: ["abcd"], + nullableTuple: ["abcd", "abcd", 1], + optionalObject: { name: "abcd" }, + optionalArray: ["abcd"], + optionalTuple: ["abcd", "abcd", 1], + }; + const result = schema.safeParse(invalidItem); + expect(result.success).toBe(false); + const error: z.inferFormattedError = result.error!.format(); + expect(error._errors).toEqual([]); + expect(error.nullableObject?._errors).toEqual([]); + expect(error.nullableObject?.name?._errors).toEqual(["Invalid input"]); + expect(error.nullableArray?._errors).toEqual([]); + expect(error.nullableArray?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.nullableTuple?._errors).toEqual([]); + expect(error.nullableTuple?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.nullableTuple?.[1]?._errors).toEqual(["Invalid input"]); + expect(error.optionalObject?._errors).toEqual([]); + expect(error.optionalObject?.name?._errors).toEqual(["Invalid input"]); + expect(error.optionalArray?._errors).toEqual([]); + expect(error.optionalArray?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.optionalTuple?._errors).toEqual([]); + expect(error.optionalTuple?.[0]?._errors).toEqual(["Invalid input"]); + expect(error.optionalTuple?.[1]?._errors).toEqual(["Invalid input"]); + + expect(error).toMatchInlineSnapshot(` + { + "_errors": [], + "nullableArray": { + "0": { + "_errors": [ + "Invalid input", + ], + }, + "_errors": [], + }, + "nullableObject": { + "_errors": [], + "name": { + "_errors": [ + "Invalid input", + ], + }, + }, + "nullableTuple": { + "0": { + "_errors": [ + "Invalid input", + ], + }, + "1": { + "_errors": [ + "Invalid input", + ], + }, + "_errors": [], + }, + "optionalArray": { + "0": { + "_errors": [ + "Invalid input", + ], + }, + "_errors": [], + }, + "optionalObject": { + "_errors": [], + "name": { + "_errors": [ + "Invalid input", + ], + }, + }, + "optionalTuple": { + "0": { + "_errors": [ + "Invalid input", + ], + }, + "1": { + "_errors": [ + "Invalid input", + ], + }, + "_errors": [], + }, + } + `); +}); + +test("inferFlattenedErrors", () => { + const schemaWithTransform = z.object({ foo: z.string() }).transform((o) => ({ bar: o.foo })); + + const result = schemaWithTransform.safeParse({}); + + expect(result.success).toBe(false); + type ValidationErrors = z.inferFlattenedErrors; + const error: ValidationErrors = result.error!.flatten(); + expect(error).toMatchInlineSnapshot(` + { + "fieldErrors": { + "foo": [ + "Invalid input: expected string, received undefined", + ], + }, + "formErrors": [], + } + `); +}); + +const stringWithCustomError = z.string({ + error: () => "bound", +}); + +test("schema-bound error map", () => { + const result = stringWithCustomError.safeParse(1234); + expect(result.success).toBe(false); + expect(result.error!.issues[0].message).toEqual("bound"); +}); + +test("bound error map overrides contextual", () => { + // support contextual override + const result = stringWithCustomError.safeParse(undefined, { + error: () => ({ message: "override" }), + }); + expect(result.success).toBe(false); + expect(result.error!.issues[0].message).toEqual("bound"); +}); + +test("z.config customError ", () => { + // support overrideErrorMap + + z.config({ customError: () => ({ message: "override" }) }); + const result = stringWithCustomError.min(10).safeParse("tooshort"); + expect(result.success).toBe(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "string", + "code": "too_small", + "minimum": 10, + "inclusive": true, + "path": [], + "message": "override" + } + ]] + `); + expect(result.error!.issues[0].message).toEqual("override"); + z.config({ customError: undefined }); +}); + +// test("invalid and required", () => { +// const str = z.string({ +// invalid_type_error: "Invalid name", +// required_error: "Name is required", +// }); +// const result1 = str.safeParse(1234); +// expect(result1.success).toBe(false); +// if (!result1.success) { +// expect(result1.error.issues[0].message).toEqual("Invalid name"); +// } +// const result2 = str.safeParse(undefined); +// expect(result2.success).toBe(false); +// if (!result2.success) { +// expect(result2.error.issues[0].message).toEqual("Name is required"); +// } +// }); + +// test("Fallback to default required error", () => { +// const str = z.string({ +// invalid_type_error: "Invalid name", +// // required_error: "Name is required", +// }); + +// const result2 = str.safeParse(undefined); +// expect(result2.success).toBe(false); +// if (!result2.success) { +// expect(result2.error.issues[0].message).toEqual("Required"); +// } +// }); + +// test("invalid and required and errorMap", () => { +// expect(() => { +// return z.string({ +// invalid_type_error: "Invalid name", +// required_error: "Name is required", +// errorMap: () => ({ message: "override" }), +// }); +// }).toThrow(); +// }); + +// test("strict error message", () => { +// const errorMsg = "Invalid object"; +// const obj = z.object({ x: z.string() }).strict(errorMsg); +// const result = obj.safeParse({ x: "a", y: "b" }); +// expect(result.success).toBe(false); +// if (!result.success) { +// expect(result.error.issues[0].message).toEqual(errorMsg); +// } +// }); + +test("empty string error message", () => { + const schema = z.string().max(1, { message: "" }); + const result = schema.safeParse("asdf"); + expect(result.success).toBe(false); + expect(result.error!.issues[0].message).toEqual(""); +}); + +test("dont short circuit on continuable errors", () => { + const user = z + .object({ + password: z.string().min(6), + confirm: z.string(), + }) + .refine((data) => data.password === data.confirm, { + message: "Passwords don't match", + path: ["confirm"], + }); + const result = user.safeParse({ password: "asdf", confirm: "qwer" }); + expect(result.success).toBe(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "string", + "code": "too_small", + "minimum": 6, + "inclusive": true, + "path": [ + "password" + ], + "message": "Too small: expected string to have >=6 characters" + }, + { + "code": "custom", + "path": [ + "confirm" + ], + "message": "Passwords don't match" + } + ]] + `); + // expect(result.error!.issues.length).toEqual(2); +}); + +test("string error params", () => { + const a = z.string("Bad!"); + expect(a.safeParse(123).error!.issues[0].message).toBe("Bad!"); + + const b = z.string().min(5, "Too short!"); + expect(b.safeParse("abc").error!.issues[0].message).toBe("Too short!"); + + const c = z.uuid("Bad UUID!"); + expect(c.safeParse("not-a-uuid").error!.issues[0].message).toBe("Bad UUID!"); + + const d = z.string().datetime({ message: "Bad date!" }); + expect(d.safeParse("not-a-date").error!.issues[0].message).toBe("Bad date!"); + + const e = z.array(z.string(), "Bad array!"); + expect(e.safeParse("not-an-array").error!.issues[0].message).toBe("Bad array!"); + + const f = z.array(z.string()).min(5, "Too few items!"); + expect(f.safeParse(["a", "b"]).error!.issues[0].message).toBe("Too few items!"); + + const g = z.set(z.string(), "Bad set!"); + expect(g.safeParse("not-a-set").error!.issues[0].message).toBe("Bad set!"); + + const h = z.array(z.string(), "Bad array!"); + expect(h.safeParse(123).error!.issues[0].message).toBe("Bad array!"); + + const i = z.set(z.string(), "Bad set!"); + expect(i.safeParse(123).error!.issues[0].message).toBe("Bad set!"); + + const j = z.array(z.string(), "Bad array!"); + expect(j.safeParse(null).error!.issues[0].message).toBe("Bad array!"); +}); + +test("error inheritance", () => { + const e1 = z.string().safeParse(123).error!; + expect(e1).toBeInstanceOf(z.core.$ZodError); + expect(e1).toBeInstanceOf(z.ZodError); + expect(e1).toBeInstanceOf(z.ZodRealError); + // expect(e1).not.toBeInstanceOf(Error); + + try { + z.string().parse(123); + } catch (e2) { + expect(e1).toBeInstanceOf(z.core.$ZodError); + expect(e2).toBeInstanceOf(z.ZodError); + expect(e2).toBeInstanceOf(z.ZodRealError); + // expect(e2).toBeInstanceOf(Error); + } +}); + +test("error serialization", () => { + try { + z.string().parse(123); + } catch (e) { + expect(e).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected string, received number" + } + ]] + `); + expect(inspect(e).split("\n").slice(0, 8).join("\n")).toMatchInlineSnapshot(` + "ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected string, received number" + } + ]" + `); + } +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/file.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/file.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1388c7ef842bfeb1dc9bb07709582b2faca1fc79 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/file.test.ts @@ -0,0 +1,91 @@ +// @ts-ignore +import { File as WebFile } from "@web-std/file"; + +import { afterEach, beforeEach, expect, test } from "vitest"; + +import * as z from "zod/v4"; + +const minCheck = z.file().min(5); +const maxCheck = z.file().max(8); +const mimeCheck = z.file().mime(["text/plain", "application/json"]); + +const originalFile = global.File; +beforeEach(async () => { + if (!globalThis.File) globalThis.File = WebFile; +}); +afterEach(() => { + if (globalThis.File !== originalFile) { + globalThis.File = originalFile; + } +}); + +test("passing validations", () => { + minCheck.safeParse(new File(["12345"], "test.txt")); + maxCheck.safeParse(new File(["12345678"], "test.txt")); + mimeCheck.safeParse(new File([""], "test.csv", { type: "text/plain" })); + expect(() => mimeCheck.parse(new File([""], "test.txt"))).toThrow(); + expect(() => mimeCheck.parse(new File([""], "test.txt", { type: "text/csv" }))).toThrow(); +}); + +test("failing validations", () => { + expect(minCheck.safeParse(new File(["1234"], "test.txt"))).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "origin": "file", + "code": "too_small", + "minimum": 5, + "path": [], + "message": "Too small: expected file to have >5 bytes" + } + ]], + "success": false, + } + `); + expect(maxCheck.safeParse(new File(["123456789"], "test.txt"))).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "origin": "file", + "code": "too_big", + "maximum": 8, + "path": [], + "message": "Too big: expected file to have <8 bytes" + } + ]], + "success": false, + } + `); + expect(mimeCheck.safeParse(new File([""], "test.csv"))).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_value", + "values": [ + "text/plain", + "application/json" + ], + "path": [], + "message": "Invalid option: expected one of \\"text/plain\\"|\\"application/json\\"" + } + ]], + "success": false, + } + `); + expect(mimeCheck.safeParse(new File([""], "test.csv", { type: "text/csv" }))).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_value", + "values": [ + "text/plain", + "application/json" + ], + "path": [], + "message": "Invalid option: expected one of \\"text/plain\\"|\\"application/json\\"" + } + ]], + "success": false, + } + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/firstparty.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/firstparty.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..de394fe0f3a639b93e3a5c892e6ba0424b832424 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/firstparty.test.ts @@ -0,0 +1,175 @@ +import { expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; +import type * as core from "zod/v4/core"; + +test("first party switch", () => { + const myType = z.string() as core.$ZodTypes; + const def = myType._zod.def; + switch (def.type) { + case "string": + break; + case "number": + break; + case "bigint": + break; + case "boolean": + break; + case "date": + break; + case "symbol": + break; + case "undefined": + break; + case "null": + break; + case "any": + break; + case "unknown": + break; + case "never": + break; + case "void": + break; + case "array": + break; + case "object": + break; + case "union": + break; + case "intersection": + break; + case "tuple": + break; + case "record": + break; + case "map": + break; + case "set": + break; + case "literal": + break; + case "enum": + break; + case "promise": + break; + case "optional": + break; + case "nonoptional": + break; + case "nullable": + break; + case "default": + break; + case "prefault": + break; + case "template_literal": + break; + case "custom": + break; + case "transform": + break; + case "readonly": + break; + case "nan": + break; + case "pipe": + break; + case "success": + break; + case "catch": + break; + case "file": + break; + case "lazy": + break; + default: + expectTypeOf(def).toEqualTypeOf(); + } +}); + +test("$ZodSchemaTypes", () => { + const type = "string" as core.$ZodTypeDef["type"]; + switch (type) { + case "string": + break; + case "number": + break; + case "int": + break; + case "bigint": + break; + case "boolean": + break; + case "date": + break; + case "symbol": + break; + case "undefined": + break; + case "null": + break; + case "any": + break; + case "unknown": + break; + case "never": + break; + case "void": + break; + case "array": + break; + case "object": + break; + case "union": + break; + case "intersection": + break; + case "tuple": + break; + case "record": + break; + case "map": + break; + case "set": + break; + case "literal": + break; + case "enum": + break; + case "promise": + break; + case "optional": + break; + case "nonoptional": + break; + case "nullable": + break; + case "default": + break; + case "prefault": + break; + case "template_literal": + break; + case "custom": + break; + case "transform": + break; + case "readonly": + break; + case "nan": + break; + case "pipe": + break; + case "success": + break; + case "catch": + break; + case "file": + break; + case "lazy": + break; + + default: + expectTypeOf(type).toEqualTypeOf(); + } +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/function.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/function.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..85ccc95abd2c8ce8130b7268a91b3451db991e0d --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/function.test.ts @@ -0,0 +1,268 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +const args1 = z.tuple([z.string()]); +const returns1 = z.number(); +const func1 = z.function({ + input: args1, + + output: returns1, +}); + +test("function parsing", () => { + const parsed = func1.implement((arg: any) => arg.length); + const result = parsed("asdf"); + expect(result).toBe(4); +}); + +test("parsed function fail 1", () => { + // @ts-expect-error + const parsed = func1.implement((x: string) => x); + expect(() => parsed("asdf")).toThrow(); +}); + +test("parsed function fail 2", () => { + // @ts-expect-error + const parsed = func1.implement((x: string) => x); + expect(() => parsed(13 as any)).toThrow(); +}); + +test("function inference 1", () => { + type func1 = (typeof func1)["_input"]; + expectTypeOf().toEqualTypeOf<(k: string) => number>(); +}); + +// test("method parsing", () => { +// const methodObject = z.object({ +// property: z.number(), +// method: z +// .function() +// .input(z.tuple([z.string()])) +// .output(z.number()), +// }); +// const methodInstance = { +// property: 3, +// method: function (s: string) { +// return s.length + this.property; +// }, +// }; +// const parsed = methodObject.parse(methodInstance); +// expect(parsed.method("length=8")).toBe(11); // 8 length + 3 property +// }); + +// test("async method parsing", async () => { +// const methodObject = z.object({ +// property: z.number(), +// method: z.function().input(z.string()).output(z.promise(z.number())), +// }); +// const methodInstance = { +// property: 3, +// method: async function (s: string) { +// return s.length + this.property; +// }, +// }; +// const parsed = methodObject.parse(methodInstance); +// expect(await parsed.method("length=8")).toBe(11); // 8 length + 3 property +// }); + +test("args method", () => { + const t1 = z.function(); + type t1 = (typeof t1)["_input"]; + expectTypeOf().toEqualTypeOf<(...args_1: never[]) => unknown>(); + t1._input; + + const t2args = z.tuple([z.string()], z.unknown()); + + const t2 = t1.input(t2args); + type t2 = (typeof t2)["_input"]; + expectTypeOf().toEqualTypeOf<(arg: string, ...args_1: unknown[]) => unknown>(); + + const t3 = t2.output(z.boolean()); + type t3 = (typeof t3)["_input"]; + expectTypeOf().toEqualTypeOf<(arg: string, ...args_1: unknown[]) => boolean>(); +}); + +// test("custom args", () => { +// const fn = z.function().implement((_a: string, _b: number) => { +// return new Date(); +// }); + +// expectTypeOf(fn).toEqualTypeOf<(a: string, b: number) => Date>(); +// }); + +const args2 = z.tuple([ + z.object({ + f1: z.number(), + f2: z.string().nullable(), + f3: z.array(z.boolean().optional()).optional(), + }), +]); +const returns2 = z.union([z.string(), z.number()]); + +const func2 = z.function({ + input: args2, + output: returns2, +}); + +test("function inference 2", () => { + type func2 = (typeof func2)["_input"]; + + expectTypeOf().toEqualTypeOf< + (arg: { + f3?: (boolean | undefined)[] | undefined; + f1: number; + f2: string | null; + }) => string | number + >(); +}); + +test("valid function run", () => { + const validFunc2Instance = func2.implement((_x) => { + _x.f2; + _x.f3![0]; + return "adf" as any; + }); + + validFunc2Instance({ + f1: 21, + f2: "asdf", + f3: [true, false], + }); +}); + +test("input validation error", () => { + const schema = z.function({ + input: z.tuple([z.string()]), + output: z.void(), + }); + const fn = schema.implement(() => 1234 as any); + + // @ts-expect-error + const checker = () => fn(); + + try { + checker(); + } catch (e: any) { + expect(e.issues).toMatchInlineSnapshot(` + [ + { + "code": "invalid_type", + "expected": "string", + "message": "Invalid input: expected string, received undefined", + "path": [ + 0, + ], + }, + ] + `); + } +}); + +test("array inputs", () => { + const a = z.function({ + input: [ + z.object({ + name: z.string(), + age: z.number().int(), + }), + ], + output: z.string(), + }); + + a.implement((args) => { + return `${args.age}`; + }); + + const b = z.function({ + input: [ + z.object({ + name: z.string(), + age: z.number().int(), + }), + ], + }); + b.implement((args) => { + return `${args.age}`; + }); +}); + +test("output validation error", () => { + const schema = z.function({ + input: z.tuple([]), + output: z.string(), + }); + const fn = schema.implement(() => 1234 as any); + try { + fn(); + } catch (e: any) { + expect(e.issues).toMatchInlineSnapshot(` + [ + { + "code": "invalid_type", + "expected": "string", + "message": "Invalid input: expected string, received number", + "path": [], + }, + ] + `); + } +}); + +test("function with async refinements", async () => { + const schema = z + .function() + .input([z.string().refine(async (val) => val.length > 10)]) + .output(z.promise(z.number().refine(async (val) => val > 10))); + + const func = schema.implementAsync(async (val) => { + return val.length; + }); + const results = []; + try { + await func("asdfasdf"); + results.push("success"); + } catch (_) { + results.push("fail"); + } + try { + await func("asdflkjasdflkjsf"); + results.push("success"); + } catch (_) { + results.push("fail"); + } + + expect(results).toEqual(["fail", "success"]); +}); + +test("non async function with async refinements should fail", async () => { + const func = z + .function() + .input([z.string().refine(async (val) => val.length > 10)]) + .output(z.number().refine(async (val) => val > 10)) + .implement((val) => { + return val.length; + }); + + const results = []; + try { + await func("asdasdfasdffasdf"); + results.push("success"); + } catch (_) { + results.push("fail"); + } + + expect(results).toEqual(["fail"]); +}); + +test("extra parameters with rest", () => { + const maxLength5 = z + .function() + .input([z.string()], z.unknown()) + .output(z.boolean()) + .implement((str, _arg, _qewr) => { + return str.length <= 5; + }); + + const filteredList = ["apple", "orange", "pear", "banana", "strawberry"].filter(maxLength5); + expect(filteredList.length).toEqual(2); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/generics.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/generics.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1ec9d67f4f2229486e445df645cc93a0ae7ee6d6 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/generics.test.ts @@ -0,0 +1,72 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +function nest(schema: TData) { + return z.object({ + nested: schema, + }); +} + +test("generics", () => { + const a = nest(z.object({ a: z.string() })); + type a = z.infer; + expectTypeOf().toEqualTypeOf<{ nested: { a: string } }>(); + + const b = nest(z.object({ a: z.string().optional() })); + type b = z.infer; + expectTypeOf().toEqualTypeOf<{ nested: { a?: string | undefined } }>(); +}); + +test("generics with optional", () => { + async function stripOuter(schema: TData, data: unknown) { + return z + .object({ + nested: schema.optional(), + }) + .transform((data) => { + return data.nested; + }) + .parse({ nested: data }); + } + + const result = stripOuter(z.object({ a: z.string() }), { a: "asdf" }); + expectTypeOf().toEqualTypeOf>(); +}); + +// test("assignability", () => { +// const createSchemaAndParse = (key: K, valueSchema: VS, data: unknown) => { +// const schema = z.object({ +// [key]: valueSchema, +// }); +// // return { [key]: valueSchema }; +// const parsed = schema.parse(data); +// return parsed; +// // const inferred: z.infer> = parsed; +// // return inferred; +// }; +// const parsed = createSchemaAndParse("foo", z.string(), { foo: "" }); +// expectTypeOf().toEqualTypeOf<{ foo: string }>(); +// }); + +test("nested no undefined", () => { + const inner = z.string().or(z.array(z.string())); + const outer = z.object({ inner }); + type outerSchema = z.infer; + expectTypeOf().toEqualTypeOf<{ inner: string | string[] }>(); + + expect(outer.safeParse({ inner: undefined }).success).toEqual(false); +}); + +test("generic on output type", () => { + const createV4Schema = (opts: { + schema: z.ZodType; + }) => { + return opts.schema; + }; + + createV4Schema({ + schema: z.object({ + name: z.string(), + }), + })?._zod?.output?.name; +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/index.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/index.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7fa6f20fc8f10bf632444c83b6fc279a7bab4c81 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/index.test.ts @@ -0,0 +1,829 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; +import type { util } from "zod/v4/core"; + +test("z.boolean", () => { + const a = z.boolean(); + expect(z.parse(a, true)).toEqual(true); + expect(z.parse(a, false)).toEqual(false); + expect(() => z.parse(a, 123)).toThrow(); + expect(() => z.parse(a, "true")).toThrow(); + type a = z.output; + expectTypeOf().toEqualTypeOf(); +}); + +test("z.bigint", () => { + const a = z.bigint(); + expect(z.parse(a, BigInt(123))).toEqual(BigInt(123)); + expect(() => z.parse(a, 123)).toThrow(); + expect(() => z.parse(a, "123")).toThrow(); +}); + +test("z.symbol", () => { + const a = z.symbol(); + const sym = Symbol(); + expect(z.parse(a, sym)).toEqual(sym); + expect(() => z.parse(a, "symbol")).toThrow(); +}); + +test("z.date", () => { + const a = z.date(); + const date = new Date(); + expect(z.parse(a, date)).toEqual(date); + expect(() => z.parse(a, "date")).toThrow(); +}); + +test("z.coerce.string", () => { + const a = z.coerce.string(); + expect(z.parse(a, 123)).toEqual("123"); + expect(z.parse(a, true)).toEqual("true"); + expect(z.parse(a, null)).toEqual("null"); + expect(z.parse(a, undefined)).toEqual("undefined"); +}); + +test("z.coerce.number", () => { + const a = z.coerce.number(); + expect(z.parse(a, "123")).toEqual(123); + expect(z.parse(a, "123.45")).toEqual(123.45); + expect(z.parse(a, true)).toEqual(1); + expect(z.parse(a, false)).toEqual(0); + expect(() => z.parse(a, "abc")).toThrow(); +}); + +test("z.coerce.boolean", () => { + const a = z.coerce.boolean(); + // test booleans + expect(z.parse(a, true)).toEqual(true); + expect(z.parse(a, false)).toEqual(false); + expect(z.parse(a, "true")).toEqual(true); + expect(z.parse(a, "false")).toEqual(true); + expect(z.parse(a, 1)).toEqual(true); + expect(z.parse(a, 0)).toEqual(false); + expect(z.parse(a, {})).toEqual(true); + expect(z.parse(a, [])).toEqual(true); + expect(z.parse(a, undefined)).toEqual(false); + expect(z.parse(a, null)).toEqual(false); + expect(z.parse(a, "")).toEqual(false); +}); + +test("z.coerce.bigint", () => { + const a = z.coerce.bigint(); + expect(z.parse(a, "123")).toEqual(BigInt(123)); + expect(z.parse(a, 123)).toEqual(BigInt(123)); + expect(() => z.parse(a, "abc")).toThrow(); +}); + +test("z.coerce.date", () => { + const a = z.coerce.date(); + const date = new Date(); + expect(z.parse(a, date.toISOString())).toEqual(date); + expect(z.parse(a, date.getTime())).toEqual(date); + expect(() => z.parse(a, "invalid date")).toThrow(); +}); + +test("z.iso.datetime", () => { + const d1 = "2021-01-01T00:00:00Z"; + const d2 = "2021-01-01T00:00:00.123Z"; + const d3 = "2021-01-01T00:00:00"; + const d4 = "2021-01-01T00:00:00+07:00"; + const d5 = "bad data"; + + // local: false, offset: false, precision: null + const a = z.iso.datetime(); + expect(z.safeParse(a, d1).success).toEqual(true); + expect(z.safeParse(a, d2).success).toEqual(true); + expect(z.safeParse(a, d3).success).toEqual(false); + expect(z.safeParse(a, d4).success).toEqual(false); + expect(z.safeParse(a, d5).success).toEqual(false); + + const b = z.iso.datetime({ local: true }); + expect(z.safeParse(b, d1).success).toEqual(true); + expect(z.safeParse(b, d2).success).toEqual(true); + expect(z.safeParse(b, d3).success).toEqual(true); + expect(z.safeParse(b, d4).success).toEqual(false); + expect(z.safeParse(b, d5).success).toEqual(false); + + const c = z.iso.datetime({ offset: true }); + expect(z.safeParse(c, d1).success).toEqual(true); + expect(z.safeParse(c, d2).success).toEqual(true); + expect(z.safeParse(c, d3).success).toEqual(false); + expect(z.safeParse(c, d4).success).toEqual(true); + expect(z.safeParse(c, d5).success).toEqual(false); + + const d = z.iso.datetime({ precision: 3 }); + expect(z.safeParse(d, d1).success).toEqual(false); + expect(z.safeParse(d, d2).success).toEqual(true); + expect(z.safeParse(d, d3).success).toEqual(false); + expect(z.safeParse(d, d4).success).toEqual(false); + expect(z.safeParse(d, d5).success).toEqual(false); +}); + +test("z.iso.date", () => { + const d1 = "2021-01-01"; + const d2 = "bad data"; + + const a = z.iso.date(); + expect(z.safeParse(a, d1).success).toEqual(true); + expect(z.safeParse(a, d2).success).toEqual(false); + + const b = z.string().check(z.iso.date()); + expect(z.safeParse(b, d1).success).toEqual(true); + expect(z.safeParse(b, d2).success).toEqual(false); +}); + +test("z.iso.time", () => { + const d1 = "00:00:00"; + const d2 = "00:00:00.123"; + const d3 = "bad data"; + + const a = z.iso.time(); + expect(z.safeParse(a, d1).success).toEqual(true); + expect(z.safeParse(a, d2).success).toEqual(true); + expect(z.safeParse(a, d3).success).toEqual(false); + + const b = z.iso.time({ precision: 3 }); + expect(z.safeParse(b, d1).success).toEqual(false); + expect(z.safeParse(b, d2).success).toEqual(true); + expect(z.safeParse(b, d3).success).toEqual(false); + + const c = z.string().check(z.iso.time()); + expect(z.safeParse(c, d1).success).toEqual(true); + expect(z.safeParse(c, d2).success).toEqual(true); + expect(z.safeParse(c, d3).success).toEqual(false); +}); + +test("z.iso.duration", () => { + const d1 = "P3Y6M4DT12H30M5S"; + const d2 = "bad data"; + + const a = z.iso.duration(); + expect(z.safeParse(a, d1).success).toEqual(true); + expect(z.safeParse(a, d2).success).toEqual(false); + + const b = z.string().check(z.iso.duration()); + expect(z.safeParse(b, d1).success).toEqual(true); + expect(z.safeParse(b, d2).success).toEqual(false); +}); + +test("z.undefined", () => { + const a = z.undefined(); + expect(z.parse(a, undefined)).toEqual(undefined); + expect(() => z.parse(a, "undefined")).toThrow(); +}); + +test("z.null", () => { + const a = z.null(); + expect(z.parse(a, null)).toEqual(null); + expect(() => z.parse(a, "null")).toThrow(); +}); + +test("z.any", () => { + const a = z.any(); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(z.parse(a, 123)).toEqual(123); + expect(z.parse(a, true)).toEqual(true); + expect(z.parse(a, null)).toEqual(null); + expect(z.parse(a, undefined)).toEqual(undefined); + z.parse(a, {}); + z.parse(a, []); + z.parse(a, Symbol()); + z.parse(a, new Date()); +}); + +test("z.unknown", () => { + const a = z.unknown(); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(z.parse(a, 123)).toEqual(123); + expect(z.parse(a, true)).toEqual(true); + expect(z.parse(a, null)).toEqual(null); + expect(z.parse(a, undefined)).toEqual(undefined); + z.parse(a, {}); + z.parse(a, []); + z.parse(a, Symbol()); + z.parse(a, new Date()); +}); + +test("z.never", () => { + const a = z.never(); + expect(() => z.parse(a, "hello")).toThrow(); +}); + +test("z.void", () => { + const a = z.void(); + expect(z.parse(a, undefined)).toEqual(undefined); + expect(() => z.parse(a, null)).toThrow(); +}); + +test("z.array", () => { + const a = z.array(z.string()); + expect(z.parse(a, ["hello", "world"])).toEqual(["hello", "world"]); + expect(() => z.parse(a, [123])).toThrow(); + expect(() => z.parse(a, "hello")).toThrow(); +}); + +test("z.union", () => { + const a = z.union([z.string(), z.number()]); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(z.parse(a, 123)).toEqual(123); + expect(() => z.parse(a, true)).toThrow(); +}); + +test("z.intersection", () => { + const a = z.intersection(z.object({ a: z.string() }), z.object({ b: z.number() })); + expect(z.parse(a, { a: "hello", b: 123 })).toEqual({ a: "hello", b: 123 }); + expect(() => z.parse(a, { a: "hello" })).toThrow(); + expect(() => z.parse(a, { b: 123 })).toThrow(); + expect(() => z.parse(a, "hello")).toThrow(); +}); + +test("z.tuple", () => { + const a = z.tuple([z.string(), z.number()]); + expect(z.parse(a, ["hello", 123])).toEqual(["hello", 123]); + expect(() => z.parse(a, ["hello", "world"])).toThrow(); + expect(() => z.parse(a, [123, 456])).toThrow(); + expect(() => z.parse(a, "hello")).toThrow(); + + // tuple with rest + const b = z.tuple([z.string(), z.number(), z.optional(z.string())], z.boolean()); + type b = z.output; + + expectTypeOf().toEqualTypeOf<[string, number, string?, ...boolean[]]>(); + const datas = [ + ["hello", 123], + ["hello", 123, "world"], + ["hello", 123, "world", true], + ["hello", 123, "world", true, false, true], + ]; + for (const data of datas) { + expect(z.parse(b, data)).toEqual(data); + } + + expect(() => z.parse(b, ["hello", 123, 123])).toThrow(); + expect(() => z.parse(b, ["hello", 123, "world", 123])).toThrow(); + + // tuple with readonly args + const cArgs = [z.string(), z.number(), z.optional(z.string())] as const; + const c = z.tuple(cArgs, z.boolean()); + type c = z.output; + expectTypeOf().toEqualTypeOf<[string, number, string?, ...boolean[]]>(); + // type c = z.output; +}); + +test("z.record", () => { + // record schema with enum keys + const a = z.record(z.string(), z.string()); + type a = z.output; + expectTypeOf().toEqualTypeOf>(); + + const b = z.record(z.union([z.string(), z.number(), z.symbol()]), z.string()); + type b = z.output; + expectTypeOf().toEqualTypeOf>(); + expect(z.parse(b, { a: "hello", 1: "world", [Symbol.for("asdf")]: "symbol" })).toEqual({ + a: "hello", + 1: "world", + [Symbol.for("asdf")]: "symbol", + }); + + // enum keys + const c = z.record(z.enum(["a", "b", "c"]), z.string()); + type c = z.output; + expectTypeOf().toEqualTypeOf>(); + expect(z.parse(c, { a: "hello", b: "world", c: "world" })).toEqual({ + a: "hello", + b: "world", + c: "world", + }); + // missing keys + expect(() => z.parse(c, { a: "hello", b: "world" })).toThrow(); + // extra keys + expect(() => z.parse(c, { a: "hello", b: "world", c: "world", d: "world" })).toThrow(); + + // partial enum + const d = z.record(z.enum(["a", "b"]).or(z.never()), z.string()); + type d = z.output; + expectTypeOf().toEqualTypeOf>(); +}); + +test("z.map", () => { + const a = z.map(z.string(), z.number()); + type a = z.output; + expectTypeOf().toEqualTypeOf>(); + expect(z.parse(a, new Map([["hello", 123]]))).toEqual(new Map([["hello", 123]])); + expect(() => z.parse(a, new Map([["hello", "world"]]))).toThrow(); + expect(() => z.parse(a, new Map([[1243, "world"]]))).toThrow(); + expect(() => z.parse(a, "hello")).toThrow(); + + const r1 = z.safeParse(a, new Map([[123, 123]])); + expect(r1.error?.issues[0].code).toEqual("invalid_type"); + expect(r1.error?.issues[0].path).toEqual([123]); + + const r2: any = z.safeParse(a, new Map([[BigInt(123), 123]])); + expect(r2.error!.issues[0].code).toEqual("invalid_key"); + expect(r2.error!.issues[0].path).toEqual([]); + + const r3: any = z.safeParse(a, new Map([["hello", "world"]])); + expect(r3.error!.issues[0].code).toEqual("invalid_type"); + expect(r3.error!.issues[0].path).toEqual(["hello"]); +}); + +test("z.map invalid_element", () => { + const a = z.map(z.bigint(), z.number()); + const r1 = z.safeParse(a, new Map([[BigInt(123), BigInt(123)]])); + + expect(r1.error!.issues[0].code).toEqual("invalid_element"); + expect(r1.error!.issues[0].path).toEqual([]); +}); + +test("z.map async", async () => { + const a = z.map(z.string().check(z.refine(async () => true)), z.number().check(z.refine(async () => true))); + const d1 = new Map([["hello", 123]]); + expect(await z.parseAsync(a, d1)).toEqual(d1); + + await expect(z.parseAsync(a, new Map([[123, 123]]))).rejects.toThrow(); + await expect(z.parseAsync(a, new Map([["hi", "world"]]))).rejects.toThrow(); + await expect(z.parseAsync(a, new Map([[1243, "world"]]))).rejects.toThrow(); + await expect(z.parseAsync(a, "hello")).rejects.toThrow(); + + const r = await z.safeParseAsync(a, new Map([[123, 123]])); + expect(r.success).toEqual(false); + expect(r.error!.issues[0].code).toEqual("invalid_type"); + expect(r.error!.issues[0].path).toEqual([123]); +}); + +test("z.set", () => { + const a = z.set(z.string()); + type a = z.output; + expectTypeOf().toEqualTypeOf>(); + expect(z.parse(a, new Set(["hello", "world"]))).toEqual(new Set(["hello", "world"])); + expect(() => z.parse(a, new Set([123]))).toThrow(); + expect(() => z.parse(a, ["hello", "world"])).toThrow(); + expect(() => z.parse(a, "hello")).toThrow(); + + const b = z.set(z.number()); + expect(z.parse(b, new Set([1, 2, 3]))).toEqual(new Set([1, 2, 3])); + expect(() => z.parse(b, new Set(["hello"]))).toThrow(); + expect(() => z.parse(b, [1, 2, 3])).toThrow(); + expect(() => z.parse(b, 123)).toThrow(); +}); + +test("z.enum", () => { + const a = z.enum(["A", "B", "C"]); + type a = z.output; + expectTypeOf().toEqualTypeOf<"A" | "B" | "C">(); + expect(z.parse(a, "A")).toEqual("A"); + expect(z.parse(a, "B")).toEqual("B"); + expect(z.parse(a, "C")).toEqual("C"); + expect(() => z.parse(a, "D")).toThrow(); + expect(() => z.parse(a, 123)).toThrow(); + + expect(a.enum.A).toEqual("A"); + expect(a.enum.B).toEqual("B"); + expect(a.enum.C).toEqual("C"); + expect((a.enum as any).D).toEqual(undefined); +}); + +test("z.enum - native", () => { + enum NativeEnum { + A = "A", + B = "B", + C = "C", + } + const a = z.enum(NativeEnum); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, NativeEnum.A)).toEqual(NativeEnum.A); + expect(z.parse(a, NativeEnum.B)).toEqual(NativeEnum.B); + expect(z.parse(a, NativeEnum.C)).toEqual(NativeEnum.C); + expect(() => z.parse(a, "D")).toThrow(); + expect(() => z.parse(a, 123)).toThrow(); + + // test a.enum + a; + expect(a.enum.A).toEqual(NativeEnum.A); + expect(a.enum.B).toEqual(NativeEnum.B); + expect(a.enum.C).toEqual(NativeEnum.C); +}); + +test("z.nativeEnum", () => { + enum NativeEnum { + A = "A", + B = "B", + C = "C", + } + const a = z.nativeEnum(NativeEnum); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, NativeEnum.A)).toEqual(NativeEnum.A); + expect(z.parse(a, NativeEnum.B)).toEqual(NativeEnum.B); + expect(z.parse(a, NativeEnum.C)).toEqual(NativeEnum.C); + expect(() => z.parse(a, "D")).toThrow(); + expect(() => z.parse(a, 123)).toThrow(); + + // test a.enum + a; + expect(a.enum.A).toEqual(NativeEnum.A); + expect(a.enum.B).toEqual(NativeEnum.B); + expect(a.enum.C).toEqual(NativeEnum.C); +}); + +test("z.literal", () => { + const a = z.literal("hello"); + type a = z.output; + expectTypeOf().toEqualTypeOf<"hello">(); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(() => z.parse(a, "world")).toThrow(); + expect(() => z.parse(a, 123)).toThrow(); +}); + +test("z.file", () => { + const a = z.file(); + const file = new File(["content"], "filename.txt", { type: "text/plain" }); + expect(z.parse(a, file)).toEqual(file); + expect(() => z.parse(a, "file")).toThrow(); + expect(() => z.parse(a, 123)).toThrow(); +}); + +test("z.transform", () => { + const a = z.pipe( + z.string(), + z.transform((val) => val.toUpperCase()) + ); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, "hello")).toEqual("HELLO"); + expect(() => z.parse(a, 123)).toThrow(); +}); + +test("z.transform async", async () => { + const a = z.pipe( + z.string(), + z.transform(async (val) => val.toUpperCase()) + ); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(await z.parseAsync(a, "hello")).toEqual("HELLO"); + await expect(() => z.parseAsync(a, 123)).rejects.toThrow(); +}); + +test("z.preprocess", () => { + const a = z.pipe( + z.transform((val) => String(val).toUpperCase()), + z.string() + ); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, 123)).toEqual("123"); + expect(z.parse(a, true)).toEqual("TRUE"); + expect(z.parse(a, BigInt(1234))).toEqual("1234"); + // expect(() => z.parse(a, Symbol("asdf"))).toThrow(); +}); + +// test("z.preprocess async", () => { +// const a = z.preprocess(async (val) => String(val), z.string()); +// type a = z.output; +// expectTypeOf().toEqualTypeOf(); +// expect(z.parse(a, 123)).toEqual("123"); +// expect(z.parse(a, true)).toEqual("true"); +// expect(() => z.parse(a, {})).toThrow(); +// }); + +test("z.optional", () => { + const a = z.optional(z.string()); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(z.parse(a, undefined)).toEqual(undefined); + expect(() => z.parse(a, 123)).toThrow(); +}); + +test("z.nullable", () => { + const a = z.nullable(z.string()); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(z.parse(a, null)).toEqual(null); + expect(() => z.parse(a, 123)).toThrow(); +}); + +test("z.default", () => { + const a = z._default(z.string(), "default"); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, undefined)).toEqual("default"); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(() => z.parse(a, 123)).toThrow(); + + const b = z._default(z.string(), () => "default"); + expect(z.parse(b, undefined)).toEqual("default"); + expect(z.parse(b, "hello")).toEqual("hello"); + expect(() => z.parse(b, 123)).toThrow(); +}); + +test("z.catch", () => { + const a = z.catch(z.string(), "default"); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(z.parse(a, 123)).toEqual("default"); + + const b = z.catch(z.string(), () => "default"); + expect(z.parse(b, "hello")).toEqual("hello"); + expect(z.parse(b, 123)).toEqual("default"); + + const c = z.catch(z.string(), (ctx) => { + return `${ctx.error.issues.length}issues`; + }); + expect(z.parse(c, 1234)).toEqual("1issues"); +}); + +test("z.nan", () => { + const a = z.nan(); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, Number.NaN)).toEqual(Number.NaN); + expect(() => z.parse(a, 123)).toThrow(); + expect(() => z.parse(a, "NaN")).toThrow(); +}); + +test("z.pipe", () => { + const a = z.pipe( + z.pipe( + z.string(), + z.transform((val) => val.length) + ), + z.number() + ); + type a_in = z.input; + expectTypeOf().toEqualTypeOf(); + type a_out = z.output; + expectTypeOf().toEqualTypeOf(); + + expect(z.parse(a, "123")).toEqual(3); + expect(z.parse(a, "hello")).toEqual(5); + expect(() => z.parse(a, 123)).toThrow(); +}); + +test("z.readonly", () => { + const a = z.readonly(z.string()); + type a = z.output; + expectTypeOf().toEqualTypeOf>(); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(() => z.parse(a, 123)).toThrow(); +}); + +test("z.templateLiteral", () => { + const a = z.templateLiteral([z.string(), z.number()]); + type a = z.output; + expectTypeOf().toEqualTypeOf<`${string}${number}`>(); + expect(z.parse(a, "hello123")).toEqual("hello123"); + expect(() => z.parse(a, "hello")).toThrow(); + expect(() => z.parse(a, 123)).toThrow(); + + // multipart + const b = z.templateLiteral([z.string(), z.number(), z.string()]); + type b = z.output; + expectTypeOf().toEqualTypeOf<`${string}${number}${string}`>(); + expect(z.parse(b, "hello123world")).toEqual("hello123world"); + expect(z.parse(b, "123")).toEqual("123"); + expect(() => z.parse(b, "hello")).toThrow(); + expect(() => z.parse(b, 123)).toThrow(); + + // include boolean + const c = z.templateLiteral([z.string(), z.boolean()]); + type c = z.output; + expectTypeOf().toEqualTypeOf<`${string}${boolean}`>(); + expect(z.parse(c, "hellotrue")).toEqual("hellotrue"); + expect(z.parse(c, "hellofalse")).toEqual("hellofalse"); + expect(() => z.parse(c, "hello")).toThrow(); + expect(() => z.parse(c, 123)).toThrow(); + + // include literal prefix + const d = z.templateLiteral([z.literal("hello"), z.number()]); + type d = z.output; + expectTypeOf().toEqualTypeOf<`hello${number}`>(); + expect(z.parse(d, "hello123")).toEqual("hello123"); + expect(() => z.parse(d, 123)).toThrow(); + expect(() => z.parse(d, "world123")).toThrow(); + + // include literal union + const e = z.templateLiteral([z.literal(["aa", "bb"]), z.number()]); + type e = z.output; + expectTypeOf().toEqualTypeOf<`aa${number}` | `bb${number}`>(); + expect(z.parse(e, "aa123")).toEqual("aa123"); + expect(z.parse(e, "bb123")).toEqual("bb123"); + expect(() => z.parse(e, "cc123")).toThrow(); + expect(() => z.parse(e, 123)).toThrow(); +}); + +// this returns both a schema and a check +test("z.custom schema", () => { + const a = z.custom((val) => { + return typeof val === "string"; + }); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(() => z.parse(a, 123)).toThrow(); +}); + +test("z.custom check", () => { + // @ts-expect-error Inference not possible, use z.refine() + z.date().check(z.custom((val) => val.getTime() > 0)); +}); + +test("z.check", () => { + // this is a more flexible version of z.custom that accepts an arbitrary _parse logic + // the function should return base.$ZodResult + const a = z.any().check( + z.check((ctx) => { + if (typeof ctx.value === "string") return; + ctx.issues.push({ + code: "custom", + origin: "custom", + message: "Expected a string", + input: ctx.value, + }); + }) + ); + expect(z.safeParse(a, "hello")).toMatchObject({ + success: true, + data: "hello", + }); + expect(z.safeParse(a, 123)).toMatchObject({ + success: false, + error: { issues: [{ code: "custom", message: "Expected a string" }] }, + }); +}); + +test("z.instanceof", () => { + class A {} + + const a = z.instanceof(A); + expect(z.parse(a, new A())).toBeInstanceOf(A); + expect(() => z.parse(a, {})).toThrow(); +}); + +test("z.refine", () => { + const a = z.number().check( + z.refine((val) => val > 3), + z.refine((val) => val < 10) + ); + expect(z.parse(a, 5)).toEqual(5); + expect(() => z.parse(a, 2)).toThrow(); + expect(() => z.parse(a, 11)).toThrow(); + expect(() => z.parse(a, "hi")).toThrow(); +}); + +// test("z.superRefine", () => { +// const a = z.number([ +// z.superRefine((val, ctx) => { +// if (val < 3) { +// return ctx.addIssue({ +// code: "custom", +// origin: "custom", +// message: "Too small", +// input: val, +// }); +// } +// if (val > 10) { +// return ctx.addIssue("Too big"); +// } +// }), +// ]); + +// expect(z.parse(a, 5)).toEqual(5); +// expect(() => z.parse(a, 2)).toThrow(); +// expect(() => z.parse(a, 11)).toThrow(); +// expect(() => z.parse(a, "hi")).toThrow(); +// }); + +test("z.transform", () => { + const a = z.transform((val: number) => { + return `${val}`; + }); + type a_in = z.input; + expectTypeOf().toEqualTypeOf(); + type a_out = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, 123)).toEqual("123"); +}); + +test("z.$brand()", () => { + const a = z.string().brand<"my-brand">(); + type a = z.output; + const branded = (_: a) => {}; + // @ts-expect-error + branded("asdf"); +}); + +test("z.lazy", () => { + const a = z.lazy(() => z.string()); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + expect(z.parse(a, "hello")).toEqual("hello"); + expect(() => z.parse(a, 123)).toThrow(); +}); + +// schema that validates JSON-like data +test("z.json", () => { + const a = z.json(); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + + expect(z.parse(a, "hello")).toEqual("hello"); + expect(z.parse(a, 123)).toEqual(123); + expect(z.parse(a, true)).toEqual(true); + expect(z.parse(a, null)).toEqual(null); + expect(z.parse(a, {})).toEqual({}); + expect(z.parse(a, { a: "hello" })).toEqual({ a: "hello" }); + expect(z.parse(a, [1, 2, 3])).toEqual([1, 2, 3]); + expect(z.parse(a, [{ a: "hello" }])).toEqual([{ a: "hello" }]); + + // fail cases + expect(() => z.parse(a, new Date())).toThrow(); + expect(() => z.parse(a, Symbol())).toThrow(); + expect(() => z.parse(a, { a: new Date() })).toThrow(); + expect(() => z.parse(a, undefined)).toThrow(); + expect(() => z.parse(a, { a: undefined })).toThrow(); +}); + +// promise +test("z.promise", async () => { + const a = z.promise(z.string()); + type a = z.output; + expectTypeOf().toEqualTypeOf(); + + expect(await z.safeParseAsync(a, Promise.resolve("hello"))).toMatchObject({ + success: true, + data: "hello", + }); + expect(await z.safeParseAsync(a, Promise.resolve(123))).toMatchObject({ + success: false, + }); + + const b = z.string(); + expect(() => z.parse(b, Promise.resolve("hello"))).toThrow(); +}); +// test("type assertions", () => { +// const schema = z.pipe( +// z.string(), +// z.transform((val) => val.length) +// ); +// schema.assertInput(); +// // @ts-expect-error +// schema.assertInput(); + +// schema.assertOutput(); +// // @ts-expect-error +// schema.assertOutput(); +// }); + +test("isPlainObject", () => { + expect(z.core.util.isPlainObject({})).toEqual(true); + expect(z.core.util.isPlainObject(Object.create(null))).toEqual(true); + expect(z.core.util.isPlainObject([])).toEqual(false); + expect(z.core.util.isPlainObject(new Date())).toEqual(false); + expect(z.core.util.isPlainObject(null)).toEqual(false); + expect(z.core.util.isPlainObject(undefined)).toEqual(false); + expect(z.core.util.isPlainObject("string")).toEqual(false); + expect(z.core.util.isPlainObject(123)).toEqual(false); + expect(z.core.util.isPlainObject(Symbol())).toEqual(false); +}); + +test("def typing", () => { + z.string().def.type satisfies "string"; + z.number().def.type satisfies "number"; + z.bigint().def.type satisfies "bigint"; + z.boolean().def.type satisfies "boolean"; + z.date().def.type satisfies "date"; + z.symbol().def.type satisfies "symbol"; + z.undefined().def.type satisfies "undefined"; + z.string().nullable().def.type satisfies "nullable"; + z.null().def.type satisfies "null"; + z.any().def.type satisfies "any"; + z.unknown().def.type satisfies "unknown"; + z.never().def.type satisfies "never"; + z.void().def.type satisfies "void"; + z.array(z.string()).def.type satisfies "array"; + z.object({ key: z.string() }).def.type satisfies "object"; + z.union([z.string(), z.number()]).def.type satisfies "union"; + z.intersection(z.string(), z.number()).def.type satisfies "intersection"; + z.tuple([z.string(), z.number()]).def.type satisfies "tuple"; + z.record(z.string(), z.number()).def.type satisfies "record"; + z.map(z.string(), z.number()).def.type satisfies "map"; + z.set(z.string()).def.type satisfies "set"; + z.literal("example").def.type satisfies "literal"; + z.enum(["a", "b", "c"]).def.type satisfies "enum"; + z.promise(z.string()).def.type satisfies "promise"; + z.lazy(() => z.string()).def.type satisfies "lazy"; + z.string().optional().def.type satisfies "optional"; + z.string().default("default").def.type satisfies "default"; + z.templateLiteral([z.literal("a"), z.literal("b")]).def.type satisfies "template_literal"; + z.custom((val) => typeof val === "string").def.type satisfies "custom"; + z.transform((val) => val as string).def.type satisfies "transform"; + z.string().optional().nonoptional().def.type satisfies "nonoptional"; + z.object({ key: z.string() }).readonly().def.type satisfies "readonly"; + z.nan().def.type satisfies "nan"; + z.unknown().pipe(z.number()).def.type satisfies "pipe"; + z.success(z.string()).def.type satisfies "success"; + z.string().catch("fallback").def.type satisfies "catch"; + z.file().def.type satisfies "file"; +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/instanceof.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/instanceof.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..37671034b46a224fe130c9250b5715613cca8b0f --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/instanceof.test.ts @@ -0,0 +1,34 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("instanceof", async () => { + class Test {} + class Subtest extends Test {} + abstract class AbstractBar { + constructor(public val: string) {} + } + class Bar extends AbstractBar {} + + const TestSchema = z.instanceof(Test); + const SubtestSchema = z.instanceof(Subtest); + const AbstractSchema = z.instanceof(AbstractBar); + const BarSchema = z.instanceof(Bar); + + TestSchema.parse(new Test()); + TestSchema.parse(new Subtest()); + SubtestSchema.parse(new Subtest()); + AbstractSchema.parse(new Bar("asdf")); + const bar = BarSchema.parse(new Bar("asdf")); + expect(bar.val).toEqual("asdf"); + + await expect(() => SubtestSchema.parse(new Test())).toThrow(); + await expect(() => TestSchema.parse(12)).toThrow(); + + expectTypeOf().toEqualTypeOf>(); +}); + +test("instanceof fatal", () => { + const schema = z.instanceof(Date).refine((d) => d.toString()); + const res = schema.safeParse(null); + expect(res.success).toBe(false); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/intersection.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/intersection.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1538c03c3ce1c714a482088ce3bd1e2a869e117 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/intersection.test.ts @@ -0,0 +1,171 @@ +import { expect, expectTypeOf, test } from "vitest"; +import type { util } from "zod/v4/core"; + +import * as z from "zod/v4"; + +test("object intersection", () => { + const A = z.object({ a: z.string() }); + const B = z.object({ b: z.string() }); + + const C = z.intersection(A, B); // BaseC.merge(HasID); + type C = z.infer; + expectTypeOf().toEqualTypeOf<{ a: string } & { b: string }>(); + const data = { a: "foo", b: "foo" }; + expect(C.parse(data)).toEqual(data); + expect(() => C.parse({ a: "foo" })).toThrow(); +}); + +test("object intersection: loose", () => { + const A = z.looseObject({ a: z.string() }); + const B = z.object({ b: z.string() }); + + const C = z.intersection(A, B); // BaseC.merge(HasID); + type C = z.infer; + expectTypeOf().toEqualTypeOf<{ a: string; [x: string]: unknown } & { b: string }>(); + const data = { a: "foo", b: "foo", c: "extra" }; + expect(C.parse(data)).toEqual(data); + expect(() => C.parse({ a: "foo" })).toThrow(); +}); + +test("object intersection: strict", () => { + const A = z.strictObject({ a: z.string() }); + const B = z.object({ b: z.string() }); + + const C = z.intersection(A, B); // BaseC.merge(HasID); + type C = z.infer; + expectTypeOf().toEqualTypeOf<{ a: string } & { b: string }>(); + const data = { a: "foo", b: "foo", c: "extra" }; + + const result = C.safeParse(data); + expect(result.success).toEqual(false); +}); + +test("deep intersection", () => { + const Animal = z.object({ + properties: z.object({ + is_animal: z.boolean(), + }), + }); + const Cat = z.intersection( + z.object({ + properties: z.object({ + jumped: z.boolean(), + }), + }), + Animal + ); + + type Cat = util.Flatten>; + expectTypeOf().toEqualTypeOf<{ properties: { is_animal: boolean } & { jumped: boolean } }>(); + const a = Cat.safeParse({ properties: { is_animal: true, jumped: true } }); + expect(a.data!.properties).toEqual({ is_animal: true, jumped: true }); +}); + +test("deep intersection of arrays", async () => { + const Author = z.object({ + posts: z.array( + z.object({ + post_id: z.number(), + }) + ), + }); + const Registry = z.intersection( + Author, + z.object({ + posts: z.array( + z.object({ + title: z.string(), + }) + ), + }) + ); + + const posts = [ + { post_id: 1, title: "Novels" }, + { post_id: 2, title: "Fairy tales" }, + ]; + const cat = Registry.parse({ posts }); + expect(cat.posts).toEqual(posts); + const asyncCat = await Registry.parseAsync({ posts }); + expect(asyncCat.posts).toEqual(posts); +}); + +test("invalid intersection types", async () => { + const numberIntersection = z.intersection( + z.number(), + z.number().transform((x) => x + 1) + ); + + expect(() => { + numberIntersection.parse(1234); + }).toThrowErrorMatchingInlineSnapshot(`[Error: Unmergable intersection. Error path: []]`); +}); + +test("invalid array merge (incompatible lengths)", async () => { + const stringArrInt = z.intersection( + z.string().array(), + z + .string() + .array() + .transform((val) => [...val, "asdf"]) + ); + + expect(() => stringArrInt.safeParse(["asdf", "qwer"])).toThrowErrorMatchingInlineSnapshot( + `[Error: Unmergable intersection. Error path: []]` + ); +}); + +test("invalid array merge (incompatible elements)", async () => { + const stringArrInt = z.intersection( + z.string().array(), + z + .string() + .array() + .transform((val) => [...val.slice(0, -1), "asdf"]) + ); + + expect(() => stringArrInt.safeParse(["asdf", "qwer"])).toThrowErrorMatchingInlineSnapshot( + `[Error: Unmergable intersection. Error path: [1]]` + ); +}); + +test("invalid object merge", async () => { + const Cat = z.object({ + phrase: z.string().transform((val) => `${val} Meow`), + }); + const Dog = z.object({ + phrase: z.string().transform((val) => `${val} Woof`), + }); + const CatDog = z.intersection(Cat, Dog); + + expect(() => CatDog.parse({ phrase: "Hello, my name is CatDog." })).toThrowErrorMatchingInlineSnapshot( + `[Error: Unmergable intersection. Error path: ["phrase"]]` + ); +}); + +test("invalid deep merge of object and array combination", async () => { + const University = z.object({ + students: z.array( + z.object({ + name: z.string().transform((val) => `Student name: ${val}`), + }) + ), + }); + const Registry = z.intersection( + University, + z.object({ + students: z.array( + z.object({ + name: z.string(), + surname: z.string(), + }) + ), + }) + ); + + const students = [{ name: "John", surname: "Doe" }]; + + expect(() => Registry.parse({ students })).toThrowErrorMatchingInlineSnapshot( + `[Error: Unmergable intersection. Error path: ["students",0,"name"]]` + ); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/json.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/json.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8ae5756832423107321d816d4250b5607f8de82 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/json.test.ts @@ -0,0 +1,108 @@ +import { test } from "vitest"; +// import * as z from "zod/v4"; + +test(() => {}); +// test("overload types", () => { +// const schema = z.string().json(); +// util.assertEqual(true); +// const schema2 = z.string().json(z.number()); +// util.assertEqual, z.ZodNumber>>(true); +// const r2 = schema2.parse("12"); +// util.assertEqual(true); +// }); +// test("parse string to json", async () => { +// const Env = z.object({ +// myJsonConfig: z.string().jsonString(z.object({ foo: z.number() })), +// someOtherValue: z.string(), +// }); + +// expect( +// Env.parse({ +// myJsonConfig: '{ "foo": 123 }', +// someOtherValue: "abc", +// }) +// ).toEqual({ +// myJsonConfig: { foo: 123 }, +// someOtherValue: "abc", +// }); + +// const invalidValues = Env.safeParse({ +// myJsonConfig: '{"foo": "not a number!"}', +// someOtherValue: null, +// }); +// expect(JSON.parse(JSON.stringify(invalidValues))).toEqual({ +// success: false, +// error: { +// name: "ZodError", +// issues: [ +// { +// code: "invalid_type", +// expected: "number", +// input: "not a number!", +// received: "string", +// path: ["myJsonConfig", "foo"], +// message: "Expected number, received string", +// }, +// { +// code: "invalid_type", +// expected: "string", +// input: null, +// received: "null", +// path: ["someOtherValue"], +// message: "Expected string, received null", +// }, +// ], +// }, +// }); + +// const invalidJsonSyntax = Env.safeParse({ +// myJsonConfig: "This is not valid json", +// someOtherValue: null, +// }); +// expect(JSON.parse(JSON.stringify(invalidJsonSyntax))).toMatchObject({ +// success: false, +// error: { +// name: "ZodError", +// issues: [ +// { +// code: "invalid_string", +// input: { +// _def: { +// catchall: { +// _def: { +// typeName: "ZodNever", +// }, +// }, +// typeName: "ZodObject", +// unknownKeys: "strip", +// }, +// }, +// validation: "json", +// message: "Invalid json", +// path: ["myJsonConfig"], +// }, +// { +// code: "invalid_type", +// expected: "string", +// input: null, +// received: "null", +// path: ["someOtherValue"], +// message: "Expected string, received null", +// }, +// ], +// }, +// }); +// }); + +// test("no argument", () => { +// const schema = z.string().json(); +// util.assertEqual(true); +// z.string().json().parse(`{}`); +// z.string().json().parse(`null`); +// z.string().json().parse(`12`); +// z.string().json().parse(`{ "test": "test"}`); +// expect(() => z.string().json().parse(`asdf`)).toThrow(); +// expect(() => z.string().json().parse(`{ "test": undefined }`)).toThrow(); +// expect(() => z.string().json().parse(`{ "test": 12n }`)).toThrow(); +// expect(() => z.string().json().parse(`{ test: "test" }`)).toThrow(); +// }); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/lazy.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/lazy.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb02348031a7e1dac730bf804b6d98451bb9f5a0 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/lazy.test.ts @@ -0,0 +1,227 @@ +import { expect, expectTypeOf, test } from "vitest"; + +import * as z from "zod/v4"; + +test("opt passthrough", () => { + const object = z.object({ + a: z.lazy(() => z.string()), + b: z.lazy(() => z.string().optional()), + c: z.lazy(() => z.string().default("default")), + }); + + type ObjectTypeIn = z.input; + expectTypeOf().toEqualTypeOf<{ + a: string; + b?: string | undefined; + c?: string | undefined; + }>(); + + type ObjectTypeOut = z.output; + expectTypeOf().toEqualTypeOf<{ + a: string; + b?: string | undefined; + c: string; + }>(); + + const result = object.parse( + { + a: "hello", + b: undefined, + }, + { jitless: true } + ); + expect(result).toEqual({ + a: "hello", + // b: undefined, + c: "default", + }); + + expect(z.lazy(() => z.string())._zod.optin).toEqual(undefined); + expect(z.lazy(() => z.string())._zod.optout).toEqual(undefined); + + expect(z.lazy(() => z.string().optional())._zod.optin).toEqual("optional"); + expect(z.lazy(() => z.string().optional())._zod.optout).toEqual("optional"); + + expect(z.lazy(() => z.string().default("asdf"))._zod.optin).toEqual("optional"); + expect(z.lazy(() => z.string().default("asdf"))._zod.optout).toEqual(undefined); +}); + +////////////// LAZY ////////////// + +test("schema getter", () => { + z.lazy(() => z.string()).parse("asdf"); +}); + +test("lazy proxy", () => { + const schema = z.lazy(() => z.string())._zod.innerType.min(6); + schema.parse("123456"); + expect(schema.safeParse("12345").success).toBe(false); +}); + +interface Category { + name: string; + subcategories: Category[]; +} + +const testCategory: Category = { + name: "I", + subcategories: [ + { + name: "A", + subcategories: [ + { + name: "1", + subcategories: [ + { + name: "a", + subcategories: [], + }, + ], + }, + ], + }, + ], +}; + +test("recursion with z.lazy", () => { + const Category: z.ZodType = z.lazy(() => + z.object({ + name: z.string(), + subcategories: z.array(Category), + }) + ); + Category.parse(testCategory); +}); + +type LinkedList = null | { value: number; next: LinkedList }; + +const linkedListExample = { + value: 1, + next: { + value: 2, + next: { + value: 3, + next: { + value: 4, + next: null, + }, + }, + }, +}; + +test("recursive union wit z.lazy", () => { + const LinkedListSchema: z.ZodType = z.lazy(() => + z.union([ + z.null(), + z.object({ + value: z.number(), + next: LinkedListSchema, + }), + ]) + ); + LinkedListSchema.parse(linkedListExample); +}); + +interface A { + val: number; + b: B; +} + +interface B { + val: number; + a?: A | undefined; +} + +test("mutual recursion with lazy", () => { + const Alazy: z.ZodType = z.lazy(() => + z.object({ + val: z.number(), + b: Blazy, + }) + ); + + const Blazy: z.ZodType = z.lazy(() => + z.object({ + val: z.number(), + a: Alazy.optional(), + }) + ); + + const testData = { + val: 1, + b: { + val: 5, + a: { + val: 3, + b: { + val: 4, + a: { + val: 2, + b: { + val: 1, + }, + }, + }, + }, + }, + }; + + Alazy.parse(testData); + Blazy.parse(testData.b); + + expect(() => Alazy.parse({ val: "asdf" })).toThrow(); +}); + +// TODO +test("mutual recursion with cyclical data", () => { + const a: any = { val: 1 }; + const b: any = { val: 2 }; + a.b = b; + b.a = a; +}); + +test("complicated self-recursion", () => { + const Category = z.object({ + name: z.string(), + age: z.optional(z.number()), + get nullself() { + return Category.nullable(); + }, + get optself() { + return Category.optional(); + }, + get self() { + return Category; + }, + get subcategories() { + return z.array(Category); + }, + nested: z.object({ + get sub() { + return Category; + }, + }), + }); + + type _Category = z.output; +}); + +test("lazy initialization", () => { + const a: any = z.lazy(() => a).optional(); + const b: any = z.lazy(() => b).nullable(); + const c: any = z.lazy(() => c).default({} as any); + const d: any = z.lazy(() => d).prefault({} as any); + const e: any = z.lazy(() => e).nonoptional(); + const f: any = z.lazy(() => f).catch({} as any); + const g: any = z.lazy(() => z.object({ g })).readonly(); + + const baseCategorySchema = z.object({ + name: z.string(), + }); + type Category = z.infer & { + subcategories: Category[]; + }; + const categorySchema: z.ZodType = baseCategorySchema.extend({ + subcategories: z.lazy(() => categorySchema.array()), + }); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/literal.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/literal.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..78d1c088f1c4c6b1afa5eb26325fb1cafae943e6 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/literal.test.ts @@ -0,0 +1,92 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +const literalTuna = z.literal("tuna"); +const literalTunaCustomMessage = z.literal("tuna", { + message: "That's not a tuna", +}); +const literalFortyTwo = z.literal(42); +const literalTrue = z.literal(true); + +test("passing validations", () => { + literalTuna.parse("tuna"); + literalFortyTwo.parse(42); + literalTrue.parse(true); +}); + +test("failing validations", () => { + expect(() => literalTuna.parse("shark")).toThrow(); + expect(() => literalFortyTwo.parse(43)).toThrow(); + expect(() => literalTrue.parse(false)).toThrow(); +}); + +test("invalid_literal should have `input` field with data", () => { + const data = "shark"; + const result = literalTuna.safeParse(data); + + const issue = result.error!.issues[0]; + expect(issue.code).toBe("invalid_value"); + expect(issue).toMatchInlineSnapshot(` + { + "code": "invalid_value", + "message": "Invalid input: expected "tuna"", + "path": [], + "values": [ + "tuna", + ], + } + `); +}); + +test("invalid_literal should return default message", () => { + const data = "shark"; + const result = literalTuna.safeParse(data); + + const issue = result.error!.issues[0]; + expect(issue.message).toEqual(`Invalid input: expected \"tuna\"`); +}); + +test("invalid_literal should return custom message", () => { + const data = "shark"; + const result = literalTunaCustomMessage.safeParse(data); + + const issue = result.error!.issues[0]; + expect(issue.message).toEqual(`That's not a tuna`); +}); + +test("literal default error message", () => { + const result = z.literal("Tuna").safeParse("Trout"); + expect(result.success).toEqual(false); + expect(result.error!.issues.length).toEqual(1); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "invalid_value", + "values": [ + "Tuna" + ], + "path": [], + "message": "Invalid input: expected \\"Tuna\\"" + } + ]] + `); +}); + +test("literal bigint default error message", () => { + const result = z.literal(BigInt(12)).safeParse(BigInt(13)); + expect(result.success).toBe(false); + + expect(result.error!.issues.length).toEqual(1); + expect(result.error!.issues[0].message).toEqual(`Invalid input: expected 12n`); +}); + +test(".value getter", () => { + expect(z.literal("tuna").value).toEqual("tuna"); + expect(() => z.literal([1, 2, 3]).value).toThrow(); +}); + +test("readonly", () => { + const a = ["asdf"] as const; + z.literal(a); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/map.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/map.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..47c19710e77038fd992096b422e55fea8dc6687e --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/map.test.ts @@ -0,0 +1,196 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +const stringMap = z.map(z.string(), z.string()); +type stringMap = z.infer; + +test("type inference", () => { + expectTypeOf().toEqualTypeOf>(); +}); + +test("valid parse", () => { + const result = stringMap.safeParse( + new Map([ + ["first", "foo"], + ["second", "bar"], + ]) + ); + expect(result.success).toEqual(true); + expect(result.data).toMatchInlineSnapshot(` + Map { + "first" => "foo", + "second" => "bar", + } + `); +}); + +test("valid parse async", async () => { + const asyncMap = z.map( + z.string().refine(async () => false, "bad key"), + z.string().refine(async () => false, "bad value") + ); + const result = await asyncMap.safeParseAsync(new Map([["first", "foo"]])); + expect(result.success).toEqual(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [ + "first" + ], + "message": "bad key" + }, + { + "code": "custom", + "path": [ + "first" + ], + "message": "bad value" + } + ]] + `); +}); + +test("throws when a Set is given", () => { + const result = stringMap.safeParse(new Set([])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].code).toEqual("invalid_type"); + } +}); + +test("throws when the given map has invalid key and invalid input", () => { + const result = stringMap.safeParse(new Map([[42, Symbol()]])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(2); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + 42 + ], + "message": "Invalid input: expected string, received number" + }, + { + "expected": "string", + "code": "invalid_type", + "path": [ + 42 + ], + "message": "Invalid input: expected string, received symbol" + } + ]] + `); + } +}); + +test("throws when the given map has multiple invalid entries", () => { + // const result = stringMap.safeParse(new Map([[42, Symbol()]])); + + const result = stringMap.safeParse( + new Map([ + [1, "foo"], + ["bar", 2], + ] as [any, any][]) as Map + ); + + // const result = stringMap.safeParse(new Map([[42, Symbol()]])); + expect(result.success).toEqual(false); + if (result.success === false) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues).toMatchInlineSnapshot(` + [ + { + "code": "invalid_type", + "expected": "string", + "message": "Invalid input: expected string, received number", + "path": [ + 1, + ], + }, + { + "code": "invalid_type", + "expected": "string", + "message": "Invalid input: expected string, received number", + "path": [ + "bar", + ], + }, + ] + `); + } +}); + +test("dirty", async () => { + const map = z.map( + z.string().refine((val) => val === val.toUpperCase(), { + message: "Keys must be uppercase", + }), + z.string() + ); + const result = await map.spa( + new Map([ + ["first", "foo"], + ["second", "bar"], + ]) + ); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(2); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [ + "first" + ], + "message": "Keys must be uppercase" + }, + { + "code": "custom", + "path": [ + "second" + ], + "message": "Keys must be uppercase" + } + ]] + `); + } +}); + +test("map with object keys", () => { + const map = z.map( + z.object({ + name: z.string(), + age: z.number(), + }), + z.string() + ); + const data = new Map([ + [{ name: "John", age: 30 }, "foo"], + [{ name: "Jane", age: 25 }, "bar"], + ]); + const result = map.safeParse(data); + expect(result.success).toEqual(true); + expect(result.data!).toEqual(data); + + const badData = new Map([["bad", "foo"]]); + const badResult = map.safeParse(badData); + expect(badResult.success).toEqual(false); + expect(badResult.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "object", + "code": "invalid_type", + "path": [ + "bad" + ], + "message": "Invalid input: expected object, received string" + } + ]] + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nan.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nan.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..05674fec92559a9e3c2eab95febe564ee0264569 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nan.test.ts @@ -0,0 +1,21 @@ +import { expect, expectTypeOf, test } from "vitest"; + +import * as z from "zod/v4"; + +const schema = z.nan(); + +test("passing validations", () => { + schema.parse(Number.NaN); + schema.parse(Number("Not a number")); + expectTypeOf().toEqualTypeOf(); +}); + +test("failing validations", () => { + expect(() => schema.parse(5)).toThrow(); + expect(() => schema.parse("John")).toThrow(); + expect(() => schema.parse(true)).toThrow(); + expect(() => schema.parse(null)).toThrow(); + expect(() => schema.parse(undefined)).toThrow(); + expect(() => schema.parse({})).toThrow(); + expect(() => schema.parse([])).toThrow(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b33b9ef44b46467e8eea14fb903e70a708973c9d --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts @@ -0,0 +1,168 @@ +import { expect, test } from "vitest"; +import * as z from "zod/v4"; + +test("nested refinements", () => { + const zodSchema = z + .object({ + password: z.string().min(1), + nested: z + .object({ + confirm: z + .string() + .min(1) + .refine((value) => value.length > 2, { + message: "Confirm length should be > 2", + }), + }) + .refine( + (data) => { + return data.confirm === "bar"; + }, + { + path: ["confirm"], + error: 'Value must be "bar"', + } + ), + }) + .refine( + (data) => { + return data.nested.confirm === data.password; + }, + { + path: ["nested", "confirm"], + error: "Password and confirm must match", + } + ); + + const DATA = { + password: "bar", + nested: { confirm: "" }, + }; + expect(zodSchema.safeParse(DATA)).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "origin": "string", + "code": "too_small", + "minimum": 1, + "inclusive": true, + "path": [ + "nested", + "confirm" + ], + "message": "Too small: expected string to have >=1 characters" + }, + { + "code": "custom", + "path": [ + "nested", + "confirm" + ], + "message": "Confirm length should be > 2" + }, + { + "code": "custom", + "path": [ + "nested", + "confirm" + ], + "message": "Value must be \\"bar\\"" + }, + { + "code": "custom", + "path": [ + "nested", + "confirm" + ], + "message": "Password and confirm must match" + } + ]], + "success": false, + } + `); + + expect(zodSchema.safeParse(DATA, { jitless: true })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "origin": "string", + "code": "too_small", + "minimum": 1, + "inclusive": true, + "path": [ + "nested", + "confirm" + ], + "message": "Too small: expected string to have >=1 characters" + }, + { + "code": "custom", + "path": [ + "nested", + "confirm" + ], + "message": "Confirm length should be > 2" + }, + { + "code": "custom", + "path": [ + "nested", + "confirm" + ], + "message": "Value must be \\"bar\\"" + }, + { + "code": "custom", + "path": [ + "nested", + "confirm" + ], + "message": "Password and confirm must match" + } + ]], + "success": false, + } + `); + + expect(zodSchema["~standard"].validate(DATA)).toMatchInlineSnapshot(` + { + "issues": [ + { + "code": "too_small", + "inclusive": true, + "message": "Too small: expected string to have >=1 characters", + "minimum": 1, + "origin": "string", + "path": [ + "nested", + "confirm", + ], + }, + { + "code": "custom", + "message": "Confirm length should be > 2", + "path": [ + "nested", + "confirm", + ], + }, + { + "code": "custom", + "message": "Value must be "bar"", + "path": [ + "nested", + "confirm", + ], + }, + { + "code": "custom", + "message": "Password and confirm must match", + "path": [ + "nested", + "confirm", + ], + }, + ], + } + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..07f40fb006efe1e14fe40dfa5a1aa57ea45d98df --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts @@ -0,0 +1,86 @@ +import { expect, expectTypeOf, test } from "vitest"; +import { z } from "zod/v4"; + +test("nonoptional", () => { + const schema = z.string().nonoptional(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + + const result = schema.safeParse(undefined); + expect(result.success).toBe(false); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected string, received undefined" + } + ]], + "success": false, + } + `); +}); + +test("nonoptional with default", () => { + const schema = z.string().optional().nonoptional(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + + const result = schema.safeParse(undefined); + expect(result.success).toBe(false); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_type", + "expected": "nonoptional", + "path": [], + "message": "Invalid input: expected nonoptional, received undefined" + } + ]], + "success": false, + } + `); +}); + +test("nonoptional in object", () => { + const schema = z.object({ hi: z.string().optional().nonoptional() }); + + expectTypeOf().toEqualTypeOf<{ hi: string }>(); + expectTypeOf().toEqualTypeOf<{ hi: string }>(); + const r1 = schema.safeParse({ hi: "asdf" }); + expect(r1.success).toEqual(true); + + const r2 = schema.safeParse({ hi: undefined }); + // expect(schema.safeParse({ hi: undefined }).success).toEqual(false); + expect(r2.success).toEqual(false); + expect(r2.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "invalid_type", + "expected": "nonoptional", + "path": [ + "hi" + ], + "message": "Invalid input: expected nonoptional, received undefined" + } + ]] + `); + + const r3 = schema.safeParse({}); + expect(r3.success).toEqual(false); + expect(r3.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "invalid_type", + "expected": "nonoptional", + "path": [ + "hi" + ], + "message": "Invalid input: expected nonoptional, received undefined" + } + ]] + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nullable.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nullable.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3b1e3894198ef160cff1878e7342f91865b2944 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/nullable.test.ts @@ -0,0 +1,22 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +test(".nullable()", () => { + const nullable = z.string().nullable(); + expect(nullable.parse(null)).toBe(null); + expect(nullable.parse("asdf")).toBe("asdf"); + expect(() => nullable.parse(123)).toThrow(); +}); + +test(".nullable unwrap", () => { + const schema = z.string().nullable(); + expect(schema).toBeInstanceOf(z.ZodNullable); + expect(schema.unwrap()).toBeInstanceOf(z.ZodString); +}); + +test("z.null", () => { + const n = z.null(); + expect(n.parse(null)).toBe(null); + expect(() => n.parse("asdf")).toThrow(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/number.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/number.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a60844747c4ca635ea6d667b404f50dce15b668d --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/number.test.ts @@ -0,0 +1,247 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +test("z.number() basic validation", () => { + const schema = z.number(); + expect(schema.parse(1234)).toEqual(1234); +}); + +test("NaN validation", () => { + const schema = z.number(); + expect(() => schema.parse(Number.NaN)).toThrow(); +}); + +test("Infinity validation", () => { + const schema = z.number(); + expect(schema.safeParse(Number.POSITIVE_INFINITY)).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "number", + "code": "invalid_type", + "received": "Infinity", + "path": [], + "message": "Invalid input: expected number, received number" + } + ]], + "success": false, + } + `); + expect(schema.safeParse(Number.NEGATIVE_INFINITY)).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "number", + "code": "invalid_type", + "received": "Infinity", + "path": [], + "message": "Invalid input: expected number, received number" + } + ]], + "success": false, + } + `); +}); + +test(".gt() validation", () => { + const schema = z.number().gt(0).gt(5); + expect(schema.parse(6)).toEqual(6); + expect(() => schema.parse(5)).toThrow(); +}); + +test(".gte() validation", () => { + const schema = z.number().gt(0).gte(1).gte(5); + expect(schema.parse(5)).toEqual(5); + expect(() => schema.parse(4)).toThrow(); +}); + +test(".min() validation", () => { + const schema = z.number().min(0).min(5); + expect(schema.parse(5)).toEqual(5); + expect(() => schema.parse(4)).toThrow(); +}); + +test(".lt() validation", () => { + const schema = z.number().lte(10).lt(5); + expect(schema.parse(4)).toEqual(4); + expect(() => schema.parse(5)).toThrow(); +}); + +test(".lte() validation", () => { + const schema = z.number().lte(10).lte(5); + expect(schema.parse(5)).toEqual(5); + expect(() => schema.parse(6)).toThrow(); +}); + +test(".max() validation", () => { + const schema = z.number().max(10).max(5); + expect(schema.parse(5)).toEqual(5); + expect(() => schema.parse(6)).toThrow(); +}); + +test(".int() validation", () => { + const schema = z.number().int(); + expect(schema.parse(4)).toEqual(4); + expect(() => schema.parse(3.14)).toThrow(); +}); + +test(".positive() validation", () => { + const schema = z.number().positive(); + expect(schema.parse(1)).toEqual(1); + expect(() => schema.parse(0)).toThrow(); + expect(() => schema.parse(-1)).toThrow(); +}); + +test(".negative() validation", () => { + const schema = z.number().negative(); + expect(schema.parse(-1)).toEqual(-1); + expect(() => schema.parse(0)).toThrow(); + expect(() => schema.parse(1)).toThrow(); +}); + +test(".nonpositive() validation", () => { + const schema = z.number().nonpositive(); + expect(schema.parse(0)).toEqual(0); + expect(schema.parse(-1)).toEqual(-1); + expect(() => schema.parse(1)).toThrow(); +}); + +test(".nonnegative() validation", () => { + const schema = z.number().nonnegative(); + expect(schema.parse(0)).toEqual(0); + expect(schema.parse(1)).toEqual(1); + expect(() => schema.parse(-1)).toThrow(); +}); + +test(".multipleOf() with positive divisor", () => { + const schema = z.number().multipleOf(5); + expect(schema.parse(15)).toEqual(15); + expect(schema.parse(-15)).toEqual(-15); + expect(() => schema.parse(7.5)).toThrow(); + expect(() => schema.parse(-7.5)).toThrow(); +}); + +test(".multipleOf() with negative divisor", () => { + const schema = z.number().multipleOf(-5); + expect(schema.parse(-15)).toEqual(-15); + expect(schema.parse(15)).toEqual(15); + expect(() => schema.parse(-7.5)).toThrow(); + expect(() => schema.parse(7.5)).toThrow(); +}); + +test(".step() validation", () => { + const schemaPointOne = z.number().step(0.1); + const schemaPointZeroZeroZeroOne = z.number().step(0.0001); + const schemaSixPointFour = z.number().step(6.4); + + expect(schemaPointOne.parse(6)).toEqual(6); + expect(schemaPointOne.parse(6.1)).toEqual(6.1); + expect(schemaSixPointFour.parse(12.8)).toEqual(12.8); + expect(schemaPointZeroZeroZeroOne.parse(3.01)).toEqual(3.01); + expect(() => schemaPointOne.parse(6.11)).toThrow(); + expect(() => schemaPointOne.parse(6.1000000001)).toThrow(); + expect(() => schemaSixPointFour.parse(6.41)).toThrow(); +}); + +test(".finite() validation", () => { + const schema = z.number().finite(); + expect(schema.parse(123)).toEqual(123); + expect(schema.safeParse(Number.POSITIVE_INFINITY)).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "number", + "code": "invalid_type", + "received": "Infinity", + "path": [], + "message": "Invalid input: expected number, received number" + } + ]], + "success": false, + } + `); + expect(schema.safeParse(Number.NEGATIVE_INFINITY)).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "number", + "code": "invalid_type", + "received": "Infinity", + "path": [], + "message": "Invalid input: expected number, received number" + } + ]], + "success": false, + } + `); +}); + +test(".safe() validation", () => { + const schema = z.number().safe(); + expect(schema.parse(Number.MIN_SAFE_INTEGER)).toEqual(Number.MIN_SAFE_INTEGER); + expect(schema.parse(Number.MAX_SAFE_INTEGER)).toEqual(Number.MAX_SAFE_INTEGER); + expect(() => schema.parse(Number.MIN_SAFE_INTEGER - 1)).toThrow(); + expect(() => schema.parse(Number.MAX_SAFE_INTEGER + 1)).toThrow(); +}); + +test("min value getters", () => { + expect(z.number().minValue).toBeNull; + expect(z.number().lt(5).minValue).toBeNull; + expect(z.number().lte(5).minValue).toBeNull; + expect(z.number().max(5).minValue).toBeNull; + expect(z.number().negative().minValue).toBeNull; + expect(z.number().nonpositive().minValue).toBeNull; + expect(z.number().int().minValue).toBeNull; + expect(z.number().multipleOf(5).minValue).toBeNull; + expect(z.number().finite().minValue).toBeNull; + expect(z.number().gt(5).minValue).toEqual(5); + expect(z.number().gte(5).minValue).toEqual(5); + expect(z.number().min(5).minValue).toEqual(5); + expect(z.number().min(5).min(10).minValue).toEqual(10); + expect(z.number().positive().minValue).toEqual(0); + expect(z.number().nonnegative().minValue).toEqual(0); + expect(z.number().safe().minValue).toEqual(Number.MIN_SAFE_INTEGER); +}); + +test("max value getters", () => { + expect(z.number().maxValue).toBeNull; + expect(z.number().gt(5).maxValue).toBeNull; + expect(z.number().gte(5).maxValue).toBeNull; + expect(z.number().min(5).maxValue).toBeNull; + expect(z.number().positive().maxValue).toBeNull; + expect(z.number().nonnegative().maxValue).toBeNull; + expect(z.number().int().minValue).toBeNull; + expect(z.number().multipleOf(5).minValue).toBeNull; + expect(z.number().finite().minValue).toBeNull; + expect(z.number().lt(5).maxValue).toEqual(5); + expect(z.number().lte(5).maxValue).toEqual(5); + expect(z.number().max(5).maxValue).toEqual(5); + expect(z.number().max(5).max(1).maxValue).toEqual(1); + expect(z.number().negative().maxValue).toEqual(0); + expect(z.number().nonpositive().maxValue).toEqual(0); + expect(z.number().safe().maxValue).toEqual(Number.MAX_SAFE_INTEGER); +}); + +test("int getter", () => { + expect(z.number().isInt).toEqual(false); + expect(z.number().int().isInt).toEqual(true); + expect(z.number().safe().isInt).toEqual(true); + expect(z.number().multipleOf(5).isInt).toEqual(true); +}); + +/** In Zod 4, number schemas don't accept infinite values. */ +test("finite getter", () => { + expect(z.number().isFinite).toEqual(true); +}); + +test("string format methods", () => { + const a = z.int32().min(5); + expect(a.parse(6)).toEqual(6); + expect(() => a.parse(1)).toThrow(); +}); + +test("error customization", () => { + z.number().gte(5, { error: (iss) => "Min: " + iss.minimum.valueOf() }); + z.number().lte(5, { error: (iss) => "Max: " + iss.maximum.valueOf() }); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/object.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/object.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c97a2a927693461b0d5d5b1281b9ab7de868bb21 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/object.test.ts @@ -0,0 +1,563 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; +import * as core from "zod/v4/core"; + +const Test = z.object({ + f1: z.number(), + f2: z.string().optional(), + f3: z.string().nullable(), + f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })), +}); + +test("object type inference", () => { + type TestType = { + f1: number; + f2?: string | undefined; + f3: string | null; + f4: { t: string | boolean }[]; + }; + + expectTypeOf>().toEqualTypeOf(); +}); + +test("unknown throw", () => { + const asdf: unknown = 35; + expect(() => Test.parse(asdf)).toThrow(); +}); + +test("shape() should return schema of particular key", () => { + const f1Schema = Test.shape.f1; + const f2Schema = Test.shape.f2; + const f3Schema = Test.shape.f3; + const f4Schema = Test.shape.f4; + + expect(f1Schema).toBeInstanceOf(z.ZodNumber); + expect(f2Schema).toBeInstanceOf(z.ZodOptional); + expect(f3Schema).toBeInstanceOf(z.ZodNullable); + expect(f4Schema).toBeInstanceOf(z.ZodArray); +}); + +test("correct parsing", () => { + Test.parse({ + f1: 12, + f2: "string", + f3: "string", + f4: [ + { + t: "string", + }, + ], + }); + + Test.parse({ + f1: 12, + f3: null, + f4: [ + { + t: false, + }, + ], + }); +}); + +test("nonstrict by default", () => { + z.object({ points: z.number() }).parse({ + points: 2314, + unknown: "asdf", + }); +}); + +test("parse optional keys ", () => { + const schema = z.object({ + a: z.string().optional(), + }); + expect(schema.parse({ a: "asdf" })).toEqual({ a: "asdf" }); +}); + +test("empty object", () => { + const schema = z.object({}); + expect(schema.parse({})).toEqual({}); + expect(schema.parse({ name: "asdf" })).toEqual({}); + expect(schema.safeParse(null).success).toEqual(false); + expect(schema.safeParse("asdf").success).toEqual(false); + expectTypeOf>().toEqualTypeOf>(); +}); + +const data = { + points: 2314, + unknown: "asdf", +}; + +test("strip by default", () => { + const val = z.object({ points: z.number() }).parse(data); + expect(val).toEqual({ points: 2314 }); +}); + +test("unknownkeys override", () => { + const val = z.object({ points: z.number() }).strict().passthrough().strip().passthrough().parse(data); + + expect(val).toEqual(data); +}); + +test("passthrough unknown", () => { + const val = z.object({ points: z.number() }).passthrough().parse(data); + + expect(val).toEqual(data); +}); + +test("strip unknown", () => { + const val = z.object({ points: z.number() }).strip().parse(data); + + expect(val).toEqual({ points: 2314 }); +}); + +test("strict", () => { + const val = z.object({ points: z.number() }).strict().safeParse(data); + + expect(val.success).toEqual(false); +}); + +test("catchall inference", () => { + const o1 = z + .object({ + first: z.string(), + }) + .catchall(z.number()); + + const d1 = o1.parse({ first: "asdf", num: 1243 }); + // expectTypeOf<(typeof d1)["asdf"]>().toEqualTypeOf(); + expectTypeOf<(typeof d1)["first"]>().toEqualTypeOf(); +}); + +test("catchall overrides strict", () => { + const o1 = z.object({ first: z.string().optional() }).strict().catchall(z.number()); + + // should run fine + // setting a catchall overrides the unknownKeys behavior + o1.parse({ + asdf: 1234, + }); + + // should only run catchall validation + // against unknown keys + o1.parse({ + first: "asdf", + asdf: 1234, + }); +}); + +test("catchall overrides strict", () => { + const o1 = z + .object({ + first: z.string(), + }) + .strict() + .catchall(z.number()); + + // should run fine + // setting a catchall overrides the unknownKeys behavior + o1.parse({ + first: "asdf", + asdf: 1234, + }); +}); + +test("optional keys are unset", async () => { + const SNamedEntity = z.object({ + id: z.string(), + set: z.string().optional(), + unset: z.string().optional(), + }); + const result = await SNamedEntity.parse({ + id: "asdf", + set: undefined, + }); + expect(Object.keys(result)).toEqual(["id", "set"]); +}); + +test("catchall parsing", async () => { + const result = z.object({ name: z.string() }).catchall(z.number()).parse({ name: "Foo", validExtraKey: 61 }); + + expect(result).toEqual({ name: "Foo", validExtraKey: 61 }); + + const result2 = z + .object({ name: z.string() }) + .catchall(z.number()) + .safeParse({ name: "Foo", validExtraKey: 61, invalid: "asdf" }); + + expect(result2.success).toEqual(false); +}); + +test("nonexistent keys", async () => { + const Schema = z.union([z.object({ a: z.string() }), z.object({ b: z.number() })]); + const obj = { a: "A" }; + const result = await Schema.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21 + expect(result.success).toBe(true); +}); + +test("test async union", async () => { + const Schema2 = z.union([ + z.object({ + ty: z.string(), + }), + z.object({ + ty: z.number(), + }), + ]); + + const obj = { ty: "A" }; + const result = await Schema2.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21 + expect(result.success).toEqual(true); +}); + +test("test inferred merged type", async () => { + const asdf = z.object({ a: z.string() }).merge(z.object({ a: z.number() })); + type asdf = z.infer; + + expectTypeOf().toEqualTypeOf<{ a: number }>(); +}); + +test("inferred type with Record shape", () => { + type A = z.ZodObject>>; + expectTypeOf>().toEqualTypeOf>(); + expectTypeOf>().toEqualTypeOf>(); + + type B = z.ZodObject; + expectTypeOf>().toEqualTypeOf>(); + expectTypeOf>().toEqualTypeOf>(); +}); + +test("inferred merged object type with optional properties", async () => { + const Merged = z + .object({ a: z.string(), b: z.string().optional() }) + .merge(z.object({ a: z.string().optional(), b: z.string() })); + type Merged = z.infer; + expectTypeOf().toEqualTypeOf<{ a?: string; b: string }>(); + expectTypeOf().toEqualTypeOf<{ a?: string; b: string }>(); +}); + +test("inferred unioned object type with optional properties", async () => { + const Unioned = z.union([ + z.object({ a: z.string(), b: z.string().optional() }), + z.object({ a: z.string().optional(), b: z.string() }), + ]); + type Unioned = z.infer; + expectTypeOf().toEqualTypeOf<{ a: string; b?: string } | { a?: string; b: string }>(); +}); + +test("inferred enum type", async () => { + const Enum = z.object({ a: z.string(), b: z.string().optional() }).keyof(); + + expect(Enum.enum).toEqual({ + a: "a", + b: "b", + }); + + expect(Enum._zod.def.entries).toEqual({ + a: "a", + b: "b", + }); + type Enum = z.infer; + expectTypeOf().toEqualTypeOf<"a" | "b">(); +}); + +test("inferred partial object type with optional properties", async () => { + const Partial = z.object({ a: z.string(), b: z.string().optional() }).partial(); + type Partial = z.infer; + expectTypeOf().toEqualTypeOf<{ a?: string; b?: string }>(); +}); + +test("inferred picked object type with optional properties", async () => { + const Picked = z.object({ a: z.string(), b: z.string().optional() }).pick({ b: true }); + type Picked = z.infer; + expectTypeOf().toEqualTypeOf<{ b?: string }>(); +}); + +test("inferred type for unknown/any keys", () => { + const myType = z.object({ + anyOptional: z.any().optional(), + anyRequired: z.any(), + unknownOptional: z.unknown().optional(), + unknownRequired: z.unknown(), + }); + type myType = z.infer; + expectTypeOf().toEqualTypeOf<{ + anyOptional?: any; + anyRequired: any; + unknownOptional?: unknown; + unknownRequired: unknown; + }>(); +}); + +test("strictObject", async () => { + const strictObj = z.strictObject({ + name: z.string(), + }); + + const syncResult = strictObj.safeParse({ name: "asdf", unexpected: 13 }); + expect(syncResult.success).toEqual(false); + + const asyncResult = await strictObj.spa({ name: "asdf", unexpected: 13 }); + expect(asyncResult.success).toEqual(false); +}); + +test("object with refine", async () => { + const schema = z + .object({ + a: z.string().default("foo"), + b: z.number(), + }) + .refine(() => true); + expect(schema.parse({ b: 5 })).toEqual({ b: 5, a: "foo" }); + const result = await schema.parseAsync({ b: 5 }); + expect(result).toEqual({ b: 5, a: "foo" }); +}); + +test("intersection of object with date", async () => { + const schema = z.object({ + a: z.date(), + }); + expect(z.intersection(schema, schema).parse({ a: new Date(1637353595983) })).toEqual({ + a: new Date(1637353595983), + }); + const result = await schema.parseAsync({ a: new Date(1637353595983) }); + expect(result).toEqual({ a: new Date(1637353595983) }); +}); + +test("intersection of object with refine with date", async () => { + const schema = z + .object({ + a: z.date(), + }) + .refine(() => true); + expect(z.intersection(schema, schema).parse({ a: new Date(1637353595983) })).toEqual({ + a: new Date(1637353595983), + }); + const result = await schema.parseAsync({ a: new Date(1637353595983) }); + expect(result).toEqual({ a: new Date(1637353595983) }); +}); + +test("constructor key", () => { + const person = z + .object({ + name: z.string(), + }) + .strict(); + + expect(() => + person.parse({ + name: "bob dylan", + constructor: 61, + }) + ).toThrow(); +}); + +test("constructor key", () => { + const Example = z.object({ + prop: z.string(), + opt: z.number().optional(), + arr: z.string().array(), + }); + + type Example = z.infer; + expectTypeOf().toEqualTypeOf<"prop" | "opt" | "arr">(); +}); + +test("catchall", () => { + const a = z.object({}); + expect(a._zod.def.catchall).toBeUndefined(); + + const b = z.strictObject({}); + expect(b._zod.def.catchall).toBeInstanceOf(core.$ZodNever); + + const c = z.looseObject({}); + expect(c._zod.def.catchall).toBeInstanceOf(core.$ZodUnknown); + + const d = z.object({}).catchall(z.number()); + expect(d._zod.def.catchall).toBeInstanceOf(core.$ZodNumber); +}); + +test("unknownkeys merging", () => { + // This one is "strict" + const a = z.looseObject({ + a: z.string(), + }); + + const b = z.strictObject({ b: z.string() }); + + // incoming object overrides + const c = a.merge(b); + expect(c._zod.def.catchall).toBeInstanceOf(core.$ZodNever); +}); + +const personToExtend = z.object({ + firstName: z.string(), + lastName: z.string(), +}); + +test("extend() should return schema with new key", () => { + const PersonWithNickname = personToExtend.extend({ nickName: z.string() }); + type PersonWithNickname = z.infer; + + const expected = { firstName: "f", nickName: "n", lastName: "l" }; + const actual = PersonWithNickname.parse(expected); + + expect(actual).toEqual(expected); + expectTypeOf().toEqualTypeOf<"firstName" | "lastName" | "nickName">(); + expectTypeOf().toEqualTypeOf<{ firstName: string; lastName: string; nickName: string }>(); +}); + +test("extend() should have power to override existing key", () => { + const PersonWithNumberAsLastName = personToExtend.extend({ + lastName: z.number(), + }); + type PersonWithNumberAsLastName = z.infer; + + const expected = { firstName: "f", lastName: 42 }; + const actual = PersonWithNumberAsLastName.parse(expected); + + expect(actual).toEqual(expected); + expectTypeOf().toEqualTypeOf<{ firstName: string; lastName: number }>(); +}); + +test("passthrough index signature", () => { + const a = z.object({ a: z.string() }); + type a = z.infer; + expectTypeOf().toEqualTypeOf<{ a: string }>(); + const b = a.passthrough(); + type b = z.infer; + expectTypeOf().toEqualTypeOf<{ a: string; [k: string]: unknown }>(); +}); + +// test("xor", () => { +// type Without = { [P in Exclude]?: never }; +// type XOR = T extends object ? (U extends object ? (Without & U) | (Without & T) : U) : T; + +// type A = { name: string; a: number }; +// type B = { name: string; b: number }; +// type C = XOR; +// type Outer = { data: C }; +// const Outer = z.object({ +// data: z.union([z.object({ name: z.string(), a: z.number() }), z.object({ name: z.string(), b: z.number() })]), +// }) satisfies z.ZodType; +// }); + +test("assignability", () => { + z.object({ a: z.string() }) satisfies z.ZodObject<{ a: z.ZodString }>; + z.object({ a: z.string() }).catchall(z.number()) satisfies z.ZodObject<{ a: z.ZodString }>; + z.object({ a: z.string() }).strict() satisfies z.ZodObject; + z.object({}) satisfies z.ZodObject; + + z.looseObject({ name: z.string() }) satisfies z.ZodObject< + { + name: z.ZodString; + }, + z.core.$loose + >; + z.looseObject({ name: z.string() }) satisfies z.ZodObject<{ + name: z.ZodString; + }>; + z.strictObject({ name: z.string() }) satisfies z.ZodObject< + { + name: z.ZodString; + }, + z.core.$loose + >; + z.strictObject({ name: z.string() }) satisfies z.ZodObject< + { + name: z.ZodString; + }, + z.core.$strict + >; + z.object({ name: z.string() }) satisfies z.ZodObject<{ + name: z.ZodString; + }>; + z.object({ + a: z.string(), + b: z.number(), + c: z.boolean(), + }) satisfies z.core.$ZodObject; +}); + +test("null prototype", () => { + const schema = z.object({ a: z.string() }); + const obj = Object.create(null); + obj.a = "foo"; + expect(schema.parse(obj)).toEqual({ a: "foo" }); +}); + +test("empty objects", () => { + const A = z.looseObject({}); + type Ain = z.input; + expectTypeOf().toEqualTypeOf>(); + type Aout = z.output; + expectTypeOf().toEqualTypeOf>(); + + const B = z.object({}); + type Bout = z.output; + expectTypeOf().toEqualTypeOf>(); + type Bin = z.input; + expectTypeOf().toEqualTypeOf>(); + + const C = z.strictObject({}); + type Cout = z.output; + expectTypeOf().toEqualTypeOf>(); + type Cin = z.input; + expectTypeOf().toEqualTypeOf>(); +}); + +test("preserve key order", () => { + const schema = z.object({ + a: z.string().optional(), + b: z.string(), + }); + const r1 = schema.safeParse({ a: "asdf", b: "qwer" }); + const r2 = schema.safeParse({ a: "asdf", b: "qwer" }, { jitless: true }); + + expect(Object.keys(r1.data!)).toMatchInlineSnapshot(` + [ + "a", + "b", + ] + `); + expect(Object.keys(r1.data!)).toEqual(Object.keys(r2.data!)); +}); + +test("empty shape", () => { + const a = z.object({}); + + a.parse({}); + a.parse({}, { jitless: true }); + a.parse(Object.create(null)); + a.parse(Object.create(null), { jitless: true }); + + expect(() => a.parse([])).toThrow(); + expect(() => a.parse([], { jitless: true })).toThrow(); +}); + +test("zodtype assignability", () => { + // Does not error + z.object({ hello: z.string().optional() }) satisfies z.ZodType<{ hello?: string | undefined }>; + z.object({ hello: z.string() }) satisfies z.ZodType<{ hello?: string | undefined }>; + // @ts-expect-error + z.object({}) satisfies z.ZodType<{ hello: string | undefined }>; + // @ts-expect-error + z.object({ hello: z.string().optional() }) satisfies z.ZodType<{ hello: string | undefined }>; + // @ts-expect-error + z.object({ hello: z.string().optional() }) satisfies z.ZodType<{ hello: string }>; + // @ts-expect-error + z.object({ hello: z.number() }) satisfies z.ZodType<{ hello?: string | undefined }>; +}); + +test("index signature in shape", () => { + function makeZodObj(key: T) { + return z.looseObject({ + [key]: z.string(), + }); + } + + const schema = makeZodObj("foo"); + type schema = z.infer; + + expectTypeOf().toEqualTypeOf>(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/optional.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/optional.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..87de0274de8caaea68993a833424f94f90e54b60 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/optional.test.ts @@ -0,0 +1,123 @@ +// @ts-ignore TS6133 +import { expect, expectTypeOf, test } from "vitest"; + +import * as z from "zod/v4"; + +test(".optional()", () => { + const schema = z.string().optional(); + expect(schema.parse("adsf")).toEqual("adsf"); + expect(schema.parse(undefined)).toEqual(undefined); + expect(schema.safeParse(null).success).toEqual(false); + + expectTypeOf().toEqualTypeOf(); +}); + +test("unwrap", () => { + const unwrapped = z.string().optional().unwrap(); + expect(unwrapped).toBeInstanceOf(z.ZodString); +}); + +test("optionality", () => { + const a = z.string(); + expect(a._zod.optin).toEqual(undefined); + expect(a._zod.optout).toEqual(undefined); + + const b = z.string().optional(); + expect(b._zod.optin).toEqual("optional"); + expect(b._zod.optout).toEqual("optional"); + + const c = z.string().default("asdf"); + expect(c._zod.optin).toEqual("optional"); + expect(c._zod.optout).toEqual(undefined); + + const d = z.string().optional().nullable(); + expect(d._zod.optin).toEqual("optional"); + expect(d._zod.optout).toEqual("optional"); + + const e = z.string().default("asdf").nullable(); + expect(e._zod.optin).toEqual("optional"); + expect(e._zod.optout).toEqual(undefined); + + // z.undefined should NOT be optional + const f = z.undefined(); + expect(f._zod.optin).toEqual("optional"); + expect(f._zod.optout).toEqual("optional"); + expectTypeOf().toEqualTypeOf<"optional" | undefined>(); + expectTypeOf().toEqualTypeOf<"optional" | undefined>(); + + // z.union should be optional if any of the types are optional + const g = z.union([z.string(), z.undefined()]); + expect(g._zod.optin).toEqual("optional"); + expect(g._zod.optout).toEqual("optional"); + expectTypeOf().toEqualTypeOf<"optional" | undefined>(); + expectTypeOf().toEqualTypeOf<"optional" | undefined>(); + + const h = z.union([z.string(), z.optional(z.string())]); + expect(h._zod.optin).toEqual("optional"); + expect(h._zod.optout).toEqual("optional"); + expectTypeOf().toEqualTypeOf<"optional">(); + expectTypeOf().toEqualTypeOf<"optional">(); +}); + +test("pipe optionality", () => { + z.string().optional()._zod.optin; + const a = z.string().optional().pipe(z.string()); + expect(a._zod.optin).toEqual("optional"); + expect(a._zod.optout).toEqual(undefined); + expectTypeOf().toEqualTypeOf<"optional">(); + expectTypeOf().toEqualTypeOf<"optional" | undefined>(); + + const b = z + .string() + .transform((val) => (Math.random() ? val : undefined)) + .pipe(z.string().optional()); + expect(b._zod.optin).toEqual(undefined); + expect(b._zod.optout).toEqual("optional"); + expectTypeOf().toEqualTypeOf<"optional" | undefined>(); + expectTypeOf().toEqualTypeOf<"optional">(); + + const c = z.string().default("asdf").pipe(z.string()); + expect(c._zod.optin).toEqual("optional"); + expect(c._zod.optout).toEqual(undefined); + + const d = z + .string() + .transform((val) => (Math.random() ? val : undefined)) + .pipe(z.string().default("asdf")); + expect(d._zod.optin).toEqual(undefined); + expect(d._zod.optout).toEqual(undefined); +}); + +test("pipe optionality inside objects", () => { + const schema = z.object({ + a: z.string().optional(), + b: z.string().optional().pipe(z.string()), + c: z.string().default("asdf").pipe(z.string()), + d: z + .string() + .transform((val) => (Math.random() ? val : undefined)) + .pipe(z.string().optional()), + e: z + .string() + .transform((val) => (Math.random() ? val : undefined)) + .pipe(z.string().default("asdf")), + }); + + type SchemaIn = z.input; + expectTypeOf().toEqualTypeOf<{ + a?: string | undefined; + b?: string | undefined; + c?: string | undefined; + d: string; + e: string; + }>(); + + type SchemaOut = z.output; + expectTypeOf().toEqualTypeOf<{ + a?: string | undefined; + b: string; + c: string; + d?: string | undefined; + e: string; + }>(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/partial.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/partial.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8739c935b400a7d40c48e34106bc9e5d25feb05 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/partial.test.ts @@ -0,0 +1,147 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +const nested = z.object({ + name: z.string(), + age: z.number(), + outer: z.object({ + inner: z.string(), + }), + array: z.array(z.object({ asdf: z.string() })), +}); + +test("shallow inference", () => { + const shallow = nested.partial(); + type shallow = z.infer; + + expectTypeOf().toEqualTypeOf<{ + name?: string | undefined; + age?: number | undefined; + outer?: { inner: string } | undefined; + array?: { asdf: string }[] | undefined; + }>(); +}); + +test("shallow partial parse", () => { + const shallow = nested.partial(); + shallow.parse({}); + shallow.parse({ + name: "asdf", + age: 23143, + }); +}); + +test("required", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + nullableField: z.number().nullable(), + nullishField: z.string().nullish(), + }); + + const requiredObject = object.required(); + expect(requiredObject.shape.name).toBeInstanceOf(z.ZodNonOptional); + expect(requiredObject.shape.name.unwrap()).toBeInstanceOf(z.ZodString); + expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNonOptional); + expect(requiredObject.shape.age.unwrap()).toBeInstanceOf(z.ZodOptional); + expect(requiredObject.shape.field).toBeInstanceOf(z.ZodNonOptional); + expect(requiredObject.shape.field.unwrap()).toBeInstanceOf(z.ZodDefault); + expect(requiredObject.shape.nullableField).toBeInstanceOf(z.ZodNonOptional); + expect(requiredObject.shape.nullableField.unwrap()).toBeInstanceOf(z.ZodNullable); + expect(requiredObject.shape.nullishField).toBeInstanceOf(z.ZodNonOptional); + expect(requiredObject.shape.nullishField.unwrap()).toBeInstanceOf(z.ZodOptional); + expect(requiredObject.shape.nullishField.unwrap().unwrap()).toBeInstanceOf(z.ZodNullable); +}); + +test("required inference", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + nullableField: z.number().nullable(), + nullishField: z.string().nullish(), + }); + + const requiredObject = object.required(); + + type required = z.infer; + type expected = { + name: string; + age: number; + field: string; + nullableField: number | null; + nullishField: string | null; + }; + expectTypeOf().toEqualTypeOf(); +}); + +test("required with mask", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string().optional(), + }); + + const requiredObject = object.required({ age: true }); + expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); + expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNonOptional); + expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); + expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional); +}); + +test("required with mask -- ignore falsy values", () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string().optional(), + }); + + // @ts-expect-error + const requiredObject = object.required({ age: true, country: false }); + expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); + expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNonOptional); + expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); + expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional); +}); + +test("partial with mask", async () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string(), + }); + + const masked = object.partial({ age: true, field: true, name: true }).strict(); + + expect(masked.shape.name).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.age).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.field).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.country).toBeInstanceOf(z.ZodString); + + masked.parse({ country: "US" }); + await masked.parseAsync({ country: "US" }); +}); + +test("partial with mask -- ignore falsy values", async () => { + const object = z.object({ + name: z.string(), + age: z.number().optional(), + field: z.string().optional().default("asdf"), + country: z.string(), + }); + + // @ts-expect-error + const masked = object.partial({ name: true, country: false }).strict(); + + expect(masked.shape.name).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.age).toBeInstanceOf(z.ZodOptional); + expect(masked.shape.field).toBeInstanceOf(z.ZodDefault); + expect(masked.shape.country).toBeInstanceOf(z.ZodString); + + masked.parse({ country: "US" }); + await masked.parseAsync({ country: "US" }); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/pickomit.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/pickomit.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7627d4b3af16eef883cab932dc0d4871c1be2bdd --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/pickomit.test.ts @@ -0,0 +1,127 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +const fish = z.object({ + name: z.string(), + age: z.number(), + nested: z.object({}), +}); + +test("pick type inference", () => { + const nameonlyFish = fish.pick({ name: true }); + type nameonlyFish = z.infer; + expectTypeOf().toEqualTypeOf<{ name: string }>(); +}); + +test("pick parse - success", () => { + const nameonlyFish = fish.pick({ name: true }); + nameonlyFish.parse({ name: "bob" }); + + // @ts-expect-error checking runtime picks `name` only. + const anotherNameonlyFish = fish.pick({ name: true, age: false }); + anotherNameonlyFish.parse({ name: "bob" }); +}); + +test("pick parse - fail", () => { + fish.pick({ name: true }).parse({ name: "12" } as any); + fish.pick({ name: true }).parse({ name: "bob", age: 12 } as any); + fish.pick({ age: true }).parse({ age: 12 } as any); + + const nameonlyFish = fish.pick({ name: true }).strict(); + const bad1 = () => nameonlyFish.parse({ name: 12 } as any); + const bad2 = () => nameonlyFish.parse({ name: "bob", age: 12 } as any); + const bad3 = () => nameonlyFish.parse({ age: 12 } as any); + + // @ts-expect-error checking runtime picks `name` only. + const anotherNameonlyFish = fish.pick({ name: true, age: false }).strict(); + const bad4 = () => anotherNameonlyFish.parse({ name: "bob", age: 12 } as any); + + expect(bad1).toThrow(); + expect(bad2).toThrow(); + expect(bad3).toThrow(); + expect(bad4).toThrow(); +}); + +test("pick - remove optional", () => { + const schema = z.object({ a: z.string(), b: z.string().optional() }); + expect("a" in schema._zod.def.shape).toEqual(true); + expect("b" in schema._zod.def.shape!).toEqual(true); + const picked = schema.pick({ a: true }); + expect("a" in picked._zod.def.shape).toEqual(true); + expect("b" in picked._zod.def.shape!).toEqual(false); +}); + +test("omit type inference", () => { + const nonameFish = fish.omit({ name: true }); + type nonameFish = z.infer; + + expectTypeOf().toEqualTypeOf<{ age: number; nested: Record }>(); +}); + +test("omit parse - success", () => { + const nonameFish = fish.omit({ name: true }); + nonameFish.parse({ age: 12, nested: {} }); + + // @ts-expect-error checking runtime omits `name` only. + const anotherNonameFish = fish.omit({ name: true, age: false }); + anotherNonameFish.parse({ age: 12, nested: {} }); +}); + +test("omit parse - fail", () => { + const nonameFish = fish.omit({ name: true }); + const bad1 = () => nonameFish.parse({ name: 12 } as any); + const bad2 = () => nonameFish.parse({ age: 12 } as any); + const bad3 = () => nonameFish.parse({} as any); + + // @ts-expect-error checking runtime omits `name` only. + const anotherNonameFish = fish.omit({ name: true, age: false }); + const bad4 = () => anotherNonameFish.parse({ nested: {} } as any); + + expect(bad1).toThrow(); + expect(bad2).toThrow(); + expect(bad3).toThrow(); + expect(bad4).toThrow(); +}); + +test("omit - remove optional", () => { + const schema = z.object({ a: z.string(), b: z.string().optional() }); + expect("a" in schema._zod.def.shape).toEqual(true); + const omitted = schema.omit({ a: true }); + expect("a" in omitted._zod.def.shape).toEqual(false); +}); + +test("nonstrict inference", () => { + const laxfish = fish.pick({ name: true }).catchall(z.any()); + type laxfish = z.infer; + expectTypeOf().toEqualTypeOf<{ name: string; [k: string]: any }>(); +}); + +test("nonstrict parsing - pass", () => { + const laxfish = fish.passthrough().pick({ name: true }); + laxfish.parse({ name: "asdf", whatever: "asdf" }); + laxfish.parse({ name: "asdf", age: 12, nested: {} }); +}); + +test("nonstrict parsing - fail", () => { + const laxfish = fish.passthrough().pick({ name: true }); + const bad = () => laxfish.parse({ whatever: "asdf" } as any); + expect(bad).toThrow(); +}); + +test("pick/omit/required/partial - do not allow unknown keys", () => { + const schema = z.object({ + name: z.string(), + age: z.number(), + }); + + expect(() => schema.pick({ name: true, asdf: true })).toThrow(); + + // @ts-expect-error + expect(() => schema.pick({ $unknown: true })).toThrow(); + // @ts-expect-error + expect(() => schema.omit({ $unknown: true })).toThrow(); + // @ts-expect-error + expect(() => schema.required({ $unknown: true })).toThrow(); + // @ts-expect-error + expect(() => schema.partial({ $unknown: true })).toThrow(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/pipe.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/pipe.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bdbc7c82cd4878855c040bd4ca0d0ef50ceba4d --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/pipe.test.ts @@ -0,0 +1,81 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +test("string to number pipe", () => { + const schema = z.string().transform(Number).pipe(z.number()); + expect(schema.parse("1234")).toEqual(1234); +}); + +test("string to number pipe async", async () => { + const schema = z + .string() + .transform(async (val) => Number(val)) + .pipe(z.number()); + expect(await schema.parseAsync("1234")).toEqual(1234); +}); + +test("string with default fallback", () => { + const stringWithDefault = z + .pipe( + z.transform((v) => (v === "none" ? undefined : v)), + z.string() + ) + .catch("default"); + + expect(stringWithDefault.parse("ok")).toBe("ok"); + expect(stringWithDefault.parse(undefined)).toBe("default"); + expect(stringWithDefault.parse("none")).toBe("default"); + expect(stringWithDefault.parse(15)).toBe("default"); +}); + +test("continue on non-fatal errors", () => { + const schema = z + .string() + .refine((c) => c === "1234", "A") + .transform((val) => Number(val)) + .refine((c) => c === 1234, "B"); + + schema.parse("1234"); + + expect(schema.safeParse("4321")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "path": [], + "message": "A" + }, + { + "code": "custom", + "path": [], + "message": "B" + } + ]], + "success": false, + } + `); +}); + +test("break on fatal errors", () => { + const schema = z + .string() + .refine((c) => c === "1234", { message: "A", abort: true }) + .transform((val) => Number(val)) + .refine((c) => c === 1234, "B"); + + schema.parse("1234"); + + expect(schema.safeParse("4321")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "path": [], + "message": "A" + } + ]], + "success": false, + } + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/prefault.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/prefault.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..72178ab6031df02d0feb00548a65b878981597c0 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/prefault.test.ts @@ -0,0 +1,37 @@ +import { expect, expectTypeOf, test } from "vitest"; +import { z } from "zod/v4"; + +test("basic prefault", () => { + const a = z.prefault(z.string().trim(), " default "); + expect(a).toBeInstanceOf(z.ZodPrefault); + expect(a.parse(" asdf ")).toEqual("asdf"); + expect(a.parse(undefined)).toEqual("default"); + + type inp = z.input; + expectTypeOf().toEqualTypeOf(); + type out = z.output; + expectTypeOf().toEqualTypeOf(); +}); + +test("prefault inside object", () => { + // test optinality + const a = z.object({ + name: z.string().optional(), + age: z.number().default(1234), + email: z.string().prefault("1234"), + }); + + type inp = z.input; + expectTypeOf().toEqualTypeOf<{ + name?: string | undefined; + age?: number | undefined; + email?: string | undefined; + }>(); + + type out = z.output; + expectTypeOf().toEqualTypeOf<{ + name?: string | undefined; + age: number; + email: string; + }>(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/preprocess.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/preprocess.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d782df06296296e713518a2d95f06fcdfa4f1ef9 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/preprocess.test.ts @@ -0,0 +1,298 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("preprocess", () => { + const schema = z.preprocess((data) => [data], z.string().array()); + const value = schema.parse("asdf"); + expect(value).toEqual(["asdf"]); + expectTypeOf<(typeof schema)["_input"]>().toEqualTypeOf(); +}); + +test("async preprocess", async () => { + const schema = z.preprocess(async (data) => { + return [data]; + }, z.string().array()); + const value = await schema.safeParseAsync("asdf"); + expect(value.data).toEqual(["asdf"]); + expect(value).toMatchInlineSnapshot(` + { + "data": [ + "asdf", + ], + "success": true, + } + `); +}); + +test("ctx.addIssue accepts string", () => { + const schema = z.preprocess((_, ctx) => { + ctx.addIssue("bad stuff"); + }, z.string()); + const result = schema.safeParse("asdf"); + expect(result.error!.issues).toHaveLength(1); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "message": "bad stuff", + "code": "custom", + "path": [] + } + ]], + "success": false, + } + `); +}); + +test("preprocess ctx.addIssue with parse", () => { + const a = z.preprocess((data, ctx) => { + ctx.addIssue({ + input: data, + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + return data; + }, z.string()); + + const result = a.safeParse("asdf"); + + // expect(result.error!.toJSON()).toContain("not one of our allowed strings"); + + expect(result.error!.issues).toHaveLength(1); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "message": "asdf is not one of our allowed strings", + "path": [] + } + ]], + "success": false, + } + `); +}); + +test("preprocess ctx.addIssue non-fatal by default", () => { + const schema = z.preprocess((data, ctx) => { + ctx.addIssue({ + code: "custom", + message: `custom error`, + }); + return data; + }, z.string()); + const result = schema.safeParse(1234); + + expect(result.error!.issues).toHaveLength(2); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "message": "custom error", + "path": [] + }, + { + "expected": "string", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected string, received number" + } + ]], + "success": false, + } + `); +}); + +test("preprocess ctx.addIssue fatal true", () => { + const schema = z.preprocess((data, ctx) => { + ctx.addIssue({ + input: data, + code: "custom", + origin: "custom", + message: `custom error`, + fatal: true, + }); + return data; + }, z.string()); + + const result = schema.safeParse(1234); + + expect(result.error!.issues).toHaveLength(1); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "origin": "custom", + "message": "custom error", + "fatal": true, + "path": [] + } + ]], + "success": false, + } + `); +}); + +test("async preprocess ctx.addIssue with parseAsync", async () => { + const schema = z.preprocess(async (data, ctx) => { + ctx.addIssue({ + input: data, + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + return data; + }, z.string()); + + const result = await schema.safeParseAsync("asdf"); + + expect(result.error!.issues).toHaveLength(1); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "message": "asdf is not one of our allowed strings", + "path": [] + } + ]], + "success": false, + } + `); +}); + +test("z.NEVER in preprocess", () => { + const foo = z.preprocess((val, ctx) => { + if (!val) { + ctx.addIssue({ input: val, code: "custom", message: "bad" }); + return z.NEVER; + } + return val; + }, z.number()); + + type foo = z.infer; + expectTypeOf().toEqualTypeOf(); + const result = foo.safeParse(undefined); + + expect(result.error!.issues).toHaveLength(2); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "message": "bad", + "path": [] + }, + { + "expected": "number", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected number, received object" + } + ]], + "success": false, + } + `); +}); + +test("preprocess as the second property of object", () => { + const schema = z.object({ + nonEmptyStr: z.string().min(1), + positiveNum: z.preprocess((v) => Number(v), z.number().positive()), + }); + const result = schema.safeParse({ + nonEmptyStr: "", + positiveNum: "", + }); + + expect(result.error!.issues).toHaveLength(2); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "origin": "string", + "code": "too_small", + "minimum": 1, + "inclusive": true, + "path": [ + "nonEmptyStr" + ], + "message": "Too small: expected string to have >=1 characters" + }, + { + "origin": "number", + "code": "too_small", + "minimum": 0, + "inclusive": false, + "path": [ + "positiveNum" + ], + "message": "Too small: expected number to be >0" + } + ]], + "success": false, + } + `); +}); + +test("preprocess validates with sibling errors", () => { + const schema = z.object({ + missing: z.string().refine(() => false), + preprocess: z.preprocess((data: any) => data?.trim(), z.string().regex(/ asdf/)), + }); + + const result = schema.safeParse({ preprocess: " asdf" }); + + expect(result.error!.issues).toHaveLength(2); + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + "missing" + ], + "message": "Invalid input: expected string, received undefined" + }, + { + "origin": "string", + "code": "invalid_format", + "format": "regex", + "pattern": "/ asdf/", + "path": [ + "preprocess" + ], + "message": "Invalid string: must match pattern / asdf/" + } + ]], + "success": false, + } + `); +}); + +test("perform transform with non-fatal issues", () => { + const A = z + .string() + .refine((_) => false) + .min(4) + .transform((val) => val.length) + .pipe(z.number()) + .refine((_) => false); + expect(A.safeParse("asdfasdf").error!.issues).toHaveLength(2); + expect(A.safeParse("asdfasdf").error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "message": "Invalid input" + }, + { + "code": "custom", + "path": [], + "message": "Invalid input" + } + ]] + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/primitive.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/primitive.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..756ddeb3548985a24ee3707659bcc84f957853d4 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/primitive.test.ts @@ -0,0 +1,175 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +const literalStringSchema = z.literal("asdf"); +const literalNumberSchema = z.literal(12); +const literalBooleanSchema = z.literal(true); +const literalBigIntSchema = z.literal(BigInt(42)); + +const stringSchema = z.string(); +const numberSchema = z.number(); +const bigintSchema = z.bigint(); +const booleanSchema = z.boolean(); +const dateSchema = z.date(); +const symbolSchema = z.symbol(); +const nullSchema = z.null(); +const undefinedSchema = z.undefined(); +const stringSchemaOptional = z.string().optional(); +const stringSchemaNullable = z.string().nullable(); +const numberSchemaOptional = z.number().optional(); +const numberSchemaNullable = z.number().nullable(); +const bigintSchemaOptional = z.bigint().optional(); +const bigintSchemaNullable = z.bigint().nullable(); +const booleanSchemaOptional = z.boolean().optional(); +const booleanSchemaNullable = z.boolean().nullable(); +const dateSchemaOptional = z.date().optional(); +const dateSchemaNullable = z.date().nullable(); +const symbolSchemaOptional = z.symbol().optional(); +const symbolSchemaNullable = z.symbol().nullable(); + +test("literal string schema", () => { + expect(literalStringSchema.parse("asdf")).toBe("asdf"); + expect(() => literalStringSchema.parse("not_asdf")).toThrow(); + expect(() => literalStringSchema.parse(123)).toThrow(); + expect(() => literalStringSchema.parse(true)).toThrow(); + expect(() => literalStringSchema.parse({})).toThrow(); +}); + +test("literal number schema", () => { + expect(literalNumberSchema.parse(12)).toBe(12); + expect(() => literalNumberSchema.parse(13)).toThrow(); + expect(() => literalNumberSchema.parse("foo")).toThrow(); + expect(() => literalNumberSchema.parse(true)).toThrow(); + expect(() => literalNumberSchema.parse({})).toThrow(); +}); + +test("literal boolean schema", () => { + expect(literalBooleanSchema.parse(true)).toBe(true); + expect(() => literalBooleanSchema.parse(false)).toThrow(); + expect(() => literalBooleanSchema.parse("asdf")).toThrow(); + expect(() => literalBooleanSchema.parse(123)).toThrow(); + expect(() => literalBooleanSchema.parse({})).toThrow(); +}); + +test("literal bigint schema", () => { + expect(literalBigIntSchema.parse(BigInt(42))).toBe(BigInt(42)); + expect(() => literalBigIntSchema.parse(BigInt(43))).toThrow(); + expect(() => literalBigIntSchema.parse("asdf")).toThrow(); + expect(() => literalBigIntSchema.parse(123)).toThrow(); + expect(() => literalBigIntSchema.parse({})).toThrow(); +}); + +test("string schema", () => { + stringSchema.parse("foo"); + expect(() => stringSchema.parse(Math.random())).toThrow(); + expect(() => stringSchema.parse(true)).toThrow(); + expect(() => stringSchema.parse(undefined)).toThrow(); + expect(() => stringSchema.parse(null)).toThrow(); +}); + +test("number schema", () => { + numberSchema.parse(Math.random()); + expect(() => numberSchema.parse("foo")).toThrow(); + expect(() => numberSchema.parse(BigInt(17))).toThrow(); + expect(() => numberSchema.parse(true)).toThrow(); + expect(() => numberSchema.parse(undefined)).toThrow(); + expect(() => numberSchema.parse(null)).toThrow(); +}); + +test("bigint schema", () => { + bigintSchema.parse(BigInt(17)); + expect(() => bigintSchema.parse("foo")).toThrow(); + expect(() => bigintSchema.parse(Math.random())).toThrow(); + expect(() => bigintSchema.parse(true)).toThrow(); + expect(() => bigintSchema.parse(undefined)).toThrow(); + expect(() => bigintSchema.parse(null)).toThrow(); +}); + +test("boolean schema", () => { + booleanSchema.parse(true); + expect(() => booleanSchema.parse("foo")).toThrow(); + expect(() => booleanSchema.parse(Math.random())).toThrow(); + expect(() => booleanSchema.parse(undefined)).toThrow(); + expect(() => booleanSchema.parse(null)).toThrow(); +}); + +test("date schema", async () => { + dateSchema.parse(new Date()); + expect(() => dateSchema.parse("foo")).toThrow(); + expect(() => dateSchema.parse(Math.random())).toThrow(); + expect(() => dateSchema.parse(true)).toThrow(); + expect(() => dateSchema.parse(undefined)).toThrow(); + expect(() => dateSchema.parse(null)).toThrow(); + expect(await dateSchema.safeParseAsync(new Date("invalid"))).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "date", + "code": "invalid_type", + "received": "Invalid Date", + "path": [], + "message": "Invalid input: expected date, received Date" + } + ]], + "success": false, + } + `); +}); + +test("symbol schema", () => { + symbolSchema.parse(Symbol("foo")); + expect(() => symbolSchema.parse("foo")).toThrow(); + expect(() => symbolSchema.parse(Math.random())).toThrow(); + expect(() => symbolSchema.parse(true)).toThrow(); + expect(() => symbolSchema.parse(new Date())).toThrow(); + expect(() => symbolSchema.parse(undefined)).toThrow(); + expect(() => symbolSchema.parse(null)).toThrow(); +}); + +test("undefined schema", () => { + undefinedSchema.parse(undefined); + expect(() => undefinedSchema.parse("foo")).toThrow(); + expect(() => undefinedSchema.parse(Math.random())).toThrow(); + expect(() => undefinedSchema.parse(true)).toThrow(); + expect(() => undefinedSchema.parse(null)).toThrow(); +}); + +test("null schema", () => { + nullSchema.parse(null); + expect(() => nullSchema.parse("foo")).toThrow(); + expect(() => nullSchema.parse(Math.random())).toThrow(); + expect(() => nullSchema.parse(true)).toThrow(); + expect(() => nullSchema.parse(undefined)).toThrow(); +}); + +test("primitive inference", () => { + expectTypeOf>().toEqualTypeOf<"asdf">(); + expectTypeOf>().toEqualTypeOf<12>(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); +}); + +test("get literal values", () => { + expect(literalStringSchema.values).toEqual(new Set(["asdf"])); + expect(literalStringSchema._zod.def.values).toEqual(["asdf"]); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/promise.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/promise.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b857a2b6401913eca8e021bc4c16597b8bf7afcc --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/promise.test.ts @@ -0,0 +1,81 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +const promSchema = z.promise( + z.object({ + name: z.string(), + age: z.number(), + }) +); + +test("promise inference", () => { + type promSchemaType = z.infer; + expectTypeOf().toEqualTypeOf<{ name: string; age: number }>(); +}); + +test("promise parsing success", async () => { + // expect(() => promSchema.parse(Promise.resolve({ name: "Bobby", age: 10 }))).toThrow(); + const pr = promSchema.parseAsync(Promise.resolve({ name: "Bobby", age: 10 })); + expect(pr).toBeInstanceOf(Promise); + const result = await pr; + expect(result).toMatchInlineSnapshot(` + { + "age": 10, + "name": "Bobby", + } + `); +}); + +test("promise parsing fail", async () => { + const bad = await promSchema.safeParseAsync(Promise.resolve({ name: "Bobby", age: "10" })); + expect(bad.success).toBe(false); + expect(bad.error).toBeInstanceOf(z.ZodError); +}); + +test("promise parsing fail 2", async () => { + const result = await promSchema.safeParseAsync(Promise.resolve({ name: "Bobby", age: "10" })); + expect(result.success).toBe(false); + expect(result.error).toBeInstanceOf(z.ZodError); +}); + +test("promise parsing fail", () => { + const bad = () => promSchema.parse({ then: () => {}, catch: {} }); + expect(bad).toThrow(); +}); + +test("sync promise parsing", () => { + expect(() => z.promise(z.string()).parse(Promise.resolve("asfd"))).toThrow(); +}); + +const asyncFunction = z.function({ + input: z.tuple([]), + output: promSchema, +}); + +test("async function pass", async () => { + const validatedFunction = asyncFunction.implementAsync(async () => { + return { name: "jimmy", age: 14 }; + }); + await expect(validatedFunction()).resolves.toEqual({ + name: "jimmy", + age: 14, + }); +}); + +test("async function fail", async () => { + const validatedFunction = asyncFunction.implementAsync(() => { + return Promise.resolve("asdf" as any); + }); + await expect(validatedFunction()).rejects.toBeInstanceOf(z.core.$ZodError); +}); + +test("async promise parsing", () => { + const res = z.promise(z.number()).parseAsync(Promise.resolve(12)); + expect(res).toBeInstanceOf(Promise); +}); + +test("resolves", () => { + const foo = z.literal("foo"); + const res = z.promise(foo); + expect(res.unwrap()).toEqual(foo); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/prototypes.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/prototypes.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..058bf6cb30da6580a7837aacb2e343a398e22819 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/prototypes.test.ts @@ -0,0 +1,23 @@ +import { expect, test } from "vitest"; +import * as z from "zod/v4"; + +declare module "zod/v4" { + interface ZodType { + /** @deprecated */ + _classic(): string; + } +} + +test("prototype extension", () => { + z.ZodType.prototype._classic = function () { + return "_classic"; + }; + + // should pass + const result = z.string()._classic(); + expect(result).toBe("_classic"); + // expectTypeOf().toEqualTypeOf(); + + // clean up + z.ZodType.prototype._classic = undefined; +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/readonly.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/readonly.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..99c692e9b5bd906992273248f92eaffd4c8cc7c7 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/readonly.test.ts @@ -0,0 +1,252 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +enum testEnum { + A = 0, + B = 1, +} + +test("flat inference", () => { + const readonlyString = z.string().readonly(); + const readonlyNumber = z.number().readonly(); + const readonlyNaN = z.nan().readonly(); + const readonlyBigInt = z.bigint().readonly(); + const readonlyBoolean = z.boolean().readonly(); + const readonlyDate = z.date().readonly(); + const readonlyUndefined = z.undefined().readonly(); + const readonlyNull = z.null().readonly(); + const readonlyAny = z.any().readonly(); + const readonlyUnknown = z.unknown().readonly(); + const readonlyVoid = z.void().readonly(); + const readonlyStringArray = z.array(z.string()).readonly(); + const readonlyTuple = z.tuple([z.string(), z.number()]).readonly(); + const readonlyMap = z.map(z.string(), z.date()).readonly(); + const readonlySet = z.set(z.string()).readonly(); + const readonlyStringRecord = z.record(z.string(), z.string()).readonly(); + const readonlyNumberRecord = z.record(z.string(), z.number()).readonly(); + const readonlyObject = z.object({ a: z.string(), 1: z.number() }).readonly(); + const readonlyEnum = z.nativeEnum(testEnum).readonly(); + const readonlyPromise = z.promise(z.string()).readonly(); + + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf>>(); + expectTypeOf().toEqualTypeOf>>(); + expectTypeOf().toEqualTypeOf<{ readonly a: string; readonly 1: number }>(); + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf(); +}); + +// test("deep inference", () => { +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[9]> +// >().toEqualTypeOf>(); +// expectTypeOf>().toEqualTypeOf(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[11]> +// >().toEqualTypeOf<(args_0: string, args_1: number, ...args_2: unknown[]) => unknown>(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[12]> +// >().toEqualTypeOf(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[13]> +// >().toEqualTypeOf(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[14]> +// >().toEqualTypeOf>(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[15]> +// >().toEqualTypeOf>>(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[16]> +// >().toEqualTypeOf>>(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[17]> +// >().toEqualTypeOf>>(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[18]> +// >().toEqualTypeOf<{ readonly a: string; readonly 1: number }>(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[19]> +// >().toEqualTypeOf>(); +// expectTypeOf< +// z.infer<(typeof deepReadonlySchemas_0)[20]> +// >().toEqualTypeOf>(); + +// expectTypeOf< +// z.infer +// >().toEqualTypeOf, +// { +// readonly a: { +// readonly [x: string]: readonly any[]; +// }; +// readonly b: { +// readonly c: { +// readonly d: { +// readonly e: { +// readonly f: { +// readonly g?: {}; +// }; +// }; +// }; +// }; +// }; +// } +// >>(); +// }); + +test("object freezing", async () => { + expect(Object.isFrozen(z.array(z.string()).readonly().parse(["a"]))).toBe(true); + expect(Object.isFrozen(z.tuple([z.string(), z.number()]).readonly().parse(["a", 1]))).toBe(true); + expect( + Object.isFrozen( + z + .map(z.string(), z.date()) + .readonly() + .parse(new Map([["a", new Date()]])) + ) + ).toBe(true); + + expect(Object.isFrozen(z.record(z.string(), z.string()).readonly().parse({ a: "b" }))).toBe(true); + expect(Object.isFrozen(z.record(z.string(), z.number()).readonly().parse({ a: 1 }))).toBe(true); + expect(Object.isFrozen(z.object({ a: z.string(), 1: z.number() }).readonly().parse({ a: "b", 1: 2 }))).toBe(true); + expect( + Object.isFrozen( + await z + .set(z.promise(z.string())) + .readonly() + .parseAsync(new Set([Promise.resolve("a")])) + ) + ).toBe(true); + expect(Object.isFrozen(await z.promise(z.string()).readonly().parseAsync(Promise.resolve("a")))).toBe(true); +}); + +test("async object freezing", async () => { + expect(Object.isFrozen(await z.array(z.string()).readonly().parseAsync(["a"]))).toBe(true); + expect(Object.isFrozen(await z.tuple([z.string(), z.number()]).readonly().parseAsync(["a", 1]))).toBe(true); + expect( + Object.isFrozen( + await z + .map(z.string(), z.date()) + .readonly() + .parseAsync(new Map([["a", new Date()]])) + ) + ).toBe(true); + expect( + Object.isFrozen( + await z + .set(z.promise(z.string())) + .readonly() + .parseAsync(new Set([Promise.resolve("a")])) + ) + ).toBe(true); + expect(Object.isFrozen(await z.record(z.string(), z.string()).readonly().parseAsync({ a: "b" }))).toBe(true); + expect(Object.isFrozen(await z.record(z.string(), z.number()).readonly().parseAsync({ a: 1 }))).toBe(true); + expect( + Object.isFrozen(await z.object({ a: z.string(), 1: z.number() }).readonly().parseAsync({ a: "b", 1: 2 })) + ).toBe(true); + expect(Object.isFrozen(await z.promise(z.string()).readonly().parseAsync(Promise.resolve("a")))).toBe(true); +}); + +test("readonly inference", () => { + const readonlyStringArray = z.string().array().readonly(); + const readonlyStringTuple = z.tuple([z.string()]).readonly(); + const deepReadonly = z.object({ a: z.string() }).readonly(); + + type readonlyStringArray = z.infer; + type readonlyStringTuple = z.infer; + type deepReadonly = z.infer; + + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf<{ readonly a: string }>(); +}); + +test("readonly parse", () => { + const schema = z.array(z.string()).readonly(); + const readonlyArray = ["a", "b", "c"] as const; + const mutableArray = ["a", "b", "c"]; + const result1 = schema.parse(readonlyArray); + const result2 = schema.parse(mutableArray); + expect(result1).toEqual(readonlyArray); + expect(result2).toEqual(mutableArray); +}); + +test("readonly parse with tuples", () => { + const schema = z.tuple([z.string(), z.number()]).readonly(); + schema.parse(["a", 1]); +}); + +test("readonly and the get method", () => { + const readonlyString = z.string().readonly(); + const readonlyNumber1 = z.number().readonly(); + const readonlyNumber2 = z.number().readonly(); + const readonlyBigInt = z.bigint().readonly(); + const readonlyBoolean = z.boolean().readonly(); + const readonlyDate = z.date().readonly(); + const readonlyUndefined = z.undefined().readonly(); + const readonlyNull = z.null().readonly(); + const readonlyAny = z.any().readonly(); + const readonlyUnknown = z.unknown().readonly(); + const readonlyVoid = z.void().readonly(); + // const readonlyFunction = z.function(z.tuple([z.string(), z.number()]), z.unknown()).readonly(); + const readonlyStringArray = z.string().array().readonly(); + const readonlyTuple = z.tuple([z.string(), z.number()]).readonly(); + + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf>(); + expectTypeOf>().toEqualTypeOf(); + // expectTypeOf>().toEqualTypeOf< + // (args_0: string, args_1: number, ...args_2: unknown[]) => unknown + // >(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + + expect(readonlyString.parse("asdf")).toEqual("asdf"); + expect(readonlyNumber1.parse(1234)).toEqual(1234); + expect(readonlyNumber2.parse(1234)).toEqual(1234); + const bigIntVal = BigInt(1); + expect(readonlyBigInt.parse(bigIntVal)).toEqual(bigIntVal); + expect(readonlyBoolean.parse(true)).toEqual(true); + const dateVal = new Date(); + expect(readonlyDate.parse(dateVal)).toEqual(dateVal); + expect(readonlyUndefined.parse(undefined)).toEqual(undefined); + expect(readonlyNull.parse(null)).toEqual(null); + expect(readonlyAny.parse("whatever")).toEqual("whatever"); + expect(readonlyUnknown.parse("whatever")).toEqual("whatever"); + expect(readonlyVoid.parse(undefined)).toEqual(undefined); + // expect(readonlyFunction.parse(() => void 0)).toEqual(() => void 0); + expect(readonlyStringArray.parse(["asdf"])).toEqual(["asdf"]); + expect(readonlyTuple.parse(["asdf", 1234])).toEqual(["asdf", 1234]); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/record.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/record.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ca7833570e0cb8a0db46795d11e44a7d159f391 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/record.test.ts @@ -0,0 +1,342 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("type inference", () => { + const booleanRecord = z.record(z.string(), z.boolean()); + type booleanRecord = typeof booleanRecord._output; + + const recordWithEnumKeys = z.record(z.enum(["Tuna", "Salmon"]), z.string()); + type recordWithEnumKeys = z.infer; + + const recordWithLiteralKey = z.record(z.literal(["Tuna", "Salmon"]), z.string()); + type recordWithLiteralKey = z.infer; + + const recordWithLiteralUnionKeys = z.record(z.union([z.literal("Tuna"), z.literal("Salmon")]), z.string()); + type recordWithLiteralUnionKeys = z.infer; + + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf>(); +}); + +test("enum exhaustiveness", () => { + const schema = z.record(z.enum(["Tuna", "Salmon"]), z.string()); + expect( + schema.parse({ + Tuna: "asdf", + Salmon: "asdf", + }) + ).toEqual({ + Tuna: "asdf", + Salmon: "asdf", + }); + + expect(schema.safeParse({ Tuna: "asdf", Salmon: "asdf", Trout: "asdf" })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "unrecognized_keys", + "keys": [ + "Trout" + ], + "path": [], + "message": "Unrecognized key: \\"Trout\\"" + } + ]], + "success": false, + } + `); + expect(schema.safeParse({ Tuna: "asdf" })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + "Salmon" + ], + "message": "Invalid input: expected string, received undefined" + } + ]], + "success": false, + } + `); +}); + +test("literal exhaustiveness", () => { + const schema = z.record(z.literal(["Tuna", "Salmon"]), z.string()); + schema.parse({ + Tuna: "asdf", + Salmon: "asdf", + }); + + expect(schema.safeParse({ Tuna: "asdf", Salmon: "asdf", Trout: "asdf" })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "unrecognized_keys", + "keys": [ + "Trout" + ], + "path": [], + "message": "Unrecognized key: \\"Trout\\"" + } + ]], + "success": false, + } + `); + expect(schema.safeParse({ Tuna: "asdf" })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + "Salmon" + ], + "message": "Invalid input: expected string, received undefined" + } + ]], + "success": false, + } + `); +}); + +test("pipe exhaustiveness", () => { + const schema = z.record(z.enum(["Tuna", "Salmon"]).pipe(z.any()), z.string()); + expect(schema.parse({ Tuna: "asdf", Salmon: "asdf" })).toEqual({ + Tuna: "asdf", + Salmon: "asdf", + }); + + expect(schema.safeParse({ Tuna: "asdf", Salmon: "asdf", Trout: "asdf" })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "unrecognized_keys", + "keys": [ + "Trout" + ], + "path": [], + "message": "Unrecognized key: \\"Trout\\"" + } + ]], + "success": false, + } + `); + expect(schema.safeParse({ Tuna: "asdf" })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + "Salmon" + ], + "message": "Invalid input: expected string, received undefined" + } + ]], + "success": false, + } + `); +}); + +test("union exhaustiveness", () => { + const schema = z.record(z.union([z.literal("Tuna"), z.literal("Salmon")]), z.string()); + expect(schema.parse({ Tuna: "asdf", Salmon: "asdf" })).toEqual({ + Tuna: "asdf", + Salmon: "asdf", + }); + + expect(schema.safeParse({ Tuna: "asdf", Salmon: "asdf", Trout: "asdf" })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "unrecognized_keys", + "keys": [ + "Trout" + ], + "path": [], + "message": "Unrecognized key: \\"Trout\\"" + } + ]], + "success": false, + } + `); + expect(schema.safeParse({ Tuna: "asdf" })).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [ + "Salmon" + ], + "message": "Invalid input: expected string, received undefined" + } + ]], + "success": false, + } + `); +}); + +test("string record parse - pass", () => { + const schema = z.record(z.string(), z.boolean()); + schema.parse({ + k1: true, + k2: false, + 1234: false, + }); + + expect(schema.safeParse({ asdf: 1234 }).success).toEqual(false); + expect(schema.safeParse("asdf")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "record", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected record, received string" + } + ]], + "success": false, + } + `); +}); + +test("key and value getters", () => { + const rec = z.record(z.string(), z.number()); + + rec.keyType.parse("asdf"); + rec.valueType.parse(1234); +}); + +test("is not vulnerable to prototype pollution", async () => { + const rec = z.record( + z.string(), + z.object({ + a: z.string(), + }) + ); + + const data = JSON.parse(` + { + "__proto__": { + "a": "evil" + }, + "b": { + "a": "good" + } + } + `); + + const obj1 = rec.parse(data); + expect(obj1.a).toBeUndefined(); + + const obj2 = rec.safeParse(data); + expect(obj2.success).toBe(true); + if (obj2.success) { + expect(obj2.data.a).toBeUndefined(); + } + + const obj3 = await rec.parseAsync(data); + expect(obj3.a).toBeUndefined(); + + const obj4 = await rec.safeParseAsync(data); + expect(obj4.success).toBe(true); + if (obj4.success) { + expect(obj4.data.a).toBeUndefined(); + } +}); + +test("dont remove undefined values", () => { + const result1 = z.record(z.string(), z.any()).parse({ foo: undefined }); + + expect(result1).toEqual({ + foo: undefined, + }); +}); + +test("allow undefined values", () => { + const schema = z.record(z.string(), z.undefined()); + + expect( + Object.keys( + schema.parse({ + _test: undefined, + }) + ) + ).toEqual(["_test"]); +}); + +test("async parsing", async () => { + const schema = z + .record( + z.string(), + z + .string() + .optional() + .refine(async () => true) + ) + .refine(async () => true); + + const data = { + foo: "bar", + baz: "qux", + }; + const result = await schema.safeParseAsync(data); + expect(result.data).toEqual(data); +}); + +test("async parsing", async () => { + const schema = z + .record( + z.string(), + z + .string() + .optional() + .refine(async () => false) + ) + .refine(async () => false); + + const data = { + foo: "bar", + baz: "qux", + }; + const result = await schema.safeParseAsync(data); + expect(result.success).toEqual(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [ + "foo" + ], + "message": "Invalid input" + }, + { + "code": "custom", + "path": [ + "baz" + ], + "message": "Invalid input" + }, + { + "code": "custom", + "path": [], + "message": "Invalid input" + } + ]] + `); +}); + +test("partial record", () => { + const schema = z.partialRecord(z.string(), z.string()); + type schema = z.infer; + expectTypeOf().toEqualTypeOf>>(); + + const Keys = z.enum(["id", "name", "email"]).or(z.never()); + const Person = z.partialRecord(Keys, z.string()); + expectTypeOf>().toEqualTypeOf>>(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce320e4b6ab895e80439e797b383dbaad6de41bd --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts @@ -0,0 +1,356 @@ +import { expect, expectTypeOf, test } from "vitest"; +import { z } from "zod/v4"; + +test("recursion with z.lazy", () => { + const data = { + name: "I", + subcategories: [ + { + name: "A", + subcategories: [ + { + name: "1", + subcategories: [ + { + name: "a", + subcategories: [], + }, + ], + }, + ], + }, + ], + }; + + const Category = z.object({ + name: z.string(), + get subcategories() { + return z.array(Category).optional().nullable(); + }, + }); + type Category = z.infer; + interface _Category { + name: string; + subcategories?: _Category[] | undefined | null; + } + expectTypeOf().toEqualTypeOf<_Category>(); + Category.parse(data); +}); + +test("recursion involving union type", () => { + const data = { + value: 1, + next: { + value: 2, + next: { + value: 3, + next: { + value: 4, + next: null, + }, + }, + }, + }; + + const LL = z.object({ + value: z.number(), + get next() { + return LL.nullable(); + }, + }); + type LL = z.infer; + type _LL = { + value: number; + next: _LL | null; + }; + expectTypeOf().toEqualTypeOf<_LL>(); + + LL.parse(data); +}); + +test("mutual recursion - native", () => { + const Alazy = z.object({ + val: z.number(), + get b() { + return Blazy; + }, + }); + + const Blazy = z.object({ + val: z.number(), + get a() { + return Alazy.optional(); + }, + }); + const testData = { + val: 1, + b: { + val: 5, + a: { + val: 3, + b: { + val: 4, + a: { + val: 2, + b: { + val: 1, + }, + }, + }, + }, + }, + }; + + type Alazy = z.infer; + type Blazy = z.infer; + interface _Alazy { + val: number; + b: _Blazy; + } + interface _Blazy { + val: number; + a?: _Alazy | undefined; + } + expectTypeOf().toEqualTypeOf<_Alazy>(); + expectTypeOf().toEqualTypeOf<_Blazy>(); + Alazy.parse(testData); + Blazy.parse(testData.b); + + expect(() => Alazy.parse({ val: "asdf" })).toThrow(); +}); + +test("pick and omit with getter", () => { + const Category = z.strictObject({ + name: z.string(), + get subcategories() { + return z.array(Category); + }, + }); + + type Category = z.infer; + + interface _Category { + name: string; + subcategories: _Category[]; + } + expectTypeOf().toEqualTypeOf<_Category>(); + + const PickedCategory = Category.pick({ name: true }); + const OmittedCategory = Category.omit({ subcategories: true }); + + const picked = { name: "test" }; + const omitted = { name: "test" }; + + PickedCategory.parse(picked); + OmittedCategory.parse(omitted); + + expect(() => PickedCategory.parse({ name: "test", subcategories: [] })).toThrow(); + expect(() => OmittedCategory.parse({ name: "test", subcategories: [] })).toThrow(); +}); + +test("deferred self-recursion", () => { + const Feature = z.object({ + title: z.string(), + get features(): z.ZodOptional> { + return z.optional(z.array(Feature)); //.optional(); + }, + }); + // type Feature = z.infer; + + const Output = z.object({ + id: z.int(), //.nonnegative(), + name: z.string(), + get features(): z.ZodArray { + return Feature.array(); + }, + }); + type Output = z.output; + + type _Feature = { + title: string; + features?: _Feature[] | undefined; + }; + + type _Output = { + id: number; + name: string; + features: _Feature[]; + }; + + // expectTypeOf().toEqualTypeOf<_Feature>(); + expectTypeOf().toEqualTypeOf<_Output>(); +}); + +test("deferred mutual recursion", () => { + const Slot = z.object({ + slotCode: z.string(), + + get blocks() { + return z.array(Block); + }, + }); + type Slot = z.infer; + + const Block = z.object({ + blockCode: z.string(), + get slots() { + return z.array(Slot).optional(); + }, + }); + type Block = z.infer; + + const Page = z.object({ + slots: z.array(Slot), + }); + type Page = z.infer; + + type _Slot = { + slotCode: string; + blocks: _Block[]; + }; + type _Block = { + blockCode: string; + slots?: _Slot[] | undefined; + }; + type _Page = { + slots: _Slot[]; + }; + expectTypeOf().toEqualTypeOf<_Slot>(); + expectTypeOf().toEqualTypeOf<_Block>(); + expectTypeOf().toEqualTypeOf<_Page>(); +}); + +test("mutual recursion with meta", () => { + const A = z + .object({ + name: z.string(), + get b() { + return B; + }, + }) + .readonly() + .meta({ id: "A" }) + .optional(); + + const B = z + .object({ + name: z.string(), + get a() { + return A; + }, + }) + .readonly() + .meta({ id: "B" }); + + type A = z.infer; + type B = z.infer; + + type _A = + | Readonly<{ + name: string; + b: _B; + }> + | undefined; + // | undefined; + type _B = Readonly<{ + name: string; + a?: _A; + }>; + expectTypeOf().toEqualTypeOf<_A>(); + expectTypeOf().toEqualTypeOf<_B>(); +}); + +test("recursion compatibility", () => { + // array + const A = z.object({ + get array() { + return A.array(); + }, + get optional() { + return A.optional(); + }, + get nullable() { + return A.nullable(); + }, + get nonoptional() { + return A.nonoptional(); + }, + get readonly() { + return A.readonly(); + }, + get describe() { + return A.describe("A recursive type"); + }, + get meta() { + return A.meta({ description: "A recursive type" }); + }, + get pipe() { + return A.pipe(z.any()); + }, + get strict() { + return A.strict(); + }, + get tuple() { + return z.tuple([A, A]); + }, + get object() { + return z + .object({ + subcategories: A, + }) + .strict() + .loose(); + }, + get union() { + return z.union([A, A]); + }, + get intersection() { + return z.intersection(A, A); + }, + get record() { + return z.record(z.string(), A); + }, + get map() { + return z.map(z.string(), A); + }, + get set() { + return z.set(A); + }, + get lazy() { + return z.lazy(() => A); + }, + get promise() { + return z.promise(A); + }, + }); +}); + +// biome-ignore lint: sadf +export type RecursiveA = z.ZodUnion< + [ + z.ZodObject<{ + a: z.ZodDefault; + b: z.ZodPrefault; + c: z.ZodNonOptional; + d: z.ZodOptional; + e: z.ZodNullable; + g: z.ZodReadonly; + h: z.ZodPipe; + i: z.ZodArray; + j: z.ZodSet; + k: z.ZodMap; + l: z.ZodRecord; + m: z.ZodUnion<[RecursiveA, RecursiveA]>; + n: z.ZodIntersection; + o: z.ZodLazy; + p: z.ZodPromise; + q: z.ZodCatch; + r: z.ZodSuccess; + s: z.ZodTransform; + t: z.ZodTuple<[RecursiveA, RecursiveA]>; + u: z.ZodObject<{ + a: RecursiveA; + }>; + }>, + ] +>; diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/refine.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/refine.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a528b2a72a7a3c92aa44ffe9bea11ce2d85a5697 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/refine.test.ts @@ -0,0 +1,532 @@ +import { describe, expect, test } from "vitest"; +import * as z from "zod/v4"; + +describe("basic refinement functionality", () => { + test("should create a new schema instance when refining", () => { + const obj1 = z.object({ + first: z.string(), + second: z.string(), + }); + const obj2 = obj1.partial().strict(); + const obj3 = obj2.refine((data) => data.first || data.second, "Either first or second should be filled in."); + + expect(obj1 === (obj2 as any)).toEqual(false); + expect(obj2 === (obj3 as any)).toEqual(false); + }); + + test("should validate according to refinement logic", () => { + const schema = z + .object({ + first: z.string(), + second: z.string(), + }) + .partial() + .strict() + .refine((data) => data.first || data.second, "Either first or second should be filled in."); + + // Should fail on empty object + expect(() => schema.parse({})).toThrow(); + + // Should pass with first property + expect(schema.parse({ first: "a" })).toEqual({ first: "a" }); + + // Should pass with second property + expect(schema.parse({ second: "a" })).toEqual({ second: "a" }); + + // Should pass with both properties + expect(schema.parse({ first: "a", second: "a" })).toEqual({ first: "a", second: "a" }); + }); + + test("should validate strict mode correctly", () => { + const schema = z + .object({ + first: z.string(), + second: z.string(), + }) + .partial() + .strict(); + + // Should throw on extra properties + expect(() => schema.parse({ third: "adsf" })).toThrow(); + }); +}); + +describe("refinement with custom error messages", () => { + test("should use custom error message when validation fails", () => { + const validationSchema = z + .object({ + email: z.string().email(), + password: z.string(), + confirmPassword: z.string(), + }) + .refine((data) => data.password === data.confirmPassword, "Both password and confirmation must match"); + + const result = validationSchema.safeParse({ + email: "aaaa@gmail.com", + password: "aaaaaaaa", + confirmPassword: "bbbbbbbb", + }); + + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].message).toEqual("Both password and confirmation must match"); + } + }); +}); + +describe("async refinements", () => { + test("should support async refinement functions", async () => { + const validationSchema = z + .object({ + email: z.string().email(), + password: z.string(), + confirmPassword: z.string(), + }) + .refine( + (data) => Promise.resolve().then(() => data.password === data.confirmPassword), + "Both password and confirmation must match" + ); + + // Should pass with matching passwords + const validData = { + email: "aaaa@gmail.com", + password: "password", + confirmPassword: "password", + }; + + await expect(validationSchema.parseAsync(validData)).resolves.toEqual(validData); + + // Should fail with non-matching passwords + await expect( + validationSchema.parseAsync({ + email: "aaaa@gmail.com", + password: "password", + confirmPassword: "different", + }) + ).rejects.toThrow(); + }); +}); + +describe("early termination options", () => { + test("should abort early with continue: false", () => { + const schema = z + .string() + .superRefine((val, ctx) => { + if (val.length < 2) { + ctx.addIssue({ + code: "custom", + message: "BAD", + continue: false, + }); + } + }) + .refine((_) => false); + + const result = schema.safeParse(""); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].message).toEqual("BAD"); + } + }); + + test("should abort early with fatal: true", () => { + const schema = z + .string() + .superRefine((val, ctx) => { + if (val.length < 2) { + ctx.addIssue({ + code: "custom", + fatal: true, + message: "BAD", + }); + } + }) + .refine((_) => false); + + const result = schema.safeParse(""); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].message).toEqual("BAD"); + } + }); + + test("should abort early with abort flag", () => { + const schema = z + .string() + .refine((_) => false, { abort: true }) + .refine((_) => false); + + const result = schema.safeParse(""); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(1); + } + }); +}); + +describe("custom error paths", () => { + test("should use custom path in error message", async () => { + const result = await z + .object({ password: z.string(), confirm: z.string() }) + .refine((data) => data.confirm === data.password, { path: ["confirm"] }) + .safeParse({ password: "asdf", confirm: "qewr" }); + + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues[0].path).toEqual(["confirm"]); + } + }); +}); + +describe("superRefine functionality", () => { + test("should support multiple validation rules", () => { + const Strings = z.array(z.string()).superRefine((val, ctx) => { + if (val.length > 3) { + ctx.addIssue({ + input: val, + code: "too_big", + origin: "array", + maximum: 3, + inclusive: true, + exact: true, + message: "Too many items 😡", + }); + } + + if (val.length !== new Set(val).size) { + ctx.addIssue({ + input: val, + code: "custom", + message: `No duplicates allowed.`, + }); + } + }); + + // Should fail with too many items and duplicates + const result = Strings.safeParse(["asfd", "asfd", "asfd", "asfd"]); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(2); + expect(result.error.issues[0].message).toEqual("Too many items 😡"); + expect(result.error.issues[1].message).toEqual("No duplicates allowed."); + } + + // Should pass with valid input + const validArray = ["asfd", "qwer"]; + expect(Strings.parse(validArray)).toEqual(validArray); + }); + + test("should support async superRefine", async () => { + const Strings = z.array(z.string()).superRefine(async (val, ctx) => { + if (val.length > 3) { + ctx.addIssue({ + input: val, + code: "too_big", + origin: "array", + maximum: 3, + inclusive: true, + message: "Too many items 😡", + }); + } + + if (val.length !== new Set(val).size) { + ctx.addIssue({ + input: val, + code: "custom", + message: `No duplicates allowed.`, + }); + } + }); + + // Should fail with too many items and duplicates + const result = await Strings.safeParseAsync(["asfd", "asfd", "asfd", "asfd"]); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(2); + } + + // Should pass with valid input + const validArray = ["asfd", "qwer"]; + await expect(Strings.parseAsync(validArray)).resolves.toEqual(validArray); + }); + + test("should accept string as shorthand for custom error message", () => { + const schema = z.string().superRefine((_, ctx) => { + ctx.addIssue("bad stuff"); + }); + + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues).toHaveLength(1); + expect(result.error.issues[0].message).toEqual("bad stuff"); + } + }); + + test("should respect fatal flag in superRefine", () => { + const schema = z + .string() + .superRefine((val, ctx) => { + if (val === "") { + ctx.addIssue({ + input: val, + code: "custom", + message: "foo", + fatal: true, + }); + } + }) + .superRefine((val, ctx) => { + if (val !== " ") { + ctx.addIssue({ + input: val, + code: "custom", + message: "bar", + }); + } + }); + + const result = schema.safeParse(""); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues.length).toEqual(1); + expect(result.error.issues[0].message).toEqual("foo"); + } + }); +}); + +describe("chained refinements", () => { + test("should collect all validation errors when appropriate", () => { + const objectSchema = z + .object({ + length: z.number(), + size: z.number(), + }) + .refine(({ length }) => length > 5, { + path: ["length"], + message: "length greater than 5", + }) + .refine(({ size }) => size > 7, { + path: ["size"], + message: "size greater than 7", + }); + + // Should fail with one error + const r1 = objectSchema.safeParse({ + length: 4, + size: 9, + }); + expect(r1.success).toEqual(false); + if (!r1.success) { + expect(r1.error.issues.length).toEqual(1); + expect(r1.error.issues[0].path).toEqual(["length"]); + } + + // Should fail with two errors + const r2 = objectSchema.safeParse({ + length: 4, + size: 3, + }); + expect(r2.success).toEqual(false); + if (!r2.success) { + expect(r2.error.issues.length).toEqual(2); + } + + // Should pass with valid input + const validData = { + length: 6, + size: 8, + }; + expect(objectSchema.parse(validData)).toEqual(validData); + }); +}); + +// Commented tests can be uncommented once type-checking issues are resolved +/* +describe("type refinement", () => { + test("refinement type guard", () => { + const validationSchema = z.object({ + a: z.string().refine((s): s is "a" => s === "a"), + }); + type Input = z.input; + type Schema = z.infer; + + expectTypeOf().not.toEqualTypeOf<"a">(); + expectTypeOf().toEqualTypeOf(); + + expectTypeOf().toEqualTypeOf<"a">(); + expectTypeOf().not.toEqualTypeOf(); + }); + + test("superRefine - type narrowing", () => { + type NarrowType = { type: string; age: number }; + const schema = z + .object({ + type: z.string(), + age: z.number(), + }) + .nullable() + .superRefine((arg, ctx): arg is NarrowType => { + if (!arg) { + // still need to make a call to ctx.addIssue + ctx.addIssue({ + input: arg, + code: "custom", + message: "cannot be null", + fatal: true, + }); + return false; + } + return true; + }); + + expectTypeOf>().toEqualTypeOf(); + + expect(schema.safeParse({ type: "test", age: 0 }).success).toEqual(true); + expect(schema.safeParse(null).success).toEqual(false); + }); + + test("chained mixed refining types", () => { + type firstRefinement = { first: string; second: number; third: true }; + type secondRefinement = { first: "bob"; second: number; third: true }; + type thirdRefinement = { first: "bob"; second: 33; third: true }; + const schema = z + .object({ + first: z.string(), + second: z.number(), + third: z.boolean(), + }) + .nullable() + .refine((arg): arg is firstRefinement => !!arg?.third) + .superRefine((arg, ctx): arg is secondRefinement => { + expectTypeOf().toEqualTypeOf(); + if (arg.first !== "bob") { + ctx.addIssue({ + input: arg, + code: "custom", + message: "`first` property must be `bob`", + }); + return false; + } + return true; + }) + .refine((arg): arg is thirdRefinement => { + expectTypeOf().toEqualTypeOf(); + return arg.second === 33; + }); + + expectTypeOf>().toEqualTypeOf(); + }); +}); +*/ + +test("when", () => { + const schema = z + .strictObject({ + password: z.string().min(8), + confirmPassword: z.string(), + other: z.string(), + }) + .refine( + (data) => { + console.log("running check..."); + console.log(data); + console.log(data.password); + return data.password === data.confirmPassword; + }, + { + message: "Passwords do not match", + path: ["confirmPassword"], + when(payload) { + if (payload.value === undefined) return false; + if (payload.value === null) return false; + // no issues with confirmPassword or password + return payload.issues.every((iss) => iss.path?.[0] !== "confirmPassword" && iss.path?.[0] !== "password"); + }, + } + ); + + expect(schema.safeParse(undefined)).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "object", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected object, received undefined" + } + ]], + "success": false, + } + `); + expect(schema.safeParse(null)).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "expected": "object", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected object, received null" + } + ]], + "success": false, + } + `); + expect( + schema.safeParse({ + password: "asdf", + confirmPassword: "asdfg", + other: "qwer", + }) + ).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "origin": "string", + "code": "too_small", + "minimum": 8, + "inclusive": true, + "path": [ + "password" + ], + "message": "Too small: expected string to have >=8 characters" + } + ]], + "success": false, + } + `); + + expect( + schema.safeParse({ + password: "asdf", + confirmPassword: "asdfg", + other: 1234, + }) + ).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "origin": "string", + "code": "too_small", + "minimum": 8, + "inclusive": true, + "path": [ + "password" + ], + "message": "Too small: expected string to have >=8 characters" + }, + { + "expected": "string", + "code": "invalid_type", + "path": [ + "other" + ], + "message": "Invalid input: expected string, received number" + } + ]], + "success": false, + } + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/registries.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/registries.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..213d9d8d3b8f17522f00036f162e85ac76a638c3 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/registries.test.ts @@ -0,0 +1,204 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("globalRegistry", () => { + const reg = z.registry(); + + const a = z.string(); + reg.add(a); + expect(reg.has(a)).toEqual(true); + + reg.remove(a); + expect(reg.has(a)).toEqual(false); + + a.register(z.globalRegistry, { field: "sup" }); + expect(z.globalRegistry.has(a)).toEqual(true); + expect(z.globalRegistry.get(a)).toEqual({ field: "sup" }); + + z.globalRegistry.remove(a); + expect(z.globalRegistry.has(a)).toEqual(false); +}); + +test("z.registry", () => { + const fieldRegistry = z.registry<{ name: string; description: string }>(); + + const a = z.string(); + fieldRegistry.add(a, { name: "hello", description: "world" }); + const a_meta = fieldRegistry.get(a); + expect(a_meta).toEqual({ name: "hello", description: "world" }); + + fieldRegistry.remove(a); + expect(fieldRegistry.has(a)).toEqual(false); + expect(fieldRegistry.get(a)).toEqual(undefined); +}); + +test("z.registry no metadata", () => { + const fieldRegistry = z.registry(); + + const a = z.string(); + fieldRegistry.add(a); + fieldRegistry.add(z.number()); + expect(fieldRegistry.get(a)).toEqual(undefined); + expect(fieldRegistry.has(a)).toEqual(true); +}); + +test("z.registry with schema constraints", () => { + const fieldRegistry = z.registry<{ name: string; description: string }, z.ZodString>(); + + const a = z.string(); + fieldRegistry.add(a, { name: "hello", description: "world" }); + // @ts-expect-error + fieldRegistry.add(z.number(), { name: "test" }); + // @ts-expect-error + z.number().register(fieldRegistry, { name: "test", description: "test" }); +}); + +// test("z.namedRegistry", () => { +// const namedReg = z +// .namedRegistry<{ name: string; description: string }>() +// .add(z.string(), { name: "hello", description: "world" }) +// .add(z.number(), { name: "number", description: "number" }); + +// expect(namedReg.get("hello")).toEqual({ +// name: "hello", +// description: "world", +// }); +// expect(namedReg.has("hello")).toEqual(true); +// expect(namedReg.get("number")).toEqual({ +// name: "number", +// description: "number", +// }); + +// // @ts-expect-error +// namedReg.get("world"); +// // @ts-expect-error +// expect(namedReg.get("world")).toEqual(undefined); + +// const hello = namedReg.get("hello"); +// expect(hello).toEqual({ name: "hello", description: "world" }); +// expectTypeOf().toEqualTypeOf<{ +// name: "hello"; +// description: "world"; +// }>(); +// expectTypeOf().toEqualTypeOf<{ +// hello: { name: "hello"; description: "world" }; +// number: { name: "number"; description: "number" }; +// }>(); +// }); + +test("output type in registry meta", () => { + const reg = z.registry<{ out: z.$output }>(); + const a = z.string(); + reg.add(a, { out: "asdf" }); + // @ts-expect-error + reg.add(a, 1234); + expectTypeOf(reg.get(a)).toEqualTypeOf<{ out: string } | undefined>(); +}); + +test("output type in registry meta - objects and arrays", () => { + const reg = z.registry<{ name: string; examples: z.$output[] }>(); + const a = z.string(); + reg.add(a, { name: "hello", examples: ["world"] }); + + // @ts-expect-error + reg.add(a, { name: "hello", examples: "world" }); + expectTypeOf(reg.get(a)).toEqualTypeOf<{ name: string; examples: string[] } | undefined>(); +}); + +test("input type in registry meta", () => { + const reg = z.registry<{ in: z.$input }>(); + const a = z.pipe(z.number(), z.transform(String)); + reg.add(a, { in: 1234 }); + // @ts-expect-error + reg.add(a, "1234"); + expectTypeOf(reg.get(a)).toEqualTypeOf<{ in: number } | undefined>(); +}); + +test("input type in registry meta - objects and arrays", () => { + const reg = z.registry<{ name: string; examples: z.$input[] }>(); + const a = z.pipe(z.number(), z.transform(String)); + reg.add(a, { name: "hello", examples: [1234] }); + + // @ts-expect-error + reg.add(a, { name: "hello", examples: "world" }); + expectTypeOf(reg.get(a)).toEqualTypeOf<{ name: string; examples: number[] } | undefined>(); +}); + +test(".meta method", () => { + const a1 = z.string(); + const a2 = a1.meta({ name: "hello" }); + + expect(a1.meta()).toEqual(undefined); + expect(a2.meta()).toEqual({ name: "hello" }); + expect(a1 === a2).toEqual(false); +}); + +test(".meta metadata does not bubble up", () => { + const a1 = z.string().meta({ name: "hello" }); + const a2 = a1.optional(); + + expect(a1.meta()).toEqual({ name: "hello" }); + expect(a2.meta()).toEqual(undefined); +}); + +test(".describe", () => { + const a1 = z.string(); + const a2 = a1.describe("Hello"); + + expect(a1.description).toEqual(undefined); + expect(a2.description).toEqual("Hello"); +}); + +test("inherit across clone", () => { + const A = z.string().meta({ a: true }); + expect(A.meta()).toEqual({ a: true }); + const B = A.meta({ b: true }); + expect(B.meta()).toEqual({ a: true, b: true }); + const C = B.describe("hello"); + expect(C.meta()).toEqual({ a: true, b: true, description: "hello" }); +}); + +test("loose examples", () => { + z.string().register(z.globalRegistry, { + examples: ["example"], + }); +}); + +test("function meta witout replacement", () => { + const myReg = z.registry<{ + defaulter: (arg: string, test: boolean) => number; + }>(); + + const mySchema = z.date(); + myReg.add(mySchema, { + defaulter: (arg, _test) => { + return arg.length; + }, + }); + + expect(myReg.get(mySchema)!.defaulter("hello", true)).toEqual(5); +}); + +test("function meta with replacement", () => { + const myReg = z.registry<{ + defaulter: (arg: z.$input, test: boolean) => z.$output; + }>(); + + const mySchema = z.string().transform((val) => val.length); + myReg.add(mySchema, { + defaulter: (arg, _test) => { + return arg.length; + }, + }); + + expect(myReg.get(mySchema)!.defaulter("hello", true)).toEqual(5); +}); + +test("test .clear()", () => { + const reg = z.registry(); + const a = z.string(); + reg.add(a); + expect(reg.has(a)).toEqual(true); + reg.clear(); + expect(reg.has(a)).toEqual(false); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/set.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/set.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5baaf2e02fb0d91c903da1f9ae5baa69baf71174 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/set.test.ts @@ -0,0 +1,179 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +const stringSet = z.set(z.string()); +type stringSet = z.infer; + +const minTwo = z.set(z.string()).min(2); +const maxTwo = z.set(z.string()).max(2); +const justTwo = z.set(z.string()).size(2); +const nonEmpty = z.set(z.string()).nonempty(); +const nonEmptyMax = z.set(z.string()).nonempty().max(2); + +test("type inference", () => { + expectTypeOf().toEqualTypeOf>(); +}); + +test("valid parse", () => { + const result = stringSet.safeParse(new Set(["first", "second"])); + expect(result.success).toEqual(true); + expect(result.data!.has("first")).toEqual(true); + expect(result.data!.has("second")).toEqual(true); + expect(result.data!.has("third")).toEqual(false); + + expect(() => { + minTwo.parse(new Set(["a", "b"])); + minTwo.parse(new Set(["a", "b", "c"])); + maxTwo.parse(new Set(["a", "b"])); + maxTwo.parse(new Set(["a"])); + justTwo.parse(new Set(["a", "b"])); + nonEmpty.parse(new Set(["a"])); + nonEmptyMax.parse(new Set(["a"])); + }).not.toThrow(); +}); + +test("valid parse async", async () => { + const result = await stringSet.spa(new Set(["first", "second"])); + expect(result.success).toEqual(true); + expect(result.data!.has("first")).toEqual(true); + expect(result.data!.has("second")).toEqual(true); + expect(result.data!.has("third")).toEqual(false); + + const asyncResult = await stringSet.safeParse(new Set(["first", "second"])); + expect(asyncResult.success).toEqual(true); + expect(asyncResult.data!.has("first")).toEqual(true); + expect(asyncResult.data!.has("second")).toEqual(true); + expect(asyncResult.data!.has("third")).toEqual(false); +}); + +test("valid parse: size-related methods", () => { + expect(() => { + minTwo.parse(new Set(["a", "b"])); + minTwo.parse(new Set(["a", "b", "c"])); + maxTwo.parse(new Set(["a", "b"])); + maxTwo.parse(new Set(["a"])); + justTwo.parse(new Set(["a", "b"])); + nonEmpty.parse(new Set(["a"])); + nonEmptyMax.parse(new Set(["a"])); + }).not.toThrow(); + + const sizeZeroResult = stringSet.parse(new Set()); + expect(sizeZeroResult.size).toBe(0); + + const sizeTwoResult = minTwo.parse(new Set(["a", "b"])); + expect(sizeTwoResult.size).toBe(2); +}); + +test("failing when parsing empty set in nonempty ", () => { + const result = nonEmpty.safeParse(new Set()); + expect(result.success).toEqual(false); + expect(result.error!.issues.length).toEqual(1); + expect(result.error!.issues[0].code).toEqual("too_small"); +}); + +test("failing when set is smaller than min() ", () => { + const result = minTwo.safeParse(new Set(["just_one"])); + expect(result.success).toEqual(false); + expect(result.error!.issues.length).toEqual(1); + expect(result.error!.issues[0].code).toEqual("too_small"); +}); + +test("failing when set is bigger than max() ", () => { + const result = maxTwo.safeParse(new Set(["one", "two", "three"])); + expect(result.success).toEqual(false); + expect(result.error!.issues.length).toEqual(1); + expect(result.error!.issues[0].code).toEqual("too_big"); +}); + +test("doesn’t throw when an empty set is given", () => { + const result = stringSet.safeParse(new Set([])); + expect(result.success).toEqual(true); +}); + +test("throws when a Map is given", () => { + const result = stringSet.safeParse(new Map([])); + expect(result.success).toEqual(false); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "set", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected set, received Map" + } + ]] + `); +}); + +test("throws when the given set has invalid input", () => { + const result = stringSet.safeParse(new Set([Symbol()])); + expect(result.success).toEqual(false); + expect(result.error!.issues.length).toEqual(1); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected string, received symbol" + } + ]] + `); +}); + +test("throws when the given set has multiple invalid entries", () => { + const result = stringSet.safeParse(new Set([1, 2] as any[])); + expect(result.success).toEqual(false); + expect(result.error!.issues.length).toEqual(2); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected string, received number" + }, + { + "expected": "string", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected string, received number" + } + ]] + `); +}); + +test("min/max", async () => { + const schema = z.set(z.string()).min(4).max(5); + + const r1 = schema.safeParse(new Set(["a", "b", "c", "d"])); + expect(r1.success).toEqual(true); + + const r2 = schema.safeParse(new Set(["a", "b", "c"])); + expect(r2.success).toEqual(false); + expect(r2.error!.issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "message": "Too small: expected set to have >4 items", + "minimum": 4, + "origin": "set", + "path": [], + }, + ] + `); + + const r3 = schema.safeParse(new Set(["a", "b", "c", "d", "e", "f"])); + expect(r3.success).toEqual(false); + expect(r3.error!.issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "maximum": 5, + "message": "Too big: expected set to have <5 items", + "origin": "set", + "path": [], + }, + ] + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..8deb7282f024dc8fb8613f263317a7d4b4fa2e0d --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts @@ -0,0 +1,57 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +test("length checks", async () => { + const schema = z.string(); + const result = await schema["~standard"].validate(12); + expect(result).toMatchInlineSnapshot(` + { + "issues": [ + { + "code": "invalid_type", + "expected": "string", + "message": "Invalid input: expected string, received number", + "path": [], + }, + ], + } + `); +}); + +test("length checks", async () => { + const schema = z.string(); + const result = await schema["~standard"].validate("asdf"); + expect(result).toMatchInlineSnapshot(` + { + "value": "asdf", + } + `); +}); + +test("length checks", async () => { + const schema = z.string().refine(async (val) => val.length > 5); + const result = await schema["~standard"].validate(12); + expect(result).toMatchInlineSnapshot(` + { + "issues": [ + { + "code": "invalid_type", + "expected": "string", + "message": "Invalid input: expected string, received number", + "path": [], + }, + ], + } + `); +}); + +test("length checks", async () => { + const schema = z.string().refine(async (val) => val.length > 5); + const result = await schema["~standard"].validate("234134134"); + expect(result).toMatchInlineSnapshot(` + { + "value": "234134134", + } + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/string-formats.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/string-formats.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..94fdedf9c8fd2ecd2a2962fde6135cd34a8080f8 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/string-formats.test.ts @@ -0,0 +1,109 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +test("string format methods", () => { + const a = z.email().min(10); + const b = z.email().max(10); + const c = z.email().length(10); + const d = z.email().uppercase(); + const e = z.email().lowercase(); + + // Positive and negative cases for `a` + expect(a.safeParse("longemail@example.com").success).toBe(true); // Positive + expect(a.safeParse("ort@e.co").success).toBe(false); // Negative + + // Positive and negative cases for `b` + expect(b.safeParse("sho@e.co").success).toBe(true); // Positive + expect(b.safeParse("longemail@example.com").success).toBe(false); // Negative + + // Positive and negative cases for `c` + expect(c.safeParse("56780@e.co").success).toBe(true); // Positive + expect(c.safeParse("shoasdfasdfrt@e.co").success).toBe(false); // Negative + + // Positive and negative cases for `d` + expect(d.safeParse("EMAIL@EXAMPLE.COM").success).toBe(true); // Positive + expect(d.safeParse("email@example.com").success).toBe(false); // Negative + + // Positive and negative cases for `e` + expect(e.safeParse("email@example.com").success).toBe(true); // Positive + expect(e.safeParse("EMAIL@EXAMPLE.COM").success).toBe(false); // Negative +}); + +test("z.stringFormat", () => { + const ccRegex = /^(?:\d{14,19}|\d{4}(?: \d{3,6}){2,4}|\d{4}(?:-\d{3,6}){2,4})$/u; + + const a = z + .stringFormat("creditCard", (val) => ccRegex.test(val), { + error: `Invalid credit card number`, + }) + .refine((_) => false, "Also bad"); + + expect(a.safeParse("asdf")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_format", + "format": "creditCard", + "path": [], + "message": "Invalid credit card number" + }, + { + "code": "custom", + "path": [], + "message": "Also bad" + } + ]], + "success": false, + } + `); + expect(a.safeParse("1234-5678-9012-3456")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "path": [], + "message": "Also bad" + } + ]], + "success": false, + } + `); + expect(a.def.pattern).toMatchInlineSnapshot(`undefined`); + + const b = z + .stringFormat("creditCard", ccRegex, { + abort: true, + error: `Invalid credit card number`, + }) + .refine((_) => false, "Also bad"); + + expect(b.safeParse("asdf")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_format", + "format": "creditCard", + "path": [], + "message": "Invalid credit card number" + } + ]], + "success": false, + } + `); + expect(b.safeParse("1234-5678-9012-3456")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "path": [], + "message": "Also bad" + } + ]], + "success": false, + } + `); + expect(b.def.pattern).toMatchInlineSnapshot( + `/\\^\\(\\?:\\\\d\\{14,19\\}\\|\\\\d\\{4\\}\\(\\?: \\\\d\\{3,6\\}\\)\\{2,4\\}\\|\\\\d\\{4\\}\\(\\?:-\\\\d\\{3,6\\}\\)\\{2,4\\}\\)\\$/u` + ); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/string.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/string.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cf1b9e13d2b0933c45b7d502921c0f698ae3c6ac --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/string.test.ts @@ -0,0 +1,881 @@ +import { randomBytes } from "node:crypto"; +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +const minFive = z.string().min(5, "min5"); +const maxFive = z.string().max(5, "max5"); +const justFive = z.string().length(5); +const nonempty = z.string().min(1, "nonempty"); +const includes = z.string().includes("includes"); +const includesFromIndex2 = z.string().includes("includes", { position: 2 }); +const startsWith = z.string().startsWith("startsWith"); +const endsWith = z.string().endsWith("endsWith"); + +test("length checks", () => { + minFive.parse("12345"); + minFive.parse("123456"); + maxFive.parse("12345"); + maxFive.parse("1234"); + nonempty.parse("1"); + justFive.parse("12345"); + + expect(() => minFive.parse("1234")).toThrow(); + expect(() => maxFive.parse("123456")).toThrow(); + expect(() => nonempty.parse("")).toThrow(); + expect(() => justFive.parse("1234")).toThrow(); + expect(() => justFive.parse("123456")).toThrow(); +}); + +test("includes", () => { + includes.parse("XincludesXX"); + includesFromIndex2.parse("XXXincludesXX"); + + expect(() => includes.parse("XincludeXX")).toThrow(); + expect(() => includesFromIndex2.parse("XincludesXX")).toThrow(); +}); + +test("startswith/endswith", () => { + startsWith.parse("startsWithX"); + endsWith.parse("XendsWith"); + + expect(() => startsWith.parse("x")).toThrow(); + expect(() => endsWith.parse("x")).toThrow(); +}); + +test("email validations", () => { + const validEmails = [ + `email@domain.com`, + `firstname.lastname@domain.com`, + `email@subdomain.domain.com`, + `firstname+lastname@domain.com`, + `1234567890@domain.com`, + `email@domain-one.com`, + `_______@domain.com`, + `email@domain.name`, + `email@domain.co.jp`, + `firstname-lastname@domain.com`, + `very.common@example.com`, + `disposable.style.email.with+symbol@example.com`, + `other.email-with-hyphen@example.com`, + `fully-qualified-domain@example.com`, + `user.name+tag+sorting@example.com`, + `x@example.com`, + `mojojojo@asdf.example.com`, + `example-indeed@strange-example.com`, + `example@s.example`, + `user-@example.org`, + `user@my-example.com`, + `a@b.cd`, + `work+user@mail.com`, + `tom@test.te-st.com`, + `something@subdomain.domain-with-hyphens.tld`, + `common'name@domain.com`, + `francois@etu.inp-n7.fr`, + ]; + const invalidEmails = [ + // no "printable characters" + // `user%example.com@example.org`, + // `mailhost!username@example.org`, + // `test/test@test.com`, + + // double @ + `francois@@etu.inp-n7.fr`, + // do not support quotes + `"email"@domain.com`, + `"e asdf sadf ?<>ail"@domain.com`, + `" "@example.org`, + `"john..doe"@example.org`, + `"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com`, + // do not support comma + `a,b@domain.com`, + + // do not support IPv4 + `email@123.123.123.123`, + `email@[123.123.123.123]`, + `postmaster@123.123.123.123`, + `user@[68.185.127.196]`, + `ipv4@[85.129.96.247]`, + `valid@[79.208.229.53]`, + `valid@[255.255.255.255]`, + `valid@[255.0.55.2]`, + `valid@[255.0.55.2]`, + + // do not support ipv6 + `hgrebert0@[IPv6:4dc8:ac7:ce79:8878:1290:6098:5c50:1f25]`, + `bshapiro4@[IPv6:3669:c709:e981:4884:59a3:75d1:166b:9ae]`, + `jsmith@[IPv6:2001:db8::1]`, + `postmaster@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:7334]`, + `postmaster@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:192.168.1.1]`, + + // microsoft test cases + `plainaddress`, + `#@%^%#$@#$@#.com`, + `@domain.com`, + `Joe Smith <email@domain.com>`, + `email.domain.com`, + `email@domain@domain.com`, + `.email@domain.com`, + `email.@domain.com`, + `email..email@domain.com`, + `あいうえお@domain.com`, + `email@domain.com (Joe Smith)`, + `email@domain`, + `email@-domain.com`, + `email@111.222.333.44444`, + `email@domain..com`, + `Abc.example.com`, + `A@b@c@example.com`, + `colin..hacks@domain.com`, + `a"b(c)d,e:f;gi[j\k]l@example.com`, + `just"not"right@example.com`, + `this is"not\allowed@example.com`, + `this\ still\"not\\allowed@example.com`, + + // random + `i_like_underscore@but_its_not_allowed_in_this_part.example.com`, + `QA[icon]CHOCOLATE[icon]@test.com`, + `invalid@-start.com`, + `invalid@end.com-`, + `a.b@c.d`, + `invalid@[1.1.1.-1]`, + `invalid@[68.185.127.196.55]`, + `temp@[192.168.1]`, + `temp@[9.18.122.]`, + `double..point@test.com`, + `asdad@test..com`, + `asdad@hghg...sd...au`, + `asdad@hghg........au`, + `invalid@[256.2.2.48]`, + `invalid@[256.2.2.48]`, + `invalid@[999.465.265.1]`, + `jkibbey4@[IPv6:82c4:19a8::70a9:2aac:557::ea69:d985:28d]`, + `mlivesay3@[9952:143f:b4df:2179:49a1:5e82:b92e:6b6]`, + `gbacher0@[IPv6:bc37:4d3f:5048:2e26:37cc:248e:df8e:2f7f:af]`, + `invalid@[IPv6:5348:4ed3:5d38:67fb:e9b:acd2:c13:192.168.256.1]`, + `test@.com`, + `aaaaaaaaaaaaaaalongemailthatcausesregexDoSvulnerability@test.c`, + ]; + const emailSchema = z.string().email(); + + expect( + validEmails.every((email) => { + return emailSchema.safeParse(email).success; + }) + ).toBe(true); + expect( + invalidEmails.every((email) => { + return emailSchema.safeParse(email).success === false; + }) + ).toBe(true); +}); + +test("base64 validations", () => { + const validBase64Strings = [ + "SGVsbG8gV29ybGQ=", // "Hello World" + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==", // "This is an encoded string" + "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcms=", // "Many hands make light work" + "UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // "Patience is the key to success" + "QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // "Base64 encoding is fun" + "MTIzNDU2Nzg5MA==", // "1234567890" + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=", // "abcdefghijklmnopqrstuvwxyz" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "ISIkJSMmJyonKCk=", // "!\"#$%&'()*" + "", // Empty string is technically a valid base64 + ]; + + for (const str of validBase64Strings) { + expect(str + z.string().base64().safeParse(str).success).toBe(`${str}true`); + } + + const invalidBase64Strings = [ + "12345", // Not padded correctly, not a multiple of 4 characters + "SGVsbG8gV29ybGQ", // Missing padding + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw", // Missing padding + "!UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // Invalid character '!' + "?QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // Invalid character '?' + ".MTIzND2Nzg5MC4=", // Invalid character '.' + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo", // Missing padding + ]; + + for (const str of invalidBase64Strings) { + expect(str + z.string().base64().safeParse(str).success).toBe(`${str}false`); + } +}); + +test("base64url validations", () => { + const base64url = z.string().base64url(); + + const validBase64URLStrings = [ + "SGVsbG8gV29ybGQ", // "Hello World" + + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw", // "This is an encoded string" + + "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcms", // "Many hands make light work" + + "UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // "Patience is the key to success" + "QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg", // "Base64 encoding is fun" + + "MTIzNDU2Nzg5MA", // "1234567890" + + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo", // "abcdefghijklmnopqrstuvwxyz" + + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + "ISIkJSMmJyonKCk", // "!\"#$%&'()*" + + "", // Empty string is technically valid base64url + "w7_Dv8O-w74K", // ÿÿþþ + "123456", + ]; + + for (const str of validBase64URLStrings) { + expect(str + base64url.safeParse(str).success).toBe(`${str}true`); + } + + const invalidBase64URLStrings = [ + "w7/Dv8O+w74K", // Has + and / characters (is base64) + "12345", // Invalid length (not a multiple of 4 characters when adding allowed number of padding characters) + "12345===", // Not padded correctly + "!UGF0aWVuY2UgaXMgdGhlIGtleSB0byBzdWNjZXNz", // Invalid character '!' + "?QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // Invalid character '?' + ".MTIzND2Nzg5MC4=", // Invalid character '.' + + // disallow valid padding + "SGVsbG8gV29ybGQ=", // "Hello World" with padding + "VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==", // "This is an encoded string" with padding + "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcms=", // "Many hands make light work" with padding + "QmFzZTY0IGVuY29kaW5nIGlzIGZ1bg==", // "Base64 encoding is fun" with padding + "MTIzNDU2Nzg5MA==", // "1234567890" with padding + "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=", // "abcdefghijklmnopqrstuvwxyz with padding" + "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=", // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" with padding + "ISIkJSMmJyonKCk=", // "!\"#$%&'()*" with padding + ]; + + for (const str of invalidBase64URLStrings) { + expect(str + base64url.safeParse(str).success).toBe(`${str}false`); + } +}); + +test("big base64 and base64url", () => { + const bigbase64 = randomBytes(1024 * 1024 * 10).toString("base64"); + z.base64().parse(bigbase64); + const bigbase64url = randomBytes(1024 * 1024 * 10).toString("base64url"); + z.base64url().parse(bigbase64url); +}); + +function makeJwt(header: object, payload: object) { + const headerBase64 = Buffer.from(JSON.stringify(header)).toString("base64url"); + const payloadBase64 = Buffer.from(JSON.stringify(payload)).toString("base64url"); + const signature = "signature"; // Placeholder for the signature + return `${headerBase64}.${payloadBase64}.${signature}`; +} + +test("jwt token", () => { + const jwt = z.string().jwt(); + expect(() => jwt.parse("invalid")).toThrow(); + expect(() => jwt.parse("invalid.invalid")).toThrow(); + expect(() => jwt.parse("invalid.invalid.invalid")).toThrow(); + + // Valid JWTs + const es256jwt = z.string().jwt({ alg: "ES256" }); + const d1 = makeJwt({ typ: "JWT", alg: "ES256" }, {}); + jwt.parse(d1); + es256jwt.parse(d1); + + // Invalid header + const d2 = makeJwt({}, {}); + expect(() => jwt.parse(d2)).toThrow(); + + // Wrong algorithm + const d3 = makeJwt({ typ: "JWT", alg: "RS256" }, {}); + expect(() => es256jwt.parse(d3)).toThrow(); + + // missing typ is fine + const d4 = makeJwt({ alg: "HS256" }, {}); + jwt.parse(d4); + + // type isn't JWT + const d5 = makeJwt({ typ: "SUP", alg: "HS256" }, { foo: "bar" }); + expect(() => jwt.parse(d5)).toThrow(); +}); + +test("url validations", () => { + const url = z.string().url(); + url.parse("http://google.com"); + url.parse("https://google.com/asdf?asdf=ljk3lk4&asdf=234#asdf"); + url.parse("https://anonymous:flabada@developer.mozilla.org/en-US/docs/Web/API/URL/password"); + url.parse("https://localhost"); + url.parse("https://my.local"); + url.parse("http://aslkfjdalsdfkjaf"); + url.parse("http://localhost"); + + url.parse("c:"); + + expect(() => url.parse("asdf")).toThrow(); + expect(() => url.parse("https:/")).toThrow(); + expect(() => url.parse("asdfj@lkjsdf.com")).toThrow(); + expect(() => url.parse("https://")).toThrow(); +}); + +test("httpurl", () => { + const httpUrl = z.url({ + protocol: /^https?$/, + hostname: z.regexes.domain, + // /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/ + }); + + httpUrl.parse("https://example.com"); + httpUrl.parse("http://example.com"); + // ports + httpUrl.parse("https://example.com:8080"); + httpUrl.parse("http://example.com:8080"); + // subdomains + httpUrl.parse("https://sub.example.com"); + httpUrl.parse("http://sub.example.com"); + // paths + httpUrl.parse("https://example.com/path/to/resource"); + httpUrl.parse("http://example.com/path/to/resource"); + // query parameters + httpUrl.parse("https://example.com/path?query=param"); + httpUrl.parse("http://example.com/path?query=param"); + // fragment identifiers + httpUrl.parse("https://example.com/path#fragment"); + httpUrl.parse("http://example.com/path#fragment"); + // fails + expect(() => httpUrl.parse("ftp://example.com")).toThrow(); + expect(() => httpUrl.parse("shttp://example.com")).toThrow(); + expect(() => httpUrl.parse("httpz://example.com")).toThrow(); + expect(() => httpUrl.parse("http://")).toThrow(); + expect(() => httpUrl.parse("http://localhost")).toThrow(); + expect(() => httpUrl.parse("http://-asdf.com")).toThrow(); + expect(() => + httpUrl.parse( + "http://asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf.com" + ) + ).toThrow(); + expect(() => httpUrl.parse("http://asdf.c")).toThrow(); + expect(() => httpUrl.parse("mailto:asdf@lckj.com")).toThrow(); +}); + +test("url error overrides", () => { + try { + z.string().url().parse("https"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("Invalid URL"); + } + try { + z.string().url("badurl").parse("https"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("badurl"); + } + try { + z.string().url({ message: "badurl" }).parse("https"); + } catch (err) { + expect((err as z.ZodError).issues[0].message).toEqual("badurl"); + } +}); + +test("emoji validations", () => { + const emoji = z.string().emoji(); + + emoji.parse("👋👋👋👋"); + emoji.parse("🍺👩‍🚀🫡"); + emoji.parse("💚💙💜💛❤️"); + emoji.parse("🐛🗝🐏🍡🎦🚢🏨💫🎌☘🗡😹🔒🎬➡️🍹🗂🚨⚜🕑〽️🚦🌊🍴💍🍌💰😳🌺🍃"); + emoji.parse("🇹🇷🤽🏿‍♂️"); + emoji.parse( + "😀😁😂🤣😃😄😅😆😉😊😋😎😍😘🥰😗😙😚☺️☺🙂🤗🤩🤔🤨😐😑😶🙄😏😣😥😮🤐😯😪😫😴😌😛😜😝🤤😒😓😔😕🙃🤑😲☹️☹🙁😖😞😟😤😢😭😦😧😨😩🤯😬😰😱🥵🥶😳🤪😵😡😠🤬😷🤒🤕🤢🤮🤧😇🤠🥳🥴🥺🤥🤫🤭🧐🤓😈👿🤡👹👺💀☠️☠👻👽👾🤖💩😺😸😹😻😼😽🙀😿😾🙈🙉🙊🏻🏼🏽🏾🏿👶👶🏻👶🏼👶🏽👶🏾👶🏿🧒🧒🏻🧒🏼🧒🏽🧒🏾🧒🏿👦👦🏻👦🏼👦🏽👦🏾👦🏿👧👧🏻👧🏼👧🏽👧🏾👧🏿🧑🧑🏻🧑🏼🧑🏽🧑🏾🧑🏿👨👨🏻👨🏼👨🏽👨🏾👨🏿👩👩🏻👩🏼👩🏽👩🏾👩🏿🧓🧓🏻🧓🏼🧓🏽🧓🏾🧓🏿👴👴🏻👴🏼👴🏽👴🏾👴🏿👵👵🏻👵🏼👵🏽👵🏾👵🏿👨‍⚕️👨‍⚕👨🏻‍⚕️👨🏻‍⚕👨🏼‍⚕️👨🏼‍⚕👨🏽‍⚕️👨🏽‍⚕👨🏾‍⚕️👨🏾‍⚕👨🏿‍⚕️👨🏿‍⚕👩‍⚕️👩‍⚕👩🏻‍⚕️👩🏻‍⚕👩🏼‍⚕️👩🏼‍⚕👩🏽‍⚕️👩🏽‍⚕👩🏾‍⚕️👩🏾‍⚕👩🏿‍⚕️👩🏿‍⚕👨‍🎓👨🏻‍🎓👨🏼‍🎓👨🏽‍🎓👨🏾‍🎓👨🏿‍🎓👩‍🎓👩🏻‍🎓👩🏼‍🎓👩🏽‍🎓👩🏾‍🎓👩🏿‍🎓👨‍🏫👨🏻‍🏫👨🏼‍🏫👨🏽‍🏫👨🏾‍🏫👨🏿‍🏫👩‍🏫👩🏻‍🏫👩🏼‍🏫👩🏽‍🏫👩🏾‍🏫👩🏿‍🏫👨‍⚖️👨‍⚖👨🏻‍⚖️👨🏻‍⚖👨🏼‍⚖️👨🏼‍⚖👨🏽‍⚖️👨🏽‍⚖👨🏾‍⚖️👨🏾‍⚖👨🏿‍⚖️👨🏿‍⚖👩‍⚖️👩‍⚖👩🏻‍⚖️👩🏻‍⚖👩🏼‍⚖️👩🏼‍⚖👩🏽‍⚖️👩🏽‍⚖👩🏾‍⚖️👩🏾‍⚖👩🏿‍⚖️👩🏿‍⚖👨‍🌾👨🏻‍🌾👨🏼‍🌾👨🏽‍🌾👨🏾‍🌾👨🏿‍🌾👩‍🌾👩🏻‍🌾👩🏼‍🌾👩🏽‍🌾👩🏾‍🌾👩🏿‍🌾👨‍🍳👨🏻‍🍳👨🏼‍🍳👨🏽‍🍳👨🏾‍🍳👨🏿‍🍳👩‍🍳👩🏻‍🍳👩🏼‍🍳👩🏽‍🍳👩🏾‍🍳👩🏿‍🍳👨‍🔧👨🏻‍🔧👨🏼‍🔧👨🏽‍🔧👨🏾‍🔧👨🏿‍🔧👩‍🔧👩🏻‍🔧👩🏼‍🔧👩🏽‍🔧👩🏾‍🔧👩🏿‍🔧👨‍🏭👨🏻‍🏭👨🏼‍🏭👨🏽‍🏭👨🏾‍🏭👨🏿‍🏭👩‍🏭👩🏻‍🏭👩🏼‍🏭👩🏽‍🏭👩🏾‍🏭👩🏿‍🏭👨‍💼👨🏻‍💼👨🏼‍💼👨🏽‍💼👨🏾‍💼👨🏿‍💼👩‍💼👩🏻‍💼👩🏼‍💼👩🏽‍💼👩🏾‍💼👩🏿‍💼👨‍🔬👨🏻‍🔬👨🏼‍🔬👨🏽‍🔬👨🏾‍🔬👨🏿‍🔬👩‍🔬👩🏻‍🔬👩🏼‍🔬👩🏽‍🔬👩🏾‍🔬👩🏿‍🔬👨‍💻👨🏻‍💻👨🏼‍💻👨🏽‍💻👨🏾‍💻👨🏿‍💻👩‍💻👩🏻‍💻👩🏼‍💻👩🏽‍💻👩🏾‍💻👩🏿‍💻👨‍🎤👨🏻‍🎤👨🏼‍🎤👨🏽‍🎤👨🏾‍🎤👨🏿‍🎤👩‍🎤👩🏻‍🎤👩🏼‍🎤👩🏽‍🎤👩🏾‍🎤👩🏿‍🎤👨‍🎨👨🏻‍🎨👨🏼‍🎨👨🏽‍🎨👨🏾‍🎨👨🏿‍🎨👩‍🎨👩🏻‍🎨👩🏼‍🎨👩🏽‍🎨👩🏾‍🎨👩🏿‍🎨👨‍✈️👨‍✈👨🏻‍✈️👨🏻‍✈👨🏼‍✈️👨🏼‍✈👨🏽‍✈️👨🏽‍✈👨🏾‍✈️👨🏾‍✈👨🏿‍✈️👨🏿‍✈👩‍✈️👩‍✈👩🏻‍✈️👩🏻‍✈👩🏼‍✈️👩🏼‍✈👩🏽‍✈️👩🏽‍✈👩🏾‍✈️👩🏾‍✈👩🏿‍✈️👩🏿‍✈👨‍🚀👨🏻‍🚀👨🏼‍🚀👨🏽‍🚀👨🏾‍🚀👨🏿‍🚀👩‍🚀👩🏻‍🚀👩🏼‍🚀👩🏽‍🚀👩🏾‍🚀👩🏿‍🚀👨‍🚒👨🏻‍🚒👨🏼‍🚒👨🏽‍🚒👨🏾‍🚒👨🏿‍🚒👩‍🚒👩🏻‍🚒👩🏼‍🚒👩🏽‍🚒👩🏾‍🚒👩🏿‍🚒👮👮🏻👮🏼👮🏽👮🏾👮🏿👮‍♂️👮‍♂👮🏻‍♂️👮🏻‍♂👮🏼‍♂️👮🏼‍♂👮🏽‍♂️👮🏽‍♂👮🏾‍♂️👮🏾‍♂👮🏿‍♂️👮🏿‍♂👮‍♀️👮‍♀👮🏻‍♀️👮🏻‍♀👮🏼‍♀️👮🏼‍♀👮🏽‍♀️👮🏽‍♀👮🏾‍♀️👮🏾‍♀👮🏿‍♀️👮🏿‍♀🕵️🕵🕵🏻🕵🏼🕵🏽🕵🏾🕵🏿🕵️‍♂️🕵‍♂️🕵️‍♂🕵‍♂🕵🏻‍♂️🕵🏻‍♂🕵🏼‍♂️🕵🏼‍♂🕵🏽‍♂️🕵🏽‍♂🕵🏾‍♂️🕵🏾‍♂🕵🏿‍♂️🕵🏿‍♂🕵️‍♀️🕵‍♀️🕵️‍♀🕵‍♀🕵🏻‍♀️🕵🏻‍♀🕵🏼‍♀️🕵🏼‍♀🕵🏽‍♀️🕵🏽‍♀🕵🏾‍♀️🕵🏾‍♀🕵🏿‍♀️🕵🏿‍♀💂💂🏻💂🏼💂🏽💂🏾💂🏿💂‍♂️💂‍♂💂🏻‍♂️💂🏻‍♂💂🏼‍♂️💂🏼‍♂💂🏽‍♂️💂🏽‍♂💂🏾‍♂️💂🏾‍♂💂🏿‍♂️💂🏿‍♂💂‍♀️💂‍♀💂🏻‍♀️💂🏻‍♀💂🏼‍♀️💂🏼‍♀💂🏽‍♀️💂🏽‍♀💂🏾‍♀️💂🏾‍♀💂🏿‍♀️💂🏿‍♀👷👷🏻👷🏼👷🏽👷🏾👷🏿👷‍♂️👷‍♂👷🏻‍♂️👷🏻‍♂👷🏼‍♂️👷🏼‍♂👷🏽‍♂️👷🏽‍♂👷🏾‍♂️👷🏾‍♂👷🏿‍♂️👷🏿‍♂👷‍♀️👷‍♀👷🏻‍♀️👷🏻‍♀👷🏼‍♀️👷🏼‍♀👷🏽‍♀️👷🏽‍♀👷🏾‍♀️👷🏾‍♀👷🏿‍♀️👷🏿‍♀🤴🤴🏻🤴🏼🤴🏽🤴🏾🤴🏿👸👸🏻👸🏼👸🏽👸🏾👸🏿👳👳🏻👳🏼👳🏽👳🏾👳🏿👳‍♂️👳‍♂👳🏻‍♂️👳🏻‍♂👳🏼‍♂️👳🏼‍♂👳🏽‍♂️👳🏽‍♂👳🏾‍♂️👳🏾‍♂👳🏿‍♂️👳🏿‍♂👳‍♀️👳‍♀👳🏻‍♀️👳🏻‍♀👳🏼‍♀️👳🏼‍♀👳🏽‍♀️👳🏽‍♀👳🏾‍♀️👳🏾‍♀👳🏿‍♀️👳🏿‍♀👲👲🏻👲🏼👲🏽👲🏾👲🏿🧕🧕🏻🧕🏼🧕🏽🧕🏾🧕🏿🧔🧔🏻🧔🏼🧔🏽🧔🏾🧔🏿👱👱🏻👱🏼👱🏽👱🏾👱🏿👱‍♂️👱‍♂👱🏻‍♂️👱🏻‍♂👱🏼‍♂️👱🏼‍♂👱🏽‍♂️👱🏽‍♂👱🏾‍♂️👱🏾‍♂👱🏿‍♂️👱🏿‍♂👱‍♀️👱‍♀👱🏻‍♀️👱🏻‍♀👱🏼‍♀️👱🏼‍♀👱🏽‍♀️👱🏽‍♀👱🏾‍♀️👱🏾‍♀👱🏿‍♀️👱🏿‍♀👨‍🦰👨🏻‍🦰👨🏼‍🦰👨🏽‍🦰👨🏾‍🦰👨🏿‍🦰👩‍🦰👩🏻‍🦰👩🏼‍🦰👩🏽‍🦰👩🏾‍🦰👩🏿‍🦰👨‍🦱👨🏻‍🦱👨🏼‍🦱👨🏽‍🦱👨🏾‍🦱👨🏿‍🦱👩‍🦱👩🏻‍🦱👩🏼‍🦱👩🏽‍🦱👩🏾‍🦱👩🏿‍🦱👨‍🦲👨🏻‍🦲👨🏼‍🦲👨🏽‍🦲👨🏾‍🦲👨🏿‍🦲👩‍🦲👩🏻‍🦲👩🏼‍🦲👩🏽‍🦲👩🏾‍🦲👩🏿‍🦲👨‍🦳👨🏻‍🦳👨🏼‍🦳👨🏽‍🦳👨🏾‍🦳👨🏿‍🦳👩‍🦳👩🏻‍🦳👩🏼‍🦳👩🏽‍🦳👩🏾‍🦳👩🏿‍🦳🤵🤵🏻🤵🏼🤵🏽🤵🏾🤵🏿👰👰🏻👰🏼👰🏽👰🏾👰🏿🤰🤰🏻🤰🏼🤰🏽🤰🏾🤰🏿🤱🤱🏻🤱🏼🤱🏽🤱🏾🤱🏿👼👼🏻👼🏼👼🏽👼🏾👼🏿🎅🎅🏻🎅🏼🎅🏽🎅🏾🎅🏿🤶🤶🏻🤶🏼🤶🏽🤶🏾🤶🏿🦸🦸🏻🦸🏼🦸🏽🦸🏾🦸🏿🦸‍♀️🦸‍♀🦸🏻‍♀️🦸🏻‍♀🦸🏼‍♀️🦸🏼‍♀🦸🏽‍♀️🦸🏽‍♀🦸🏾‍♀️🦸🏾‍♀🦸🏿‍♀️🦸🏿‍♀🦸‍♂️🦸‍♂🦸🏻‍♂️🦸🏻‍♂🦸🏼‍♂️🦸🏼‍♂🦸🏽‍♂️🦸🏽‍♂🦸🏾‍♂️🦸🏾‍♂🦸🏿‍♂️🦸🏿‍♂🦹🦹🏻🦹🏼🦹🏽🦹🏾🦹🏿🦹‍♀️🦹‍♀🦹🏻‍♀️🦹🏻‍♀🦹🏼‍♀️🦹🏼‍♀🦹🏽‍♀️🦹🏽‍♀🦹🏾‍♀️🦹🏾‍♀🦹🏿‍♀️🦹🏿‍♀🦹‍♂️🦹‍♂🦹🏻‍♂️🦹🏻‍♂🦹🏼‍♂️🦹🏼‍♂🦹🏽‍♂️🦹🏽‍♂🦹🏾‍♂️🦹🏾‍♂🦹🏿‍♂️🦹🏿‍♂🧙🧙🏻🧙🏼🧙🏽🧙🏾🧙🏿🧙‍♀️🧙‍♀🧙🏻‍♀️🧙🏻‍♀🧙🏼‍♀️🧙🏼‍♀🧙🏽‍♀️🧙🏽‍♀🧙🏾‍♀️🧙🏾‍♀🧙🏿‍♀️🧙🏿‍♀🧙‍♂️🧙‍♂🧙🏻‍♂️🧙🏻‍♂🧙🏼‍♂️🧙🏼‍♂🧙🏽‍♂️🧙🏽‍♂🧙🏾‍♂️🧙🏾‍♂🧙🏿‍♂️🧙🏿‍♂🧚🧚🏻🧚🏼🧚🏽🧚🏾🧚🏿🧚‍♀️🧚‍♀🧚🏻‍♀️🧚🏻‍♀🧚🏼‍♀️🧚🏼‍♀🧚🏽‍♀️🧚🏽‍♀🧚🏾‍♀️🧚🏾‍♀🧚🏿‍♀️🧚🏿‍♀🧚‍♂️🧚‍♂🧚🏻‍♂️🧚🏻‍♂🧚🏼‍♂️🧚🏼‍♂🧚🏽‍♂️🧚🏽‍♂🧚🏾‍♂️🧚🏾‍♂🧚🏿‍♂️🧚🏿‍♂🧛🧛🏻🧛🏼🧛🏽🧛🏾🧛🏿🧛‍♀️🧛‍♀🧛🏻‍♀️🧛🏻‍♀🧛🏼‍♀️🧛🏼‍♀🧛🏽‍♀️🧛🏽‍♀🧛🏾‍♀️🧛🏾‍♀🧛🏿‍♀️🧛🏿‍♀🧛‍♂️🧛‍♂🧛🏻‍♂️🧛🏻‍♂🧛🏼‍♂️🧛🏼‍♂🧛🏽‍♂️🧛🏽‍♂🧛🏾‍♂️🧛🏾‍♂🧛🏿‍♂️🧛🏿‍♂🧜🧜🏻🧜🏼🧜🏽🧜🏾🧜🏿🧜‍♀️🧜‍♀🧜🏻‍♀️🧜🏻‍♀🧜🏼‍♀️🧜🏼‍♀🧜🏽‍♀️🧜🏽‍♀🧜🏾‍♀️🧜🏾‍♀🧜🏿‍♀️🧜🏿‍♀🧜‍♂️🧜‍♂🧜🏻‍♂️🧜🏻‍♂🧜🏼‍♂️🧜🏼‍♂🧜🏽‍♂️🧜🏽‍♂🧜🏾‍♂️🧜🏾‍♂🧜🏿‍♂️🧜🏿‍♂🧝🧝🏻🧝🏼🧝🏽🧝🏾🧝🏿🧝‍♀️🧝‍♀🧝🏻‍♀️🧝🏻‍♀🧝🏼‍♀️🧝🏼‍♀🧝🏽‍♀️🧝🏽‍♀🧝🏾‍♀️🧝🏾‍♀🧝🏿‍♀️🧝🏿‍♀🧝‍♂️🧝‍♂🧝🏻‍♂️🧝🏻‍♂🧝🏼‍♂️🧝🏼‍♂🧝🏽‍♂️🧝🏽‍♂🧝🏾‍♂️🧝🏾‍♂🧝🏿‍♂️🧝🏿‍♂🧞🧞‍♀️🧞‍♀🧞‍♂️🧞‍♂🧟🧟‍♀️🧟‍♀🧟‍♂️🧟‍♂🙍🙍🏻🙍🏼🙍🏽🙍🏾🙍🏿🙍‍♂️🙍‍♂🙍🏻‍♂️🙍🏻‍♂🙍🏼‍♂️🙍🏼‍♂🙍🏽‍♂️🙍🏽‍♂🙍🏾‍♂️🙍🏾‍♂🙍🏿‍♂️🙍🏿‍♂🙍‍♀️🙍‍♀🙍🏻‍♀️🙍🏻‍♀🙍🏼‍♀️🙍🏼‍♀🙍🏽‍♀️🙍🏽‍♀🙍🏾‍♀️🙍🏾‍♀🙍🏿‍♀️🙍🏿‍♀🙎🙎🏻🙎🏼🙎🏽🙎🏾🙎🏿🙎‍♂️🙎‍♂🙎🏻‍♂️🙎🏻‍♂🙎🏼‍♂️🙎🏼‍♂🙎🏽‍♂️🙎🏽‍♂🙎🏾‍♂️🙎🏾‍♂🙎🏿‍♂️🙎🏿‍♂🙎‍♀️🙎‍♀🙎🏻‍♀️🙎🏻‍♀🙎🏼‍♀️🙎🏼‍♀🙎🏽‍♀️🙎🏽‍♀🙎🏾‍♀️🙎🏾‍♀🙎🏿‍♀️🙎🏿‍♀🙅🙅🏻🙅🏼🙅🏽🙅🏾🙅🏿🙅‍♂️🙅‍♂🙅🏻‍♂️🙅🏻‍♂🙅🏼‍♂️🙅🏼‍♂🙅🏽‍♂️🙅🏽‍♂🙅🏾‍♂️🙅🏾‍♂🙅🏿‍♂️🙅🏿‍♂🙅‍♀️🙅‍♀🙅🏻‍♀️🙅🏻‍♀🙅🏼‍♀️🙅🏼‍♀🙅🏽‍♀️🙅🏽‍♀🙅🏾‍♀️🙅🏾‍♀🙅🏿‍♀️🙅🏿‍♀🙆🙆🏻🙆🏼🙆🏽🙆🏾🙆🏿🙆‍♂️🙆‍♂🙆🏻‍♂️🙆🏻‍♂🙆🏼‍♂️🙆🏼‍♂🙆🏽‍♂️🙆🏽‍♂🙆🏾‍♂️🙆🏾‍♂🙆🏿‍♂️🙆🏿‍♂🙆‍♀️🙆‍♀🙆🏻‍♀️🙆🏻‍♀🙆🏼‍♀️🙆🏼‍♀🙆🏽‍♀️🙆🏽‍♀🙆🏾‍♀️🙆🏾‍♀🙆🏿‍♀️🙆🏿‍♀💁💁🏻💁🏼💁🏽💁🏾💁🏿💁‍♂️💁‍♂💁🏻‍♂️💁🏻‍♂💁🏼‍♂️💁🏼‍♂💁🏽‍♂️💁🏽‍♂💁🏾‍♂️💁🏾‍♂💁🏿‍♂️💁🏿‍♂💁‍♀️💁‍♀💁🏻‍♀️💁🏻‍♀💁🏼‍♀️💁🏼‍♀💁🏽‍♀️💁🏽‍♀💁🏾‍♀️💁🏾‍♀💁🏿‍♀️💁🏿‍♀🙋🙋🏻🙋🏼🙋🏽🙋🏾🙋🏿🙋‍♂️🙋‍♂🙋🏻‍♂️🙋🏻‍♂🙋🏼‍♂️🙋🏼‍♂🙋🏽‍♂️🙋🏽‍♂🙋🏾‍♂️🙋🏾‍♂🙋🏿‍♂️🙋🏿‍♂🙋‍♀️🙋‍♀🙋🏻‍♀️🙋🏻‍♀🙋🏼‍♀️🙋🏼‍♀🙋🏽‍♀️🙋🏽‍♀🙋🏾‍♀️🙋🏾‍♀🙋🏿‍♀️🙋🏿‍♀🙇🙇🏻🙇🏼🙇🏽🙇🏾🙇🏿🙇‍♂️🙇‍♂🙇🏻‍♂️🙇🏻‍♂🙇🏼‍♂️🙇🏼‍♂🙇🏽‍♂️🙇🏽‍♂🙇🏾‍♂️🙇🏾‍♂🙇🏿‍♂️🙇🏿‍♂🙇‍♀️🙇‍♀🙇🏻‍♀️🙇🏻‍♀🙇🏼‍♀️🙇🏼‍♀🙇🏽‍♀️🙇🏽‍♀🙇🏾‍♀️🙇🏾‍♀🙇🏿‍♀️🙇🏿‍♀🤦🤦🏻🤦🏼🤦🏽🤦🏾🤦🏿🤦‍♂️🤦‍♂🤦🏻‍♂️🤦🏻‍♂🤦🏼‍♂️🤦🏼‍♂🤦🏽‍♂️🤦🏽‍♂🤦🏾‍♂️🤦🏾‍♂🤦🏿‍♂️🤦🏿‍♂🤦‍♀️🤦‍♀🤦🏻‍♀️🤦🏻‍♀🤦🏼‍♀️🤦🏼‍♀🤦🏽‍♀️🤦🏽‍♀🤦🏾‍♀️🤦🏾‍♀🤦🏿‍♀️🤦🏿‍♀🤷🤷🏻🤷🏼🤷🏽🤷🏾🤷🏿🤷‍♂️🤷‍♂🤷🏻‍♂️🤷🏻‍♂🤷🏼‍♂️🤷🏼‍♂🤷🏽‍♂️🤷🏽‍♂🤷🏾‍♂️🤷🏾‍♂🤷🏿‍♂️🤷🏿‍♂🤷‍♀️🤷‍♀🤷🏻‍♀️🤷🏻‍♀🤷🏼‍♀️🤷🏼‍♀🤷🏽‍♀️🤷🏽‍♀🤷🏾‍♀️🤷🏾‍♀🤷🏿‍♀️🤷🏿‍♀💆💆🏻💆🏼💆🏽💆🏾💆🏿💆‍♂️💆‍♂💆🏻‍♂️💆🏻‍♂💆🏼‍♂️💆🏼‍♂💆🏽‍♂️💆🏽‍♂💆🏾‍♂️💆🏾‍♂💆🏿‍♂️💆🏿‍♂💆‍♀️💆‍♀💆🏻‍♀️💆🏻‍♀💆🏼‍♀️💆🏼‍♀💆🏽‍♀️💆🏽‍♀💆🏾‍♀️💆🏾‍♀💆🏿‍♀️💆🏿‍♀💇💇🏻💇🏼💇🏽💇🏾💇🏿💇‍♂️💇‍♂💇🏻‍♂️💇🏻‍♂💇🏼‍♂️💇🏼‍♂💇🏽‍♂️💇🏽‍♂💇🏾‍♂️💇🏾‍♂💇🏿‍♂️💇🏿‍♂💇‍♀️💇‍♀💇🏻‍♀️💇🏻‍♀💇🏼‍♀️💇🏼‍♀💇🏽‍♀️💇🏽‍♀💇🏾‍♀️💇🏾‍♀💇🏿‍♀️💇🏿‍♀🚶🚶🏻🚶🏼🚶🏽🚶🏾🚶🏿🚶‍♂️🚶‍♂🚶🏻‍♂️🚶🏻‍♂🚶🏼‍♂️🚶🏼‍♂🚶🏽‍♂️🚶🏽‍♂🚶🏾‍♂️🚶🏾‍♂🚶🏿‍♂️🚶🏿‍♂🚶‍♀️🚶‍♀🚶🏻‍♀️🚶🏻‍♀🚶🏼‍♀️🚶🏼‍♀🚶🏽‍♀️🚶🏽‍♀🚶🏾‍♀️🚶🏾‍♀🚶🏿‍♀️🚶🏿‍♀🏃🏃🏻🏃🏼🏃🏽🏃🏾🏃🏿🏃‍♂️🏃‍♂🏃🏻‍♂️🏃🏻‍♂🏃🏼‍♂️🏃🏼‍♂🏃🏽‍♂️🏃🏽‍♂🏃🏾‍♂️🏃🏾‍♂🏃🏿‍♂️🏃🏿‍♂🏃‍♀️🏃‍♀🏃🏻‍♀️🏃🏻‍♀🏃🏼‍♀️🏃🏼‍♀🏃🏽‍♀️🏃🏽‍♀🏃🏾‍♀️🏃🏾‍♀🏃🏿‍♀️🏃🏿‍♀💃💃🏻💃🏼💃🏽💃🏾💃🏿🕺🕺🏻🕺🏼🕺🏽🕺🏾🕺🏿👯👯‍♂️👯‍♂👯‍♀️👯‍♀🧖🧖🏻🧖🏼🧖🏽🧖🏾🧖🏿🧖‍♀️🧖‍♀🧖🏻‍♀️🧖🏻‍♀🧖🏼‍♀️🧖🏼‍♀🧖🏽‍♀️🧖🏽‍♀🧖🏾‍♀️🧖🏾‍♀🧖🏿‍♀️🧖🏿‍♀🧖‍♂️🧖‍♂🧖🏻‍♂️🧖🏻‍♂🧖🏼‍♂️🧖🏼‍♂🧖🏽‍♂️🧖🏽‍♂🧖🏾‍♂️🧖🏾‍♂🧖🏿‍♂️🧖🏿‍♂🧗🧗🏻🧗🏼🧗🏽🧗🏾🧗🏿🧗‍♀️🧗‍♀🧗🏻‍♀️🧗🏻‍♀🧗🏼‍♀️🧗🏼‍♀🧗🏽‍♀️🧗🏽‍♀🧗🏾‍♀️🧗🏾‍♀🧗🏿‍♀️🧗🏿‍♀🧗‍♂️🧗‍♂🧗🏻‍♂️🧗🏻‍♂🧗🏼‍♂️🧗🏼‍♂🧗🏽‍♂️🧗🏽‍♂🧗🏾‍♂️🧗🏾‍♂🧗🏿‍♂️🧗🏿‍♂🧘🧘🏻🧘🏼🧘🏽🧘🏾🧘🏿🧘‍♀️🧘‍♀🧘🏻‍♀️🧘🏻‍♀🧘🏼‍♀️🧘🏼‍♀🧘🏽‍♀️🧘🏽‍♀🧘🏾‍♀️🧘🏾‍♀🧘🏿‍♀️🧘🏿‍♀🧘‍♂️🧘‍♂🧘🏻‍♂️🧘🏻‍♂🧘🏼‍♂️🧘🏼‍♂🧘🏽‍♂️🧘🏽‍♂🧘🏾‍♂️🧘🏾‍♂🧘🏿‍♂️🧘🏿‍♂🛀🛀🏻🛀🏼🛀🏽🛀🏾🛀🏿🛌🛌🏻🛌🏼🛌🏽🛌🏾🛌🏿🕴️🕴🕴🏻🕴🏼🕴🏽🕴🏾🕴🏿🗣️🗣👤👥🤺🏇🏇🏻🏇🏼🏇🏽🏇🏾🏇🏿⛷️⛷🏂🏂🏻🏂🏼🏂🏽🏂🏾🏂🏿🏌️🏌🏌🏻🏌🏼🏌🏽🏌🏾🏌🏿🏌️‍♂️🏌‍♂️🏌️‍♂🏌‍♂🏌🏻‍♂️🏌🏻‍♂🏌🏼‍♂️🏌🏼‍♂🏌🏽‍♂️🏌🏽‍♂🏌🏾‍♂️🏌🏾‍♂🏌🏿‍♂️🏌🏿‍♂🏌️‍♀️🏌‍♀️🏌️‍♀🏌‍♀🏌🏻‍♀️🏌🏻‍♀🏌🏼‍♀️🏌🏼‍♀🏌🏽‍♀️🏌🏽‍♀🏌🏾‍♀️🏌🏾‍♀🏌🏿‍♀️🏌🏿‍♀🏄🏄🏻🏄🏼🏄🏽🏄🏾🏄🏿🏄‍♂️🏄‍♂🏄🏻‍♂️🏄🏻‍♂🏄🏼‍♂️🏄🏼‍♂🏄🏽‍♂️🏄🏽‍♂🏄🏾‍♂️🏄🏾‍♂🏄🏿‍♂️🏄🏿‍♂🏄‍♀️🏄‍♀🏄🏻‍♀️🏄🏻‍♀🏄🏼‍♀️🏄🏼‍♀🏄🏽‍♀️🏄🏽‍♀🏄🏾‍♀️🏄🏾‍♀🏄🏿‍♀️🏄🏿‍♀🚣🚣🏻🚣🏼🚣🏽🚣🏾🚣🏿🚣‍♂️🚣‍♂🚣🏻‍♂️🚣🏻‍♂🚣🏼‍♂️🚣🏼‍♂🚣🏽‍♂️🚣🏽‍♂🚣🏾‍♂️🚣🏾‍♂🚣🏿‍♂️🚣🏿‍♂🚣‍♀️🚣‍♀🚣🏻‍♀️🚣🏻‍♀🚣🏼‍♀️🚣🏼‍♀🚣🏽‍♀️🚣🏽‍♀🚣🏾‍♀️🚣🏾‍♀🚣🏿‍♀️🚣🏿‍♀🏊🏊🏻🏊🏼🏊🏽🏊🏾🏊🏿🏊‍♂️🏊‍♂🏊🏻‍♂️🏊🏻‍♂🏊🏼‍♂️🏊🏼‍♂🏊🏽‍♂️🏊🏽‍♂🏊🏾‍♂️🏊🏾‍♂🏊🏿‍♂️🏊🏿‍♂🏊‍♀️🏊‍♀🏊🏻‍♀️🏊🏻‍♀🏊🏼‍♀️🏊🏼‍♀🏊🏽‍♀️🏊🏽‍♀🏊🏾‍♀️🏊🏾‍♀🏊🏿‍♀️🏊🏿‍♀⛹️⛹⛹🏻⛹🏼⛹🏽⛹🏾⛹🏿⛹️‍♂️⛹‍♂️⛹️‍♂⛹‍♂⛹🏻‍♂️⛹🏻‍♂⛹🏼‍♂️⛹🏼‍♂⛹🏽‍♂️⛹🏽‍♂⛹🏾‍♂️⛹🏾‍♂⛹🏿‍♂️⛹🏿‍♂⛹️‍♀️⛹‍♀️⛹️‍♀⛹‍♀⛹🏻‍♀️⛹🏻‍♀⛹🏼‍♀️⛹🏼‍♀⛹🏽‍♀️⛹🏽‍♀⛹🏾‍♀️⛹🏾‍♀⛹🏿‍♀️⛹🏿‍♀🏋️🏋🏋🏻🏋🏼🏋🏽🏋🏾🏋🏿🏋️‍♂️🏋‍♂️🏋️‍♂🏋‍♂🏋🏻‍♂️🏋🏻‍♂🏋🏼‍♂️🏋🏼‍♂🏋🏽‍♂️🏋🏽‍♂🏋🏾‍♂️🏋🏾‍♂🏋🏿‍♂️🏋🏿‍♂🏋️‍♀️🏋‍♀️🏋️‍♀🏋‍♀🏋🏻‍♀️🏋🏻‍♀🏋🏼‍♀️🏋🏼‍♀🏋🏽‍♀️🏋🏽‍♀🏋🏾‍♀️🏋🏾‍♀🏋🏿‍♀️🏋🏿‍♀🚴🚴🏻🚴🏼🚴🏽🚴🏾🚴🏿🚴‍♂️🚴‍♂🚴🏻‍♂️🚴🏻‍♂🚴🏼‍♂️🚴🏼‍♂🚴🏽‍♂️🚴🏽‍♂🚴🏾‍♂️🚴🏾‍♂🚴🏿‍♂️🚴🏿‍♂🚴‍♀️🚴‍♀🚴🏻‍♀️🚴🏻‍♀🚴🏼‍♀️🚴🏼‍♀🚴🏽‍♀️🚴🏽‍♀🚴🏾‍♀️🚴🏾‍♀🚴🏿‍♀️🚴🏿‍♀🚵🚵🏻🚵🏼🚵🏽🚵🏾🚵🏿🚵‍♂️🚵‍♂🚵🏻‍♂️🚵🏻‍♂🚵🏼‍♂️🚵🏼‍♂🚵🏽‍♂️🚵🏽‍♂🚵🏾‍♂️🚵🏾‍♂🚵🏿‍♂️🚵🏿‍♂🚵‍♀️🚵‍♀🚵🏻‍♀️🚵🏻‍♀🚵🏼‍♀️🚵🏼‍♀🚵🏽‍♀️🚵🏽‍♀🚵🏾‍♀️🚵🏾‍♀🚵🏿‍♀️🚵🏿‍♀🏎️🏎🏍️🏍🤸🤸🏻🤸🏼🤸🏽🤸🏾🤸🏿🤸‍♂️🤸‍♂🤸🏻‍♂️🤸🏻‍♂🤸🏼‍♂️🤸🏼‍♂🤸🏽‍♂️🤸🏽‍♂🤸🏾‍♂️🤸🏾‍♂🤸🏿‍♂️🤸🏿‍♂🤸‍♀️🤸‍♀🤸🏻‍♀️🤸🏻‍♀🤸🏼‍♀️🤸🏼‍♀🤸🏽‍♀️🤸🏽‍♀🤸🏾‍♀️🤸🏾‍♀🤸🏿‍♀️🤸🏿‍♀🤼🤼‍♂️🤼‍♂🤼‍♀️🤼‍♀🤽🤽🏻🤽🏼🤽🏽🤽🏾🤽🏿🤽‍♂️🤽‍♂🤽🏻‍♂️🤽🏻‍♂🤽🏼‍♂️🤽🏼‍♂🤽🏽‍♂️🤽🏽‍♂🤽🏾‍♂️🤽🏾‍♂🤽🏿‍♂️🤽🏿‍♂🤽‍♀️🤽‍♀🤽🏻‍♀️🤽🏻‍♀🤽🏼‍♀️🤽🏼‍♀🤽🏽‍♀️🤽🏽‍♀🤽🏾‍♀️🤽🏾‍♀🤽🏿‍♀️🤽🏿‍♀🤾🤾🏻🤾🏼🤾🏽🤾🏾🤾🏿🤾‍♂️🤾‍♂🤾🏻‍♂️🤾🏻‍♂🤾🏼‍♂️🤾🏼‍♂🤾🏽‍♂️🤾🏽‍♂🤾🏾‍♂️🤾🏾‍♂🤾🏿‍♂️🤾🏿‍♂🤾‍♀️🤾‍♀🤾🏻‍♀️🤾🏻‍♀🤾🏼‍♀️🤾🏼‍♀🤾🏽‍♀️🤾🏽‍♀🤾🏾‍♀️🤾🏾‍♀🤾🏿‍♀️🤾🏿‍♀🤹🤹🏻🤹🏼🤹🏽🤹🏾🤹🏿🤹‍♂️🤹‍♂🤹🏻‍♂️🤹🏻‍♂🤹🏼‍♂️🤹🏼‍♂🤹🏽‍♂️🤹🏽‍♂🤹🏾‍♂️🤹🏾‍♂🤹🏿‍♂️🤹🏿‍♂🤹‍♀️🤹‍♀🤹🏻‍♀️🤹🏻‍♀🤹🏼‍♀️🤹🏼‍♀🤹🏽‍♀️🤹🏽‍♀🤹🏾‍♀️🤹🏾‍♀🤹🏿‍♀️🤹🏿‍♀👫👬👭💏👩‍❤️‍💋‍👨👩‍❤‍💋‍👨👨‍❤️‍💋‍👨👨‍❤‍💋‍👨👩‍❤️‍💋‍👩👩‍❤‍💋‍👩💑👩‍❤️‍👨👩‍❤‍👨👨‍❤️‍👨👨‍❤‍👨👩‍❤️‍👩👩‍❤‍👩👪👨‍👩‍👦👨‍👩‍👧👨‍👩‍👧‍👦👨‍👩‍👦‍👦👨‍👩‍👧‍👧👨‍👨‍👦👨‍👨‍👧👨‍👨‍👧‍👦👨‍👨‍👦‍👦👨‍👨‍👧‍👧👩‍👩‍👦👩‍👩‍👧👩‍👩‍👧‍👦👩‍👩‍👦‍👦👩‍👩‍👧‍👧👨‍👦👨‍👦‍👦👨‍👧👨‍👧‍👦👨‍👧‍👧👩‍👦👩‍👦‍👦👩‍👧👩‍👧‍👦👩‍👧‍👧🤳🤳🏻🤳🏼🤳🏽🤳🏾🤳🏿💪💪🏻💪🏼💪🏽💪🏾💪🏿🦵🦵🏻🦵🏼🦵🏽🦵🏾🦵🏿🦶🦶🏻🦶🏼🦶🏽🦶🏾🦶🏿👈👈🏻👈🏼👈🏽👈🏾👈🏿👉👉🏻👉🏼👉🏽👉🏾👉🏿☝️☝☝🏻☝🏼☝🏽☝🏾☝🏿👆👆🏻👆🏼👆🏽👆🏾👆🏿🖕🖕🏻🖕🏼🖕🏽🖕🏾🖕🏿👇👇🏻👇🏼👇🏽👇🏾👇🏿✌️✌✌🏻✌🏼✌🏽✌🏾✌🏿🤞🤞🏻🤞🏼🤞🏽🤞🏾🤞🏿🖖🖖🏻🖖🏼🖖🏽🖖🏾🖖🏿🤘🤘🏻🤘🏼🤘🏽🤘🏾🤘🏿🤙🤙🏻🤙🏼🤙🏽🤙🏾🤙🏿🖐️🖐🖐🏻🖐🏼🖐🏽🖐🏾🖐🏿✋✋🏻✋🏼✋🏽✋🏾✋🏿👌👌🏻👌🏼👌🏽👌🏾👌🏿👍👍🏻👍🏼👍🏽👍🏾👍🏿👎👎🏻👎🏼👎🏽👎🏾👎🏿✊✊🏻✊🏼✊🏽✊🏾✊🏿👊👊🏻👊🏼👊🏽👊🏾👊🏿🤛🤛🏻🤛🏼🤛🏽🤛🏾🤛🏿🤜🤜🏻🤜🏼🤜🏽🤜🏾🤜🏿🤚🤚🏻🤚🏼🤚🏽🤚🏾🤚🏿👋👋🏻👋🏼👋🏽👋🏾👋🏿🤟🤟🏻🤟🏼🤟🏽🤟🏾🤟🏿✍️✍✍🏻✍🏼✍🏽✍🏾✍🏿👏👏🏻👏🏼👏🏽👏🏾👏🏿👐👐🏻👐🏼👐🏽👐🏾👐🏿🙌🙌🏻🙌🏼🙌🏽🙌🏾🙌🏿🤲🤲🏻🤲🏼🤲🏽🤲🏾🤲🏿🙏🙏🏻🙏🏼🙏🏽🙏🏾🙏🏿🤝💅💅🏻💅🏼💅🏽💅🏾💅🏿👂👂🏻👂🏼👂🏽👂🏾👂🏿👃👃🏻👃🏼👃🏽👃🏾👃🏿🦰🦱🦲🦳👣👀👁️👁👁️‍🗨️👁‍🗨️👁️‍🗨👁‍🗨🧠🦴🦷👅👄💋💘❤️❤💓💔💕💖💗💙💚💛🧡💜🖤💝💞💟❣️❣💌💤💢💣💥💦💨💫💬🗨️🗨🗯️🗯💭🕳️🕳👓🕶️🕶🥽🥼👔👕👖🧣🧤🧥🧦👗👘👙👚👛👜👝🛍️🛍🎒👞👟🥾🥿👠👡👢👑👒🎩🎓🧢⛑️⛑📿💄💍💎🐵🐒🦍🐶🐕🐩🐺🦊🦝🐱🐈🦁🐯🐅🐆🐴🐎🦄🦓🦌🐮🐂🐃🐄🐷🐖🐗🐽🐏🐑🐐🐪🐫🦙🦒🐘🦏🦛🐭🐁🐀🐹🐰🐇🐿️🐿🦔🦇🐻🐨🐼🦘🦡🐾🦃🐔🐓🐣🐤🐥🐦🐧🕊️🕊🦅🦆🦢🦉🦚🦜🐸🐊🐢🦎🐍🐲🐉🦕🦖🐳🐋🐬🐟🐠🐡🦈🐙🐚🦀🦞🦐🦑🐌🦋🐛🐜🐝🐞🦗🕷️🕷🕸️🕸🦂🦟🦠💐🌸💮🏵️🏵🌹🥀🌺🌻🌼🌷🌱🌲🌳🌴🌵🌾🌿☘️☘🍀🍁🍂🍃🍇🍈🍉🍊🍋🍌🍍🥭🍎🍏🍐🍑🍒🍓🥝🍅🥥🥑🍆🥔🥕🌽🌶️🌶🥒🥬🥦🍄🥜🌰🍞🥐🥖🥨🥯🥞🧀🍖🍗🥩🥓🍔🍟🍕🌭🥪🌮🌯🥙🥚🍳🥘🍲🥣🥗🍿🧂🥫🍱🍘🍙🍚🍛🍜🍝🍠🍢🍣🍤🍥🥮🍡🥟🥠🥡🍦🍧🍨🍩🍪🎂🍰🧁🥧🍫🍬🍭🍮🍯🍼🥛☕🍵🍶🍾🍷🍸🍹🍺🍻🥂🥃🥤🥢🍽️🍽🍴🥄🔪🏺🌍🌎🌏🌐🗺️🗺🗾🧭🏔️🏔⛰️⛰🌋🗻🏕️🏕🏖️🏖🏜️🏜🏝️🏝🏞️🏞🏟️🏟🏛️🏛🏗️🏗🧱🏘️🏘🏚️🏚🏠🏡🏢🏣🏤🏥🏦🏨🏩🏪🏫🏬🏭🏯🏰💒🗼🗽⛪🕌🕍⛩️⛩🕋⛲⛺🌁🌃🏙️🏙🌄🌅🌆🌇🌉♨️♨🌌🎠🎡🎢💈🎪🚂🚃🚄🚅🚆🚇🚈🚉🚊🚝🚞🚋🚌🚍🚎🚐🚑🚒🚓🚔🚕🚖🚗🚘🚙🚚🚛🚜🚲🛴🛹🛵🚏🛣️🛣🛤️🛤🛢️🛢⛽🚨🚥🚦🛑🚧⚓⛵🛶🚤🛳️🛳⛴️⛴🛥️🛥🚢✈️✈🛩️🛩🛫🛬💺🚁🚟🚠🚡🛰️🛰🚀🛸🛎️🛎🧳⌛⏳⌚⏰⏱️⏱⏲️⏲🕰️🕰🕛🕧🕐🕜🕑🕝🕒🕞🕓🕟🕔🕠🕕🕡🕖🕢🕗🕣🕘🕤🕙🕥🕚🕦🌑🌒🌓🌔🌕🌖🌗🌘🌙🌚🌛🌜🌡️🌡☀️☀🌝🌞⭐🌟🌠☁️☁⛅⛈️⛈🌤️🌤🌥️🌥🌦️🌦🌧️🌧🌨️🌨🌩️🌩🌪️🌪🌫️🌫🌬️🌬🌀🌈🌂☂️☂☔⛱️⛱⚡❄️❄☃️☃⛄☄️☄🔥💧🌊🎃🎄🎆🎇🧨✨🎈🎉🎊🎋🎍🎎🎏🎐🎑🧧🎀🎁🎗️🎗🎟️🎟🎫🎖️🎖🏆🏅🥇🥈🥉⚽⚾🥎🏀🏐🏈🏉🎾🥏🎳🏏🏑🏒🥍🏓🏸🥊🥋🥅⛳⛸️⛸🎣🎽🎿🛷🥌🎯🎱🔮🧿🎮🕹️🕹🎰🎲🧩🧸♠️♠♥️♥♦️♦♣️♣♟️♟🃏🀄🎴🎭🖼️🖼🎨🧵🧶🔇🔈🔉🔊📢📣📯🔔🔕🎼🎵🎶🎙️🎙🎚️🎚🎛️🎛🎤🎧📻🎷🎸🎹🎺🎻🥁📱📲☎️☎📞📟📠🔋🔌💻🖥️🖥🖨️🖨⌨️⌨🖱️🖱🖲️🖲💽💾💿📀🧮🎥🎞️🎞📽️📽🎬📺📷📸📹📼🔍🔎🕯️🕯💡🔦🏮📔📕📖📗📘📙📚📓📒📃📜📄📰🗞️🗞📑🔖🏷️🏷💰💴💵💶💷💸💳🧾💹💱💲✉️✉📧📨📩📤📥📦📫📪📬📭📮🗳️🗳✏️✏✒️✒🖋️🖋🖊️🖊🖌️🖌🖍️🖍📝💼📁📂🗂️🗂📅📆🗒️🗒🗓️🗓📇📈📉📊📋📌📍📎🖇️🖇📏📐✂️✂🗃️🗃🗄️🗄🗑️🗑🔒🔓🔏🔐🔑🗝️🗝🔨⛏️⛏⚒️⚒🛠️🛠🗡️🗡⚔️⚔🔫🏹🛡️🛡🔧🔩⚙️⚙🗜️🗜⚖️⚖🔗⛓️⛓🧰🧲⚗️⚗🧪🧫🧬🔬🔭📡💉💊🚪🛏️🛏🛋️🛋🚽🚿🛁🧴🧷🧹🧺🧻🧼🧽🧯🛒🚬⚰️⚰⚱️⚱🗿🏧🚮🚰♿🚹🚺🚻🚼🚾🛂🛃🛄🛅⚠️⚠🚸⛔🚫🚳🚭🚯🚱🚷📵🔞☢️☢☣️☣⬆️⬆↗️↗➡️➡↘️↘⬇️⬇↙️↙⬅️⬅↖️↖↕️↕↔️↔↩️↩↪️↪⤴️⤴⤵️⤵🔃🔄🔙🔚🔛🔜🔝🛐⚛️⚛🕉️🕉✡️✡☸️☸☯️☯✝️✝☦️☦☪️☪☮️☮🕎🔯♈♉♊♋♌♍♎♏♐♑♒♓⛎🔀🔁🔂▶️▶⏩⏭️⏭⏯️⏯◀️◀⏪⏮️⏮🔼⏫🔽⏬⏸️⏸⏹️⏹⏺️⏺⏏️⏏🎦🔅🔆📶📳📴♀️♀♂️♂⚕️⚕♾️♾♻️♻⚜️⚜🔱📛🔰⭕✅☑️☑✔️✔✖️✖❌❎➕➖➗➰➿〽️〽✳️✳✴️✴❇️❇‼️‼⁉️⁉❓❔❕❗〰️〰©️©®️®™️™#️⃣#⃣*️⃣*⃣0️⃣0⃣1️⃣1⃣2️⃣2⃣3️⃣3⃣4️⃣4⃣5️⃣5⃣6️⃣6⃣7️⃣7⃣8️⃣8⃣9️⃣9⃣🔟💯🔠🔡🔢🔣🔤🅰️🅰🆎🅱️🅱🆑🆒🆓ℹ️ℹ🆔Ⓜ️Ⓜ🆕🆖🅾️🅾🆗🅿️🅿🆘🆙🆚🈁🈂️🈂🈷️🈷🈶🈯🉐🈹🈚🈲🉑🈸🈴🈳㊗️㊗㊙️㊙🈺🈵▪️▪▫️▫◻️◻◼️◼◽◾⬛⬜🔶🔷🔸🔹🔺🔻💠🔘🔲🔳⚪⚫🔴🔵🏁🚩🎌🏴🏳️🏳🏳️‍🌈🏳‍🌈🏴‍☠️🏴‍☠🇦🇨🇦🇩🇦🇪🇦🇫🇦🇬🇦🇮🇦🇱🇦🇲🇦🇴🇦🇶🇦🇷🇦🇸🇦🇹🇦🇺🇦🇼🇦🇽🇦🇿🇧🇦🇧🇧🇧🇩🇧🇪🇧🇫🇧🇬🇧🇭🇧🇮🇧🇯🇧🇱🇧🇲🇧🇳🇧🇴🇧🇶🇧🇷🇧🇸🇧🇹🇧🇻🇧🇼🇧🇾🇧🇿🇨🇦🇨🇨🇨🇩🇨🇫🇨🇬🇨🇭🇨🇮🇨🇰🇨🇱🇨🇲🇨🇳🇨🇴🇨🇵🇨🇷🇨🇺🇨🇻🇨🇼🇨🇽🇨🇾🇨🇿🇩🇪🇩🇬🇩🇯🇩🇰🇩🇲🇩🇴🇩🇿🇪🇦🇪🇨🇪🇪🇪🇬🇪🇭🇪🇷🇪🇸🇪🇹🇪🇺🇫🇮🇫🇯🇫🇰🇫🇲🇫🇴🇫🇷🇬🇦🇬🇧🇬🇩🇬🇪🇬🇫🇬🇬🇬🇭🇬🇮🇬🇱🇬🇲🇬🇳🇬🇵🇬🇶🇬🇷🇬🇸🇬🇹🇬🇺🇬🇼🇬🇾🇭🇰🇭🇲🇭🇳🇭🇷🇭🇹🇭🇺🇮🇨🇮🇩🇮🇪🇮🇱🇮🇲🇮🇳🇮🇴🇮🇶🇮🇷🇮🇸🇮🇹🇯🇪🇯🇲🇯🇴🇯🇵🇰🇪🇰🇬🇰🇭🇰🇮🇰🇲🇰🇳🇰🇵🇰🇷🇰🇼🇰🇾🇰🇿🇱🇦🇱🇧🇱🇨🇱🇮🇱🇰🇱🇷🇱🇸🇱🇹🇱🇺🇱🇻🇱🇾🇲🇦🇲🇨🇲🇩🇲🇪🇲🇫🇲🇬🇲🇭🇲🇰🇲🇱🇲🇲🇲🇳🇲🇴🇲🇵🇲🇶🇲🇷🇲🇸🇲🇹🇲🇺🇲🇻🇲🇼🇲🇽🇲🇾🇲🇿🇳🇦🇳🇨🇳🇪🇳🇫🇳🇬🇳🇮🇳🇱🇳🇴🇳🇵🇳🇷🇳🇺🇳🇿🇴🇲🇵🇦🇵🇪🇵🇫🇵🇬🇵🇭🇵🇰🇵🇱🇵🇲🇵🇳🇵🇷🇵🇸🇵🇹🇵🇼🇵🇾🇶🇦🇷🇪🇷🇴🇷🇸🇷🇺🇷🇼🇸🇦🇸🇧🇸🇨🇸🇩🇸🇪🇸🇬🇸🇭🇸🇮🇸🇯🇸🇰🇸🇱🇸🇲🇸🇳🇸🇴🇸🇷🇸🇸🇸🇹🇸🇻🇸🇽🇸🇾🇸🇿🇹🇦🇹🇨🇹🇩🇹🇫🇹🇬🇹🇭🇹🇯🇹🇰🇹🇱🇹🇲🇹🇳🇹🇴🇹🇷🇹🇹🇹🇻🇹🇼🇹🇿🇺🇦🇺🇬🇺🇲🇺🇳🇺🇸🇺🇾🇺🇿🇻🇦🇻🇨🇻🇪🇻🇬🇻🇮🇻🇳🇻🇺🇼🇫🇼🇸🇽🇰🇾🇪🇾🇹🇿🇦🇿🇲🇿🇼🏴󠁧󠁢󠁥󠁮󠁧󠁿🏴󠁧󠁢󠁳󠁣󠁴󠁿🏴󠁧󠁢󠁷󠁬󠁳󠁿" + ); + expect(() => emoji.parse(":-)")).toThrow(); + expect(() => emoji.parse("😀 is an emoji")).toThrow(); + expect(() => emoji.parse("😀stuff")).toThrow(); + expect(() => emoji.parse("stuff😀")).toThrow(); +}); + +test("nanoid", () => { + const nanoid = z.string().nanoid("custom error"); + nanoid.parse("lfNZluvAxMkf7Q8C5H-QS"); + nanoid.parse("mIU_4PJWikaU8fMbmkouz"); + nanoid.parse("Hb9ZUtUa2JDm_dD-47EGv"); + nanoid.parse("5Noocgv_8vQ9oPijj4ioQ"); + const result = nanoid.safeParse("Xq90uDyhddC53KsoASYJGX"); + expect(result).toMatchObject({ success: false }); + + expect(result.error!.issues[0].message).toEqual("custom error"); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "string", + "code": "invalid_format", + "format": "nanoid", + "pattern": "/^[a-zA-Z0-9_-]{21}$/", + "path": [], + "message": "custom error" + } + ]] + `); +}); + +test("bad nanoid", () => { + const nanoid = z.string().nanoid("custom error"); + nanoid.parse("ySh_984wpDUu7IQRrLXAp"); + const result = nanoid.safeParse("invalid nanoid"); + expect(result).toMatchObject({ success: false }); + + expect(result.error!.issues[0].message).toEqual("custom error"); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "string", + "code": "invalid_format", + "format": "nanoid", + "pattern": "/^[a-zA-Z0-9_-]{21}$/", + "path": [], + "message": "custom error" + } + ]] + `); +}); + +test("good uuid", () => { + const uuid = z.string().uuid("custom error"); + const goodUuids = [ + "9491d710-3185-1e06-bea0-6a2f275345e0", + "9491d710-3185-2e06-bea0-6a2f275345e0", + "9491d710-3185-3e06-bea0-6a2f275345e0", + "9491d710-3185-4e06-bea0-6a2f275345e0", + "9491d710-3185-5e06-bea0-6a2f275345e0", + "9491d710-3185-5e06-aea0-6a2f275345e0", + "9491d710-3185-5e06-8ea0-6a2f275345e0", + "9491d710-3185-5e06-9ea0-6a2f275345e0", + "00000000-0000-0000-0000-000000000000", + ]; + + for (const goodUuid of goodUuids) { + const result = uuid.safeParse(goodUuid); + expect(result.success).toEqual(true); + } +}); + +test(`bad uuid`, () => { + const uuid = z.string().uuid("custom error"); + for (const badUuid of [ + "9491d710-3185-0e06-bea0-6a2f275345e0", + "9491d710-3185-5e06-0ea0-6a2f275345e0", + "d89e7b01-7598-ed11-9d7a-0022489382fd", // new sequential id + "b3ce60f8-e8b9-40f5-1150-172ede56ff74", // Variant 0 - RFC 4122: Reserved, NCS backward compatibility + "92e76bf9-28b3-4730-cd7f-cb6bc51f8c09", // Variant 2 - RFC 4122: Reserved, Microsoft Corporation backward compatibility + "invalid uuid", + "9491d710-3185-4e06-bea0-6a2f275345e0X", + "ffffffff-ffff-ffff-ffff-ffffffffffff", + ]) { + const result = uuid.safeParse(badUuid); + expect(result).toMatchObject({ success: false }); + expect(result.error?.issues[0].message).toEqual("custom error"); + } +}); + +test("good guid", () => { + const guid = z.string().guid("custom error"); + for (const goodGuid of [ + "9491d710-3185-4e06-bea0-6a2f275345e0", + "d89e7b01-7598-ed11-9d7a-0022489382fd", // new sequential id + "b3ce60f8-e8b9-40f5-1150-172ede56ff74", // Variant 0 - RFC 4122: Reserved, NCS backward compatibility + "92e76bf9-28b3-4730-cd7f-cb6bc51f8c09", // Variant 2 - RFC 4122: Reserved, Microsoft Corporation backward compatibility + "00000000-0000-0000-0000-000000000000", + "ffffffff-ffff-ffff-ffff-ffffffffffff", + ]) { + const result = guid.safeParse(goodGuid); + expect(result.success).toEqual(true); + } +}); + +test("bad guid", () => { + const guid = z.string().guid("custom error"); + for (const badGuid of ["9491d710-3185-4e06-bea0-6a2f275345e0X"]) { + const result = guid.safeParse(badGuid); + expect(result).toMatchObject({ success: false }); + expect(result.error?.issues[0].message).toEqual("custom error"); + } +}); + +test("cuid", () => { + const cuid = z.string().cuid(); + cuid.parse("ckopqwooh000001la8mbi2im9"); + const result = cuid.safeParse("cifjhdsfhsd-invalid-cuid"); + expect(result).toMatchObject({ success: false }); + + expect(result.error!.issues[0].message).toEqual("Invalid cuid"); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "string", + "code": "invalid_format", + "format": "cuid", + "pattern": "/^[cC][^\\\\s-]{8,}$/", + "path": [], + "message": "Invalid cuid" + } + ]] + `); +}); + +test("cuid2", () => { + const cuid2 = z.string().cuid2(); + const validStrings = [ + "a", // short string + "tz4a98xxat96iws9zmbrgj3a", // normal string + "kf5vz6ssxe4zjcb409rjgo747tc5qjazgptvotk6", // longer than require("@paralleldrive/cuid2").bigLength + ]; + for (const s of validStrings) { + cuid2.parse(s); + } + + const invalidStrings = [ + "", // empty string + "tz4a98xxat96iws9zMbrgj3a", // include uppercase + "tz4a98xxat96iws-zmbrgj3a", // involve symbols + ]; + const results = invalidStrings.map((s) => cuid2.safeParse(s)); + expect(results.every((r) => !r.success)).toEqual(true); + if (!results[0].success) { + expect(results[0].error.issues[0].message).toEqual("Invalid cuid2"); + } +}); + +test("ulid", () => { + const ulid = z.string().ulid(); + ulid.parse("01ARZ3NDEKTSV4RRFFQ69G5FAV"); + const result = ulid.safeParse("invalidulid"); + expect(result).toMatchObject({ success: false }); + const tooLong = "01ARZ3NDEKTSV4RRFFQ69G5FAVA"; + expect(ulid.safeParse(tooLong)).toMatchObject({ success: false }); + + const caseInsensitive = ulid.safeParse("01arZ3nDeKTsV4RRffQ69G5FAV"); + expect(caseInsensitive.success).toEqual(true); + + expect(result.error!.issues[0].message).toEqual("Invalid ULID"); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "string", + "code": "invalid_format", + "format": "ulid", + "pattern": "/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/", + "path": [], + "message": "Invalid ULID" + } + ]] + `); +}); + +test("xid", () => { + const xid = z.string().xid(); + xid.parse("9m4e2mr0ui3e8a215n4g"); + const result = xid.safeParse("invalidxid"); + expect(result).toMatchObject({ success: false }); + + expect(result.error!.issues[0].message).toEqual("Invalid XID"); + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "string", + "code": "invalid_format", + "format": "xid", + "pattern": "/^[0-9a-vA-V]{20}$/", + "path": [], + "message": "Invalid XID" + } + ]] + `); +}); + +test("ksuid", () => { + const ksuid = z.string().ksuid(); + ksuid.parse("0o0t9hkGxgFLtd3lmJ4TSTeY0Vb"); + const result = ksuid.safeParse("invalidksuid"); + expect(result).toMatchObject({ success: false }); + const tooLong = "0o0t9hkGxgFLtd3lmJ4TSTeY0VbA"; + expect(ksuid.safeParse(tooLong)).toMatchObject({ success: false }); + expect(result.error!.issues).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "ksuid", + "message": "Invalid KSUID", + "origin": "string", + "path": [], + "pattern": "/^[A-Za-z0-9]{27}$/", + }, + ] + `); +}); + +test("regex", () => { + z.string() + .regex(/^moo+$/) + .parse("mooooo"); + expect(() => z.string().uuid().parse("purr")).toThrow(); +}); + +test("regexp error message", () => { + const result = z + .string() + .regex(/^moo+$/) + .safeParse("boooo"); + expect(result.error!.issues).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "regex", + "message": "Invalid string: must match pattern /^moo+$/", + "origin": "string", + "path": [], + "pattern": "/^moo+$/", + }, + ] + `); + + expect(() => z.string().uuid().parse("purr")).toThrow(); +}); + +test("regexp error custom message", () => { + const result = z + .string() + .regex(/^moo+$/, { message: "Custom error message" }) + .safeParse("boooo"); + expect(result.error!.issues).toMatchInlineSnapshot(` + [ + { + "code": "invalid_format", + "format": "regex", + "message": "Custom error message", + "origin": "string", + "path": [], + "pattern": "/^moo+$/", + }, + ] + `); + + expect(() => z.string().uuid().parse("purr")).toThrow(); +}); + +test("regex lastIndex reset", () => { + const schema = z.string().regex(/^\d+$/g); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); + expect(schema.safeParse("123").success).toEqual(true); +}); + +test("format", () => { + expect(z.string().email().format).toEqual("email"); + expect(z.string().url().format).toEqual("url"); + expect(z.string().jwt().format).toEqual("jwt"); + expect(z.string().emoji().format).toEqual("emoji"); + expect(z.string().guid().format).toEqual("guid"); + expect(z.string().uuid().format).toEqual("uuid"); + expect(z.string().uuidv4().format).toEqual("uuid"); + expect(z.string().uuidv6().format).toEqual("uuid"); + expect(z.string().uuidv7().format).toEqual("uuid"); + expect(z.string().nanoid().format).toEqual("nanoid"); + expect(z.string().guid().format).toEqual("guid"); + expect(z.string().cuid().format).toEqual("cuid"); + expect(z.string().cuid2().format).toEqual("cuid2"); + expect(z.string().ulid().format).toEqual("ulid"); + expect(z.string().base64().format).toEqual("base64"); + // expect(z.string().jsonString().format).toEqual("json_string"); + // expect(z.string().json().format).toEqual("json_string"); + expect(z.string().xid().format).toEqual("xid"); + expect(z.string().ksuid().format).toEqual("ksuid"); + // expect(z.string().ip().format).toEqual("ip"); + expect(z.string().ipv4().format).toEqual("ipv4"); + expect(z.string().ipv6().format).toEqual("ipv6"); + expect(z.string().e164().format).toEqual("e164"); + expect(z.string().datetime().format).toEqual("datetime"); + expect(z.string().date().format).toEqual("date"); + expect(z.string().time().format).toEqual("time"); + expect(z.string().duration().format).toEqual("duration"); +}); + +test("min max getters", () => { + expect(z.string().min(5).minLength).toEqual(5); + expect(z.string().min(5).min(10).minLength).toEqual(10); + expect(z.string().minLength).toEqual(null); + + expect(z.string().max(5).maxLength).toEqual(5); + expect(z.string().max(5).max(1).maxLength).toEqual(1); + expect(z.string().max(5).max(10).maxLength).toEqual(5); + expect(z.string().maxLength).toEqual(null); +}); + +test("trim", () => { + expect(z.string().trim().min(2).parse(" 12 ")).toEqual("12"); + + // ordering of methods is respected + expect(z.string().min(2).trim().parse(" 1 ")).toEqual("1"); + expect(() => z.string().trim().min(2).parse(" 1 ")).toThrow(); +}); + +test("lowerCase", () => { + expect(z.string().toLowerCase().parse("ASDF")).toEqual("asdf"); + expect(z.string().toUpperCase().parse("asdf")).toEqual("ASDF"); +}); + +// test("IP validation", () => { +// const ipSchema = z.string().ip(); + +// // General IP validation (accepts both v4 and v6) +// expect(ipSchema.safeParse("114.71.82.94").success).toBe(true); +// expect(ipSchema.safeParse("0.0.0.0").success).toBe(true); +// expect(ipSchema.safeParse("37.85.236.115").success).toBe(true); +// expect(ipSchema.safeParse("1e5e:e6c8:daac:514b:114b:e360:d8c0:682c").success).toBe(true); +// expect(ipSchema.safeParse("9d4:c956:420f:5788:4339:9b3b:2418:75c3").success).toBe(true); +// expect(ipSchema.safeParse("a6ea::2454:a5ce:94.105.123.75").success).toBe(true); +// expect(ipSchema.safeParse("474f:4c83::4e40:a47:ff95:0cda").success).toBe(true); +// expect(ipSchema.safeParse("d329:0:25b4:db47:a9d1:0:4926:0000").success).toBe(true); +// expect(ipSchema.safeParse("e48:10fb:1499:3e28:e4b6:dea5:4692:912c").success).toBe(true); + +// expect(ipSchema.safeParse("d329:1be4:25b4:db47:a9d1:dc71:4926:992c:14af").success).toBe(false); +// expect(ipSchema.safeParse("d5e7:7214:2b78::3906:85e6:53cc:709:32ba").success).toBe(false); +// expect(ipSchema.safeParse("8f69::c757:395e:976e::3441").success).toBe(false); +// expect(ipSchema.safeParse("54cb::473f:d516:0.255.256.22").success).toBe(false); +// expect(ipSchema.safeParse("54cb::473f:d516:192.168.1").success).toBe(false); +// expect(ipSchema.safeParse("256.0.4.4").success).toBe(false); +// expect(ipSchema.safeParse("-1.0.555.4").success).toBe(false); +// expect(ipSchema.safeParse("0.0.0.0.0").success).toBe(false); +// expect(ipSchema.safeParse("1.1.1").success).toBe(false); +// }); + +test("IPv4 validation", () => { + const ipv4 = z.string().ipv4(); + + // Valid IPv4 addresses + expect(ipv4.safeParse("114.71.82.94").success).toBe(true); + expect(ipv4.safeParse("0.0.0.0").success).toBe(true); + expect(ipv4.safeParse("37.85.236.115").success).toBe(true); + expect(ipv4.safeParse("192.168.0.1").success).toBe(true); + expect(ipv4.safeParse("255.255.255.255").success).toBe(true); + expect(ipv4.safeParse("1.2.3.4").success).toBe(true); + + // Invalid IPv4 addresses + expect(ipv4.safeParse("256.0.4.4").success).toBe(false); + expect(ipv4.safeParse("-1.0.555.4").success).toBe(false); + expect(ipv4.safeParse("0.0.0.0.0").success).toBe(false); + expect(ipv4.safeParse("1.1.1").success).toBe(false); + expect(ipv4.safeParse("1e5e:e6c8:daac:514b:114b:e360:d8c0:682c").success).toBe(false); + expect(ipv4.safeParse("a6ea::2454:a5ce:94.105.123.75").success).toBe(false); + expect(ipv4.safeParse("not an ip").success).toBe(false); + expect(ipv4.safeParse("1.2.3").success).toBe(false); + expect(ipv4.safeParse("1.2.3.4.5").success).toBe(false); + expect(ipv4.safeParse("1.2.3.256").success).toBe(false); + + // Test specific error + expect(() => ipv4.parse("6097:adfa:6f0b:220d:db08:5021:6191:7990")).toThrow(); +}); + +test("IPv6 validation", () => { + const ipv6 = z.string().ipv6(); + + // Valid IPv6 addresses + expect(ipv6.safeParse("1e5e:e6c8:daac:514b:114b:e360:d8c0:682c").success).toBe(true); + expect(ipv6.safeParse("9d4:c956:420f:5788:4339:9b3b:2418:75c3").success).toBe(true); + expect(ipv6.safeParse("a6ea::2454:a5ce:94.105.123.75").success).toBe(true); + expect(ipv6.safeParse("474f:4c83::4e40:a47:ff95:0cda").success).toBe(true); + expect(ipv6.safeParse("d329:0:25b4:db47:a9d1:0:4926:0000").success).toBe(true); + expect(ipv6.safeParse("e48:10fb:1499:3e28:e4b6:dea5:4692:912c").success).toBe(true); + expect(ipv6.safeParse("::1").success).toBe(true); + expect(ipv6.safeParse("2001:db8::").success).toBe(true); + expect(ipv6.safeParse("2001:0db8:85a3:0000:0000:8a2e:0370:7334").success).toBe(true); + expect(ipv6.safeParse("2001:db8::192.168.0.1").success).toBe(true); + expect(ipv6.safeParse("::ffff:192.168.0.1").success).toBe(true); + expect(ipv6.safeParse("::ffff:c000:0280").success).toBe(true); // IPv4-mapped IPv6 address + expect(ipv6.safeParse("64:ff9b::192.168.0.1").success).toBe(true); // IPv4/IPv6 translation + + // Invalid IPv6 addresses + expect(ipv6.safeParse("d329:1be4:25b4:db47:a9d1:dc71:4926:992c:14af").success).toBe(false); + expect(ipv6.safeParse("d5e7:7214:2b78::3906:85e6:53cc:709:32ba").success).toBe(false); + expect(ipv6.safeParse("8f69::c757:395e:976e::3441").success).toBe(false); + expect(ipv6.safeParse("54cb::473f:d516:0.255.256.22").success).toBe(false); + expect(ipv6.safeParse("54cb::473f:d516:192.168.1").success).toBe(false); + expect(ipv6.safeParse("114.71.82.94").success).toBe(false); + expect(ipv6.safeParse("not an ip").success).toBe(false); + expect(ipv6.safeParse("g123::1234:5678").success).toBe(false); + + // Test specific error + expect(() => ipv6.parse("254.164.77.1")).toThrow(); +}); + +test("CIDR v4 validation", () => { + const cidrV4 = z.string().cidrv4(); + + // Valid CIDR v4 addresses + expect(cidrV4.safeParse("192.168.0.0/24").success).toBe(true); + expect(cidrV4.safeParse("10.0.0.0/8").success).toBe(true); + expect(cidrV4.safeParse("172.16.0.0/12").success).toBe(true); + expect(cidrV4.safeParse("0.0.0.0/0").success).toBe(true); + expect(cidrV4.safeParse("255.255.255.255/32").success).toBe(true); + + // Invalid CIDR v4 addresses + expect(cidrV4.safeParse("192.168.0.0").success).toBe(false); // Missing prefix + expect(cidrV4.safeParse("192.168.0.0/33").success).toBe(false); // Invalid prefix length + expect(cidrV4.safeParse("256.0.0.0/24").success).toBe(false); // Invalid IP + expect(cidrV4.safeParse("192.168.0.0/-1").success).toBe(false); // Negative prefix length + expect(cidrV4.safeParse("not a cidr").success).toBe(false); // Invalid format +}); + +test("CIDR v6 validation", () => { + const cidrV6 = z.string().cidrv6(); + + // Valid CIDR v6 addresses + expect(cidrV6.safeParse("2001:db8::/32").success).toBe(true); + expect(cidrV6.safeParse("::/0").success).toBe(true); + expect(cidrV6.safeParse("fe80::/10").success).toBe(true); + expect(cidrV6.safeParse("::1/128").success).toBe(true); + expect(cidrV6.safeParse("2001:0db8:85a3::/64").success).toBe(true); + + // Invalid CIDR v6 addresses + expect(cidrV6.safeParse("2001:db8::").success).toBe(false); // Missing prefix + expect(cidrV6.safeParse("2001:db8::/129").success).toBe(false); // Invalid prefix length + expect(cidrV6.safeParse("2001:db8::/abc").success).toBe(false); // Invalid prefix format + expect(cidrV6.safeParse("not a cidr").success).toBe(false); // Invalid format + expect(cidrV6.safeParse("192.168.0.0/24").success).toBe(false); // IPv4 CIDR in v6 validation +}); + +test("E.164 validation", () => { + const e164Number = z.string().e164(); + expect(e164Number.safeParse("+1555555").success).toBe(true); + + const validE164Numbers = [ + "+1555555", // min-length (7 digits + '+') + "+15555555", + "+155555555", + "+1555555555", + "+15555555555", + "+155555555555", + "+1555555555555", + "+15555555555555", + "+155555555555555", + "+105555555555555", + "+100555555555555", // max-length (15 digits + '+') + ]; + + const invalidE164Numbers = [ + "", // empty + "+", // only plus sign + "-", // wrong sign + " 555555555", // starts with space + "555555555", // missing plus sign + "+1 555 555 555", // space after plus sign + "+1555 555 555", // space between numbers + "+1555+555", // multiple plus signs + "+1555555555555555", // too long + "+115abc55", // non numeric characters in number part + "+1555555 ", // space after number + ]; + + expect(validE164Numbers.every((number) => e164Number.safeParse(number).success)).toBe(true); + expect(invalidE164Numbers.every((number) => e164Number.safeParse(number).success === false)).toBe(true); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/stringbool.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/stringbool.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fe6c913f2eb70cef870757040de5c52d6f39550 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/stringbool.test.ts @@ -0,0 +1,66 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("z.stringbool", () => { + const a = z.stringbool(); + type a = z.infer; + expectTypeOf().toEqualTypeOf(); + type a_in = z.input; + expectTypeOf().toEqualTypeOf(); + + expect(z.parse(a, "true")).toEqual(true); + expect(z.parse(a, "yes")).toEqual(true); + expect(z.parse(a, "1")).toEqual(true); + expect(z.parse(a, "on")).toEqual(true); + expect(z.parse(a, "y")).toEqual(true); + expect(z.parse(a, "enabled")).toEqual(true); + expect(z.parse(a, "TRUE")).toEqual(true); + + expect(z.parse(a, "false")).toEqual(false); + expect(z.parse(a, "no")).toEqual(false); + expect(z.parse(a, "0")).toEqual(false); + expect(z.parse(a, "off")).toEqual(false); + expect(z.parse(a, "n")).toEqual(false); + expect(z.parse(a, "disabled")).toEqual(false); + expect(z.parse(a, "FALSE")).toEqual(false); + + expect(z.safeParse(a, "other")).toMatchObject({ success: false }); + expect(z.safeParse(a, "")).toMatchObject({ success: false }); + expect(z.safeParse(a, undefined)).toMatchObject({ success: false }); + expect(z.safeParse(a, {})).toMatchObject({ success: false }); + expect(z.safeParse(a, true)).toMatchObject({ success: false }); + expect(z.safeParse(a, false)).toMatchObject({ success: false }); +}); + +test("custom values", () => { + const b = z.stringbool({ + truthy: ["y"], + falsy: ["N"], + }); + expect(z.parse(b, "y")).toEqual(true); + expect(z.parse(b, "Y")).toEqual(true); + expect(z.parse(b, "n")).toEqual(false); + expect(z.parse(b, "N")).toEqual(false); + expect(z.safeParse(b, "true")).toMatchObject({ success: false }); + expect(z.safeParse(b, "false")).toMatchObject({ success: false }); +}); + +test("custom values - case sensitive", () => { + const c = z.stringbool({ + truthy: ["y"], + falsy: ["N"], + case: "sensitive", + }); + expect(z.parse(c, "y")).toEqual(true); + expect(z.safeParse(c, "Y")).toMatchObject({ success: false }); + expect(z.parse(c, "N")).toEqual(false); + expect(z.safeParse(c, "n")).toMatchObject({ success: false }); + expect(z.safeParse(c, "TRUE")).toMatchObject({ success: false }); +}); + +// test custom error messages +test("z.stringbool with custom error messages", () => { + const a = z.stringbool("wrong!"); + + expect(() => a.parse("")).toThrowError("wrong!"); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/template-literal.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/template-literal.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..17e3a6894ff6f49c109bbc3ced79f34b90b703f5 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/template-literal.test.ts @@ -0,0 +1,758 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +const empty = z.templateLiteral([]); +const hello = z.templateLiteral(["hello"]); +const world = z.templateLiteral(["", z.literal("world")]); +const one = z.templateLiteral([1]); +const two = z.templateLiteral(["", z.literal(2)]); +const truee = z.templateLiteral([true]); +const anotherTrue = z.templateLiteral(["", z.literal(true)]); +const falsee = z.templateLiteral([false]); +const anotherFalse = z.templateLiteral(["", z.literal(false)]); +const nulll = z.templateLiteral([null]); +const anotherNull = z.templateLiteral(["", z.null()]); +const undefinedd = z.templateLiteral([undefined]); +const anotherUndefined = z.templateLiteral(["", z.undefined()]); +const anyString = z.templateLiteral(["", z.string()]); +const lazyString = z.templateLiteral(["", z.lazy(() => z.string())]); +const anyNumber = z.templateLiteral(["", z.number()]); +const anyInt = z.templateLiteral(["", z.number().int()]); +// const anyFiniteNumber = z.templateLiteral(["", z.number().finite()]); +// const anyNegativeNumber = z.templateLiteral(["", z.number().negative()]); +// const anyPositiveNumber = z.templateLiteral(["", z.number().positive()]); +// const zeroButInADumbWay = z.templateLiteral(["", z.number().nonnegative().nonpositive()]); +// const finiteButInADumbWay = z.templateLiteral(["", z.number().min(5).max(10)]); +const bool = z.templateLiteral(["", z.boolean()]); +const bigone = z.templateLiteral(["", z.literal(BigInt(1))]); +const anyBigint = z.templateLiteral(["", z.bigint()]); +const nullableYo = z.templateLiteral(["", z.nullable(z.literal("yo"))]); +const nullableString = z.templateLiteral(["", z.nullable(z.string())]); +const optionalYeah = z.templateLiteral(["", z.literal("yeah").optional()]); + +const optionalString = z.templateLiteral(["", z.string().optional()]); +const optionalNumber = z.templateLiteral(["", z.number().optional()]); +const nullishBruh = z.templateLiteral(["", z.literal("bruh").nullish()]); +const nullishString = z.templateLiteral(["", z.string().nullish()]); +const cuid = z.templateLiteral(["", z.string().cuid()]); +const cuidZZZ = z.templateLiteral(["", z.string().cuid(), "ZZZ"]); +const cuid2 = z.templateLiteral(["", z.string().cuid2()]); +const datetime = z.templateLiteral(["", z.string().datetime()]); +const email = z.templateLiteral(["", z.string().email()]); +// const ip = z.templateLiteral(["", z.string().ip()]); +const ipv4 = z.templateLiteral(["", z.string().ipv4()]); +const ipv6 = z.templateLiteral(["", z.string().ipv6()]); +const ulid = z.templateLiteral(["", z.string().ulid()]); +const uuid = z.templateLiteral(["", z.string().uuid()]); +const stringAToZ = z.templateLiteral(["", z.string().regex(/^[a-z]+$/)]); +const stringStartsWith = z.templateLiteral(["", z.string().startsWith("hello")]); +const stringEndsWith = z.templateLiteral(["", z.string().endsWith("world")]); +const stringMax5 = z.templateLiteral(["", z.string().max(5)]); +const stringMin5 = z.templateLiteral(["", z.string().min(5)]); +const stringLen5 = z.templateLiteral(["", z.string().length(5)]); +const stringMin5Max10 = z.templateLiteral(["", z.string().min(5).max(10)]); +const stringStartsWithMax5 = z.templateLiteral(["", z.string().startsWith("hello").max(5)]); +const brandedString = z.templateLiteral(["", z.string().min(1).brand("myBrand")]); +// const anything = z.templateLiteral(["", z.any()]); + +const url = z.templateLiteral(["https://", z.string().regex(/\w+/), ".", z.enum(["com", "net"])]); + +const measurement = z.templateLiteral([ + "", + z.number().finite(), + z.enum(["px", "em", "rem", "vh", "vw", "vmin", "vmax"]).optional(), +]); + +const connectionString = z.templateLiteral([ + "mongodb://", + z + .templateLiteral([ + "", + z.string().regex(/\w+/).describe("username"), + ":", + z.string().regex(/\w+/).describe("password"), + "@", + ]) + .optional(), + z.string().regex(/\w+/).describe("host"), + ":", + z.number().finite().int().positive().describe("port"), + z + .templateLiteral([ + "/", + z.string().regex(/\w+/).optional().describe("defaultauthdb"), + z + .templateLiteral([ + "?", + z + .string() + .regex(/^\w+=\w+(&\w+=\w+)*$/) + .optional() + .describe("options"), + ]) + .optional(), + ]) + .optional(), +]); + +test("template literal type inference", () => { + expectTypeOf>().toEqualTypeOf<``>(); + expectTypeOf>().toEqualTypeOf<`hello`>(); + expectTypeOf>().toEqualTypeOf<`world`>(); + expectTypeOf>().toEqualTypeOf<`1`>(); + expectTypeOf>().toEqualTypeOf<`2`>(); + expectTypeOf>().toEqualTypeOf<`true`>(); + expectTypeOf>().toEqualTypeOf<`true`>(); + expectTypeOf>().toEqualTypeOf<`false`>(); + expectTypeOf>().toEqualTypeOf<`false`>(); + expectTypeOf>().toEqualTypeOf<`null`>(); + expectTypeOf>().toEqualTypeOf<`null`>(); + expectTypeOf>().toEqualTypeOf<``>(); + expectTypeOf>().toEqualTypeOf<``>(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf<`${number}`>(); + expectTypeOf>().toEqualTypeOf<`${number}`>(); + // expectTypeOf>().toEqualTypeOf<`${number}`>(); + // expectTypeOf>().toEqualTypeOf<`${number}`>(); + // expectTypeOf>().toEqualTypeOf<`${number}`>(); + // expectTypeOf>().toEqualTypeOf<`${number}`>(); + // expectTypeOf>().toEqualTypeOf<`${number}`>(); + expectTypeOf>().toEqualTypeOf<`true` | `false`>(); + expectTypeOf>().toEqualTypeOf<`${bigint}`>(); + expectTypeOf>().toEqualTypeOf<`${bigint}`>(); + expectTypeOf>().toEqualTypeOf<`yo` | `null`>(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf<`yeah` | ``>(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf<`${number}` | ``>(); + expectTypeOf>().toEqualTypeOf<`bruh` | `null` | ``>(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf<`${string}ZZZ`>(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + // expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf<`${string & z.core.$brand<"myBrand">}`>(); + + // expectTypeOf>().toEqualTypeOf<`${any}`>(); + + expectTypeOf>().toEqualTypeOf<`https://${string}.com` | `https://${string}.net`>(); + + expectTypeOf>().toEqualTypeOf< + | `${number}` + | `${number}px` + | `${number}em` + | `${number}rem` + | `${number}vh` + | `${number}vw` + | `${number}vmin` + | `${number}vmax` + >(); + + expectTypeOf>().toEqualTypeOf< + | `mongodb://${string}:${number}` + | `mongodb://${string}:${number}/${string}` + | `mongodb://${string}:${number}/${string}?${string}` + | `mongodb://${string}:${string}@${string}:${number}` + | `mongodb://${string}:${string}@${string}:${number}/${string}` + | `mongodb://${string}:${string}@${string}:${number}/${string}?${string}` + >(); +}); + +test("template literal unsupported args", () => { + expect(() => + // @ts-expect-error + z.templateLiteral([z.object({})]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.array(z.object({}))]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.union([z.object({}), z.string()])]) + ).toThrow(); + // @ts-expect-error + expect(() => z.templateLiteral([z.date()])).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.custom((_) => true)]) + ).toThrow(); + expect(() => + z.templateLiteral([ + // @ts-expect-error + z.discriminatedUnion("discriminator", [z.object({}), z.object({})]), + ]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.function()]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.instanceof(class MyClass {})]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.intersection(z.object({}), z.object({}))]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.map(z.string(), z.string())]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.nullable(z.object({}))]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.optional(z.object({}))]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.promise()]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.record(z.unknown())]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.set(z.string())]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.symbol()]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.tuple([z.string()])]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.unknown()]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.void()]) + ).toThrow(); + + expect(() => + // @ts-expect-error + z.templateLiteral([z.never()]) + ).toThrow(); + // @ts-expect-error + expect(() => z.templateLiteral([z.nan()])).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.pipe(z.string(), z.string())]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.preprocess(() => true, z.boolean())]) + ).toThrow(); + expect(() => + // @ts-expect-error + z.templateLiteral([z.object({}).brand("brand")]) + ).toThrow(); + + // these constraints aren't enforced but they shouldn't throw + z.templateLiteral([z.number().multipleOf(2)]); + z.templateLiteral([z.string().emoji()]); + z.templateLiteral([z.string().url()]); + z.templateLiteral([z.string().url()]); + z.templateLiteral([z.string().trim()]); + z.templateLiteral([z.string().includes("train")]); + z.templateLiteral([z.string().toLowerCase()]); + z.templateLiteral([z.string().toUpperCase()]); +}); + +test("template literal parsing - success - basic cases", () => { + expect(() => z.templateLiteral([]).parse(7)).toThrow(); + + empty.parse(""); + hello.parse("hello"); + world.parse("world"); + one.parse("1"); + two.parse("2"); + truee.parse("true"); + anotherTrue.parse("true"); + falsee.parse("false"); + anotherFalse.parse("false"); + nulll.parse("null"); + anotherNull.parse("null"); + undefinedd.parse("undefined"); + anotherUndefined.parse("undefined"); + anyString.parse("blahblahblah"); + anyString.parse(""); + lazyString.parse("blahblahblah"); + lazyString.parse(""); + anyNumber.parse("123"); + anyNumber.parse("1.23"); + anyNumber.parse("0"); + anyNumber.parse("-1.23"); + anyNumber.parse("-123"); + // anyNumber.parse("Infinity"); + // anyNumber.parse("-Infinity"); + anyInt.parse("123"); + // anyInt.parse("-123"); + // anyFiniteNumber.parse("123"); + // anyFiniteNumber.parse("1.23"); + // anyFiniteNumber.parse("0"); + // anyFiniteNumber.parse("-1.23"); + // anyFiniteNumber.parse("-123"); + // anyNegativeNumber.parse("-123"); + // anyNegativeNumber.parse("-1.23"); + // anyNegativeNumber.parse("-Infinity"); + // anyPositiveNumber.parse("123"); + // anyPositiveNumber.parse("1.23"); + // anyPositiveNumber.parse("Infinity"); + // zeroButInADumbWay.parse("0"); + // zeroButInADumbWay.parse("00000"); + // finiteButInADumbWay.parse("5"); + // finiteButInADumbWay.parse("10"); + // finiteButInADumbWay.parse("6.66"); + bool.parse("true"); + bool.parse("false"); + bigone.parse("1"); + anyBigint.parse("123456"); + anyBigint.parse("0"); + // anyBigint.parse("-123456"); + nullableYo.parse("yo"); + nullableYo.parse("null"); + nullableString.parse("abc"); + nullableString.parse("null"); + optionalYeah.parse("yeah"); + optionalYeah.parse(""); + optionalString.parse("abc"); + optionalString.parse(""); + optionalNumber.parse("123"); + optionalNumber.parse("1.23"); + optionalNumber.parse("0"); + optionalNumber.parse("-1.23"); + optionalNumber.parse("-123"); + // optionalNumber.parse("Infinity"); + // optionalNumber.parse("-Infinity"); + nullishBruh.parse("bruh"); + nullishBruh.parse("null"); + nullishBruh.parse(""); + cuid.parse("cjld2cyuq0000t3rmniod1foy"); + cuidZZZ.parse("cjld2cyuq0000t3rmniod1foyZZZ"); + cuid2.parse("tz4a98xxat96iws9zmbrgj3a"); + datetime.parse(new Date().toISOString()); + email.parse("info@example.com"); + // ip.parse("213.174.246.205"); + // ip.parse("c359:f57c:21e5:39eb:1187:e501:f936:b452"); + ipv4.parse("213.174.246.205"); + ipv6.parse("c359:f57c:21e5:39eb:1187:e501:f936:b452"); + ulid.parse("01GW3D2QZJBYB6P1Z1AE997VPW"); + uuid.parse("808989fd-3a6e-4af2-b607-737323a176f6"); + stringAToZ.parse("asudgaskhdgashd"); + stringStartsWith.parse("hello world"); + stringEndsWith.parse("hello world"); + stringMax5.parse("hello"); + stringMin5.parse("hello"); + stringLen5.parse("hello"); + stringMin5Max10.parse("hello worl"); + stringStartsWithMax5.parse("hello"); + brandedString.parse("branded string"); +}); + +test("template literal parsing - failure - basic cases", () => { + expect(() => empty.parse("a")).toThrow(); + expect(() => hello.parse("hello!")).toThrow(); + expect(() => hello.parse("!hello")).toThrow(); + expect(() => world.parse("world!")).toThrow(); + expect(() => world.parse("!world")).toThrow(); + expect(() => one.parse("2")).toThrow(); + expect(() => one.parse("12")).toThrow(); + expect(() => one.parse("21")).toThrow(); + expect(() => two.parse("1")).toThrow(); + expect(() => two.parse("21")).toThrow(); + expect(() => two.parse("12")).toThrow(); + expect(() => truee.parse("false")).toThrow(); + expect(() => truee.parse("1true")).toThrow(); + expect(() => truee.parse("true1")).toThrow(); + expect(() => anotherTrue.parse("false")).toThrow(); + expect(() => anotherTrue.parse("1true")).toThrow(); + expect(() => anotherTrue.parse("true1")).toThrow(); + expect(() => falsee.parse("true")).toThrow(); + expect(() => falsee.parse("1false")).toThrow(); + expect(() => falsee.parse("false1")).toThrow(); + expect(() => anotherFalse.parse("true")).toThrow(); + expect(() => anotherFalse.parse("1false")).toThrow(); + expect(() => anotherFalse.parse("false1")).toThrow(); + expect(() => nulll.parse("123")).toThrow(); + expect(() => nulll.parse("null1")).toThrow(); + expect(() => nulll.parse("1null")).toThrow(); + expect(() => anotherNull.parse("123")).toThrow(); + expect(() => anotherNull.parse("null1")).toThrow(); + expect(() => anotherNull.parse("1null")).toThrow(); + expect(() => undefinedd.parse("123")).toThrow(); + expect(() => undefinedd.parse("undefined1")).toThrow(); + expect(() => undefinedd.parse("1undefined")).toThrow(); + expect(() => anotherUndefined.parse("123")).toThrow(); + expect(() => anotherUndefined.parse("undefined1")).toThrow(); + expect(() => anotherUndefined.parse("1undefined")).toThrow(); + expect(() => anyNumber.parse("2a")).toThrow(); + expect(() => anyNumber.parse("a2")).toThrow(); + expect(() => anyNumber.parse("-2a")).toThrow(); + expect(() => anyNumber.parse("a-2")).toThrow(); + expect(() => anyNumber.parse("2.5a")).toThrow(); + expect(() => anyNumber.parse("a2.5")).toThrow(); + expect(() => anyNumber.parse("Infinitya")).toThrow(); + expect(() => anyNumber.parse("aInfinity")).toThrow(); + expect(() => anyNumber.parse("-Infinitya")).toThrow(); + expect(() => anyNumber.parse("a-Infinity")).toThrow(); + expect(() => anyNumber.parse("2e5")).toThrow(); + expect(() => anyNumber.parse("2e-5")).toThrow(); + expect(() => anyNumber.parse("2e+5")).toThrow(); + expect(() => anyNumber.parse("-2e5")).toThrow(); + expect(() => anyNumber.parse("-2e-5")).toThrow(); + expect(() => anyNumber.parse("-2e+5")).toThrow(); + expect(() => anyNumber.parse("2.1e5")).toThrow(); + expect(() => anyNumber.parse("2.1e-5")).toThrow(); + expect(() => anyNumber.parse("2.1e+5")).toThrow(); + expect(() => anyNumber.parse("-2.1e5")).toThrow(); + expect(() => anyNumber.parse("-2.1e-5")).toThrow(); + expect(() => anyNumber.parse("-2.1e+5")).toThrow(); + expect(() => anyNumber.parse("-Infinity")).toThrow(); + expect(() => anyNumber.parse("Infinity")).toThrow(); + expect(() => anyInt.parse("1.23")).toThrow(); + expect(() => anyInt.parse("-1.23")).toThrow(); + expect(() => anyInt.parse("d1")).toThrow(); + expect(() => anyInt.parse("1d")).toThrow(); + // expect(() => anyFiniteNumber.parse("Infinity")).toThrow(); + // expect(() => anyFiniteNumber.parse("-Infinity")).toThrow(); + // expect(() => anyFiniteNumber.parse("123a")).toThrow(); + // expect(() => anyFiniteNumber.parse("a123")).toThrow(); + // expect(() => anyNegativeNumber.parse("0")).toThrow(); + // expect(() => anyNegativeNumber.parse("1")).toThrow(); + // expect(() => anyNegativeNumber.parse("Infinity")).toThrow(); + // expect(() => anyPositiveNumber.parse("0")).toThrow(); + // expect(() => anyPositiveNumber.parse("-1")).toThrow(); + // expect(() => anyPositiveNumber.parse("-Infinity")).toThrow(); + // expect(() => zeroButInADumbWay.parse("1")).toThrow(); + // expect(() => zeroButInADumbWay.parse("-1")).toThrow(); + // expect(() => finiteButInADumbWay.parse("Infinity")).toThrow(); + // expect(() => finiteButInADumbWay.parse("-Infinity")).toThrow(); + // expect(() => finiteButInADumbWay.parse("-5")).toThrow(); + // expect(() => finiteButInADumbWay.parse("10a")).toThrow(); + // expect(() => finiteButInADumbWay.parse("a10")).toThrow(); + expect(() => bool.parse("123")).toThrow(); + expect(() => bigone.parse("2")).toThrow(); + expect(() => bigone.parse("c1")).toThrow(); + expect(() => anyBigint.parse("1.23")).toThrow(); + expect(() => anyBigint.parse("-1.23")).toThrow(); + expect(() => anyBigint.parse("c123")).toThrow(); + expect(() => nullableYo.parse("yo1")).toThrow(); + expect(() => nullableYo.parse("1yo")).toThrow(); + expect(() => nullableYo.parse("null1")).toThrow(); + expect(() => nullableYo.parse("1null")).toThrow(); + expect(() => optionalYeah.parse("yeah1")).toThrow(); + expect(() => optionalYeah.parse("1yeah")).toThrow(); + expect(() => optionalYeah.parse("undefined")).toThrow(); + expect(() => optionalNumber.parse("123a")).toThrow(); + expect(() => optionalNumber.parse("a123")).toThrow(); + // expect(() => optionalNumber.parse("Infinitya")).toThrow(); + // expect(() => optionalNumber.parse("aInfinity")).toThrow(); + expect(() => nullishBruh.parse("bruh1")).toThrow(); + expect(() => nullishBruh.parse("1bruh")).toThrow(); + expect(() => nullishBruh.parse("null1")).toThrow(); + expect(() => nullishBruh.parse("1null")).toThrow(); + expect(() => nullishBruh.parse("undefined")).toThrow(); + expect(() => cuid.parse("bjld2cyuq0000t3rmniod1foy")).toThrow(); + expect(() => cuid.parse("cjld2cyu")).toThrow(); + expect(() => cuid.parse("cjld2 cyu")).toThrow(); + expect(() => cuid.parse("cjld2cyuq0000t3rmniod1foy ")).toThrow(); + expect(() => cuid.parse("1cjld2cyuq0000t3rmniod1foy")).toThrow(); + expect(() => cuidZZZ.parse("cjld2cyuq0000t3rmniod1foy")).toThrow(); + expect(() => cuidZZZ.parse("cjld2cyuq0000t3rmniod1foyZZY")).toThrow(); + expect(() => cuidZZZ.parse("cjld2cyuq0000t3rmniod1foyZZZ1")).toThrow(); + expect(() => cuidZZZ.parse("1cjld2cyuq0000t3rmniod1foyZZZ")).toThrow(); + expect(() => cuid2.parse("A9z4a98xxat96iws9zmbrgj3a")).toThrow(); + expect(() => cuid2.parse("tz4a98xxat96iws9zmbrgj3!")).toThrow(); + expect(() => datetime.parse("2022-01-01 00:00:00")).toThrow(); + expect(() => email.parse("info@example.com@")).toThrow(); + // expect(() => ip.parse("213.174.246:205")).toThrow(); + // expect(() => ip.parse("c359.f57c:21e5:39eb:1187:e501:f936:b452")).toThrow(); + expect(() => ipv4.parse("1213.174.246.205")).toThrow(); + expect(() => ipv4.parse("c359:f57c:21e5:39eb:1187:e501:f936:b452")).toThrow(); + expect(() => ipv6.parse("c359:f57c:21e5:39eb:1187:e501:f936:b4521")).toThrow(); + expect(() => ipv6.parse("213.174.246.205")).toThrow(); + expect(() => ulid.parse("01GW3D2QZJBYB6P1Z1AE997VPW!")).toThrow(); + expect(() => uuid.parse("808989fd-3a6e-4af2-b607-737323a176f6Z")).toThrow(); + expect(() => uuid.parse("Z808989fd-3a6e-4af2-b607-737323a176f6")).toThrow(); + expect(() => stringAToZ.parse("asdasdasd1")).toThrow(); + expect(() => stringAToZ.parse("1asdasdasd")).toThrow(); + expect(() => stringStartsWith.parse("ahello")).toThrow(); + expect(() => stringEndsWith.parse("worlda")).toThrow(); + expect(() => stringMax5.parse("123456")).toThrow(); + expect(() => stringMin5.parse("1234")).toThrow(); + expect(() => stringLen5.parse("123456")).toThrow(); + expect(() => stringLen5.parse("1234")).toThrow(); + expect(() => stringMin5Max10.parse("1234")).toThrow(); + expect(() => stringMin5Max10.parse("12345678901")).toThrow(); + + // the "startswith" overrides the max length + // expect(() => stringStartsWithMax5.parse("hello1")).toThrow(); + expect(() => stringStartsWithMax5.parse("1hell")).toThrow(); + expect(() => brandedString.parse("")).toThrow(); +}); + +test("regexes", () => { + expect(empty._zod.pattern.source).toMatchInlineSnapshot(`"^$"`); + expect(hello._zod.pattern.source).toMatchInlineSnapshot(`"^hello$"`); + expect(world._zod.pattern.source).toMatchInlineSnapshot(`"^(world)$"`); + expect(one._zod.pattern.source).toMatchInlineSnapshot(`"^1$"`); + expect(two._zod.pattern.source).toMatchInlineSnapshot(`"^(2)$"`); + expect(truee._zod.pattern.source).toMatchInlineSnapshot(`"^true$"`); + expect(anotherTrue._zod.pattern.source).toMatchInlineSnapshot(`"^(true)$"`); + expect(falsee._zod.pattern.source).toMatchInlineSnapshot(`"^false$"`); + expect(anotherFalse._zod.pattern.source).toMatchInlineSnapshot(`"^(false)$"`); + expect(nulll._zod.pattern.source).toMatchInlineSnapshot(`"^null$"`); + expect(anotherNull._zod.pattern.source).toMatchInlineSnapshot(`"^null$"`); + expect(undefinedd._zod.pattern.source).toMatchInlineSnapshot(`"^undefined$"`); + expect(anotherUndefined._zod.pattern.source).toMatchInlineSnapshot(`"^undefined$"`); + expect(anyString._zod.pattern.source).toMatchInlineSnapshot(`"^[\\s\\S]{0,}$"`); + expect(lazyString._zod.pattern.source).toMatchInlineSnapshot(`"^[\\s\\S]{0,}$"`); + expect(anyNumber._zod.pattern.source).toMatchInlineSnapshot(`"^-?\\d+(?:\\.\\d+)?$"`); + expect(anyInt._zod.pattern.source).toMatchInlineSnapshot(`"^\\d+$"`); + // expect(anyFiniteNumber._zod.pattern.source).toMatchInlineSnapshot(`"^-?\\d+(?:\\.\\d+)?$"`); + // expect(anyNegativeNumber._zod.pattern.source).toMatchInlineSnapshot(`"^-?\\d+(?:\\.\\d+)?$"`); + // expect(anyPositiveNumber._zod.pattern.source).toMatchInlineSnapshot(`"^-?\\d+(?:\\.\\d+)?$"`); + // expect(zeroButInADumbWay._zod.pattern.source).toMatchInlineSnapshot(`"^-?\\d+(?:\\.\\d+)?$"`); + // expect(finiteButInADumbWay._zod.pattern.source).toMatchInlineSnapshot(`"^-?\\d+(?:\\.\\d+)?$"`); + expect(bool._zod.pattern.source).toMatchInlineSnapshot(`"^true|false$"`); + expect(bigone._zod.pattern.source).toMatchInlineSnapshot(`"^(1)$"`); + expect(anyBigint._zod.pattern.source).toMatchInlineSnapshot(`"^\\d+n?$"`); + expect(nullableYo._zod.pattern.source).toMatchInlineSnapshot(`"^((yo)|null)$"`); + expect(nullableString._zod.pattern.source).toMatchInlineSnapshot(`"^([\\s\\S]{0,}|null)$"`); + expect(optionalYeah._zod.pattern.source).toMatchInlineSnapshot(`"^((yeah))?$"`); + expect(optionalString._zod.pattern.source).toMatchInlineSnapshot(`"^([\\s\\S]{0,})?$"`); + expect(optionalNumber._zod.pattern.source).toMatchInlineSnapshot(`"^(-?\\d+(?:\\.\\d+)?)?$"`); + expect(nullishBruh._zod.pattern.source).toMatchInlineSnapshot(`"^(((bruh)|null))?$"`); + expect(nullishString._zod.pattern.source).toMatchInlineSnapshot(`"^(([\\s\\S]{0,}|null))?$"`); + expect(cuid._zod.pattern.source).toMatchInlineSnapshot(`"^[cC][^\\s-]{8,}$"`); + expect(cuidZZZ._zod.pattern.source).toMatchInlineSnapshot(`"^[cC][^\\s-]{8,}ZZZ$"`); + expect(cuid2._zod.pattern.source).toMatchInlineSnapshot(`"^[0-9a-z]+$"`); + expect(datetime._zod.pattern.source).toMatchInlineSnapshot( + `"^(?:(?:\\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])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$"` + ); + expect(email._zod.pattern.source).toMatchInlineSnapshot( + `"^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"` + ); + // expect(ip._zod.pattern.source).toMatchInlineSnapshot( + // `"^(^(?:(?: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])$)|(^(([a-fA-F0-9]{1,4}:){7}|::([a-fA-F0-9]{1,4}:){0,6}|([a-fA-F0-9]{1,4}:){1}:([a-fA-F0-9]{1,4}:){0,5}|([a-fA-F0-9]{1,4}:){2}:([a-fA-F0-9]{1,4}:){0,4}|([a-fA-F0-9]{1,4}:){3}:([a-fA-F0-9]{1,4}:){0,3}|([a-fA-F0-9]{1,4}:){4}:([a-fA-F0-9]{1,4}:){0,2}|([a-fA-F0-9]{1,4}:){5}:([a-fA-F0-9]{1,4}:){0,1})([a-fA-F0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$)$"` + // ); + expect(ipv4._zod.pattern.source).toMatchInlineSnapshot( + `"^(?:(?: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])$"` + ); + expect(ipv6._zod.pattern.source).toMatchInlineSnapshot( + `"^(([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})$"` + ); + expect(ulid._zod.pattern.source).toMatchInlineSnapshot(`"^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$"`); + expect(uuid._zod.pattern.source).toMatchInlineSnapshot( + `"^([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)$"` + ); + expect(stringAToZ._zod.pattern.source).toMatchInlineSnapshot(`"^[a-z]+$"`); + expect(stringStartsWith._zod.pattern.source).toMatchInlineSnapshot(`"^hello.*$"`); + expect(stringEndsWith._zod.pattern.source).toMatchInlineSnapshot(`"^.*world$"`); + expect(stringMax5._zod.pattern.source).toMatchInlineSnapshot(`"^[\\s\\S]{0,5}$"`); + expect(stringMin5._zod.pattern.source).toMatchInlineSnapshot(`"^[\\s\\S]{5,}$"`); + expect(stringLen5._zod.pattern.source).toMatchInlineSnapshot(`"^[\\s\\S]{5,5}$"`); + expect(stringMin5Max10._zod.pattern.source).toMatchInlineSnapshot(`"^[\\s\\S]{5,10}$"`); + expect(brandedString._zod.pattern.source).toMatchInlineSnapshot(`"^[\\s\\S]{1,}$"`); + expect(url._zod.pattern.source).toMatchInlineSnapshot(`"^https:\\/\\/\\w+\\.(com|net)$"`); + expect(measurement._zod.pattern.source).toMatchInlineSnapshot(`"^-?\\d+(?:\\.\\d+)?((px|em|rem|vh|vw|vmin|vmax))?$"`); + expect(connectionString._zod.pattern.source).toMatchInlineSnapshot( + `"^mongodb:\\/\\/(\\w+:\\w+@)?\\w+:\\d+(\\/(\\w+)?(\\?(\\w+=\\w+(&\\w+=\\w+)*)?)?)?$"` + ); +}); + +test("template literal parsing - success - complex cases", () => { + url.parse("https://example.com"); + url.parse("https://speedtest.net"); + + // measurement.parse(1); + // measurement.parse(1.1); + // measurement.parse(0); + // measurement.parse(-1.1); + // measurement.parse(-1); + measurement.parse("1"); + measurement.parse("1.1"); + measurement.parse("0"); + measurement.parse("-1"); + measurement.parse("-1.1"); + measurement.parse("1px"); + measurement.parse("1.1px"); + measurement.parse("0px"); + measurement.parse("-1px"); + measurement.parse("-1.1px"); + measurement.parse("1em"); + measurement.parse("1.1em"); + measurement.parse("0em"); + measurement.parse("-1em"); + measurement.parse("-1.1em"); + measurement.parse("1rem"); + measurement.parse("1.1rem"); + measurement.parse("0rem"); + measurement.parse("-1rem"); + measurement.parse("-1.1rem"); + measurement.parse("1vh"); + measurement.parse("1.1vh"); + measurement.parse("0vh"); + measurement.parse("-1vh"); + measurement.parse("-1.1vh"); + measurement.parse("1vw"); + measurement.parse("1.1vw"); + measurement.parse("0vw"); + measurement.parse("-1vw"); + measurement.parse("-1.1vw"); + measurement.parse("1vmin"); + measurement.parse("1.1vmin"); + measurement.parse("0vmin"); + measurement.parse("-1vmin"); + measurement.parse("-1.1vmin"); + measurement.parse("1vmax"); + measurement.parse("1.1vmax"); + measurement.parse("0vmax"); + measurement.parse("-1vmax"); + measurement.parse("-1.1vmax"); + + connectionString.parse("mongodb://host:1234"); + connectionString.parse("mongodb://host:1234/"); + connectionString.parse("mongodb://host:1234/defaultauthdb"); + connectionString.parse("mongodb://host:1234/defaultauthdb?authSource=admin"); + connectionString.parse("mongodb://host:1234/defaultauthdb?authSource=admin&connectTimeoutMS=300000"); + connectionString.parse("mongodb://host:1234/?authSource=admin"); + connectionString.parse("mongodb://host:1234/?authSource=admin&connectTimeoutMS=300000"); + connectionString.parse("mongodb://username:password@host:1234"); + connectionString.parse("mongodb://username:password@host:1234/"); + connectionString.parse("mongodb://username:password@host:1234/defaultauthdb"); + connectionString.parse("mongodb://username:password@host:1234/defaultauthdb?authSource=admin"); + connectionString.parse( + "mongodb://username:password@host:1234/defaultauthdb?authSource=admin&connectTimeoutMS=300000" + ); + connectionString.parse("mongodb://username:password@host:1234/?authSource=admin"); + connectionString.parse("mongodb://username:password@host:1234/?authSource=admin&connectTimeoutMS=300000"); +}); + +test("template literal parsing - failure - complex cases", () => { + expect(() => url.parse("http://example.com")).toThrow(); + expect(() => url.parse("https://.com")).toThrow(); + expect(() => url.parse("https://examplecom")).toThrow(); + expect(() => url.parse("https://example.org")).toThrow(); + expect(() => url.parse("https://example.net.il")).toThrow(); + + expect(() => measurement.parse("1.1.1")).toThrow(); + expect(() => measurement.parse("Infinity")).toThrow(); + expect(() => measurement.parse("-Infinity")).toThrow(); + expect(() => measurement.parse("NaN")).toThrow(); + expect(() => measurement.parse("1%")).toThrow(); + + expect(() => connectionString.parse("mongod://host:1234")).toThrow(); + expect(() => connectionString.parse("mongodb://:1234")).toThrow(); + expect(() => connectionString.parse("mongodb://host1234")).toThrow(); + expect(() => connectionString.parse("mongodb://host:d234")).toThrow(); + expect(() => connectionString.parse("mongodb://host:12.34")).toThrow(); + expect(() => connectionString.parse("mongodb://host:-1234")).toThrow(); + expect(() => connectionString.parse("mongodb://host:-12.34")).toThrow(); + expect(() => connectionString.parse("mongodb://host:")).toThrow(); + expect(() => connectionString.parse("mongodb://:password@host:1234")).toThrow(); + expect(() => connectionString.parse("mongodb://usernamepassword@host:1234")).toThrow(); + expect(() => connectionString.parse("mongodb://username:@host:1234")).toThrow(); + expect(() => connectionString.parse("mongodb://@host:1234")).toThrow(); + expect(() => connectionString.parse("mongodb://host:1234/defaultauthdb?authSourceadmin")).toThrow(); + expect(() => connectionString.parse("mongodb://host:1234/?authSourceadmin")).toThrow(); + expect(() => connectionString.parse("mongodb://host:1234/defaultauthdb?&authSource=admin")).toThrow(); + expect(() => connectionString.parse("mongodb://host:1234/?&authSource=admin")).toThrow(); +}); + +test("template literal parsing - failure - issue format", () => { + expect(anotherNull.safeParse("1null")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_format", + "format": "template_literal", + "pattern": "^null$", + "path": [], + "message": "Invalid input" + } + ]], + "success": false, + } + `); + expect(cuidZZZ.safeParse("1cjld2cyuq0000t3rmniod1foyZZZ")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_format", + "format": "template_literal", + "pattern": "^[cC][^\\\\s-]{8,}ZZZ$", + "path": [], + "message": "Invalid input" + } + ]], + "success": false, + } + `); + expect(stringMin5Max10.safeParse("1234")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_format", + "format": "template_literal", + "pattern": "^[\\\\s\\\\S]{5,10}$", + "path": [], + "message": "Invalid input" + } + ]], + "success": false, + } + `); + expect(connectionString.safeParse("mongodb://host:1234/defaultauthdb?authSourceadmin")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_format", + "format": "template_literal", + "pattern": "^mongodb:\\\\/\\\\/(\\\\w+:\\\\w+@)?\\\\w+:\\\\d+(\\\\/(\\\\w+)?(\\\\?(\\\\w+=\\\\w+(&\\\\w+=\\\\w+)*)?)?)?$", + "path": [], + "message": "Invalid input" + } + ]], + "success": false, + } + `); + + expect(stringStartsWithMax5.safeParse("1hell")).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "invalid_format", + "format": "template_literal", + "pattern": "^hello.*$", + "path": [], + "message": "Invalid input" + } + ]], + "success": false, + } + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..87834d87cf63f38cce75591d344ffe084c3b75a3 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts @@ -0,0 +1,2314 @@ +import { describe, expect, test } from "vitest"; +import * as z from "zod/v4"; +// import * as zCore from "zod/v4/core"; + +describe("toJSONSchema", () => { + test("primitive types", () => { + expect(z.toJSONSchema(z.string())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "string", + } + `); + expect(z.toJSONSchema(z.number())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "number", + } + `); + expect(z.toJSONSchema(z.boolean())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "boolean", + } + `); + expect(z.toJSONSchema(z.null())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "null", + } + `); + expect(z.toJSONSchema(z.undefined(), { unrepresentable: "any" })).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + } + `); + expect(z.toJSONSchema(z.any())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + } + `); + expect(z.toJSONSchema(z.unknown())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + } + `); + expect(z.toJSONSchema(z.never())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "not": {}, + } + `); + expect(z.toJSONSchema(z.email())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "email", + "pattern": "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.iso.datetime())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "date-time", + "pattern": "^(?:(?:\\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])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.iso.date())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "date", + "pattern": "^(?:(?:\\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])))$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.iso.time())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "time", + "pattern": "^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.iso.duration())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "duration", + "pattern": "^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.ipv4())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "ipv4", + "pattern": "^(?:(?: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])$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.ipv6())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "ipv6", + "pattern": "^(([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})$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.uuid())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "uuid", + "pattern": "^([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)$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.guid())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "uuid", + "pattern": "^([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})$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.url())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "uri", + "type": "string", + } + `); + expect(z.toJSONSchema(z.base64())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "contentEncoding": "base64", + "format": "base64", + "pattern": "^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.cuid())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "cuid", + "pattern": "^[cC][^\\s-]{8,}$", + "type": "string", + } + `); + // expect(z.toJSONSchema(z.regex(/asdf/))).toMatchInlineSnapshot(); + expect(z.toJSONSchema(z.emoji())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "emoji", + "pattern": "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.nanoid())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "nanoid", + "pattern": "^[a-zA-Z0-9_-]{21}$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.cuid2())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "cuid2", + "pattern": "^[0-9a-z]+$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.ulid())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "ulid", + "pattern": "^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$", + "type": "string", + } + `); + // expect(z.toJSONSchema(z.cidr())).toMatchInlineSnapshot(); + expect(z.toJSONSchema(z.number())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "number", + } + `); + expect(z.toJSONSchema(z.int())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer", + } + `); + expect(z.toJSONSchema(z.int32())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer", + } + `); + expect(z.toJSONSchema(z.float32())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "maximum": 3.4028234663852886e+38, + "minimum": -3.4028234663852886e+38, + "type": "number", + } + `); + expect(z.toJSONSchema(z.float64())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "maximum": 1.7976931348623157e+308, + "minimum": -1.7976931348623157e+308, + "type": "number", + } + `); + expect(z.toJSONSchema(z.jwt())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "jwt", + "type": "string", + } + `); + }); + + test("unsupported schema types", () => { + expect(() => z.toJSONSchema(z.bigint())).toThrow("BigInt cannot be represented in JSON Schema"); + expect(() => z.toJSONSchema(z.int64())).toThrow("BigInt cannot be represented in JSON Schema"); + expect(() => z.toJSONSchema(z.symbol())).toThrow("Symbols cannot be represented in JSON Schema"); + expect(() => z.toJSONSchema(z.void())).toThrow("Void cannot be represented in JSON Schema"); + expect(() => z.toJSONSchema(z.undefined())).toThrow("Undefined cannot be represented in JSON Schema"); + expect(() => z.toJSONSchema(z.date())).toThrow("Date cannot be represented in JSON Schema"); + expect(() => z.toJSONSchema(z.map(z.string(), z.number()))).toThrow("Map cannot be represented in JSON Schema"); + expect(() => z.toJSONSchema(z.set(z.string()))).toThrow("Set cannot be represented in JSON Schema"); + expect(() => z.toJSONSchema(z.custom(() => true))).toThrow("Custom types cannot be represented in JSON Schema"); + + // Transform + const transformSchema = z.string().transform((val) => Number.parseInt(val)); + expect(() => z.toJSONSchema(transformSchema)).toThrow("Transforms cannot be represented in JSON Schema"); + + // Static catch values + const staticCatchSchema = z.string().catch(() => "sup"); + expect(z.toJSONSchema(staticCatchSchema)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "default": "sup", + "type": "string", + } + `); + + // Dynamic catch values + const dynamicCatchSchema = z.string().catch((ctx) => `${ctx.issues.length}`); + expect(() => z.toJSONSchema(dynamicCatchSchema)).toThrow("Dynamic catch values are not supported in JSON Schema"); + }); + + test("string formats", () => { + expect(z.toJSONSchema(z.string().email())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "email", + "pattern": "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.string().uuid())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "uuid", + "pattern": "^([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)$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.iso.datetime())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "date-time", + "pattern": "^(?:(?:\\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])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "type": "string", + } + `); + + expect(z.toJSONSchema(z.iso.date())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "date", + "pattern": "^(?:(?:\\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])))$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.iso.time())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "time", + "pattern": "^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.iso.duration())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "duration", + "pattern": "^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$", + "type": "string", + } + `); + // expect(z.toJSONSchema(z.string().ip())).toMatchInlineSnapshot(` + // { + // "pattern": /\\(\\^\\(\\?:\\(\\?: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\\]\\)\\$\\)\\|\\(\\^\\(\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{7\\}\\|::\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{0,6\\}\\|\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{1\\}:\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{0,5\\}\\|\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{2\\}:\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{0,4\\}\\|\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{3\\}:\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{0,3\\}\\|\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{4\\}:\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{0,2\\}\\|\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{5\\}:\\(\\[a-fA-F0-9\\]\\{1,4\\}:\\)\\{0,1\\}\\)\\(\\[a-fA-F0-9\\]\\{1,4\\}\\|\\(\\(\\(25\\[0-5\\]\\)\\|\\(2\\[0-4\\]\\[0-9\\]\\)\\|\\(1\\[0-9\\]\\{2\\}\\)\\|\\(\\[0-9\\]\\{1,2\\}\\)\\)\\\\\\.\\)\\{3\\}\\(\\(25\\[0-5\\]\\)\\|\\(2\\[0-4\\]\\[0-9\\]\\)\\|\\(1\\[0-9\\]\\{2\\}\\)\\|\\(\\[0-9\\]\\{1,2\\}\\)\\)\\)\\$\\)/, + // "type": "string", + // } + // `); + expect(z.toJSONSchema(z.ipv4())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "ipv4", + "pattern": "^(?:(?: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])$", + "type": "string", + } + `); + + expect(z.toJSONSchema(z.ipv6())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "ipv6", + "pattern": "^(([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})$", + "type": "string", + } + `); + + expect(z.toJSONSchema(z.base64())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "contentEncoding": "base64", + "format": "base64", + "pattern": "^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.url())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "uri", + "type": "string", + } + `); + expect(z.toJSONSchema(z.guid())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "uuid", + "pattern": "^([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})$", + "type": "string", + } + `); + expect(z.toJSONSchema(z.string().regex(/asdf/))).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "pattern": "asdf", + "type": "string", + } + `); + }); + + test("string patterns", () => { + expect( + z.toJSONSchema( + z + .string() + .startsWith("hello") + .includes("cruel") + .includes("dark", { position: 10 }) + .endsWith("world") + .regex(/stuff/) + ) + ).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "allOf": [ + { + "pattern": "^hello.*", + }, + { + "pattern": "cruel", + }, + { + "pattern": "^.{10}dark", + }, + { + "pattern": ".*world$", + }, + { + "pattern": "stuff", + }, + ], + "type": "string", + } + `); + + expect( + z.toJSONSchema( + z + .string() + .startsWith("hello") + .includes("cruel") + .includes("dark", { position: 10 }) + .endsWith("world") + .regex(/stuff/), + { + target: "draft-7", + } + ) + ).toMatchInlineSnapshot(` + { + "$schema": "http://json-schema.org/draft-07/schema#", + "allOf": [ + { + "pattern": "^hello.*", + "type": "string", + }, + { + "pattern": "cruel", + "type": "string", + }, + { + "pattern": "^.{10}dark", + "type": "string", + }, + { + "pattern": ".*world$", + "type": "string", + }, + { + "pattern": "stuff", + "type": "string", + }, + ], + "type": "string", + } + `); + }); + + test("number constraints", () => { + expect(z.toJSONSchema(z.number().min(5).max(10))).toMatchInlineSnapshot( + ` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "maximum": 10, + "minimum": 5, + "type": "number", + } + ` + ); + + expect(z.toJSONSchema(z.number().gt(5).gt(10))).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "exclusiveMinimum": 10, + "type": "number", + } + `); + + expect(z.toJSONSchema(z.number().gt(5).gte(10))).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "minimum": 10, + "type": "number", + } + `); + + expect(z.toJSONSchema(z.number().lt(5).lt(3))).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "exclusiveMaximum": 3, + "type": "number", + } + `); + + expect(z.toJSONSchema(z.number().lt(5).lt(3).lte(2))).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "maximum": 2, + "type": "number", + } + `); + + expect(z.toJSONSchema(z.number().lt(5).lte(3))).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "maximum": 3, + "type": "number", + } + `); + + expect(z.toJSONSchema(z.number().gt(5).lt(10))).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "exclusiveMaximum": 10, + "exclusiveMinimum": 5, + "type": "number", + } + `); + expect(z.toJSONSchema(z.number().gte(5).lte(10))).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "maximum": 10, + "minimum": 5, + "type": "number", + } + `); + expect(z.toJSONSchema(z.number().positive())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "exclusiveMinimum": 0, + "type": "number", + } + `); + expect(z.toJSONSchema(z.number().negative())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "exclusiveMaximum": 0, + "type": "number", + } + `); + expect(z.toJSONSchema(z.number().nonpositive())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "maximum": 0, + "type": "number", + } + `); + expect(z.toJSONSchema(z.number().nonnegative())).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "minimum": 0, + "type": "number", + } + `); + }); + + test("arrays", () => { + expect(z.toJSONSchema(z.array(z.string()))).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "items": { + "type": "string", + }, + "type": "array", + } + `); + }); + + test("unions", () => { + const schema = z.union([z.string(), z.number()]); + expect(z.toJSONSchema(schema)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "anyOf": [ + { + "type": "string", + }, + { + "type": "number", + }, + ], + } + `); + }); + + test("intersections", () => { + const schema = z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() })); + + expect(z.toJSONSchema(schema)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "allOf": [ + { + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + }, + }, + "required": [ + "name", + ], + "type": "object", + }, + { + "additionalProperties": false, + "properties": { + "age": { + "type": "number", + }, + }, + "required": [ + "age", + ], + "type": "object", + }, + ], + } + `); + }); + + test("record", () => { + const schema = z.record(z.string(), z.boolean()); + expect(z.toJSONSchema(schema)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": { + "type": "boolean", + }, + "propertyNames": { + "type": "string", + }, + "type": "object", + } + `); + }); + + test("tuple", () => { + const schema = z.tuple([z.string(), z.number()]).rest(z.boolean()); + expect(z.toJSONSchema(schema)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "items": { + "type": "boolean", + }, + "prefixItems": [ + { + "type": "string", + }, + { + "type": "number", + }, + ], + "type": "array", + } + `); + }); + + test("promise", () => { + const schema = z.promise(z.string()); + expect(z.toJSONSchema(schema)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "string", + } + `); + }); + + test("lazy", () => { + const schema = z.lazy(() => z.string()); + expect(z.toJSONSchema(schema)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "string", + } + `); + }); + + // enum + test("enum", () => { + const a = z.enum(["a", "b", "c"]); + expect(z.toJSONSchema(a)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "enum": [ + "a", + "b", + "c", + ], + "type": "string", + } + `); + + enum B { + A = 0, + B = 1, + C = 2, + } + + const b = z.enum(B); + expect(z.toJSONSchema(b)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "enum": [ + 0, + 1, + 2, + ], + "type": "number", + } + `); + }); + + // literal + test("literal", () => { + const a = z.literal("hello"); + expect(z.toJSONSchema(a)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "const": "hello", + "type": "string", + } + `); + + const b = z.literal(7); + expect(z.toJSONSchema(b)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "const": 7, + "type": "number", + } + `); + + const c = z.literal(["hello", undefined, null, 5, BigInt(1324)]); + expect(() => z.toJSONSchema(c)).toThrow(); + + const d = z.literal(["hello", null, 5]); + expect(z.toJSONSchema(d)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "enum": [ + "hello", + null, + 5, + ], + } + `); + + const e = z.literal(["hello", "zod", "v4"]); + expect(z.toJSONSchema(e)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "enum": [ + "hello", + "zod", + "v4", + ], + "type": "string", + } + `); + }); + + // pipe + test("pipe", () => { + const schema = z + .string() + .transform((val) => Number.parseInt(val)) + .pipe(z.number()); + expect(z.toJSONSchema(schema)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "number", + } + `); + }); + + test("simple objects", () => { + const schema = z.object({ + name: z.string(), + age: z.number(), + }); + + expect(z.toJSONSchema(schema)).toMatchInlineSnapshot( + ` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "age": { + "type": "number", + }, + "name": { + "type": "string", + }, + }, + "required": [ + "name", + "age", + ], + "type": "object", + } + ` + ); + }); + + test("additionalproperties in z.object", () => { + const a = z.object({ + name: z.string(), + }); + expect(z.toJSONSchema(a)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + }, + }, + "required": [ + "name", + ], + "type": "object", + } + `); + expect(z.toJSONSchema(a, { io: "input" })).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "name": { + "type": "string", + }, + }, + "required": [ + "name", + ], + "type": "object", + } + `); + expect( + z.toJSONSchema(a, { + io: "input", + override(ctx) { + const def = ctx.zodSchema._zod.def; + if (def.type === "object" && !def.catchall) { + (ctx.jsonSchema as z.core.JSONSchema.ObjectSchema).additionalProperties = false; + } + }, + }) + ).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + }, + }, + "required": [ + "name", + ], + "type": "object", + } + `); + }); + + test("catchall objects", () => { + const a = z.strictObject({ + name: z.string(), + age: z.number(), + }); + + expect(z.toJSONSchema(a)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "age": { + "type": "number", + }, + "name": { + "type": "string", + }, + }, + "required": [ + "name", + "age", + ], + "type": "object", + } + `); + + const b = z + .object({ + name: z.string(), + }) + .catchall(z.string()); + + expect(z.toJSONSchema(b)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": { + "type": "string", + }, + "properties": { + "name": { + "type": "string", + }, + }, + "required": [ + "name", + ], + "type": "object", + } + `); + + const c = z.looseObject({ + name: z.string(), + }); + + expect(z.toJSONSchema(c)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": {}, + "properties": { + "name": { + "type": "string", + }, + }, + "required": [ + "name", + ], + "type": "object", + } + `); + }); + + test("optional fields - object", () => { + const schema = z.object({ + required: z.string(), + optional: z.string().optional(), + nonoptional: z.string().optional().nonoptional(), + }); + + const result = z.toJSONSchema(schema); + + expect(result).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "nonoptional": { + "type": "string", + }, + "optional": { + "type": "string", + }, + "required": { + "type": "string", + }, + }, + "required": [ + "required", + "nonoptional", + ], + "type": "object", + } + `); + }); + + test("recursive object", () => { + interface Category { + name: string; + subcategories: Category[]; + } + + const categorySchema: z.ZodType = z.object({ + name: z.string(), + subcategories: z.array(z.lazy(() => categorySchema)), + }); + + const result = z.toJSONSchema(categorySchema); + expect(result).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + }, + "subcategories": { + "items": { + "$ref": "#", + }, + "type": "array", + }, + }, + "required": [ + "name", + "subcategories", + ], + "type": "object", + } + `); + }); + + test("simple interface", () => { + const userSchema = z.object({ + name: z.string(), + age: z.number().optional(), + }); + + const result = z.toJSONSchema(userSchema); + expect(result).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "age": { + "type": "number", + }, + "name": { + "type": "string", + }, + }, + "required": [ + "name", + ], + "type": "object", + } + `); + }); + + test("catchall interface", () => { + const a = z.strictObject({ + name: z.string(), + age: z.number(), + }); + + expect(z.toJSONSchema(a)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "age": { + "type": "number", + }, + "name": { + "type": "string", + }, + }, + "required": [ + "name", + "age", + ], + "type": "object", + } + `); + + const b = z + .object({ + name: z.string(), + }) + .catchall(z.string()); + + expect(z.toJSONSchema(b)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": { + "type": "string", + }, + "properties": { + "name": { + "type": "string", + }, + }, + "required": [ + "name", + ], + "type": "object", + } + `); + + const c = z.looseObject({ + name: z.string(), + }); + + expect(z.toJSONSchema(c)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": {}, + "properties": { + "name": { + "type": "string", + }, + }, + "required": [ + "name", + ], + "type": "object", + } + `); + }); + + test("recursive interface schemas", () => { + const TreeNodeSchema = z.object({ + id: z.string(), + get children() { + return TreeNodeSchema; + }, + }); + + const result = z.toJSONSchema(TreeNodeSchema); + + // Should have definitions for recursive schema + expect(JSON.stringify(result, null, 2)).toMatchInlineSnapshot( + ` + "{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "children": { + "$ref": "#" + } + }, + "required": [ + "id", + "children" + ], + "additionalProperties": false + }" + ` + ); + }); + + test("mutually recursive interface schemas", () => { + const FolderSchema = z.object({ + name: z.string(), + get files() { + return z.array(FileSchema); + }, + }); + + const FileSchema = z.object({ + name: z.string(), + get parent() { + return FolderSchema; + }, + }); + + const result = z.toJSONSchema(FolderSchema); + + // Should have definitions for both schemas + expect(JSON.stringify(result, null, 2)).toMatchInlineSnapshot( + ` + "{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "parent": { + "$ref": "#" + } + }, + "required": [ + "name", + "parent" + ], + "additionalProperties": false + } + } + }, + "required": [ + "name", + "files" + ], + "additionalProperties": false + }" + ` + ); + }); +}); + +test("override", () => { + const schema = z.z.toJSONSchema(z.string(), { + override: (ctx) => { + ctx.zodSchema; + ctx.jsonSchema; + ctx.jsonSchema.whatever = "sup"; + }, + }); + expect(schema).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "string", + "whatever": "sup", + } + `); +}); + +test("override: do not run on references", () => { + let overrideCount = 0; + const schema = z + .union([z.string().date(), z.string().datetime(), z.string().datetime({ local: true })]) + .meta({ a: true }) + .transform((str) => new Date(str)) + .meta({ b: true }) + .pipe(z.date()) + .meta({ c: true }) + .brand("dateIn"); + z.z.toJSONSchema(schema, { + unrepresentable: "any", + io: "input", + override(_) { + overrideCount++; + }, + }); + + expect(overrideCount).toBe(6); +}); + +test("override with refs", () => { + const a = z.string().optional(); + const result = z.z.toJSONSchema(a, { + override(ctx) { + if (ctx.zodSchema._zod.def.type === "string") { + ctx.jsonSchema.type = "STRING" as "string"; + } + }, + }); + + expect(result).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "STRING", + } + `); +}); + +test("override execution order", () => { + const schema = z.union([z.string(), z.number()]); + let unionSchema!: any; + z.z.toJSONSchema(schema, { + override(ctx) { + if (ctx.zodSchema._zod.def.type === "union") { + unionSchema = ctx.jsonSchema; + } + }, + }); + + expect(unionSchema).toMatchInlineSnapshot(` + { + "anyOf": [ + { + "type": "string", + }, + { + "type": "number", + }, + ], + } + `); +}); + +test("override with path", () => { + const userSchema = z.object({ + name: z.string(), + age: z.number(), + }); + + const capturedPaths: (string | number)[][] = []; + + z.toJSONSchema(userSchema, { + override(ctx) { + capturedPaths.push(ctx.path); + }, + }); + + expect(capturedPaths).toMatchInlineSnapshot(` + [ + [ + "properties", + "age", + ], + [ + "properties", + "name", + ], + [], + ] + `); +}); + +test("pipe", () => { + const mySchema = z + .string() + .transform((val) => val.length) + .pipe(z.number()); + // ZodPipe + + const a = z.z.toJSONSchema(mySchema); + expect(a).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "number", + } + `); + // => { type: "number" } + + const b = z.z.toJSONSchema(mySchema, { io: "input" }); + expect(b).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "string", + } + `); + // => { type: "string" } +}); + +test("passthrough schemas", () => { + const Internal = z.object({ + num: z.number(), + str: z.string(), + }); + //.meta({ id: "Internal" }); + + const External = z.object({ + a: Internal, + b: Internal.optional(), + c: z.lazy(() => Internal), + d: z.promise(Internal), + e: z.pipe(Internal, Internal), + }); + + const result = z.z.toJSONSchema(External, { + reused: "ref", + }); + expect(result).toMatchInlineSnapshot(` + { + "$defs": { + "__schema0": { + "additionalProperties": false, + "properties": { + "num": { + "type": "number", + }, + "str": { + "type": "string", + }, + }, + "required": [ + "num", + "str", + ], + "type": "object", + }, + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "a": { + "$ref": "#/$defs/__schema0", + }, + "b": { + "$ref": "#/$defs/__schema0", + }, + "c": { + "$ref": "#/$defs/__schema0", + }, + "d": { + "$ref": "#/$defs/__schema0", + }, + "e": { + "$ref": "#/$defs/__schema0", + }, + }, + "required": [ + "a", + "c", + "d", + "e", + ], + "type": "object", + } + `); +}); + +test("extract schemas with id", () => { + const name = z.string().meta({ id: "name" }); + const result = z.z.toJSONSchema( + z.object({ + first_name: name, + last_name: name.nullable(), + middle_name: name.optional(), + age: z.number().meta({ id: "age" }), + }) + ); + expect(result).toMatchInlineSnapshot(` + { + "$defs": { + "age": { + "id": "age", + "type": "number", + }, + "name": { + "id": "name", + "type": "string", + }, + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "age": { + "$ref": "#/$defs/age", + }, + "first_name": { + "$ref": "#/$defs/name", + }, + "last_name": { + "anyOf": [ + { + "$ref": "#/$defs/name", + }, + { + "type": "null", + }, + ], + }, + "middle_name": { + "$ref": "#/$defs/name", + }, + }, + "required": [ + "first_name", + "last_name", + "age", + ], + "type": "object", + } + `); +}); + +test("unrepresentable literal values are ignored", () => { + const a = z.z.toJSONSchema(z.literal(["hello", null, 5, BigInt(1324), undefined]), { unrepresentable: "any" }); + expect(a).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "enum": [ + "hello", + null, + 5, + 1324, + ], + } + `); + + const b = z.z.toJSONSchema(z.literal([undefined, null, 5, BigInt(1324)]), { unrepresentable: "any" }); + expect(b).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "enum": [ + null, + 5, + 1324, + ], + } + `); + + const c = z.z.toJSONSchema(z.literal([undefined]), { unrepresentable: "any" }); + expect(c).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + } + `); +}); + +test("describe with id", () => { + const jobId = z.string().meta({ id: "jobId" }); + + const a = z.z.toJSONSchema( + z.object({ + current: jobId.describe("Current job"), + previous: jobId.describe("Previous job"), + }) + ); + expect(a).toMatchInlineSnapshot(` + { + "$defs": { + "jobId": { + "id": "jobId", + "type": "string", + }, + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "current": { + "$ref": "#/$defs/jobId", + "description": "Current job", + }, + "previous": { + "$ref": "#/$defs/jobId", + "description": "Previous job", + }, + }, + "required": [ + "current", + "previous", + ], + "type": "object", + } + `); +}); + +test("overwrite id", () => { + const jobId = z.string().meta({ id: "aaa" }); + + const a = z.z.toJSONSchema( + z.object({ + current: jobId, + previous: jobId.meta({ id: "bbb" }), + }) + ); + expect(a).toMatchInlineSnapshot(` + { + "$defs": { + "aaa": { + "id": "aaa", + "type": "string", + }, + "bbb": { + "$ref": "#/$defs/aaa", + "id": "bbb", + }, + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "current": { + "$ref": "#/$defs/aaa", + }, + "previous": { + "$ref": "#/$defs/bbb", + }, + }, + "required": [ + "current", + "previous", + ], + "type": "object", + } + `); + + const b = z.z.toJSONSchema( + z.object({ + current: jobId, + previous: jobId.meta({ id: "ccc" }), + }), + { + reused: "ref", + } + ); + expect(b).toMatchInlineSnapshot(` + { + "$defs": { + "aaa": { + "id": "aaa", + "type": "string", + }, + "ccc": { + "$ref": "#/$defs/aaa", + "id": "ccc", + }, + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "current": { + "$ref": "#/$defs/aaa", + }, + "previous": { + "$ref": "#/$defs/ccc", + }, + }, + "required": [ + "current", + "previous", + ], + "type": "object", + } + `); +}); + +test("overwrite descriptions", () => { + const field = z.string().describe("a").describe("b").describe("c"); + + const a = z.z.toJSONSchema( + z.object({ + d: field.describe("d"), + e: field.describe("e"), + }) + ); + expect(a).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "d": { + "description": "d", + "type": "string", + }, + "e": { + "description": "e", + "type": "string", + }, + }, + "required": [ + "d", + "e", + ], + "type": "object", + } + `); + + const b = z.z.toJSONSchema( + z.object({ + d: field.describe("d"), + e: field.describe("e"), + }), + { + reused: "ref", + } + ); + expect(b).toMatchInlineSnapshot(` + { + "$defs": { + "__schema0": { + "description": "c", + "type": "string", + }, + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "d": { + "$ref": "#/$defs/__schema0", + "description": "d", + }, + "e": { + "$ref": "#/$defs/__schema0", + "description": "e", + }, + }, + "required": [ + "d", + "e", + ], + "type": "object", + } + `); +}); + +test("top-level readonly", () => { + const A = z + .object({ + name: z.string(), + get b() { + return B; + }, + }) + .readonly() + .meta({ id: "A" }); + // z.globalRegistry.add(A, { id: "A" }); + // .meta({ id: "A" }); + + const B = z + .object({ + name: z.string(), + get a() { + return A; + }, + }) + .readonly() + .meta({ id: "B" }); + // z.globalRegistry.add(B, { id: "B" }); + // .meta({ id: "B" }); + + const result = z.z.toJSONSchema(A); + expect(result).toMatchInlineSnapshot(` + { + "$defs": { + "B": { + "additionalProperties": false, + "id": "B", + "properties": { + "a": { + "$ref": "#", + }, + "name": { + "type": "string", + }, + }, + "readOnly": true, + "required": [ + "name", + "a", + ], + "type": "object", + }, + }, + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "id": "A", + "properties": { + "b": { + "$ref": "#/$defs/B", + }, + "name": { + "type": "string", + }, + }, + "readOnly": true, + "required": [ + "name", + "b", + ], + "type": "object", + } + `); +}); + +test("basic registry", () => { + const myRegistry = z.registry<{ id: string }>(); + const User = z.object({ + name: z.string(), + get posts() { + return z.array(Post); + }, + }); + + const Post = z.object({ + title: z.string(), + content: z.string(), + get author() { + return User; + }, + }); + + myRegistry.add(User, { id: "User" }); + myRegistry.add(Post, { id: "Post" }); + + const result = z.z.toJSONSchema(myRegistry, { uri: (id) => `https://example.com/${id}.json` }); + expect(result).toMatchInlineSnapshot(` + { + "schemas": { + "Post": { + "$id": "https://example.com/Post.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "author": { + "$ref": "https://example.com/User.json", + }, + "content": { + "type": "string", + }, + "title": { + "type": "string", + }, + }, + "required": [ + "title", + "content", + "author", + ], + "type": "object", + }, + "User": { + "$id": "https://example.com/User.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + }, + "posts": { + "items": { + "$ref": "https://example.com/Post.json", + }, + "type": "array", + }, + }, + "required": [ + "name", + "posts", + ], + "type": "object", + }, + }, + } + `); +}); + +test("_ref", () => { + // const a = z.promise(z.string().describe("a")); + const a = z.z.toJSONSchema(z.promise(z.string().describe("a"))); + expect(a).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "a", + "type": "string", + } + `); + + const b = z.z.toJSONSchema(z.lazy(() => z.string().describe("a"))); + expect(b).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "a", + "type": "string", + } + `); + + const c = z.z.toJSONSchema(z.optional(z.string().describe("a"))); + expect(c).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "a", + "type": "string", + } + `); +}); + +test("defaults/prefaults", () => { + const a = z + .string() + .transform((val) => val.length) + .pipe(z.number()); + const b = a.prefault("hello"); + const c = a.default(1234); + + // a + expect(z.toJSONSchema(a)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "number", + } + `); + expect(z.toJSONSchema(a, { io: "input" })).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "string", + } + `); + + // b + expect(z.toJSONSchema(b)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "number", + } + `); + expect(z.toJSONSchema(b, { io: "input" })).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "default": "hello", + "type": "string", + } + `); + // c + expect(z.toJSONSchema(c)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "default": 1234, + "type": "number", + } + `); + expect(z.toJSONSchema(c, { io: "input" })).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "string", + } + `); +}); + +test("input type", () => { + const schema = z.object({ + a: z.string(), + b: z.string().optional(), + c: z.string().default("hello"), + d: z.string().nullable(), + e: z.string().prefault("hello"), + f: z.string().catch("hello"), + g: z.never(), + h: z.union([z.string(), z.number().default(2)]), + i: z.union([z.string(), z.string().optional()]), + }); + expect(z.toJSONSchema(schema, { io: "input" })).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "a": { + "type": "string", + }, + "b": { + "type": "string", + }, + "c": { + "default": "hello", + "type": "string", + }, + "d": { + "anyOf": [ + { + "type": "string", + }, + { + "type": "null", + }, + ], + }, + "e": { + "default": "hello", + "type": "string", + }, + "f": { + "default": "hello", + "type": "string", + }, + "g": { + "not": {}, + }, + "h": { + "anyOf": [ + { + "type": "string", + }, + { + "default": 2, + "type": "number", + }, + ], + }, + "i": { + "anyOf": [ + { + "type": "string", + }, + { + "type": "string", + }, + ], + }, + }, + "required": [ + "a", + "d", + "g", + ], + "type": "object", + } + `); + expect(z.toJSONSchema(schema, { io: "output" })).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "a": { + "type": "string", + }, + "b": { + "type": "string", + }, + "c": { + "default": "hello", + "type": "string", + }, + "d": { + "anyOf": [ + { + "type": "string", + }, + { + "type": "null", + }, + ], + }, + "e": { + "type": "string", + }, + "f": { + "default": "hello", + "type": "string", + }, + "g": { + "not": {}, + }, + "h": { + "anyOf": [ + { + "type": "string", + }, + { + "default": 2, + "type": "number", + }, + ], + }, + "i": { + "anyOf": [ + { + "type": "string", + }, + { + "type": "string", + }, + ], + }, + }, + "required": [ + "a", + "c", + "d", + "e", + "f", + "g", + "h", + ], + "type": "object", + } + `); +}); + +test("examples on pipe", () => { + const schema = z + .string() + .meta({ examples: ["test"] }) + .transform(Number) + // .pipe(z.transform(Number).meta({ examples: [4] })) + .meta({ examples: [4] }); + + const i = z.z.toJSONSchema(schema, { io: "input", unrepresentable: "any" }); + expect(i).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "examples": [ + "test", + ], + "type": "string", + } + `); + const o = z.z.toJSONSchema(schema, { io: "output", unrepresentable: "any" }); + expect(o).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "examples": [ + 4, + ], + } + `); +}); + +// test("number checks", () => { +// expect(z.z.toJSONSchema(z.number().int())).toMatchInlineSnapshot(` +// { +// "maximum": 9007199254740991, +// "minimum": -9007199254740991, +// "type": "integer", +// } +// `); +// expect(z.z.toJSONSchema(z.int())).toMatchInlineSnapshot(` +// { +// "maximum": 9007199254740991, +// "minimum": -9007199254740991, +// "type": "integer", +// } +// `); +// expect(z.z.toJSONSchema(z.int().positive())).toMatchInlineSnapshot(` +// { +// "exclusiveMinimum": 0, +// "maximum": 9007199254740991, +// "minimum": -9007199254740991, +// "type": "integer", +// } +// `); +// expect(z.z.toJSONSchema(z.int().nonnegative())).toMatchInlineSnapshot(` +// { +// "maximum": 9007199254740991, +// "minimum": 0, +// "type": "integer", +// } +// `); +// expect(z.z.toJSONSchema(z.int().gt(0))).toMatchInlineSnapshot(` +// { +// "exclusiveMinimum": 0, +// "maximum": 9007199254740991, +// "minimum": -9007199254740991, +// "type": "integer", +// } +// `); +// expect(z.z.toJSONSchema(z.int().gte(0))).toMatchInlineSnapshot(` +// { +// "maximum": 9007199254740991, +// "minimum": 0, +// "type": "integer", +// } +// `); + +// }); + +test("use output type for preprocess", () => { + const a = z.preprocess((val) => String(val), z.string()); + + expect(z.toJSONSchema(a, { io: "input" })).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "string", + } + `); +}); + +// test("isTransforming", () => { +// const tx = z.core.isTransforming; +// expect(tx(z.string())).toEqual(false); +// expect(tx(z.string().transform((val) => val))).toEqual(true); +// expect(tx(z.string().pipe(z.string()))).toEqual(false); +// expect( +// tx( +// z +// .string() +// .transform((val) => val) +// .pipe(z.string()) +// ) +// ).toEqual(true); + +// const a = z.transform((val) => val); +// expect(tx(z.transform((val) => val))).toEqual(true); +// expect(tx(a.optional())).toEqual(true); + +// const b = z.string().optional(); +// expect(tx(b)).toEqual(false); + +// const c = z.string().prefault("hello"); +// expect(tx(c)).toEqual(false); + +// const d = z.string().default("hello"); +// expect(tx(d)).toEqual(false); +// }); + +test("flatten simple intersections", () => { + const FirstSchema = z.object({ + testNum: z.number(), + }); + + const SecondSchema = z.object({ + testStr: z.string(), + }); + + const ThirdSchema = z.object({ + testBool: z.boolean(), + }); + + const HelloSchema = FirstSchema.and(SecondSchema).and(ThirdSchema).describe("123"); + + // Zod 3 + // console.log(JSON.stringify(zodToJsonSchema(HelloSchema), null, 2)); + + // Zod 4 + const result = z.toJSONSchema(HelloSchema, { target: "draft-7" }); + expect(result).toMatchInlineSnapshot(` + { + "$schema": "http://json-schema.org/draft-07/schema#", + "allOf": [ + { + "additionalProperties": false, + "properties": { + "testNum": { + "type": "number", + }, + }, + "required": [ + "testNum", + ], + "type": "object", + }, + { + "additionalProperties": false, + "properties": { + "testStr": { + "type": "string", + }, + }, + "required": [ + "testStr", + ], + "type": "object", + }, + { + "additionalProperties": false, + "properties": { + "testBool": { + "type": "boolean", + }, + }, + "required": [ + "testBool", + ], + "type": "object", + }, + ], + "description": "123", + } + `); +}); + +test("z.file()", () => { + const a = z.file(); + expect(z.toJSONSchema(a)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "contentEncoding": "binary", + "format": "binary", + "type": "string", + } + `); + + const b = z.file().mime("image/png").min(1000).max(10000); + expect(z.toJSONSchema(b)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "contentEncoding": "binary", + "contentMediaType": "image/png", + "format": "binary", + "maxLength": 10000, + "minLength": 1000, + "type": "string", + } + `); + + const c = z.file().mime(["image/png", "image/jpg"]).min(1000).max(10000); + expect(z.toJSONSchema(c)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "anyOf": [ + { + "contentEncoding": "binary", + "contentMediaType": "image/png", + "format": "binary", + "maxLength": 10000, + "minLength": 1000, + "type": "string", + }, + { + "contentEncoding": "binary", + "contentMediaType": "image/jpg", + "format": "binary", + "maxLength": 10000, + "minLength": 1000, + "type": "string", + }, + ], + } + `); +}); + +test("custom toJSONSchema", () => { + const schema = z.instanceof(Date); + schema._zod.toJSONSchema = () => ({ + type: "string", + format: "date-time", + }); + + expect(z.toJSONSchema(schema)).toMatchInlineSnapshot(` + { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "format": "date-time", + "type": "string", + } + `); +}); + +test("cycle detection - root", () => { + const schema = z.object({ + name: z.string(), + get subcategories() { + return z.array(schema); + }, + }); + + expect(() => z.toJSONSchema(schema, { cycles: "throw" })).toThrowErrorMatchingInlineSnapshot(` + [Error: Cycle detected: #/properties/subcategories/items/ + + Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.] + `); +}); + +test("cycle detection - mutual recursion", () => { + const A = z.object({ + name: z.string(), + get subcategories() { + return z.array(B); + }, + }); + + const B = z.object({ + name: z.string(), + get subcategories() { + return z.array(A); + }, + }); + + expect(() => z.toJSONSchema(A, { cycles: "throw" })).toThrowErrorMatchingInlineSnapshot(` + [Error: Cycle detected: #/properties/subcategories/items/properties/subcategories/items/ + + Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.] + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/transform.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/transform.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce8749fce6f9e995ac31aae8a75a836ac12ca0da --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/transform.test.ts @@ -0,0 +1,250 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("transform ctx.addIssue with parse", () => { + const strs = ["foo", "bar"]; + const schema = z.string().transform((data, ctx) => { + const i = strs.indexOf(data); + if (i === -1) { + ctx.addIssue({ + input: data, + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + } + return data.length; + }); + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); + expect(result.error!).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "message": "asdf is not one of our allowed strings", + "path": [] + } + ]] + `); +}); + +test("transform ctx.addIssue with parseAsync", async () => { + const strs = ["foo", "bar"]; + + const result = await z + .string() + .transform(async (data, ctx) => { + const i = strs.indexOf(data); + if (i === -1) { + ctx.addIssue({ + input: data, + code: "custom", + message: `${data} is not one of our allowed strings`, + }); + } + return data.length; + }) + .safeParseAsync("asdf"); + + expect(result).toMatchInlineSnapshot(` + { + "error": [ZodError: [ + { + "code": "custom", + "message": "asdf is not one of our allowed strings", + "path": [] + } + ]], + "success": false, + } + `); +}); + +test("z.NEVER in transform", () => { + const foo = z + .number() + .optional() + .transform((val, ctx) => { + if (!val) { + ctx.addIssue({ + input: val, + code: z.ZodIssueCode.custom, + message: "bad", + }); + return z.NEVER; + } + return val; + }); + type foo = z.infer; + expectTypeOf().toEqualTypeOf(); + const arg = foo.safeParse(undefined); + if (!arg.success) { + expect(arg.error.issues[0].message).toEqual("bad"); + } +}); + +test("basic transformations", () => { + const r1 = z + .string() + .transform((data) => data.length) + .parse("asdf"); + expect(r1).toEqual(4); +}); + +test("coercion", () => { + const numToString = z.number().transform((n) => String(n)); + const data = z + .object({ + id: numToString, + }) + .parse({ id: 5 }); + + expect(data).toEqual({ id: "5" }); +}); + +test("async coercion", async () => { + const numToString = z.number().transform(async (n) => String(n)); + const data = await z + .object({ + id: numToString, + }) + .parseAsync({ id: 5 }); + + expect(data).toEqual({ id: "5" }); +}); + +test("sync coercion async error", async () => { + const asyncNumberToString = z.number().transform(async (n) => String(n)); + expect(() => + z + .object({ + id: asyncNumberToString, + }) + .parse({ id: 5 }) + ).toThrow(); + // expect(data).toEqual({ id: '5' }); +}); + +test("default", () => { + const data = z.string().default("asdf").parse(undefined); // => "asdf" + expect(data).toEqual("asdf"); +}); + +test("dynamic default", () => { + const data = z + .string() + .default(() => "string") + .parse(undefined); // => "asdf" + expect(data).toEqual("string"); +}); + +test("default when property is null or undefined", () => { + const data = z + .object({ + foo: z.boolean().nullable().default(true), + bar: z.boolean().default(true), + }) + .parse({ foo: null }); + + expect(data).toEqual({ foo: null, bar: true }); +}); + +test("default with falsy values", () => { + const schema = z.object({ + emptyStr: z.string().default("def"), + zero: z.number().default(5), + falseBoolean: z.boolean().default(true), + }); + const input = { emptyStr: "", zero: 0, falseBoolean: true }; + const output = schema.parse(input); + // defaults are not supposed to be used + expect(output).toEqual(input); +}); + +test("object typing", () => { + const stringToNumber = z.string().transform((arg) => Number.parseFloat(arg)); + + const t1 = z.object({ + stringToNumber, + }); + + type t1 = z.input; + type t2 = z.output; + + expectTypeOf().toEqualTypeOf<{ stringToNumber: string }>(); + expectTypeOf().toEqualTypeOf<{ stringToNumber: number }>(); +}); + +test("transform method overloads", () => { + const t1 = z.string().transform((val) => val.toUpperCase()); + expect(t1.parse("asdf")).toEqual("ASDF"); + + const t2 = z.string().transform((val) => val.length); + expect(t2.parse("asdf")).toEqual(4); +}); + +test("multiple transformers", () => { + const stringToNumber = z.string().transform((arg) => Number.parseFloat(arg)); + + const doubler = stringToNumber.transform((val) => { + return val * 2; + }); + expect(doubler.parse("5")).toEqual(10); +}); + +test("short circuit on dirty", () => { + const schema = z + .string() + .refine(() => false) + .transform((val) => val.toUpperCase()); + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); + + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "message": "Invalid input" + } + ]] + `); + + const result2 = schema.safeParse(1234); + expect(result2.success).toEqual(false); + if (!result2.success) { + expect(result2.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); + } +}); + +test("async short circuit on dirty", async () => { + const schema = z + .string() + .refine(() => false) + .transform((val) => val.toUpperCase()); + const result = await schema.spa("asdf"); + expect(result.success).toEqual(false); + + expect(result.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "code": "custom", + "path": [], + "message": "Invalid input" + } + ]] + `); + + const result2 = await schema.spa(1234); + expect(result2.success).toEqual(false); + + expect(result2.error).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "string", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected string, received number" + } + ]] + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/tuple.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/tuple.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..94291f1e8ca79ea590d497bf8364db29ff9b4f6b --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/tuple.test.ts @@ -0,0 +1,163 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; + +test("successful validation", () => { + const testTuple = z.tuple([z.string(), z.number()]); + expectTypeOf().toEqualTypeOf<[string, number]>(); + + const val = testTuple.parse(["asdf", 1234]); + expect(val).toEqual(val); + + const r1 = testTuple.safeParse(["asdf", "asdf"]); + expect(r1.success).toEqual(false); + expect(r1.error!).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "number", + "code": "invalid_type", + "path": [ + 1 + ], + "message": "Invalid input: expected number, received string" + } + ]] + `); + + const r2 = testTuple.safeParse(["asdf", 1234, true]); + expect(r2.success).toEqual(false); + expect(r2.error!).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "array", + "code": "too_big", + "maximum": 2, + "path": [], + "message": "Too big: expected array to have <2 items" + } + ]] + `); + + const r3 = testTuple.safeParse({}); + expect(r3.success).toEqual(false); + expect(r3.error!).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "tuple", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected tuple, received object" + } + ]] + `); +}); + +test("async validation", async () => { + const testTuple = z + .tuple([z.string().refine(async () => true), z.number().refine(async () => true)]) + .refine(async () => true); + expectTypeOf().toEqualTypeOf<[string, number]>(); + + const val = await testTuple.parseAsync(["asdf", 1234]); + expect(val).toEqual(val); + + const r1 = await testTuple.safeParseAsync(["asdf", "asdf"]); + expect(r1.success).toEqual(false); + expect(r1.error!).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "number", + "code": "invalid_type", + "path": [ + 1 + ], + "message": "Invalid input: expected number, received string" + } + ]] + `); + + const r2 = await testTuple.safeParseAsync(["asdf", 1234, true]); + expect(r2.success).toEqual(false); + expect(r2.error!).toMatchInlineSnapshot(` + [ZodError: [ + { + "origin": "array", + "code": "too_big", + "maximum": 2, + "path": [], + "message": "Too big: expected array to have <2 items" + } + ]] + `); + + const r3 = await testTuple.safeParseAsync({}); + expect(r3.success).toEqual(false); + expect(r3.error!).toMatchInlineSnapshot(` + [ZodError: [ + { + "expected": "tuple", + "code": "invalid_type", + "path": [], + "message": "Invalid input: expected tuple, received object" + } + ]] + `); +}); + +test("tuple with optional elements", () => { + const myTuple = z.tuple([z.string(), z.number().optional(), z.string().optional()]).rest(z.boolean()); + expectTypeOf().toEqualTypeOf<[string, number?, string?, ...boolean[]]>(); + + const goodData = [["asdf"], ["asdf", 1234], ["asdf", 1234, "asdf"], ["asdf", 1234, "asdf", true, false, true]]; + for (const data of goodData) { + expect(myTuple.parse(data)).toEqual(data); + } + + const badData = [ + ["asdf", "asdf"], + ["asdf", 1234, "asdf", "asdf"], + ["asdf", 1234, "asdf", true, false, "asdf"], + ]; + for (const data of badData) { + expect(() => myTuple.parse(data)).toThrow(); + } +}); + +test("tuple with optional elements followed by required", () => { + const myTuple = z.tuple([z.string(), z.number().optional(), z.string()]).rest(z.boolean()); + expectTypeOf().toEqualTypeOf<[string, number | undefined, string, ...boolean[]]>(); + + const goodData = [ + ["asdf", 1234, "asdf"], + ["asdf", 1234, "asdf", true, false, true], + ]; + for (const data of goodData) { + expect(myTuple.parse(data)).toEqual(data); + } + + const badData = [ + ["asdf"], + ["asdf", 1234], + ["asdf", 1234, "asdf", "asdf"], + ["asdf", 1234, "asdf", true, false, "asdf"], + ]; + for (const data of badData) { + expect(() => myTuple.parse(data)).toThrow(); + } +}); + +test("tuple with rest schema", () => { + const myTuple = z.tuple([z.string(), z.number()]).rest(z.boolean()); + expect(myTuple.parse(["asdf", 1234, true, false, true])).toEqual(["asdf", 1234, true, false, true]); + + expect(myTuple.parse(["asdf", 1234])).toEqual(["asdf", 1234]); + + expect(() => myTuple.parse(["asdf", 1234, "asdf"])).toThrow(); + type t1 = z.output; + + expectTypeOf().toEqualTypeOf<[string, number, ...boolean[]]>(); +}); + +test("sparse array input", () => { + const schema = z.tuple([z.string(), z.number()]); + expect(() => schema.parse(new Array(2))).toThrow(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/union.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/union.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d5ecb8e08f6736df1ff6d62bceabbaf95487e17f --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/union.test.ts @@ -0,0 +1,94 @@ +import { expect, expectTypeOf, test } from "vitest"; + +import * as z from "zod/v4"; + +test("function parsing", () => { + const schema = z.union([z.string().refine(() => false), z.number().refine(() => false)]); + const result = schema.safeParse("asdf"); + expect(result.success).toEqual(false); +}); + +test("union 2", () => { + const result = z.union([z.number(), z.string().refine(() => false)]).safeParse("a"); + expect(result.success).toEqual(false); +}); + +test("return valid over invalid", () => { + const schema = z.union([ + z.object({ + email: z.string().email(), + }), + z.string(), + ]); + expect(schema.parse("asdf")).toEqual("asdf"); + expect(schema.parse({ email: "asdlkjf@lkajsdf.com" })).toEqual({ + email: "asdlkjf@lkajsdf.com", + }); +}); + +test("return errors from both union arms", () => { + const result = z.union([z.number(), z.string().refine(() => false)]).safeParse("a"); + expect(result.success).toEqual(false); + if (!result.success) { + expect(result.error.issues).toMatchInlineSnapshot(` + [ + { + "code": "invalid_union", + "errors": [ + [ + { + "code": "invalid_type", + "expected": "number", + "message": "Invalid input: expected number, received string", + "path": [], + }, + ], + [ + { + "code": "custom", + "message": "Invalid input", + "path": [], + }, + ], + ], + "message": "Invalid input", + "path": [], + }, + ] + `); + } +}); + +test("options getter", async () => { + const union = z.union([z.string(), z.number()]); + union.options[0].parse("asdf"); + union.options[1].parse(1234); + await union.options[0].parseAsync("asdf"); + await union.options[1].parseAsync(1234); +}); + +test("readonly union", async () => { + const options = [z.string(), z.number()] as const; + const union = z.union(options); + union.parse("asdf"); + union.parse(12); +}); + +test("union inferred types", () => { + const test = z.object({}).or(z.array(z.object({}))); + + type Test = z.output; // <— any + expectTypeOf().toEqualTypeOf | Array>>(); +}); + +test("union values", () => { + const schema = z.union([z.literal("a"), z.literal("b"), z.literal("c")]); + + expect(schema._zod.values).toMatchInlineSnapshot(` + Set { + "a", + "b", + "c", + } + `); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/validations.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/validations.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..eea9831c3f273c0dbf57cf0825104fd85c65f7be --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/validations.test.ts @@ -0,0 +1,283 @@ +import { expect, test } from "vitest"; + +import * as z from "zod/v4"; + +test("string length", async () => { + try { + await z.string().length(4).parseAsync("asd"); + } catch (err) { + // ("String must contain exactly 4 character(s)"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "exact": true, + "inclusive": true, + "message": "Too small: expected string to have >=4 characters", + "minimum": 4, + "origin": "string", + "path": [], + }, + ] + `); + } + + try { + await z.string().length(4).parseAsync("asdaa"); + } catch (err) { + // ("String must contain exactly 4 character(s)"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "exact": true, + "inclusive": true, + "maximum": 4, + "message": "Too big: expected string to have <=4 characters", + "origin": "string", + "path": [], + }, + ] + `); + } +}); + +test("string min/max", async () => { + try { + await z.string().min(4).parseAsync("asd"); + } catch (err) { + // ("String must contain at least 4 character(s)"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "inclusive": true, + "message": "Too small: expected string to have >=4 characters", + "minimum": 4, + "origin": "string", + "path": [], + }, + ] + `); + } +}); + +test("string max", async () => { + try { + await z.string().max(4).parseAsync("aasdfsdfsd"); + } catch (err) { + // ("String must contain at most 4 character(s)"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "inclusive": true, + "maximum": 4, + "message": "Too big: expected string to have <=4 characters", + "origin": "string", + "path": [], + }, + ] + `); + } +}); + +test("number min", async () => { + try { + await z.number().min(3).parseAsync(2); + } catch (err) { + // ("Number must be greater than or equal to 3"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "inclusive": true, + "message": "Too small: expected number to be >=3", + "minimum": 3, + "origin": "number", + "path": [], + }, + ] + `); + } +}); + +test("number gte", async () => { + try { + await z.number().gte(3).parseAsync(2); + } catch (err) { + // ("Number must be greater than or equal to 3"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "inclusive": true, + "message": "Too small: expected number to be >=3", + "minimum": 3, + "origin": "number", + "path": [], + }, + ] + `); + } +}); + +test("number gt", async () => { + try { + await z.number().gt(3).parseAsync(3); + } catch (err) { + // ("Number must be greater than or equal to 3"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "inclusive": false, + "message": "Too small: expected number to be >3", + "minimum": 3, + "origin": "number", + "path": [], + }, + ] + `); + } +}); + +test("number max", async () => { + try { + await z.number().max(3).parseAsync(4); + } catch (err) { + // ("Number must be less than or equal to 3"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "inclusive": true, + "maximum": 3, + "message": "Too big: expected number to be <=3", + "origin": "number", + "path": [], + }, + ] + `); + } +}); + +test("number lte", async () => { + try { + await z.number().lte(3).parseAsync(4); + } catch (err) { + // ("Number must be less than or equal to 3"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "inclusive": true, + "maximum": 3, + "message": "Too big: expected number to be <=3", + "origin": "number", + "path": [], + }, + ] + `); + } +}); + +test("number lt", async () => { + try { + await z.number().lt(3).parseAsync(3); + } catch (err) { + // ("Number must be less than or equal to 3"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "inclusive": false, + "maximum": 3, + "message": "Too big: expected number to be <3", + "origin": "number", + "path": [], + }, + ] + `); + } +}); + +test("number nonnegative", async () => { + try { + await z.number().nonnegative().parseAsync(-1); + } catch (err) { + // ("Number must be greater than or equal to 0"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "inclusive": true, + "message": "Too small: expected number to be >=0", + "minimum": 0, + "origin": "number", + "path": [], + }, + ] + `); + } +}); + +test("number nonpositive", async () => { + try { + await z.number().nonpositive().parseAsync(1); + } catch (err) { + // ("Number must be less than or equal to 0"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "inclusive": true, + "maximum": 0, + "message": "Too big: expected number to be <=0", + "origin": "number", + "path": [], + }, + ] + `); + } +}); + +test("number negative", async () => { + try { + await z.number().negative().parseAsync(1); + } catch (err) { + // ("Number must be less than 0"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_big", + "inclusive": false, + "maximum": 0, + "message": "Too big: expected number to be <0", + "origin": "number", + "path": [], + }, + ] + `); + } +}); + +test("number positive", async () => { + try { + await z.number().positive().parseAsync(-1); + } catch (err) { + // ("Number must be greater than 0"); + expect((err as z.ZodError).issues).toMatchInlineSnapshot(` + [ + { + "code": "too_small", + "inclusive": false, + "message": "Too small: expected number to be >0", + "minimum": 0, + "origin": "number", + "path": [], + }, + ] + `); + } +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/void.test.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/void.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec0ee127d13ee0a54ec503cc69244b0bc23fc1ae --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/classic/tests/void.test.ts @@ -0,0 +1,12 @@ +import { expect, expectTypeOf, test } from "vitest"; +import * as z from "zod/v4"; +test("void", () => { + const v = z.void(); + v.parse(undefined); + + expect(() => v.parse(null)).toThrow(); + expect(() => v.parse("")).toThrow(); + + type v = z.infer; + expectTypeOf().toEqualTypeOf(); +}); diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/api.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/api.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a487c35095040d9dac7c3dda3c853d04218fdd5 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/api.ts @@ -0,0 +1,1594 @@ +import * as checks from "./checks.js"; +import type * as core from "./core.js"; +import type * as errors from "./errors.js"; +import * as schemas from "./schemas.js"; +import * as util from "./util.js"; + +export type Params< + T extends schemas.$ZodType | checks.$ZodCheck, + IssueTypes extends errors.$ZodIssueBase, + OmitKeys extends keyof T["_zod"]["def"] = never, +> = util.Flatten< + Partial< + util.EmptyToNever< + Omit & + ([IssueTypes] extends [never] + ? {} // unknown + : { + error?: string | errors.$ZodErrorMap | undefined; + /** @deprecated This parameter is deprecated. Use `error` instead. */ + message?: string | undefined; // supported in Zod 3 + }) + > + > +>; + +export type TypeParams< + T extends schemas.$ZodType = schemas.$ZodType & { _isst: never }, + AlsoOmit extends Exclude = never, +> = Params, "type" | "checks" | "error" | AlsoOmit>; + +// strips types that are not exposed in the public factory +// incl. `error`, `check` +export type CheckParams< + T extends checks.$ZodCheck = checks.$ZodCheck, // & { _issc: never }, + AlsoOmit extends Exclude = never, +> = Params, "check" | "error" | AlsoOmit>; + +// strips types that are not exposed in the public factory +// incl. `type`, `checks`, `error`, `check`, `format` +export type StringFormatParams< + T extends schemas.$ZodStringFormat = schemas.$ZodStringFormat, + AlsoOmit extends Exclude = never, +> = Params< + T, + NonNullable, + "type" | "coerce" | "checks" | "error" | "check" | "format" | AlsoOmit +>; + +export type CheckStringFormatParams< + T extends schemas.$ZodStringFormat = schemas.$ZodStringFormat, + AlsoOmit extends Exclude = never, +> = Params, "type" | "coerce" | "checks" | "error" | "check" | "format" | AlsoOmit>; + +export type CheckTypeParams< + T extends schemas.$ZodType & checks.$ZodCheck = schemas.$ZodType & checks.$ZodCheck, + AlsoOmit extends Exclude = never, +> = Params, "type" | "checks" | "error" | "check" | AlsoOmit>; + +// String +export type $ZodStringParams = TypeParams, "coerce">; +export function _string( + Class: util.SchemaClass, + params?: string | $ZodStringParams +): T { + return new Class({ + type: "string", + ...util.normalizeParams(params), + }); +} + +export function _coercedString( + Class: util.SchemaClass, + params?: string | $ZodStringParams +): T { + return new Class({ + type: "string", + coerce: true, + ...util.normalizeParams(params), + }); +} + +export type $ZodStringFormatParams = CheckTypeParams; +export type $ZodCheckStringFormatParams = CheckParams; +// custom format + +// Email +export type $ZodEmailParams = StringFormatParams; +export type $ZodCheckEmailParams = CheckStringFormatParams; +export function _email( + Class: util.SchemaClass, + params?: string | $ZodEmailParams | $ZodCheckEmailParams +): T { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// GUID +export type $ZodGUIDParams = StringFormatParams; +export type $ZodCheckGUIDParams = CheckStringFormatParams; +export function _guid( + Class: util.SchemaClass, + params?: string | $ZodGUIDParams | $ZodCheckGUIDParams +): T { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// UUID +export type $ZodUUIDParams = StringFormatParams; +export type $ZodCheckUUIDParams = CheckStringFormatParams; +export function _uuid( + Class: util.SchemaClass, + params?: string | $ZodUUIDParams | $ZodCheckUUIDParams +): T { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// UUIDv4 +export type $ZodUUIDv4Params = StringFormatParams; +export type $ZodCheckUUIDv4Params = CheckStringFormatParams; +export function _uuidv4( + Class: util.SchemaClass, + params?: string | $ZodUUIDv4Params | $ZodCheckUUIDv4Params +): T { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...util.normalizeParams(params), + }); +} + +// UUIDv6 +export type $ZodUUIDv6Params = StringFormatParams; +export type $ZodCheckUUIDv6Params = CheckStringFormatParams; +export function _uuidv6( + Class: util.SchemaClass, + params?: string | $ZodUUIDv6Params | $ZodCheckUUIDv6Params +): T { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...util.normalizeParams(params), + }); +} + +// UUIDv7 +export type $ZodUUIDv7Params = StringFormatParams; +export type $ZodCheckUUIDv7Params = CheckStringFormatParams; +export function _uuidv7( + Class: util.SchemaClass, + params?: string | $ZodUUIDv7Params | $ZodCheckUUIDv7Params +): T { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...util.normalizeParams(params), + }); +} + +// URL +export type $ZodURLParams = StringFormatParams; +export type $ZodCheckURLParams = CheckStringFormatParams; +export function _url( + Class: util.SchemaClass, + params?: string | $ZodURLParams | $ZodCheckURLParams +): T { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// Emoji +export type $ZodEmojiParams = StringFormatParams; +export type $ZodCheckEmojiParams = CheckStringFormatParams; +export function _emoji( + Class: util.SchemaClass, + params?: string | $ZodEmojiParams | $ZodCheckEmojiParams +): T { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// NanoID +export type $ZodNanoIDParams = StringFormatParams; +export type $ZodCheckNanoIDParams = CheckStringFormatParams; +export function _nanoid( + Class: util.SchemaClass, + params?: string | $ZodNanoIDParams | $ZodCheckNanoIDParams +): T { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// CUID +export type $ZodCUIDParams = StringFormatParams; +export type $ZodCheckCUIDParams = CheckStringFormatParams; +export function _cuid( + Class: util.SchemaClass, + params?: string | $ZodCUIDParams | $ZodCheckCUIDParams +): T { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// CUID2 +export type $ZodCUID2Params = StringFormatParams; +export type $ZodCheckCUID2Params = CheckStringFormatParams; +export function _cuid2( + Class: util.SchemaClass, + params?: string | $ZodCUID2Params | $ZodCheckCUID2Params +): T { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// ULID +export type $ZodULIDParams = StringFormatParams; +export type $ZodCheckULIDParams = CheckStringFormatParams; +export function _ulid( + Class: util.SchemaClass, + params?: string | $ZodULIDParams | $ZodCheckULIDParams +): T { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// XID +export type $ZodXIDParams = StringFormatParams; +export type $ZodCheckXIDParams = CheckStringFormatParams; +export function _xid( + Class: util.SchemaClass, + params?: string | $ZodXIDParams | $ZodCheckXIDParams +): T { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// KSUID +export type $ZodKSUIDParams = StringFormatParams; +export type $ZodCheckKSUIDParams = CheckStringFormatParams; +export function _ksuid( + Class: util.SchemaClass, + params?: string | $ZodKSUIDParams | $ZodCheckKSUIDParams +): T { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// IP +// export type $ZodIPParams = StringFormatParams; +// export type $ZodCheckIPParams = CheckStringFormatParams; +// export function _ip( +// Class: util.SchemaClass, +// params?: string | $ZodIPParams | $ZodCheckIPParams +// ): T { +// return new Class({ +// type: "string", +// format: "ip", +// check: "string_format", +// abort: false, +// ...util.normalizeParams(params), +// }); +// } + +// IPv4 +export type $ZodIPv4Params = StringFormatParams; +export type $ZodCheckIPv4Params = CheckStringFormatParams; +export function _ipv4( + Class: util.SchemaClass, + params?: string | $ZodIPv4Params | $ZodCheckIPv4Params +): T { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// IPv6 +export type $ZodIPv6Params = StringFormatParams; +export type $ZodCheckIPv6Params = CheckStringFormatParams; +export function _ipv6( + Class: util.SchemaClass, + params?: string | $ZodIPv6Params | $ZodCheckIPv6Params +): T { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// CIDRv4 +export type $ZodCIDRv4Params = StringFormatParams; +export type $ZodCheckCIDRv4Params = CheckStringFormatParams; +export function _cidrv4( + Class: util.SchemaClass, + params?: string | $ZodCIDRv4Params | $ZodCheckCIDRv4Params +): T { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// CIDRv6 +export type $ZodCIDRv6Params = StringFormatParams; +export type $ZodCheckCIDRv6Params = CheckStringFormatParams; +export function _cidrv6( + Class: util.SchemaClass, + params?: string | $ZodCIDRv6Params | $ZodCheckCIDRv6Params +): T { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// Base64 +export type $ZodBase64Params = StringFormatParams; +export type $ZodCheckBase64Params = CheckStringFormatParams; +export function _base64( + Class: util.SchemaClass, + params?: string | $ZodBase64Params | $ZodCheckBase64Params +): T { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// base64url +export type $ZodBase64URLParams = StringFormatParams; +export type $ZodCheckBase64URLParams = CheckStringFormatParams; +export function _base64url( + Class: util.SchemaClass, + params?: string | $ZodBase64URLParams | $ZodCheckBase64URLParams +): T { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// E164 +export type $ZodE164Params = StringFormatParams; +export type $ZodCheckE164Params = CheckStringFormatParams; +export function _e164( + Class: util.SchemaClass, + params?: string | $ZodE164Params | $ZodCheckE164Params +): T { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +// JWT +export type $ZodJWTParams = StringFormatParams; +export type $ZodCheckJWTParams = CheckStringFormatParams; +export function _jwt( + Class: util.SchemaClass, + params?: string | $ZodJWTParams | $ZodCheckJWTParams +): T { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} + +export const TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +} as const; +// ISODateTime +export type $ZodISODateTimeParams = StringFormatParams; +export type $ZodCheckISODateTimeParams = CheckStringFormatParams; +export function _isoDateTime( + Class: util.SchemaClass, + params?: string | $ZodISODateTimeParams | $ZodCheckISODateTimeParams +): T { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...util.normalizeParams(params), + }); +} + +// ISODate +export type $ZodISODateParams = StringFormatParams; +export type $ZodCheckISODateParams = CheckStringFormatParams; +export function _isoDate( + Class: util.SchemaClass, + params?: string | $ZodISODateParams | $ZodCheckISODateParams +): T { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...util.normalizeParams(params), + }); +} + +// ISOTime +export type $ZodISOTimeParams = StringFormatParams; +export type $ZodCheckISOTimeParams = CheckStringFormatParams; +export function _isoTime( + Class: util.SchemaClass, + params?: string | $ZodISOTimeParams | $ZodCheckISOTimeParams +): T { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...util.normalizeParams(params), + }); +} + +// ISODuration +export type $ZodISODurationParams = StringFormatParams; +export type $ZodCheckISODurationParams = CheckStringFormatParams; +export function _isoDuration( + Class: util.SchemaClass, + params?: string | $ZodISODurationParams | $ZodCheckISODurationParams +): T { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...util.normalizeParams(params), + }); +} + +// Number +export type $ZodNumberParams = TypeParams, "coerce">; +export type $ZodNumberFormatParams = CheckTypeParams; +export type $ZodCheckNumberFormatParams = CheckParams; +export function _number( + Class: util.SchemaClass, + params?: string | $ZodNumberParams +): T { + return new Class({ + type: "number", + checks: [], + ...util.normalizeParams(params), + }); +} + +export function _coercedNumber( + Class: util.SchemaClass, + params?: string | $ZodNumberParams +): T { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...util.normalizeParams(params), + }); +} + +export function _int( + Class: util.SchemaClass, + params?: string | $ZodCheckNumberFormatParams +): T { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...util.normalizeParams(params), + }); +} +export function _float32( + Class: util.SchemaClass, + params?: string | $ZodCheckNumberFormatParams +): T { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +export function _float64( + Class: util.SchemaClass, + params?: string | $ZodCheckNumberFormatParams +): T { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +export function _int32( + Class: util.SchemaClass, + params?: string | $ZodCheckNumberFormatParams +): T { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +export function _uint32( + Class: util.SchemaClass, + params?: string | $ZodCheckNumberFormatParams +): T { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} + +// Boolean +export type $ZodBooleanParams = TypeParams, "coerce">; +export function _boolean( + Class: util.SchemaClass, + params?: string | $ZodBooleanParams +): T { + return new Class({ + type: "boolean", + ...util.normalizeParams(params), + }); +} +export function _coercedBoolean( + Class: util.SchemaClass, + params?: string | $ZodBooleanParams +): T { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} + +// BigInt +export type $ZodBigIntParams = TypeParams>; +export type $ZodBigIntFormatParams = CheckTypeParams; +export type $ZodCheckBigIntFormatParams = CheckParams; +export function _bigint( + Class: util.SchemaClass, + params?: string | $ZodBigIntParams +): T { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +export function _coercedBigint( + Class: util.SchemaClass, + params?: string | $ZodBigIntParams +): T { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} + +export function _int64( + Class: util.SchemaClass, + params?: string | $ZodBigIntFormatParams +): T { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...util.normalizeParams(params), + }); +} +export function _uint64( + Class: util.SchemaClass, + params?: string | $ZodBigIntFormatParams +): T { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} + +// Symbol +export type $ZodSymbolParams = TypeParams; +export function _symbol( + Class: util.SchemaClass, + params?: string | $ZodSymbolParams +): T { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} + +// Undefined +export type $ZodUndefinedParams = TypeParams; +export function _undefined( + Class: util.SchemaClass, + params?: string | $ZodUndefinedParams +): T { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} + +// Null +export type $ZodNullParams = TypeParams; +export function _null(Class: util.SchemaClass, params?: string | $ZodNullParams): T { + return new Class({ + type: "null", + ...util.normalizeParams(params), + }); +} + +// Any +export type $ZodAnyParams = TypeParams; +export function _any(Class: util.SchemaClass): T { + return new Class({ + type: "any", + }); +} + +// Unknown +export type $ZodUnknownParams = TypeParams; +export function _unknown(Class: util.SchemaClass): T { + return new Class({ + type: "unknown", + }); +} + +// Never +export type $ZodNeverParams = TypeParams; +export function _never(Class: util.SchemaClass, params?: string | $ZodNeverParams): T { + return new Class({ + type: "never", + ...util.normalizeParams(params), + }); +} + +// Void +export type $ZodVoidParams = TypeParams; +export function _void(Class: util.SchemaClass, params?: string | $ZodVoidParams): T { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} + +// Date +export type $ZodDateParams = TypeParams; +export function _date(Class: util.SchemaClass, params?: string | $ZodDateParams): T { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +export function _coercedDate( + Class: util.SchemaClass, + params?: string | $ZodDateParams +): T { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} + +// NaN +export type $ZodNaNParams = TypeParams; +export function _nan(Class: util.SchemaClass, params?: string | $ZodNaNParams): T { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} + +// export type $ZodCheckParams = CheckParams; + +export type $ZodCheckLessThanParams = CheckParams; +export function _lt( + value: util.Numeric, + params?: string | $ZodCheckLessThanParams +): checks.$ZodCheckLessThan { + return new checks.$ZodCheckLessThan({ + check: "less_than", + ...util.normalizeParams(params), + value, + inclusive: false, + }); +} + +export function _lte( + value: util.Numeric, + params?: string | $ZodCheckLessThanParams +): checks.$ZodCheckLessThan { + return new checks.$ZodCheckLessThan({ + check: "less_than", + + ...util.normalizeParams(params), + value, + inclusive: true, + }); +} +export { + /** @deprecated Use `z.lte()` instead. */ + _lte as _max, +}; + +// ZodCheckGreaterThan +export type $ZodCheckGreaterThanParams = CheckParams; +export function _gt(value: util.Numeric, params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan { + return new checks.$ZodCheckGreaterThan({ + check: "greater_than", + + ...util.normalizeParams(params), + value, + inclusive: false, + }); +} + +export function _gte(value: util.Numeric, params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan { + return new checks.$ZodCheckGreaterThan({ + check: "greater_than", + ...util.normalizeParams(params), + value, + inclusive: true, + }); +} + +export { + /** @deprecated Use `z.gte()` instead. */ + _gte as _min, +}; + +export function _positive(params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan { + return _gt(0, params); +} + +// negative +export function _negative(params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan { + return _lt(0, params); +} + +// nonpositive +export function _nonpositive(params?: string | $ZodCheckLessThanParams): checks.$ZodCheckLessThan { + return _lte(0, params); +} + +// nonnegative +export function _nonnegative(params?: string | $ZodCheckGreaterThanParams): checks.$ZodCheckGreaterThan { + return _gte(0, params); +} + +export type $ZodCheckMultipleOfParams = CheckParams; +export function _multipleOf( + value: number | bigint, + params?: string | $ZodCheckMultipleOfParams +): checks.$ZodCheckMultipleOf { + return new checks.$ZodCheckMultipleOf({ + check: "multiple_of", + ...util.normalizeParams(params), + value, + }); +} + +export type $ZodCheckMaxSizeParams = CheckParams; +export function _maxSize( + maximum: number, + params?: string | $ZodCheckMaxSizeParams +): checks.$ZodCheckMaxSize { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} + +export type $ZodCheckMinSizeParams = CheckParams; +export function _minSize( + minimum: number, + params?: string | $ZodCheckMinSizeParams +): checks.$ZodCheckMinSize { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} + +export type $ZodCheckSizeEqualsParams = CheckParams; +export function _size( + size: number, + params?: string | $ZodCheckSizeEqualsParams +): checks.$ZodCheckSizeEquals { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} + +export type $ZodCheckMaxLengthParams = CheckParams; +export function _maxLength( + maximum: number, + params?: string | $ZodCheckMaxLengthParams +): checks.$ZodCheckMaxLength { + const ch = new checks.$ZodCheckMaxLength({ + check: "max_length", + ...util.normalizeParams(params), + maximum, + }); + return ch; +} + +export type $ZodCheckMinLengthParams = CheckParams; +export function _minLength( + minimum: number, + params?: string | $ZodCheckMinLengthParams +): checks.$ZodCheckMinLength { + return new checks.$ZodCheckMinLength({ + check: "min_length", + ...util.normalizeParams(params), + minimum, + }); +} + +export type $ZodCheckLengthEqualsParams = CheckParams; +export function _length( + length: number, + params?: string | $ZodCheckLengthEqualsParams +): checks.$ZodCheckLengthEquals { + return new checks.$ZodCheckLengthEquals({ + check: "length_equals", + ...util.normalizeParams(params), + length, + }); +} + +export type $ZodCheckRegexParams = CheckParams; +export function _regex(pattern: RegExp, params?: string | $ZodCheckRegexParams): checks.$ZodCheckRegex { + return new checks.$ZodCheckRegex({ + check: "string_format", + format: "regex", + ...util.normalizeParams(params), + pattern, + }); +} + +export type $ZodCheckLowerCaseParams = CheckParams; +export function _lowercase(params?: string | $ZodCheckLowerCaseParams): checks.$ZodCheckLowerCase { + return new checks.$ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...util.normalizeParams(params), + }); +} + +export type $ZodCheckUpperCaseParams = CheckParams; + +export function _uppercase(params?: string | $ZodCheckUpperCaseParams): checks.$ZodCheckUpperCase { + return new checks.$ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...util.normalizeParams(params), + }); +} + +export type $ZodCheckIncludesParams = CheckParams; +export function _includes(includes: string, params?: string | $ZodCheckIncludesParams): checks.$ZodCheckIncludes { + return new checks.$ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...util.normalizeParams(params), + includes, + }); +} +export type $ZodCheckStartsWithParams = CheckParams; +export function _startsWith(prefix: string, params?: string | $ZodCheckStartsWithParams): checks.$ZodCheckStartsWith { + return new checks.$ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...util.normalizeParams(params), + prefix, + }); +} + +export type $ZodCheckEndsWithParams = CheckParams; + +export function _endsWith(suffix: string, params?: string | $ZodCheckEndsWithParams): checks.$ZodCheckEndsWith { + return new checks.$ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...util.normalizeParams(params), + suffix, + }); +} + +export type $ZodCheckPropertyParams = CheckParams; +export function _property( + property: K, + schema: T, + params?: string | $ZodCheckPropertyParams +): checks.$ZodCheckProperty<{ [k in K]: core.output }> { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} + +export type $ZodCheckMimeTypeParams = CheckParams; +export function _mime(types: util.MimeTypes[], params?: string | $ZodCheckMimeTypeParams): checks.$ZodCheckMimeType { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} + +export function _overwrite(tx: (input: T) => T): checks.$ZodCheckOverwrite { + return new checks.$ZodCheckOverwrite({ + check: "overwrite", + tx, + }) as checks.$ZodCheckOverwrite; +} +// normalize +export function _normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): checks.$ZodCheckOverwrite { + return _overwrite((input) => input.normalize(form)); +} + +// trim +export function _trim(): checks.$ZodCheckOverwrite { + return _overwrite((input) => input.trim()); +} +// toLowerCase +export function _toLowerCase(): checks.$ZodCheckOverwrite { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +export function _toUpperCase(): checks.$ZodCheckOverwrite { + return _overwrite((input) => input.toUpperCase()); +} + +/////// collections /////// + +// Array +export type $ZodArrayParams = TypeParams; +export function _array( + Class: util.SchemaClass, + element: T, + params?: string | $ZodArrayParams +): schemas.$ZodArray { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...util.normalizeParams(params), + }) as any; +} + +export type $ZodObjectParams = TypeParams; + +// ZodUnion +export type $ZodUnionParams = TypeParams; +export function _union( + Class: util.SchemaClass, + options: T, + params?: string | $ZodUnionParams +): schemas.$ZodUnion { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }) as any; +} + +// ZodDiscriminatedUnion +export interface $ZodTypeDiscriminableInternals extends schemas.$ZodTypeInternals { + propValues: util.PropValues; +} + +export interface $ZodTypeDiscriminable extends schemas.$ZodType { + _zod: $ZodTypeDiscriminableInternals; +} +export type $ZodDiscriminatedUnionParams = TypeParams; +export function _discriminatedUnion( + Class: util.SchemaClass, + discriminator: string, + options: Types, + params?: string | $ZodDiscriminatedUnionParams +): schemas.$ZodDiscriminatedUnion { + return new Class({ + type: "union", + options, + discriminator, + ...util.normalizeParams(params), + }) as any; +} + +// ZodIntersection +export type $ZodIntersectionParams = TypeParams; +export function _intersection( + Class: util.SchemaClass, + left: T, + right: U +): schemas.$ZodIntersection { + return new Class({ + type: "intersection", + left, + right, + }) as any; +} + +// ZodTuple +export type $ZodTupleParams = TypeParams; +export function _tuple( + Class: util.SchemaClass, + items: T, + params?: string | $ZodTupleParams +): schemas.$ZodTuple; +export function _tuple( + Class: util.SchemaClass, + items: T, + rest: Rest, + params?: string | $ZodTupleParams +): schemas.$ZodTuple; +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +export function _tuple( + Class: util.SchemaClass, + items: schemas.$ZodType[], + _paramsOrRest?: string | $ZodTupleParams | schemas.$ZodType, + _params?: string | $ZodTupleParams +) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} + +// ZodRecord +export type $ZodRecordParams = TypeParams; +export function _record( + Class: util.SchemaClass, + keyType: Key, + valueType: Value, + params?: string | $ZodRecordParams +): schemas.$ZodRecord { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodMap +export type $ZodMapParams = TypeParams; +export function _map( + Class: util.SchemaClass, + keyType: Key, + valueType: Value, + params?: string | $ZodMapParams +): schemas.$ZodMap { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodSet +export type $ZodSetParams = TypeParams; +export function _set( + Class: util.SchemaClass, + valueType: Value, + params?: string | $ZodSetParams +): schemas.$ZodSet { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodEnum +export type $ZodEnumParams = TypeParams; +export function _enum( + Class: util.SchemaClass, + values: T, + params?: string | $ZodEnumParams +): schemas.$ZodEnum>; +export function _enum( + Class: util.SchemaClass, + entries: T, + params?: string | $ZodEnumParams +): schemas.$ZodEnum; +export function _enum(Class: util.SchemaClass, values: any, params?: string | $ZodEnumParams) { + const entries: any = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }) as any; +} + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +export function _nativeEnum( + Class: util.SchemaClass, + entries: T, + params?: string | $ZodEnumParams +): schemas.$ZodEnum { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }) as any; +} + +// ZodLiteral +export type $ZodLiteralParams = TypeParams; +export function _literal>( + Class: util.SchemaClass, + value: T, + params?: string | $ZodLiteralParams +): schemas.$ZodLiteral; +export function _literal( + Class: util.SchemaClass, + value: T, + params?: string | $ZodLiteralParams +): schemas.$ZodLiteral; +export function _literal(Class: util.SchemaClass, value: any, params: any) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} + +// ZodFile +export type $ZodFileParams = TypeParams; +export function _file(Class: util.SchemaClass, params?: string | $ZodFileParams): schemas.$ZodFile { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} + +// ZodTransform +export type $ZodTransformParams = TypeParams; +export function _transform( + Class: util.SchemaClass, + fn: (input: I, ctx?: schemas.ParsePayload) => O +): schemas.$ZodTransform, I> { + return new Class({ + type: "transform", + transform: fn as any, + }) as any; +} + +// ZodOptional +export type $ZodOptionalParams = TypeParams; +export function _optional( + Class: util.SchemaClass, + innerType: T +): schemas.$ZodOptional { + return new Class({ + type: "optional", + innerType, + }) as any; +} + +// ZodNullable +export type $ZodNullableParams = TypeParams; +export function _nullable( + Class: util.SchemaClass, + innerType: T +): schemas.$ZodNullable { + return new Class({ + type: "nullable", + innerType, + }) as any; +} + +// ZodDefault +export type $ZodDefaultParams = TypeParams; +export function _default( + Class: util.SchemaClass, + innerType: T, + defaultValue: util.NoUndefined> | (() => util.NoUndefined>) +): schemas.$ZodDefault { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? (defaultValue as Function)() : defaultValue; + }, + }) as any; +} + +// ZodNonOptional +export type $ZodNonOptionalParams = TypeParams; +export function _nonoptional( + Class: util.SchemaClass, + innerType: T, + params?: string | $ZodNonOptionalParams +): schemas.$ZodNonOptional { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }) as any; +} + +// ZodSuccess +export type $ZodSuccessParams = TypeParams; +export function _success( + Class: util.SchemaClass, + innerType: T +): schemas.$ZodSuccess { + return new Class({ + type: "success", + innerType, + }) as any; +} + +// ZodCatch +export type $ZodCatchParams = TypeParams; +export function _catch( + Class: util.SchemaClass, + innerType: T, + catchValue: core.output | ((ctx: schemas.$ZodCatchCtx) => core.output) +): schemas.$ZodCatch { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue) as any, + }) as any; +} + +// ZodPipe +export type $ZodPipeParams = TypeParams; +export function _pipe< + const A extends schemas.$ZodType, + B extends schemas.$ZodType> = schemas.$ZodType>, +>( + Class: util.SchemaClass, + in_: A, + out: B | schemas.$ZodType> +): schemas.$ZodPipe { + return new Class({ + type: "pipe", + in: in_, + out, + }) as any; +} + +// ZodReadonly +export type $ZodReadonlyParams = TypeParams; +export function _readonly( + Class: util.SchemaClass, + innerType: T +): schemas.$ZodReadonly { + return new Class({ + type: "readonly", + innerType, + }) as any; +} + +// ZodTemplateLiteral +export type $ZodTemplateLiteralParams = TypeParams; +export function _templateLiteral( + Class: util.SchemaClass, + parts: Parts, + params?: string | $ZodTemplateLiteralParams +): schemas.$ZodTemplateLiteral> { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }) as any; +} + +// ZodLazy +export type $ZodLazyParams = TypeParams; +export function _lazy( + Class: util.SchemaClass, + getter: () => T +): schemas.$ZodLazy { + return new Class({ + type: "lazy", + getter, + }) as any; +} + +// ZodPromise +export type $ZodPromiseParams = TypeParams; +export function _promise( + Class: util.SchemaClass, + innerType: T +): schemas.$ZodPromise { + return new Class({ + type: "promise", + innerType, + }) as any; +} + +// ZodCustom +export type $ZodCustomParams = CheckTypeParams; +export function _custom( + Class: util.SchemaClass, + fn: (data: O) => unknown, + _params: string | $ZodCustomParams | undefined +): schemas.$ZodCustom { + const norm = util.normalizeParams(_params); + norm.abort ??= true; // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn as any, + ...norm, + }); + + return schema as any; +} + +// export function _refine( +// Class: util.SchemaClass, +// fn: (arg: NoInfer) => util.MaybeAsync, +// _params: string | $ZodCustomParams = {} +// ): checks.$ZodCheck { +// return _custom(Class, fn, _params); +// } +// same as _custom but defaults to abort:false +export function _refine( + Class: util.SchemaClass, + fn: (data: O) => unknown, + _params: string | $ZodCustomParams | undefined +): schemas.$ZodCustom { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn as any, + ...util.normalizeParams(_params), + }); + + return schema as any; +} + +// export type $ZodCustomParams = CheckTypeParams + +///////// STRINGBOOL ///////// + +// stringbool +export interface $ZodStringBoolParams extends TypeParams { + truthy?: string[]; + falsy?: string[]; + /** + * Options: `"sensitive"`, `"insensitive"` + * + * @default `"insensitive"` + */ + case?: "sensitive" | "insensitive" | undefined; +} + +export function _stringbool( + Classes: { + Pipe?: typeof schemas.$ZodPipe; + Boolean?: typeof schemas.$ZodBoolean; + Transform?: typeof schemas.$ZodTransform; + String?: typeof schemas.$ZodString; + }, + _params?: string | $ZodStringBoolParams +): schemas.$ZodPipe< + schemas.$ZodPipe>, + schemas.$ZodBoolean +> { + const params = util.normalizeParams(_params); + + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + + const _Pipe = Classes.Pipe ?? schemas.$ZodPipe; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const _Transform = Classes.Transform ?? schemas.$ZodTransform; + + const tx = new _Transform({ + type: "transform", + transform: (input, payload: schemas.ParsePayload) => { + let data: string = input as string; + if (params.case !== "sensitive") data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } else if (falsySet.has(data)) { + return false; + } else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: tx, + }); + return {} as never; + } + }, + error: params.error, + }); + // params.error; + + const innerPipe = new _Pipe({ + type: "pipe", + in: new _String({ type: "string", error: params.error }), + out: tx, + error: params.error, + }); + + const outerPipe = new _Pipe({ + type: "pipe", + in: innerPipe, + out: new _Boolean({ + type: "boolean", + error: params.error, + }), + error: params.error, + }); + return outerPipe as any; +} + +export function _stringFormat( + Class: typeof schemas.$ZodCustomStringFormat, + format: Format, + fnOrRegex: ((arg: string) => util.MaybeAsync) | RegExp, + _params: string | $ZodStringFormatParams = {} +): schemas.$ZodCustomStringFormat { + const params = util.normalizeParams(_params); + const def: schemas.$ZodCustomStringFormatDef = { + ...util.normalizeParams(_params), + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params, + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + + const inst = new Class(def); + return inst as any; +} diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/checks.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/checks.ts new file mode 100644 index 0000000000000000000000000000000000000000..85a7ce7b8ac2876330b992b71871a51661c90fdd --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/checks.ts @@ -0,0 +1,1283 @@ +// import { $ZodType } from "./schemas.js"; + +import * as core from "./core.js"; +import type * as errors from "./errors.js"; +import * as regexes from "./regexes.js"; +import type * as schemas from "./schemas.js"; +import * as util from "./util.js"; + +////////////////////////////// CHECKS /////////////////////////////////////// + +export interface $ZodCheckDef { + check: string; + error?: errors.$ZodErrorMap | undefined; + /** If true, no later checks will be executed if this check fails. Default `false`. */ + abort?: boolean | undefined; + /** If provided, this check will only be executed if the function returns `true`. Defaults to `payload => z.util.isAborted(payload)`. */ + when?: ((payload: schemas.ParsePayload) => boolean) | undefined; +} + +export interface $ZodCheckInternals { + def: $ZodCheckDef; + /** The set of issues this check might throw. */ + issc?: errors.$ZodIssueBase; + check(payload: schemas.ParsePayload): util.MaybeAsync; + onattach: ((schema: schemas.$ZodType) => void)[]; +} + +export interface $ZodCheck { + _zod: $ZodCheckInternals; +} + +export const $ZodCheck: core.$constructor<$ZodCheck> = /*@__PURE__*/ core.$constructor( + "$ZodCheck", + (inst, def) => { + inst._zod ??= {} as any; + inst._zod.def = def; + inst._zod.onattach ??= []; + } +); + +/////////////////////////////////////// +///// $ZodCheckLessThan ///// +/////////////////////////////////////// +export interface $ZodCheckLessThanDef extends $ZodCheckDef { + check: "less_than"; + value: util.Numeric; + inclusive: boolean; +} + +export interface $ZodCheckLessThanInternals extends $ZodCheckInternals { + def: $ZodCheckLessThanDef; + issc: errors.$ZodIssueTooBig; +} + +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +} as const; +export interface $ZodCheckLessThan extends $ZodCheck { + _zod: $ZodCheckLessThanInternals; +} + +export const $ZodCheckLessThan: core.$constructor<$ZodCheckLessThan> = /*@__PURE__*/ core.$constructor( + "$ZodCheckLessThan", + (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value as "number" | "bigint" | "object"]; + + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) bag.maximum = def.value; + else bag.exclusiveMaximum = def.value; + } + }); + + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + + payload.issues.push({ + origin, + code: "too_big", + maximum: def.value as number, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; + } +); + +///////////////////////////////////// +///// $ZodCheckGreaterThan ///// +///////////////////////////////////// +export interface $ZodCheckGreaterThanDef extends $ZodCheckDef { + check: "greater_than"; + value: util.Numeric; + inclusive: boolean; +} + +export interface $ZodCheckGreaterThanInternals extends $ZodCheckInternals { + def: $ZodCheckGreaterThanDef; + issc: errors.$ZodIssueTooSmall; +} + +export interface $ZodCheckGreaterThan extends $ZodCheck { + _zod: $ZodCheckGreaterThanInternals; +} + +export const $ZodCheckGreaterThan: core.$constructor<$ZodCheckGreaterThan> = /*@__PURE__*/ core.$constructor( + "$ZodCheckGreaterThan", + (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value as "number" | "bigint" | "object"]; + + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) bag.minimum = def.value; + else bag.exclusiveMinimum = def.value; + } + }); + + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + + payload.issues.push({ + origin, + code: "too_small", + minimum: def.value as number, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; + } +); + +///////////////////////////////////// +///// $ZodCheckMultipleOf ///// +///////////////////////////////////// +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 + +export interface $ZodCheckMultipleOfDef extends $ZodCheckDef { + check: "multiple_of"; + value: T; +} + +export interface $ZodCheckMultipleOfInternals + extends $ZodCheckInternals { + def: $ZodCheckMultipleOfDef; + issc: errors.$ZodIssueNotMultipleOf; +} + +export interface $ZodCheckMultipleOf extends $ZodCheck { + _zod: $ZodCheckMultipleOfInternals; +} + +export const $ZodCheckMultipleOf: core.$constructor<$ZodCheckMultipleOf> = + /*@__PURE__*/ core.$constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.onattach.push((inst) => { + inst._zod.bag.multipleOf ??= def.value; + }); + + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = + typeof payload.value === "bigint" + ? payload.value % (def.value as bigint) === BigInt(0) + : util.floatSafeRemainder(payload.value, def.value as number) === 0; + + if (isMultiple) return; + payload.issues.push({ + origin: typeof payload.value as "number", + code: "not_multiple_of", + divisor: def.value as number, + input: payload.value, + inst, + continue: !def.abort, + }); + }; + }); + +///////////////////////////////////// +///// $ZodCheckFinite ///// +///////////////////////////////////// +// interface $ZodCheckFiniteDef extends $ZodCheckDef { +// check: "finite"; +// } + +// export interface $ZodCheckFinite extends $ZodCheckInternals { +// _def: $ZodCheckFiniteDef; +// _issc: +// | errors.$ZodIssueTooBig<"number", number> +// | errors.$ZodIssueTooSmall<"number", number>; +// } + +// export const $ZodCheckFinite: core.$constructor<$ZodCheckFinite> = +// core.$constructor("$ZodCheckFinite", (inst, def) => { +// $ZodCheck.init(inst, def); + +// inst._zod.onattach = (inst) => { +// inst["_bag"].finite = true; +// }; + +// inst._zod.check = (payload) => { +// if (Number.isFinite(payload.value)) return; +// payload.issues.push({ +// origin: "number", +// ...(payload.value === Number.POSITIVE_INFINITY +// ? { +// code: "too_big", +// maximum: Number.POSITIVE_INFINITY, +// } +// : { +// code: "too_small", +// minimum: Number.NEGATIVE_INFINITY, +// }), +// // code: payload.value === Number.POSITIVE_INFINITY ? "too_big" : "too_big", +// // maximum: Number.POSITIVE_INFINITY, +// inclusive: false, +// input: payload.value, +// inst, +// }); +// }; +// }); + +/////////////////////////////////////// +///// $ZodCheckNumberFormat ///// +/////////////////////////////////////// + +export type $ZodNumberFormats = "int32" | "uint32" | "float32" | "float64" | "safeint"; + +export interface $ZodCheckNumberFormatDef extends $ZodCheckDef { + check: "number_format"; + format: $ZodNumberFormats; + // abort?: boolean; +} + +export interface $ZodCheckNumberFormatInternals extends $ZodCheckInternals { + def: $ZodCheckNumberFormatDef; + issc: errors.$ZodIssueInvalidType | errors.$ZodIssueTooBig<"number"> | errors.$ZodIssueTooSmall<"number">; + // bag: util.LoosePartial<{ + // minimum?: number | undefined; + // }>; +} + +export interface $ZodCheckNumberFormat extends $ZodCheck { + _zod: $ZodCheckNumberFormatInternals; +} + +export const $ZodCheckNumberFormat: core.$constructor<$ZodCheckNumberFormat> = /*@__PURE__*/ core.$constructor( + "$ZodCheckNumberFormat", + (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format]; + + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) bag.pattern = regexes.integer; + }); + + inst._zod.check = (payload) => { + const input = payload.value; + + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + input, + inst, + }); + + return; + + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort, + }); + } else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort, + }); + } + + return; + } + } + + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inst, + } as any); + } + }; + } +); + +///////////////////////////////////// +///// $ZodCheckBigIntFormat ///// +///////////////////////////////////// + +export type $ZodBigIntFormats = "int64" | "uint64"; + +export interface $ZodCheckBigIntFormatDef extends $ZodCheckDef { + check: "bigint_format"; + format: $ZodBigIntFormats | undefined; +} + +export interface $ZodCheckBigIntFormatInternals extends $ZodCheckInternals { + def: $ZodCheckBigIntFormatDef; + issc: errors.$ZodIssueTooBig<"bigint"> | errors.$ZodIssueTooSmall<"bigint">; +} + +export interface $ZodCheckBigIntFormat extends $ZodCheck { + _zod: $ZodCheckBigIntFormatInternals; +} + +export const $ZodCheckBigIntFormat: core.$constructor<$ZodCheckBigIntFormat> = /*@__PURE__*/ core.$constructor( + "$ZodCheckBigIntFormat", + (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format!]; + + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + + inst._zod.check = (payload) => { + const input = payload.value; + + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum as any, + inclusive: true, + inst, + continue: !def.abort, + }); + } + + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inst, + } as any); + } + }; + } +); + +////////////////////////////////// +///// $ZodCheckMaxSize ///// +////////////////////////////////// +export interface $ZodCheckMaxSizeDef extends $ZodCheckDef { + check: "max_size"; + maximum: number; +} + +export interface $ZodCheckMaxSizeInternals extends $ZodCheckInternals { + def: $ZodCheckMaxSizeDef; + issc: errors.$ZodIssueTooBig; +} + +export interface $ZodCheckMaxSize extends $ZodCheck { + _zod: $ZodCheckMaxSizeInternals; +} + +export const $ZodCheckMaxSize: core.$constructor<$ZodCheckMaxSize> = /*@__PURE__*/ core.$constructor( + "$ZodCheckMaxSize", + (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.def.when ??= (payload) => { + const val = payload.value; + return !util.nullish(val) && (val as any).size !== undefined; + }; + + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY) as number; + if (def.maximum < curr) inst._zod.bag.maximum = def.maximum; + }); + + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + + if (size <= def.maximum) return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + input, + inst, + continue: !def.abort, + }); + }; + } +); + +////////////////////////////////// +///// $ZodCheckMinSize ///// +////////////////////////////////// +export interface $ZodCheckMinSizeDef extends $ZodCheckDef { + check: "min_size"; + minimum: number; +} + +export interface $ZodCheckMinSizeInternals extends $ZodCheckInternals { + def: $ZodCheckMinSizeDef; + issc: errors.$ZodIssueTooSmall; +} + +export interface $ZodCheckMinSize extends $ZodCheck { + _zod: $ZodCheckMinSizeInternals; +} + +export const $ZodCheckMinSize: core.$constructor<$ZodCheckMinSize> = /*@__PURE__*/ core.$constructor( + "$ZodCheckMinSize", + (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.def.when ??= (payload) => { + const val = payload.value; + return !util.nullish(val) && (val as any).size !== undefined; + }; + + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY) as number; + if (def.minimum > curr) inst._zod.bag.minimum = def.minimum; + }); + + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + + if (size >= def.minimum) return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + input, + inst, + continue: !def.abort, + }); + }; + } +); + +///////////////////////////////////// +///// $ZodCheckSizeEquals ///// +///////////////////////////////////// +export interface $ZodCheckSizeEqualsDef extends $ZodCheckDef { + check: "size_equals"; + size: number; +} + +export interface $ZodCheckSizeEqualsInternals extends $ZodCheckInternals { + def: $ZodCheckSizeEqualsDef; + issc: errors.$ZodIssueTooBig | errors.$ZodIssueTooSmall; +} + +export interface $ZodCheckSizeEquals extends $ZodCheck { + _zod: $ZodCheckSizeEqualsInternals; +} + +export const $ZodCheckSizeEquals: core.$constructor<$ZodCheckSizeEquals> = /*@__PURE__*/ core.$constructor( + "$ZodCheckSizeEquals", + (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.def.when ??= (payload) => { + const val = payload.value; + return !util.nullish(val) && (val as any).size !== undefined; + }; + + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) return; + + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; + } +); + +////////////////////////////////// +///// $ZodCheckMaxLength ///// +////////////////////////////////// + +export interface $ZodCheckMaxLengthDef extends $ZodCheckDef { + check: "max_length"; + maximum: number; +} + +export interface $ZodCheckMaxLengthInternals extends $ZodCheckInternals { + def: $ZodCheckMaxLengthDef; + issc: errors.$ZodIssueTooBig; +} + +export interface $ZodCheckMaxLength extends $ZodCheck { + _zod: $ZodCheckMaxLengthInternals; +} + +export const $ZodCheckMaxLength: core.$constructor<$ZodCheckMaxLength> = /*@__PURE__*/ core.$constructor( + "$ZodCheckMaxLength", + (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.def.when ??= (payload) => { + const val = payload.value; + return !util.nullish(val) && (val as any).length !== undefined; + }; + + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY) as number; + if (def.maximum < curr) inst._zod.bag.maximum = def.maximum; + }); + + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + + if (length <= def.maximum) return; + const origin = util.getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; + } +); + +////////////////////////////////// +///// $ZodCheckMinLength ///// +////////////////////////////////// +export interface $ZodCheckMinLengthDef extends $ZodCheckDef { + check: "min_length"; + minimum: number; +} + +export interface $ZodCheckMinLengthInternals extends $ZodCheckInternals { + def: $ZodCheckMinLengthDef; + issc: errors.$ZodIssueTooSmall; +} + +export interface $ZodCheckMinLength extends $ZodCheck { + _zod: $ZodCheckMinLengthInternals; +} + +export const $ZodCheckMinLength: core.$constructor<$ZodCheckMinLength> = /*@__PURE__*/ core.$constructor( + "$ZodCheckMinLength", + (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.def.when ??= (payload) => { + const val = payload.value; + return !util.nullish(val) && (val as any).length !== undefined; + }; + + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY) as number; + if (def.minimum > curr) inst._zod.bag.minimum = def.minimum; + }); + + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + + if (length >= def.minimum) return; + const origin = util.getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; + } +); + +///////////////////////////////////// +///// $ZodCheckLengthEquals ///// +///////////////////////////////////// +export interface $ZodCheckLengthEqualsDef extends $ZodCheckDef { + check: "length_equals"; + length: number; +} + +export interface $ZodCheckLengthEqualsInternals + extends $ZodCheckInternals { + def: $ZodCheckLengthEqualsDef; + issc: errors.$ZodIssueTooBig | errors.$ZodIssueTooSmall; +} + +export interface $ZodCheckLengthEquals extends $ZodCheck { + _zod: $ZodCheckLengthEqualsInternals; +} + +export const $ZodCheckLengthEquals: core.$constructor<$ZodCheckLengthEquals> = /*@__PURE__*/ core.$constructor( + "$ZodCheckLengthEquals", + (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.def.when ??= (payload) => { + const val = payload.value; + return !util.nullish(val) && (val as any).length !== undefined; + }; + + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) return; + const origin = util.getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; + } +); + +///////////////////////////////////////////// +///// $ZodCheckStringFormatRegex ///// +///////////////////////////////////////////// +export type $ZodStringFormats = + | "email" + | "url" + | "emoji" + | "uuid" + | "guid" + | "nanoid" + | "cuid" + | "cuid2" + | "ulid" + | "xid" + | "ksuid" + | "datetime" + | "date" + | "time" + | "duration" + | "ipv4" + | "ipv6" + | "cidrv4" + | "cidrv6" + | "base64" + | "base64url" + | "json_string" + | "e164" + | "lowercase" + | "uppercase" + | "regex" + | "jwt" + | "starts_with" + | "ends_with" + | "includes"; +export interface $ZodCheckStringFormatDef extends $ZodCheckDef { + check: "string_format"; + format: Format; + pattern?: RegExp | undefined; +} + +export interface $ZodCheckStringFormatInternals extends $ZodCheckInternals { + def: $ZodCheckStringFormatDef; + issc: errors.$ZodIssueInvalidStringFormat; +} + +export interface $ZodCheckStringFormat extends $ZodCheck { + _zod: $ZodCheckStringFormatInternals; +} + +export const $ZodCheckStringFormat: core.$constructor<$ZodCheckStringFormat> = /*@__PURE__*/ core.$constructor( + "$ZodCheckStringFormat", + (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag as schemas.$ZodStringInternals["bag"]; + bag.format = def.format; + if (def.pattern) { + bag.patterns ??= new Set(); + bag.patterns.add(def.pattern); + } + }); + + if (def.pattern) + inst._zod.check ??= (payload) => { + def.pattern!.lastIndex = 0; + if (def.pattern!.test(payload.value)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }; + else inst._zod.check ??= () => {}; + } +); + +//////////////////////////////// +///// $ZodCheckRegex ///// +//////////////////////////////// +export interface $ZodCheckRegexDef extends $ZodCheckStringFormatDef { + format: "regex"; + pattern: RegExp; +} + +export interface $ZodCheckRegexInternals extends $ZodCheckInternals { + def: $ZodCheckRegexDef; + issc: errors.$ZodIssueInvalidStringFormat; +} + +export interface $ZodCheckRegex extends $ZodCheck { + _zod: $ZodCheckRegexInternals; +} + +export const $ZodCheckRegex: core.$constructor<$ZodCheckRegex> = /*@__PURE__*/ core.$constructor( + "$ZodCheckRegex", + (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; + } +); + +/////////////////////////////////// +///// $ZodCheckJSONString ///// +/////////////////////////////////// +// interface $ZodCheckJSONStringDef extends $ZodCheckStringFormatDef<"json_string"> { +// // check: "string_format"; +// // format: "json_string"; +// // error?: errors.$ZodErrorMap | undefined; +// } + +// export interface $ZodCheckJSONString extends $ZodCheckStringFormat { +// _def: $ZodCheckJSONStringDef; +// } + +// export const $ZodCheckJSONString: core.$constructor<$ZodCheckJSONString> = /*@__PURE__*/ core.$constructor( +// "$ZodCheckJSONString", +// (inst, def) => { +// $ZodCheck.init(inst, def); + +// inst._zod.check = (payload) => { +// try { +// JSON.parse(payload.value); +// return; +// } catch (_) { +// payload.issues.push({ +// origin: "string", +// code: "invalid_format", +// format: def.format, +// input: payload.value, +// inst, +// continue: !def.abort, +// }); +// } +// }; +// } +// ); + +////////////////////////////////////// +///// $ZodCheckLowerCase ///// +////////////////////////////////////// +export interface $ZodCheckLowerCaseDef extends $ZodCheckStringFormatDef<"lowercase"> {} + +export interface $ZodCheckLowerCaseInternals extends $ZodCheckInternals { + def: $ZodCheckLowerCaseDef; + issc: errors.$ZodIssueInvalidStringFormat; +} + +export interface $ZodCheckLowerCase extends $ZodCheck { + _zod: $ZodCheckLowerCaseInternals; +} + +export const $ZodCheckLowerCase: core.$constructor<$ZodCheckLowerCase> = /*@__PURE__*/ core.$constructor( + "$ZodCheckLowerCase", + (inst, def) => { + def.pattern ??= regexes.lowercase; + $ZodCheckStringFormat.init(inst, def); + } +); + +////////////////////////////////////// +///// $ZodCheckUpperCase ///// +////////////////////////////////////// +export interface $ZodCheckUpperCaseDef extends $ZodCheckStringFormatDef<"uppercase"> {} + +export interface $ZodCheckUpperCaseInternals extends $ZodCheckInternals { + def: $ZodCheckUpperCaseDef; + issc: errors.$ZodIssueInvalidStringFormat; +} + +export interface $ZodCheckUpperCase extends $ZodCheck { + _zod: $ZodCheckUpperCaseInternals; +} + +export const $ZodCheckUpperCase: core.$constructor<$ZodCheckUpperCase> = /*@__PURE__*/ core.$constructor( + "$ZodCheckUpperCase", + (inst, def) => { + def.pattern ??= regexes.uppercase; + $ZodCheckStringFormat.init(inst, def); + } +); + +/////////////////////////////////// +///// $ZodCheckIncludes ///// +/////////////////////////////////// +export interface $ZodCheckIncludesDef extends $ZodCheckStringFormatDef<"includes"> { + includes: string; + position?: number | undefined; +} + +export interface $ZodCheckIncludesInternals extends $ZodCheckInternals { + def: $ZodCheckIncludesDef; + issc: errors.$ZodIssueInvalidStringFormat; +} + +export interface $ZodCheckIncludes extends $ZodCheck { + _zod: $ZodCheckIncludesInternals; +} + +export const $ZodCheckIncludes: core.$constructor<$ZodCheckIncludes> = /*@__PURE__*/ core.$constructor( + "$ZodCheckIncludes", + (inst, def) => { + $ZodCheck.init(inst, def); + + const escapedRegex = util.escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag as schemas.$ZodStringInternals["bag"]; + bag.patterns ??= new Set(); + bag.patterns.add(pattern); + }); + + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; + } +); + +///////////////////////////////////// +///// $ZodCheckStartsWith ///// +///////////////////////////////////// +export interface $ZodCheckStartsWithDef extends $ZodCheckStringFormatDef<"starts_with"> { + prefix: string; +} + +export interface $ZodCheckStartsWithInternals extends $ZodCheckInternals { + def: $ZodCheckStartsWithDef; + issc: errors.$ZodIssueInvalidStringFormat; +} + +export interface $ZodCheckStartsWith extends $ZodCheck { + _zod: $ZodCheckStartsWithInternals; +} + +export const $ZodCheckStartsWith: core.$constructor<$ZodCheckStartsWith> = /*@__PURE__*/ core.$constructor( + "$ZodCheckStartsWith", + (inst, def) => { + $ZodCheck.init(inst, def); + + const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`); + def.pattern ??= pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag as schemas.$ZodStringInternals["bag"]; + bag.patterns ??= new Set(); + bag.patterns.add(pattern); + }); + + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; + } +); + +////////////////////////////////// +///// $ZodCheckEndsWith ///// +////////////////////////////////// +export interface $ZodCheckEndsWithDef extends $ZodCheckStringFormatDef<"ends_with"> { + suffix: string; +} + +export interface $ZodCheckEndsWithInternals extends $ZodCheckInternals { + def: $ZodCheckEndsWithDef; + issc: errors.$ZodIssueInvalidStringFormat; +} + +export interface $ZodCheckEndsWith extends $ZodCheckInternals { + _zod: $ZodCheckEndsWithInternals; +} + +export const $ZodCheckEndsWith: core.$constructor<$ZodCheckEndsWith> = /*@__PURE__*/ core.$constructor( + "$ZodCheckEndsWith", + (inst, def) => { + $ZodCheck.init(inst, def); + + const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`); + def.pattern ??= pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag as schemas.$ZodStringInternals["bag"]; + bag.patterns ??= new Set(); + bag.patterns.add(pattern); + }); + + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; + } +); + +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult( + result: schemas.ParsePayload, + payload: schemas.ParsePayload, + property: string +) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +export interface $ZodCheckPropertyDef extends $ZodCheckDef { + check: "property"; + property: string; + schema: schemas.$ZodType; +} + +export interface $ZodCheckPropertyInternals extends $ZodCheckInternals { + def: $ZodCheckPropertyDef; + issc: errors.$ZodIssue; +} + +export interface $ZodCheckProperty extends $ZodCheck { + _zod: $ZodCheckPropertyInternals; +} + +export const $ZodCheckProperty: core.$constructor<$ZodCheckProperty> = /*@__PURE__*/ core.$constructor( + "$ZodCheckProperty", + (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.check = (payload) => { + const result = def.schema._zod.run( + { + value: (payload.value as any)[def.property], + issues: [], + }, + {} + ); + + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + + handleCheckPropertyResult(result, payload, def.property); + return; + }; + } +); + +/////////////////////////////////// +///// $ZodCheckMimeType ///// +/////////////////////////////////// +export interface $ZodCheckMimeTypeDef extends $ZodCheckDef { + check: "mime_type"; + mime: util.MimeTypes[]; +} + +export interface $ZodCheckMimeTypeInternals extends $ZodCheckInternals { + def: $ZodCheckMimeTypeDef; + issc: errors.$ZodIssueInvalidValue; +} + +export interface $ZodCheckMimeType extends $ZodCheck { + _zod: $ZodCheckMimeTypeInternals; +} + +export const $ZodCheckMimeType: core.$constructor<$ZodCheckMimeType> = /*@__PURE__*/ core.$constructor( + "$ZodCheckMimeType", + (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + }); + }; + } +); + +/////////////////////////////////// +///// $ZodCheckFileName ///// +/////////////////////////////////// +// interface $ZodCheckFileNameDef extends $ZodCheckDef { +// check: "file_name"; +// fileName: string; +// error?: errors.$ZodErrorMap | undefined; +// } +// export interface $ZodCheckFileName +// extends $ZodCheckInternals { +// _def: $ZodCheckFileNameDef; +// } + +// export const $ZodCheckFileName: core.$constructor<$ZodCheckFileName> = +// core.$constructor("$ZodCheckFileName", (inst, def) => { +// $ZodCheck.init(inst, def); + +// inst._zod.check = (payload) => { +// if (def.fileName === payload.value.name) return; +// payload.issues.push({ +// origin: "file", +// code: "invalid_value", +// options: [def.fileName], +// input: payload.value, +// path: ["name"], +// inst, +// }); +// }; +// }); + +/////////////////////////////////// +///// $ZodCheckOverwrite ///// +/////////////////////////////////// +export interface $ZodCheckOverwriteDef extends $ZodCheckDef { + check: "overwrite"; + tx(value: T): T; +} + +export interface $ZodCheckOverwriteInternals extends $ZodCheckInternals { + def: $ZodCheckOverwriteDef; + issc: never; +} + +export interface $ZodCheckOverwrite extends $ZodCheck { + _zod: $ZodCheckOverwriteInternals; +} + +export const $ZodCheckOverwrite: core.$constructor<$ZodCheckOverwrite> = /*@__PURE__*/ core.$constructor( + "$ZodCheckOverwrite", + (inst, def) => { + $ZodCheck.init(inst, def); + + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; + } +); + +// /////////////////////////////// +// ///// $ZodCheckTrim ///// +// /////////////////////////////// +// export interface $ZodCheckTrimDef extends $ZodCheckDef { +// check: "trim"; +// error?: errors.$ZodErrorMap | undefined; +// } +// export interface $ZodCheckTrim extends $ZodCheckInternals { +// _def: $ZodCheckTrimDef; +// } + +// export const $ZodCheckTrim: core.$constructor<$ZodCheckTrim> = +// core.$constructor("$ZodCheckTrim", (inst, def) => { +// $ZodCheck.init(inst, def); + +// inst._zod.check = (payload) => { +// payload.value = payload.value.trim(); +// }; +// }); + +// ////////////////////////////////////// +// ///// $ZodCheckNormalize ///// +// ////////////////////////////////////// +// interface $ZodCheckNormalizeDef extends $ZodCheckDef { +// check: "normalize"; +// error?: errors.$ZodErrorMap | undefined; +// } + +// export interface $ZodCheckNormalize extends $ZodCheckInternals { +// _def: $ZodCheckNormalizeDef; +// } + +// export const $ZodCheckNormalize: core.$constructor<$ZodCheckNormalize> = +// core.$constructor("$ZodCheckNormalize", (inst, def) => { +// $ZodCheck.init(inst, def); + +// inst._zod.check = (payload) => { +// payload.value = payload.value.normalize(); +// }; +// }); + +export type $ZodChecks = + | $ZodCheckLessThan + | $ZodCheckGreaterThan + | $ZodCheckMultipleOf + | $ZodCheckNumberFormat + | $ZodCheckBigIntFormat + | $ZodCheckMaxSize + | $ZodCheckMinSize + | $ZodCheckSizeEquals + | $ZodCheckMaxLength + | $ZodCheckMinLength + | $ZodCheckLengthEquals + | $ZodCheckStringFormat + | $ZodCheckProperty + | $ZodCheckMimeType + | $ZodCheckOverwrite; + +export type $ZodStringFormatChecks = + | $ZodCheckRegex + | $ZodCheckLowerCase + | $ZodCheckUpperCase + | $ZodCheckIncludes + | $ZodCheckStartsWith + | $ZodCheckEndsWith + | schemas.$ZodStringFormatTypes; // union of string format schema types diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/config.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/config.ts new file mode 100644 index 0000000000000000000000000000000000000000..38510d89720d99950344fb8d180b1359a73c7317 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/config.ts @@ -0,0 +1,15 @@ +import type * as errors from "./errors.js"; + +export interface $ZodConfig { + /** Custom error map. Overrides `config().localeError`. */ + customError?: errors.$ZodErrorMap | undefined; + /** Localized error map. Lowest priority. */ + localeError?: errors.$ZodErrorMap | undefined; +} + +export const globalConfig: $ZodConfig = {}; + +export function config(config?: Partial<$ZodConfig>): $ZodConfig { + if (config) Object.assign(globalConfig, config); + return globalConfig; +} diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/core.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/core.ts new file mode 100644 index 0000000000000000000000000000000000000000..26494b60262dcdb0a70ca3203afd54630501bc7a --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/core.ts @@ -0,0 +1,134 @@ +import type * as errors from "./errors.js"; +import type * as schemas from "./schemas.js"; +import type { Class } from "./util.js"; +////////////////////////////// CONSTRUCTORS /////////////////////////////////////// + +type ZodTrait = { _zod: { def: any; [k: string]: any } }; +export interface $constructor { + new (def: D): T; + init(inst: T, def: D): asserts inst is T; +} + +/** A special constant with type `never` */ +export const NEVER: never = Object.freeze({ + status: "aborted", +}) as never; + +export /*@__NO_SIDE_EFFECTS__*/ function $constructor( + name: string, + initializer: (inst: T, def: D) => void, + params?: { Parent?: typeof Class } +): $constructor { + function init(inst: T, def: D) { + Object.defineProperty(inst, "_zod", { + value: inst._zod ?? {}, + enumerable: false, + }); + + inst._zod.traits ??= new Set(); + + inst._zod.traits.add(name); + initializer(inst, def); + // support prototype modifications + for (const k in _.prototype) { + if (!(k in inst)) Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); + } + inst._zod.constr = _; + inst._zod.def = def; + } + + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent {} + Object.defineProperty(Definition, "name", { value: name }); + + function _(this: any, def: D) { + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + inst._zod.deferred ??= []; + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst: any) => { + if (params?.Parent && inst instanceof params.Parent) return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _ as any; +} + +////////////////////////////// UTILITIES /////////////////////////////////////// +export const $brand: unique symbol = Symbol("zod_brand"); +export type $brand = { + [$brand]: { [k in T]: true }; +}; + +export type $ZodBranded = T & + Record<"_zod", Record<"output", output & $brand>>; + +export class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} + +//////////////////////////// TYPE HELPERS /////////////////////////////////// + +// export type input = T["_zod"]["input"]; +// export type output = T["_zod"]["output"]; +// export type input = T["_zod"]["input"]; +// export type output = T["_zod"]["output"]; +export type input = T extends { _zod: { input: any } } ? Required["input"] : unknown; +export type output = T extends { _zod: { output: any } } ? Required["output"] : unknown; + +// Mk2 +// export type input = T extends { _zod: { "~input": any } } +// ? T["_zod"]["~input"] +// : T extends { _zod: { input: any } } +// ? T["_zod"]["input"] +// : never; +// export type output = T extends { _zod: { "~output": any } } +// ? T["_zod"]["~output"] +// : T extends { _zod: { output: any } } +// ? T["_zod"]["output"] +// : never; +// Mk 3 +// export type input = T["_zod"]["input"]; +// export type output = T["_zod"]["output"]; +// Mk 4 +// export type input = T[] extends { _zod: { "~input": any } } +// ? T["_zod"]["~input"] +// : T extends { _zod: { input: any } } +// ? T["_zod"]["input"] +// : never; +// export type output = T extends { _zod: { "~output": any } } +// ? T["_zod"]["~output"] +// : T extends { _zod: { output: any } } +// ? T["_zod"]["output"] +// : never; + +export type { output as infer }; + +////////////////////////////// CONFIG /////////////////////////////////////// + +export interface $ZodConfig { + /** Custom error map. Overrides `config().localeError`. */ + customError?: errors.$ZodErrorMap | undefined; + /** Localized error map. Lowest priority. */ + localeError?: errors.$ZodErrorMap | undefined; + /** Disable JIT schema compilation. Useful in environments that disallow `eval`. */ + jitless?: boolean | undefined; +} + +export const globalConfig: $ZodConfig = {}; + +export function config(newConfig?: Partial<$ZodConfig>): $ZodConfig { + if (newConfig) Object.assign(globalConfig, newConfig); + return globalConfig; +} diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/doc.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/doc.ts new file mode 100644 index 0000000000000000000000000000000000000000..9591fe7a136ca4c06ee9c89f3ab2afaa0eae4b23 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/doc.ts @@ -0,0 +1,44 @@ +type ModeWriter = (doc: Doc, modes: { execution: "sync" | "async" }) => void; + +export class Doc { + args!: string[]; + content: string[] = []; + indent = 0; + + constructor(args: string[] = []) { + if (this) this.args = args; + } + + indented(fn: (doc: Doc) => void) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + + write(fn: ModeWriter): void; + write(line: string): void; + write(arg: any) { + if (typeof arg === "function") { + (arg as ModeWriter)(this, { execution: "sync" }); + (arg as ModeWriter)(this, { execution: "async" }); + return; + } + + const content = arg as string; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + + compile() { + const F = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + // console.log(lines.join("\n")); + return new F(...args, lines.join("\n")); + } +} diff --git a/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/errors.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..699c81f31beb0655d26c6cc863807e3cf7740a66 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/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-threshold/node_modules/zod/src/v4/core/function.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/function.ts new file mode 100644 index 0000000000000000000000000000000000000000..79fd2caad61548f1357b6ced87e180a42effb950 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/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-threshold/node_modules/zod/src/v4/core/index.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6887877a45610d7f498aeeeaa369c70742ff188 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/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-threshold/node_modules/zod/src/v4/core/json-schema.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/json-schema.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b3abfbe02e824f677a35a3a966ade0e81572025 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/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-threshold/node_modules/zod/src/v4/core/parse.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/parse.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec046dfe914ab42e33f964955470d161125229d9 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/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-threshold/node_modules/zod/src/v4/core/regexes.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/regexes.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfcb6a0e1661157a561d5016344bf8dfde0d5fe1 --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/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-threshold/node_modules/zod/src/v4/core/registries.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/registries.ts new file mode 100644 index 0000000000000000000000000000000000000000..14652be8ef041a10431c4e0b374a543827baa73f --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/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-threshold/node_modules/zod/src/v4/core/schemas.ts b/node_modules/@jimp/plugin-threshold/node_modules/zod/src/v4/core/schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce16838549a39ff2522a1b6eea2b8994265f1b0f --- /dev/null +++ b/node_modules/@jimp/plugin-threshold/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