@ptolemy2002/zod-utils 1.2.0 → 1.4.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/README.md CHANGED
@@ -5,7 +5,9 @@ Various utilities for working with Zod schemas.
5
5
  - [Type Reference](docs/type-reference.md) - Complete type definitions for all exported types
6
6
  - `util` - Utilities for working with Zod schemas and errors
7
7
  - [clone](docs/util/clone.md) - Utility for cloning Zod schemas without affecting the original
8
+ - [function](docs/util/function.md) - Schema factory for validating callable functions with input/output schemas
8
9
  - [interpret](docs/util/interpret.md) - Utilities for formatting Zod errors as strings
10
+ - [issuePathStartsWith](docs/util/issuePathStartsWith.md) - Utility for checking whether a Zod issue path starts with a given prefix
9
11
  - [prefixIssuePath](docs/util/prefixIssuePath.md) - Utility for prepending a path prefix to a Zod issue
10
12
  - [typeGuards](docs/util/typeGuards.md) - Type guards for Zod-related values
11
13
  - [validate](docs/util/validate.md) - Schema-wrapping factories for creating validators
@@ -0,0 +1,23 @@
1
+ import z, { ZodArray, ZodType, ZodUnknown } from "zod";
2
+ import { $ZodFunctionArgs, $ZodFunctionOut } from "zod/v4/core";
3
+ export type TrialErrorMode = "allow" | "forbid" | "require" | ((e: unknown) => boolean) | {
4
+ require: (e: unknown) => boolean;
5
+ };
6
+ export type FunctionTrial<Input extends unknown[]> = {
7
+ id?: string;
8
+ input: Input;
9
+ outputSchema?: ZodType;
10
+ error?: TrialErrorMode;
11
+ errorStringify?: (e: unknown) => string;
12
+ };
13
+ export type ZodFunctionParseOptions<In extends $ZodFunctionArgs, Out extends $ZodFunctionOut> = {
14
+ input?: In;
15
+ output?: Out;
16
+ inputPath?: PropertyKey | PropertyKey[];
17
+ outputPath?: PropertyKey | PropertyKey[];
18
+ };
19
+ export type ZodFunctionSchemaOptions<In extends $ZodFunctionArgs, Out extends $ZodFunctionOut> = {
20
+ trials?: FunctionTrial<z.infer<In>>[];
21
+ } & ZodFunctionParseOptions<In, Out>;
22
+ export declare function zodValidatedFunction<In extends $ZodFunctionArgs = ZodArray<ZodUnknown>, Out extends $ZodFunctionOut = ZodUnknown>(func: unknown, { inputPath, outputPath, input, output }?: ZodFunctionParseOptions<In, Out>): (...args: z.infer<In>) => z.core.output<Out>;
23
+ export declare function zodFunctionSchema<In extends $ZodFunctionArgs = ZodArray<ZodUnknown>, Out extends $ZodFunctionOut = ZodUnknown>({ trials, inputPath, outputPath, ...options }?: ZodFunctionSchemaOptions<In, Out>): z.ZodPipe<z.ZodAny, z.ZodTransform<(...args: z.core.output<In>) => z.core.output<Out>, any>>;
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.zodValidatedFunction = zodValidatedFunction;
40
+ exports.zodFunctionSchema = zodFunctionSchema;
41
+ const zod_1 = __importStar(require("zod"));
42
+ const typeGuards_1 = require("./typeGuards");
43
+ const prefixIssuePath_1 = require("./prefixIssuePath");
44
+ const issuePathStartsWith_1 = require("./issuePathStartsWith");
45
+ const is_callable_1 = __importDefault(require("is-callable"));
46
+ const interpret_1 = require("./interpret");
47
+ function zodValidatedFunction(func, { inputPath = "args", outputPath = "return", input = zod_1.default.array(zod_1.default.unknown()), output = zod_1.default.unknown() } = {}) {
48
+ if (!(0, is_callable_1.default)(func)) {
49
+ throw new zod_1.ZodError([{
50
+ message: `Expected a callable function, but received ${typeof func}`,
51
+ path: [],
52
+ code: "invalid_type",
53
+ expected: "function"
54
+ }]);
55
+ }
56
+ const functionFactory = zod_1.default.function({ input, output });
57
+ const wrappedFunction = (setReachedCaller, setFinishedCall, ...args) => {
58
+ setReachedCaller(true);
59
+ const result = func(...args);
60
+ setFinishedCall(true);
61
+ return result;
62
+ };
63
+ return (...args) => {
64
+ // This is how we will differentiate between argument and
65
+ // parameter validation errors
66
+ let reachedCaller = false;
67
+ let finishedCall = false;
68
+ try {
69
+ const implementedFunction = functionFactory.implement(((...args) => wrappedFunction((v) => (reachedCaller = v), (v) => (finishedCall = v), ...args)));
70
+ return implementedFunction(...args);
71
+ }
72
+ catch (e) {
73
+ if ((0, typeGuards_1.isZodError)(e)) {
74
+ if (!reachedCaller || finishedCall)
75
+ e = new zod_1.ZodError(e.issues.map(i => (0, prefixIssuePath_1.prefixZodIssuePath)(i, reachedCaller ? outputPath : inputPath)));
76
+ }
77
+ throw e;
78
+ }
79
+ finally {
80
+ // Reset reachedCaller and finishedCall for the next call
81
+ reachedCaller = false;
82
+ finishedCall = false;
83
+ }
84
+ };
85
+ }
86
+ function zodFunctionSchema({ trials = [], inputPath = "args", outputPath = "return", ...options } = {}) {
87
+ // Transform the input value using zodFunctionParse
88
+ // so that this schema can be used to validate functions
89
+ return zod_1.default.any().transform((v, ctx) => {
90
+ try {
91
+ const result = zodValidatedFunction(v, {
92
+ inputPath, outputPath,
93
+ ...options
94
+ });
95
+ // That zodValidatedFunction call guarantees that this is a function.
96
+ // We will not call it if there are no trials,
97
+ // as functions with side effects would be problematic to test.
98
+ if (trials.length > 0) {
99
+ trials.forEach((trial, i) => {
100
+ var _a;
101
+ const id = (_a = trial.id) !== null && _a !== void 0 ? _a : `trial_${i}`;
102
+ const { outputSchema = zod_1.default.unknown(), error, errorStringify = (e) => {
103
+ if ((0, typeGuards_1.isZodError)(e))
104
+ return (0, interpret_1.interpretZodError)(e);
105
+ if (e instanceof Error)
106
+ return e.message;
107
+ return String(e);
108
+ } } = trial;
109
+ const requiresError = error === "require" || (typeof error === "object" && error !== null);
110
+ const isExpectedError = (err) => {
111
+ if (error === "allow" || error === "require")
112
+ return true;
113
+ if (error === undefined || error === "forbid")
114
+ return false;
115
+ if (typeof error === "function")
116
+ return error(err);
117
+ return error.require(err);
118
+ };
119
+ try {
120
+ const output = result(...trial.input);
121
+ if (requiresError) {
122
+ ctx.addIssue({
123
+ code: "custom",
124
+ message: "Unexpected Success",
125
+ path: [id],
126
+ });
127
+ return;
128
+ }
129
+ const { success: outputSuccess, error: outputError } = outputSchema.safeParse(output);
130
+ if (!outputSuccess) {
131
+ // Indicate the trial where the error occurred to each issue.
132
+ // The fact that the error is in the output is already indicated,
133
+ // courtesy of the wrapper zodValidatedFunction provides.
134
+ outputError.issues.forEach(issue => ctx.addIssue({
135
+ ...issue,
136
+ path: [id, ...issue.path]
137
+ }));
138
+ }
139
+ }
140
+ catch (err) {
141
+ if ((0, typeGuards_1.isZodError)(err)) {
142
+ if (err.issues.every(issue => (0, issuePathStartsWith_1.issuePathStartsWith)(issue.path, inputPath) ||
143
+ (0, issuePathStartsWith_1.issuePathStartsWith)(issue.path, outputPath))) {
144
+ // Indicate the trial where the error occurred to each issue.
145
+ // The fact that the error is in either the input or output is
146
+ // already indicated, courtesy of the wrapper zodValidatedFunction provides.
147
+ err.issues.forEach(issue => ctx.addIssue({
148
+ ...issue,
149
+ path: [id, ...issue.path]
150
+ }));
151
+ return;
152
+ }
153
+ }
154
+ if (!isExpectedError(err)) {
155
+ ctx.addIssue({
156
+ code: "custom",
157
+ message: `Unexpected Error: ${errorStringify(err)}`,
158
+ path: [id],
159
+ });
160
+ }
161
+ }
162
+ });
163
+ }
164
+ return result;
165
+ }
166
+ catch (e) {
167
+ if ((0, typeGuards_1.isZodError)(e)) {
168
+ e.issues.forEach(issue => ctx.addIssue(issue));
169
+ }
170
+ return zod_1.default.NEVER;
171
+ }
172
+ });
173
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
+ export * from './function';
1
2
  export * from './types';
2
3
  export * from './typeGuards';
3
4
  export * from './interpret';
4
5
  export * from './validate';
5
6
  export * from './clone';
6
7
  export * from './prefixIssuePath';
8
+ export * from './issuePathStartsWith';
package/dist/index.js CHANGED
@@ -14,9 +14,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./function"), exports);
17
18
  __exportStar(require("./types"), exports);
18
19
  __exportStar(require("./typeGuards"), exports);
19
20
  __exportStar(require("./interpret"), exports);
20
21
  __exportStar(require("./validate"), exports);
21
22
  __exportStar(require("./clone"), exports);
22
23
  __exportStar(require("./prefixIssuePath"), exports);
24
+ __exportStar(require("./issuePathStartsWith"), exports);
@@ -1,2 +1,3 @@
1
1
  import { ZodError } from 'zod';
2
- export declare function interpretZodError(err: ZodError, prefix?: PropertyKey | PropertyKey[]): string;
2
+ import { $ZodError } from 'zod/v4/core';
3
+ export declare function interpretZodError(err: ZodError | $ZodError, prefix?: PropertyKey | PropertyKey[]): string;
@@ -0,0 +1 @@
1
+ export declare function issuePathStartsWith(issuePath: PropertyKey[], prefix: PropertyKey | PropertyKey[]): boolean;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.issuePathStartsWith = issuePathStartsWith;
4
+ function issuePathStartsWith(issuePath, prefix) {
5
+ if (!Array.isArray(prefix))
6
+ prefix = [prefix];
7
+ if (issuePath.length < prefix.length)
8
+ return false;
9
+ return prefix.every((segment, i) => issuePath[i] === segment);
10
+ }
@@ -1,2 +1,3 @@
1
1
  import { ZodError } from 'zod';
2
- export declare function isZodError(err: unknown): err is ZodError;
2
+ import { $ZodError } from 'zod/v4/core';
3
+ export declare function isZodError(err: unknown): err is ZodError | $ZodError;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isZodError = isZodError;
4
4
  const zod_1 = require("zod");
5
+ const core_1 = require("zod/v4/core");
5
6
  function isZodError(err) {
6
- return !!err && (err instanceof zod_1.ZodError || (err instanceof Error && err.name === 'ZodError'));
7
+ return !!err && (err instanceof zod_1.ZodError || err instanceof core_1.$ZodError || (err instanceof Error && (err.name === 'ZodError' || err.name === '$ZodError')));
7
8
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptolemy2002/zod-utils",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "private": false,
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -32,6 +32,7 @@
32
32
  "zod": "^4.3.6"
33
33
  },
34
34
  "devDependencies": {
35
+ "@types/is-callable": "^1.1.2",
35
36
  "@types/jest": "^29.5.0",
36
37
  "@types/node": "^25.3.5",
37
38
  "jest": "^29.5.0",
@@ -40,5 +41,8 @@
40
41
  "tsconfig-paths": "^4.2.0",
41
42
  "typescript-transform-paths": "^3.5.3",
42
43
  "zod": "^4.3.6"
44
+ },
45
+ "dependencies": {
46
+ "is-callable": "^1.2.7"
43
47
  }
44
48
  }