1import assert from "node:assert/strict"
2import { z } from "zod/v4"
3import { invalidData, validData } from "./data.ts"
4
5// Extracted from open-circle/schema-benchmarks at
6// 11fab2a741cef95a1374910276023c51218c0683.
7
8const makeSchema = () => {
9 const image = z.object({
10 id: z.number(),
11 created: z.date(),
12 title: z.string().min(1).max(100),
13 type: z.enum(["jpg", "png"]),
14 size: z.number(),
15 url: z.url()
16 })
17 const rating = z.object({
18 id: z.number(),
19 stars: z.number().min(0).max(5),
20 title: z.string().min(1).max(100),
21 text: z.string().min(1).max(1000),
22 images: z.array(image)
23 })
24 return z.object({
25 id: z.number(),
26 created: z.date(),
27 title: z.string().min(1).max(100),
28 brand: z.string().min(1).max(30),
29 description: z.string().min(1).max(500),
30 price: z.number().min(1).max(10000),
31 discount: z.number().min(1).max(100).nullable(),
32 quantity: z.number().min(1).max(10),
33 tags: z.array(z.string().min(1).max(30)),
34 images: z.array(image),
35 ratings: z.array(rating)
36 })
37}
38
39export const initializationSchema = () => ({
40 run: makeSchema,
41 validate: (schema) => assert.equal(schema.type, "object")
42})
43
44const parsingCase = (input, success) => () => {
45 const schema = makeSchema()
46 const options = { jitless: true }
47 return {
48 run: () => schema.safeParse(input, options),
49 validate: (result) => {
50 assert.equal(result.success, success)
51 if (success) assert.deepEqual(result.data, validData)
52 }
53 }
54}
55
56export const parsingAllValid = parsingCase(validData, true)
57export const parsingAllInvalid = parsingCase(invalidData, false)
58
59const standardCase = (input, success) => () => {
60 const schema = makeSchema()
61 return {
62 run: () => schema["~standard"].validate(input),
63 validate: (result) => {
64 assert.equal(typeof result?.then, "undefined")
65 assert.equal(result.issues === undefined, success)
66 if (success) assert.deepEqual(result.value, validData)
67 }
68 }
69}
70
71export const standardAllValid = standardCase(validData, true)
72export const standardAllInvalid = standardCase(invalidData, false)
73
74const codec = z.codec(z.string(), z.bigint(), {
75 decode: (value) => BigInt(value),
76 encode: (value) => value.toString()
77})
78const bigint = BigInt("1234567890123456789")
79const bigintString = bigint.toString()
80
81export const codecTypedEncode = () => ({
82 run: () => codec.encode(bigint),
83 validate: (result) => assert.equal(result, bigintString)
84})
85
86export const codecTypedDecode = () => ({
87 run: () => codec.decode(bigintString),
88 validate: (result) => assert.equal(result, bigint)
89})