zodzilla 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Edward Schauman-Haigh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,326 @@
1
- # Temporary Holding Version
1
+ ![zodzilla: API fuzz testing with Zod](.github/banner.jpg)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Finds the requests that break your API. Give it an endpoint and the Zod schema for its body, and it sends a few hundred made-up requests: good ones your endpoint should handle, and bad ones it should turn away. When one breaks it, you get the simplest request that does, and the line of your code that crashed.
4
+
5
+ This is called fuzzing. You don't need to know anything about it to use zodzilla.
6
+
7
+ ```ts
8
+ test('POST /orders', () => zz.checkRoute(app.fetch, { method: 'POST', path: '/orders', body: CreateOrder }))
9
+ ```
10
+
11
+ It works with Zod 4, any test runner, tRPC, and any framework whose handlers take a `Request` and return a `Response`, like Hono, Elysia and Next.js route handlers. There's also `zz.check` for plain functions.
12
+
13
+ ## What it finds
14
+
15
+ - Good requests that crash your endpoint, or get a 4xx you didn't mean
16
+ - Bad requests your endpoint lets through when it should send back a 400
17
+ - Broken JSON that crashes your endpoint instead of getting a 400
18
+ - Responses that don't match the shape you said they'd have
19
+
20
+ The good requests aren't polite. They use empty strings, missing optional fields, accented, non-Latin and control characters, numbers right on their limits, and the odd field you didn't ask for. Each bad request breaks one rule: a number one past its limit, a missing field, a field of the wrong type, text that isn't an email, JSON cut off half way.
21
+
22
+ ## Quick start
23
+
24
+ ```sh
25
+ pnpm add -D zodzilla zod fast-check vitest
26
+ ```
27
+
28
+ zodzilla is built on [fast-check](https://fast-check.dev), so that goes in too. You won't need to use it directly.
29
+
30
+ Say you have this Hono app. It has a bug: a coupon code nobody's set up crashes it.
31
+
32
+ ```ts
33
+ // app.ts
34
+ import { zValidator } from '@hono/zod-validator'
35
+ import { Hono } from 'hono'
36
+ import * as z from 'zod'
37
+
38
+ const COUPONS: Record<string, { percent: number }> = { VIP10: { percent: 10 } }
39
+
40
+ export const CreateOrder = z.object({
41
+ items: z.array(z.object({ sku: z.string(), qty: z.int().min(1) })).min(1),
42
+ coupon: z.string().optional(),
43
+ })
44
+
45
+ export const app = new Hono()
46
+
47
+ app.post('/orders', zValidator('json', CreateOrder), (c) => {
48
+ const order = c.req.valid('json')
49
+ const discount = order.coupon ? COUPONS[order.coupon].percent : 0
50
+ return c.json({ id: crypto.randomUUID(), discount }, 201)
51
+ })
52
+ ```
53
+
54
+ Add a test next to it:
55
+
56
+ ```ts
57
+ // app.test.ts
58
+ import { test } from 'vitest'
59
+ import { zz } from 'zodzilla'
60
+ import { app, CreateOrder } from './app'
61
+
62
+ test('POST /orders', () => zz.checkRoute(app.fetch, { method: 'POST', path: '/orders', body: CreateOrder }))
63
+ ```
64
+
65
+ and run it with `pnpm vitest`. Each check sends 200 requests, 100 good and 100 bad. Against an app like this one that takes a fraction of a second.
66
+
67
+ ## Reading a report
68
+
69
+ ```
70
+ CheckFailure: POST /orders returned 500 for a valid body
71
+
72
+ body {"items":[{"sku":"","qty":1}],"coupon":" "}
73
+ status 500
74
+ response Internal Server Error
75
+ found on run 2, then simplified 6 times
76
+ rerun just this replay: 'valid:1:1:0:0:0:0:3:1'
77
+ always test it examples: [{"items":[{"sku":"","qty":1}],"coupon":" "}]
78
+
79
+ Logged while handling it: TypeError: Cannot read properties of undefined (reading 'percent')
80
+ ❯ app.ts:16:57
81
+ 15| const order = c.req.valid('json')
82
+ 16| const discount = order.coupon ? COUPONS[order.coupon].percent : 0
83
+ | ^
84
+ ```
85
+
86
+ - **body** is the request that broke it. zodzilla found a failing request on its second try, then cut it down six times to the simplest one that still fails: one item, and a coupon code of a single space.
87
+ - **status** and **response** are what your endpoint sent back.
88
+ - **Logged while handling it** is the error your server logged, and the code below it is the line that crashed. Hono turned the crash into a plain 500, but zodzilla caught the log on the way.
89
+
90
+ ## Fixing a bug
91
+
92
+ The last two lines of the report are there to copy.
93
+
94
+ While you fix it, add the `rerun just this` line to the options. The test then sends just that one request, so it's quick to rerun as you go, and it passes once the bug's gone:
95
+
96
+ ```ts
97
+ zz.checkRoute(app.fetch, {
98
+ method: 'POST',
99
+ path: '/orders',
100
+ body: CreateOrder,
101
+ replay: 'valid:1:1:0:0:0:0:3:1',
102
+ })
103
+ ```
104
+
105
+ Once it's fixed, swap `replay` for the `always test it` line. That request then gets sent first on every run, so the bug can't quietly come back:
106
+
107
+ ```ts
108
+ examples: [{"items":[{"sku":"","qty":1}],"coupon":" "}],
109
+ ```
110
+
111
+ ## Bad requests
112
+
113
+ An endpoint should turn a bad request away with a 400 (or a 422). This one reads the body without checking it:
114
+
115
+ ```ts
116
+ app.post('/signup', async (c) => {
117
+ const { email } = await c.req.json()
118
+ return c.json({ welcome: email.toLowerCase() }, 201)
119
+ })
120
+ ```
121
+
122
+ ```
123
+ CheckFailure: POST /signup returned 500 for an invalid body, instead of rejecting it with 400 or 422
124
+
125
+ body "1970-01-01T00:00:00.000Z"
126
+ why bad body: Invalid input: expected object, received string
127
+ status 500
128
+ response Internal Server Error
129
+ ```
130
+
131
+ **why bad** says which rule the request broke. Here the body is a string rather than an object, so there's no email to read. The fix is to check the body before using it: `zValidator('json', Signup)` in Hono, or `Signup.safeParse(body)` anywhere else.
132
+
133
+ ## Your framework
134
+
135
+ `checkRoute` takes any function that gets a `Request` and returns a `Response`, or a promise of one.
136
+
137
+ | Framework | Pass |
138
+ | -------------------- | ----------------------------------------------------------------- |
139
+ | Hono | `app.fetch` |
140
+ | Elysia | `app.handle` |
141
+ | Next.js (app router) | The `POST`, `PUT`, `PATCH` or `DELETE` exported from a `route.ts` |
142
+ | tRPC | A caller, or the fetch adapter. See [tRPC](#trpc) |
143
+ | Express, Fastify | Not supported yet, as their handlers don't take a `Request` |
144
+
145
+ Next.js handlers that use `cookies()` or `headers()` from `next/headers` need Next's request context, so they won't run here.
146
+
147
+ There's a small working app for each, with tests, in [examples](examples).
148
+
149
+ ## tRPC
150
+
151
+ The simplest way is to check a procedure through a caller. It needs no server, and covers queries as well as mutations:
152
+
153
+ ```ts
154
+ import { TRPCError } from '@trpc/server'
155
+ import { zz } from 'zodzilla'
156
+
157
+ const caller = createCaller({}) // your context goes here
158
+
159
+ test('orders.create', () =>
160
+ zz.check(caller.orders.create, {
161
+ input: CreateOrder,
162
+ allowErrors: (e) => e instanceof TRPCError && e.code !== 'INTERNAL_SERVER_ERROR',
163
+ }))
164
+ ```
165
+
166
+ tRPC turns bad input away with a `BAD_REQUEST` error caused by the `ZodError`, which is what `zz.check` expects, so there's nothing to set for that. `allowErrors` lets the procedure throw its own errors on good input, like `NOT_FOUND`. It leaves out `INTERNAL_SERVER_ERROR` because that's how tRPC hands back a crash, and crashes are what you want to hear about:
167
+
168
+ ```
169
+ CheckFailure: orders.create threw on valid input
170
+
171
+ input {"items":[{"sku":"","qty":1}],"coupon":" "}
172
+ ...
173
+
174
+ Thrown by orders.create: TRPCError: Cannot read properties of undefined (reading 'percent')
175
+ ❯ router.ts:16:61
176
+ 16| const discount = input.coupon ? COUPONS[input.coupon].percent : 0
177
+ | ^
178
+ ```
179
+
180
+ To check a mutation over HTTP instead, go through tRPC's fetch adapter. Queries are GET requests, so they can't be checked this way yet.
181
+
182
+ ```ts
183
+ import { fetchRequestHandler } from '@trpc/server/adapters/fetch'
184
+
185
+ const handler = (req: Request) =>
186
+ fetchRequestHandler({
187
+ endpoint: '/trpc',
188
+ req,
189
+ router: appRouter,
190
+ createContext: () => ({}),
191
+ // tRPC doesn't log crashes itself. Logging them here lets the report show the line that crashed
192
+ onError: ({ error }) => console.error(error),
193
+ })
194
+
195
+ test('POST /trpc/orders.create', () =>
196
+ zz.checkRoute(handler, { method: 'POST', path: '/trpc/orders.create', body: CreateOrder }))
197
+ ```
198
+
199
+ tRPC wraps a successful result as `{ "result": { "data": ... } }`, so a `response` schema needs the same wrapping.
200
+
201
+ ## Options
202
+
203
+ Only `method`, `path` and `body` are needed.
204
+
205
+ | Option | What it's for |
206
+ | -------------- | -------------------------------------------------------------------------------------------------- |
207
+ | `method` | `POST`, `PUT`, `PATCH` or `DELETE` |
208
+ | `path` | Where the requests go, like `/orders` |
209
+ | `body` | The Zod schema for the JSON body |
210
+ | `response` | A schema the JSON response must match, when a good request succeeds |
211
+ | `allowStatus` | Statuses a good request may get besides 2xx and 3xx, like `[404, 409]`. Anything else is a failure |
212
+ | `rejectStatus` | The statuses a bad request must get. Default `[400, 422]` |
213
+ | `headers` | Headers to send with every request, like an auth token |
214
+ | `examples` | Requests to send first, every time. See [Fixing a bug](#fixing-a-bug) |
215
+ | `replay` | Rerun just one earlier failure |
216
+ | `numRuns` | How many good and how many bad requests to send. Default 100 each |
217
+ | `seed` | Send the same requests on every run |
218
+
219
+ ## Good to know
220
+
221
+ - **Bodies are JSON.** A schema using `z.date()`, `z.bigint()` or `z.map()` can't arrive as JSON, and zodzilla will say so. Use `z.coerce.date()` or `z.iso.datetime()` for dates.
222
+ - **JSON bodies only, for now.** GET requests, query strings and path parameters aren't supported yet.
223
+ - **Your server's error logs are held back.** While a check runs, anything logged with `console.error` is caught rather than printed, so one bug doesn't fill your terminal. The log from the failing request goes in the report.
224
+ - **Requests are real.** An endpoint that writes to a database writes a row per request, so point checks at a test database.
225
+ - **Some rules random data won't hit.** A `.refine()` that compares two fields, like a password and its confirmation, almost never holds for made-up values. zodzilla tells you which field, and you can show it how to make good ones. See [Custom values](#custom-values).
226
+ - **Runs are repeatable.** Pass `seed` to send the same requests every time, and raise `numRuns` for a deeper search, say in a nightly job.
227
+
228
+ ## Testing functions
229
+
230
+ Not everything is an endpoint. `zz.check` does the same for any function that takes input you check with Zod:
231
+
232
+ ```ts
233
+ test('createOrder', () => zz.check(createOrder, { input: CreateOrder }))
234
+ ```
235
+
236
+ Good input must not make it throw. Bad input must make it throw a `ZodError`, or an error with one as its `cause`. Reports look the same as for endpoints.
237
+
238
+ | Option | What it's for |
239
+ | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
240
+ | `input` | The Zod schema for the function's argument |
241
+ | `output` | A schema for what it returns |
242
+ | `allowErrors` | Errors it may throw on good input, like `[NotFoundError]`, or a function that decides |
243
+ | `given: 'parsed'` | For functions that take already-parsed data, typed with `z.infer`. They get what `schema.parse` returns, and no bad input |
244
+ | `rejects` | How it turns bad input away, if not with a `ZodError`: `'throws'` (any error that isn't a crash like a `TypeError`), a function that decides, or `false` to skip bad input |
245
+ | `examples`, `replay`, `numRuns`, `seed` | As for `checkRoute` |
246
+
247
+ ## Custom values
248
+
249
+ `z.custom()` and `z.instanceof()` can't be looked inside, and some `.refine()`s are too strict for random values. When zodzilla meets one it says which field. Show it how to make values for that schema with `zz.override` and a [fast-check arbitrary](https://fast-check.dev/docs/core-blocks/arbitraries/):
250
+
251
+ ```ts
252
+ import { fc, zz } from 'zodzilla'
253
+
254
+ const Signup = z.object({ password: z.string().min(8), confirm: z.string() }).refine((s) => s.password === s.confirm)
255
+
256
+ const matching = fc.string({ minLength: 8 }).map((password) => ({ password, confirm: password }))
257
+
258
+ zz.checkRoute(app.fetch, {
259
+ method: 'POST',
260
+ path: '/signup',
261
+ body: Signup,
262
+ overrides: [zz.override(Signup, matching)],
263
+ })
264
+ ```
265
+
266
+ The override is keyed by the schema object itself, so it applies wherever that schema is used.
267
+
268
+ ## Seeing what it sends
269
+
270
+ ```ts
271
+ import { fc, zz } from 'zodzilla'
272
+
273
+ console.log(fc.sample(zz.valid(CreateOrder), 5)) // good bodies
274
+ console.log(fc.sample(zz.invalid(CreateOrder), 5).map((bad) => bad.value)) // bad ones
275
+ ```
276
+
277
+ `zz.valid`, `zz.parsed` and `zz.invalid` are fast-check arbitraries, so if you already write property tests, for example with [@fast-check/vitest](https://www.npmjs.com/package/@fast-check/vitest), you can use them directly. If you do use `@fast-check/vitest`, set `numRuns` per check rather than globally with `fc.configureGlobal`, which makes its plain `test()` run every test body that many times.
278
+
279
+ ## Speed
280
+
281
+ Measured with `pnpm bench` on an Apple M5 Max with Node 24. All figures are per second.
282
+
283
+ | Schema | What's in it | Good values | Bad values |
284
+ | ------ | ------------------------------------------------------------------------ | ----------- | ---------- |
285
+ | User | A UUID, an email, a name, an age and up to 5 tags | 128k | 91k |
286
+ | Order | Up to 20 line items, each a price and a quantity, and an optional coupon | 166k | 95k |
287
+ | Event | A v4 UUID, an ISO datetime, an IPv4 address and an enum | 191k | 132k |
288
+ | Tree | A name and child trees, nested up to 5 deep | 117k | 107k |
289
+
290
+ | Check | Per second |
291
+ | ----------------------------------------------------------------------------- | ------------ |
292
+ | `zz.checkRoute` on a Hono endpoint that uses `zValidator`, with an Order body | 37k requests |
293
+ | `zz.check` on a function that parses an Order | 89k calls |
294
+
295
+ A check makes 200 values, which takes about 2 milliseconds, so how long one takes comes down to your own code. The endpoint figure includes Hono's routing, `zValidator`, and building each `Request` and `Response`.
296
+
297
+ GitHub's CI runners come in at roughly a third to two thirds of these figures, and vary from run to run. Every CI run prints its own in the Benchmark step.
298
+
299
+ ## Reference
300
+
301
+ | | |
302
+ | --------------------------------- | ----------------------------------------------------------------------------------------- |
303
+ | `zz.checkRoute(handler, options)` | Check an endpoint |
304
+ | `zz.check(fn, options)` | Check a function |
305
+ | `zz.valid(schema)` | Generates values the schema accepts |
306
+ | `zz.parsed(schema)` | Generates what `schema.parse` returns for them |
307
+ | `zz.invalid(schema)` | Generates `{ value, path, issues }`: values that break one rule, where, and what Zod says |
308
+ | `zz.override(schema, arbitrary)` | An entry for `overrides` |
309
+ | `zz.rawBody(text)` | A request body that isn't JSON, for `examples` |
310
+ | `fc` | fast-check |
311
+
312
+ A failed check throws a `CheckFailure`, with `pass` (`'valid'` or `'invalid'`), `input`, `replay` and `thrown` alongside the report. Every name is also exported on its own (`import { checkRoute } from 'zodzilla'`), but `zz` stops names like `check` clashing with yours.
313
+
314
+ Every check and generator also takes `overrides`, `extraKeys` (add unknown fields to some objects, default `true`), `maxRejections` (how many made-up values a strict rule can turn down in a row before zodzilla gives up, default 1000) and `maxDepth` (how deep `z.lazy` schemas nest, default 5).
315
+
316
+ ## Development
317
+
318
+ ```sh
319
+ nix develop # or direnv allow
320
+ pnpm install
321
+ pnpm test
322
+ pnpm typecheck
323
+ pnpm bench # values generated, checks run and Zod parses per second
324
+ ```
325
+
326
+ To release a new version, see [RELEASING.md](RELEASING.md).
package/dist/api.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export { default as fc } from 'fast-check';
2
+ export { check, type CheckOptions, type CheckParsedOptions, type Outcome } from './check.js';
3
+ export { ZodzillaError } from './internal.js';
4
+ export { invalid, type InvalidInput } from './invalid.js';
5
+ export { override, type Options, type Override } from './options.js';
6
+ export { checkRoute, rawBody, type RouteOptions } from './route.js';
7
+ export { CheckFailure } from './runner.js';
8
+ export { parsed, valid } from './valid.js';
package/dist/api.js ADDED
@@ -0,0 +1,8 @@
1
+ export { default as fc } from 'fast-check';
2
+ export { check } from './check.js';
3
+ export { ZodzillaError } from './internal.js';
4
+ export { invalid } from './invalid.js';
5
+ export { override } from './options.js';
6
+ export { checkRoute, rawBody } from './route.js';
7
+ export { CheckFailure } from './runner.js';
8
+ export { parsed, valid } from './valid.js';
@@ -0,0 +1,53 @@
1
+ import type * as core from 'zod/v4/core';
2
+ import { type Schema } from './internal.js';
3
+ import { type InvalidInput } from './invalid.js';
4
+ import type { Options } from './options.js';
5
+ export type Outcome = {
6
+ threw: true;
7
+ error: unknown;
8
+ } | {
9
+ threw: false;
10
+ value: unknown;
11
+ };
12
+ type ErrorClass = abstract new (...args: never[]) => unknown;
13
+ interface SharedOptions<S extends Schema> extends Options {
14
+ /** Schema for the argument fn takes */
15
+ input: S;
16
+ /** If given, whatever fn returns for valid input must match it */
17
+ output?: Schema;
18
+ /**
19
+ * Errors fn may throw on valid input because they're part of how it works (not found, insufficient
20
+ * funds): a list of error classes, or a predicate. Anything else thrown on valid input is a failure
21
+ */
22
+ allowErrors?: ErrorClass[] | ((error: unknown) => boolean);
23
+ /** Inputs to always try first, like the `always test it` line from an earlier failure. Each goes to the pass it fits */
24
+ examples?: unknown[];
25
+ /** Rerun just one earlier failure, using the `rerun just this` line from its report */
26
+ replay?: string;
27
+ numRuns?: number;
28
+ seed?: number;
29
+ }
30
+ export interface CheckOptions<S extends Schema> extends SharedOptions<S> {
31
+ /** fn takes raw, unparsed input (the default), so it gets both valid and invalid values */
32
+ given?: 'raw';
33
+ /**
34
+ * What fn must do with invalid input:
35
+ * - 'zod-error' (default): throw a ZodError, or an error whose cause chain contains one
36
+ * - 'throws': throw anything except a TypeError, RangeError, ReferenceError or SyntaxError,
37
+ * which mean the code crashed on the input rather than rejecting it
38
+ * - a predicate, for code that reports bad input some other way (an error result, a 400 response)
39
+ * - false: don't test invalid input
40
+ */
41
+ rejects?: 'zod-error' | 'throws' | ((outcome: Outcome, input: InvalidInput) => boolean) | false;
42
+ }
43
+ export interface CheckParsedOptions<S extends Schema> extends SharedOptions<S> {
44
+ /** fn takes what schema.parse() returns, so it only gets valid values, with defaults and transforms applied */
45
+ given: 'parsed';
46
+ }
47
+ /**
48
+ * Fuzzes fn with inputs generated from a Zod schema. Valid inputs must not make it throw (beyond
49
+ * `allowErrors`) and must produce `output`, if given; invalid inputs must be rejected as `rejects` says.
50
+ */
51
+ export declare function check<S extends Schema>(fn: (input: core.output<S>) => unknown, options: CheckParsedOptions<S>): Promise<void>;
52
+ export declare function check<S extends Schema>(fn: (input: core.input<S>) => unknown, options: CheckOptions<S>): Promise<void>;
53
+ export {};
package/dist/check.js ADDED
@@ -0,0 +1,103 @@
1
+ import fc from 'fast-check';
2
+ import { $ZodError, safeParse } from 'zod/v4/core';
3
+ import { accepts, issueList } from './internal.js';
4
+ import { describeInvalid, invalid } from './invalid.js';
5
+ import { frames, parseReplay, runPass, Verdict } from './runner.js';
6
+ import { parsed, valid } from './valid.js';
7
+ export async function check(fn, options) {
8
+ const settings = {
9
+ subject: nameOf(fn),
10
+ callSite: frames(new Error()),
11
+ replay: parseReplay(options.replay),
12
+ numRuns: options.numRuns,
13
+ seed: options.seed,
14
+ };
15
+ const { subject } = settings;
16
+ const schema = options.input;
17
+ const raw = options.given !== 'parsed';
18
+ const examples = options.examples ?? [];
19
+ const shown = (value) => ({
20
+ input: value,
21
+ rows: [['input', fc.stringify(value)]],
22
+ pin: fc.stringify(value),
23
+ });
24
+ await runPass('valid', raw ? valid(schema, options) : parsed(schema, options), raw ? examples.filter((e) => accepts(schema, e)) : examples, async (value) => {
25
+ const outcome = await run(fn, value);
26
+ if (outcome.threw) {
27
+ if (allowed(options.allowErrors, outcome.error))
28
+ return;
29
+ throw new Verdict(`${subject} threw on valid input`, { thrown: outcome.error });
30
+ }
31
+ if (options.output) {
32
+ const result = safeParse(options.output, outcome.value);
33
+ if (!result.success) {
34
+ throw new Verdict(`${subject} returned a value that doesn't match the output schema`, {
35
+ notes: [
36
+ ['returned', fc.stringify(outcome.value)],
37
+ ['mismatch', issueList(result.error.issues)],
38
+ ],
39
+ });
40
+ }
41
+ }
42
+ }, shown, settings);
43
+ const rejects = options.given === 'parsed' ? false : (options.rejects ?? 'zod-error');
44
+ if (rejects === false)
45
+ return;
46
+ const rejected = typeof rejects === 'function' ? rejects : REJECTIONS[rejects];
47
+ await runPass('invalid', invalid(schema, options), examples.filter((e) => !accepts(schema, e)).map((e) => describeInvalid(schema, e, [])), async (bad) => {
48
+ const outcome = await run(fn, bad.value);
49
+ if (rejected(outcome, bad))
50
+ return;
51
+ const notes = [['why bad', issueList(bad.issues)]];
52
+ if (!outcome.threw)
53
+ notes.push(['returned', fc.stringify(outcome.value)]);
54
+ throw new Verdict(invalidHeadline(subject, outcome, rejects), {
55
+ notes,
56
+ ...(outcome.threw ? { thrown: outcome.error } : {}),
57
+ });
58
+ }, (bad) => shown(bad.value), settings);
59
+ }
60
+ /** What reports call the function under test. Inline lambdas have no name, so they're "fn" */
61
+ function nameOf(fn) {
62
+ // tRPC callers are proxies that answer `.name` with "tRPC.proxy(<procedure path>.name)"
63
+ const trpc = /^tRPC\.proxy\((.+)\.name\)$/.exec(fn.name);
64
+ return trpc ? trpc[1] : fn.name || 'fn';
65
+ }
66
+ const crashes = [TypeError, RangeError, ReferenceError, SyntaxError];
67
+ const isCrash = (error) => crashes.some((kind) => error instanceof kind);
68
+ function invalidHeadline(subject, outcome, rejects) {
69
+ if (typeof rejects === 'function')
70
+ return `${subject}'s response to invalid input didn't satisfy rejects`;
71
+ if (!outcome.threw)
72
+ return `${subject} accepted invalid input`;
73
+ if (rejects === 'zod-error' && !isCrash(outcome.error)) {
74
+ return `${subject} threw on invalid input, but not a ZodError. If that's how it rejects input, set rejects: 'throws' or pass a predicate`;
75
+ }
76
+ return `${subject} crashed on invalid input instead of rejecting it`;
77
+ }
78
+ const REJECTIONS = {
79
+ 'zod-error': (outcome) => outcome.threw && causedByZod(outcome.error),
80
+ throws: (outcome) => outcome.threw && !isCrash(outcome.error),
81
+ };
82
+ function allowed(allowErrors, error) {
83
+ if (typeof allowErrors === 'function')
84
+ return allowErrors(error);
85
+ return (allowErrors ?? []).some((kind) => error instanceof kind);
86
+ }
87
+ function causedByZod(error) {
88
+ // Bounded, in case of a cyclic cause chain
89
+ for (let depth = 0; depth < 10 && error instanceof Error; depth++) {
90
+ if (error instanceof $ZodError)
91
+ return true;
92
+ error = error.cause;
93
+ }
94
+ return error instanceof $ZodError;
95
+ }
96
+ async function run(fn, value) {
97
+ try {
98
+ return { threw: false, value: await fn(value) };
99
+ }
100
+ catch (error) {
101
+ return { threw: true, error };
102
+ }
103
+ }
@@ -0,0 +1,2 @@
1
+ export * from './api.js';
2
+ export * as zz from './api.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './api.js';
2
+ // The same API under one name, so `valid` or `check` don't collide with names in the code under test
3
+ export * as zz from './api.js';
@@ -0,0 +1,58 @@
1
+ import fc from 'fast-check';
2
+ import type * as core from 'zod/v4/core';
3
+ import type { Options } from './options.js';
4
+ export type Schema = core.$ZodType;
5
+ /** Where a node sits in the schema: object keys, tuple indexes, and '[]' for any array element */
6
+ export type Path = readonly PropertyKey[];
7
+ export declare class ZodzillaError extends Error {
8
+ name: string;
9
+ }
10
+ export declare const defOf: (schema: Schema) => core.$ZodAnyDef | core.$ZodArrayDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodBigIntDef | core.$ZodBooleanDef | core.$ZodCatchDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodCustomDef<unknown> | core.$ZodDateDef | core.$ZodDefaultDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodEnumDef<Readonly<Record<string, core.util.EnumValue>>> | core.$ZodFileDef | core.$ZodFunctionDef<core.$ZodFunctionArgs, core.$ZodFunctionOut> | core.$ZodIntersectionDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>, core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodLazyDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodLiteralDef<core.util.Literal> | core.$ZodMapDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>, core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodNaNDef | core.$ZodNeverDef | core.$ZodNonOptionalDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodNullDef | core.$ZodNullableDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodNumberDef | core.$ZodObjectDef<Readonly<Readonly<{
11
+ [k: string]: core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>;
12
+ }>>> | core.$ZodOptionalDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodPipeDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>, core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodPrefaultDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodPromiseDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodReadonlyDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodRecordDef<core.$ZodRecordKey, core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodSetDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodStringDef | core.$ZodSuccessDef<core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>> | core.$ZodSymbolDef | core.$ZodTemplateLiteralDef | core.$ZodTransformDef | core.$ZodTupleDef<readonly core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>[], core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>> | null> | core.$ZodUndefinedDef | core.$ZodUnionDef<readonly core.$ZodType<unknown, unknown, core.$ZodTypeInternals<unknown, unknown>>[]> | core.$ZodUnknownDef | core.$ZodVoidDef;
13
+ export declare const checksOf: (schema: Schema) => (core.$ZodCheckBigIntFormatDef<core.$ZodBigIntFormats> | core.$ZodCheckGreaterThanDef | core.$ZodCheckLengthEqualsDef | core.$ZodCheckLessThanDef | core.$ZodCheckMaxLengthDef | core.$ZodCheckMaxSizeDef | core.$ZodCheckMimeTypeDef | core.$ZodCheckMinLengthDef | core.$ZodCheckMinSizeDef | core.$ZodCheckMultipleOfDef<number | bigint> | core.$ZodCheckNumberFormatDef<core.$ZodNumberFormats> | core.$ZodCheckOverwriteDef<unknown> | core.$ZodCheckPropertyDef | core.$ZodCheckSizeEqualsDef | core.$ZodCheckStringFormatDef<string>)[];
14
+ export declare const accepts: (schema: Schema, value: unknown) => boolean;
15
+ export declare function formatPath(path: Path, root?: string): string;
16
+ export declare const issueList: (issues: readonly core.$ZodIssue[], root?: string) => string;
17
+ export declare const unsatisfiable: (path: Path, reason: string) => ZodzillaError;
18
+ export declare const unsupported: (schema: Schema, path: Path) => ZodzillaError;
19
+ /** Length or size bounds from a schema's checks */
20
+ export declare function sizeBounds(schema: Schema): {
21
+ min: number;
22
+ max: number | undefined;
23
+ other: boolean;
24
+ };
25
+ export declare const budgetedFilter: <T>(arb: fc.Arbitrary<T>, keep: (value: T) => boolean, budget: number, describe: () => string) => fc.Arbitrary<T>;
26
+ /** Keep only the values schema accepts: for refinements, pipes, and anything else not modelled exactly */
27
+ export declare const validated: <T>(arb: fc.Arbitrary<T>, schema: Schema, path: Path, ctx: Context) => fc.Arbitrary<T>;
28
+ export interface Context {
29
+ overrides: ReadonlyMap<Schema, fc.Arbitrary<unknown>>;
30
+ extraKeys: boolean;
31
+ maxRejections: number;
32
+ maxDepth: number;
33
+ /** True while building inside a z.lazy(), where collections and optionals have to thin out with depth */
34
+ recursive: boolean;
35
+ depth: fc.DepthIdentifier;
36
+ tie: (key: string) => fc.Arbitrary<unknown>;
37
+ members: Record<string, fc.Arbitrary<unknown>>;
38
+ lazyKeys: {
39
+ valid: Map<Schema, string>;
40
+ invalid: Map<Schema, string>;
41
+ };
42
+ }
43
+ /** Runs a build inside fc.letrec so z.lazy() schemas can refer back to themselves */
44
+ export declare function withContext<T>(options: Options, build: (ctx: Context) => fc.Arbitrary<T>): fc.Arbitrary<T>;
45
+ /** Builds a z.lazy() schema once per kind, handing out a letrec reference on every later visit */
46
+ export declare function recurse(kind: keyof Context['lazyKeys'], schema: Schema, ctx: Context, build: () => fc.Arbitrary<unknown>): fc.Arbitrary<unknown>;
47
+ /** fast-check depth settings inside recursive schemas: deeper levels favour the first (smallest) choice */
48
+ export declare const depthOptions: (ctx: Context) => {
49
+ depthIdentifier: fc.DepthContext;
50
+ depthSize: 'small';
51
+ maxDepth: number;
52
+ } | {
53
+ depthIdentifier?: undefined;
54
+ depthSize?: undefined;
55
+ maxDepth?: undefined;
56
+ };
57
+ /** A collection arbitrary that, inside recursive schemas, tends to empty as it nests so trees stay finite */
58
+ export declare function collection<T>(ctx: Context, minLength: number, maxLength: number | undefined, make: (minLength: number, maxLength: number | undefined) => fc.Arbitrary<T>): fc.Arbitrary<T>;