@ptolemy2002/zod-utils 1.3.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 +1 -0
- package/dist/function.d.ts +16 -2
- package/dist/function.js +92 -7
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/issuePathStartsWith.d.ts +1 -0
- package/dist/issuePathStartsWith.js +10 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,6 +7,7 @@ Various utilities for working with Zod schemas.
|
|
|
7
7
|
- [clone](docs/util/clone.md) - Utility for cloning Zod schemas without affecting the original
|
|
8
8
|
- [function](docs/util/function.md) - Schema factory for validating callable functions with input/output schemas
|
|
9
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
|
|
10
11
|
- [prefixIssuePath](docs/util/prefixIssuePath.md) - Utility for prepending a path prefix to a Zod issue
|
|
11
12
|
- [typeGuards](docs/util/typeGuards.md) - Type guards for Zod-related values
|
|
12
13
|
- [validate](docs/util/validate.md) - Schema-wrapping factories for creating validators
|
package/dist/function.d.ts
CHANGED
|
@@ -1,9 +1,23 @@
|
|
|
1
|
-
import z, { ZodArray, ZodUnknown } from "zod";
|
|
1
|
+
import z, { ZodArray, ZodType, ZodUnknown } from "zod";
|
|
2
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
|
+
};
|
|
3
13
|
export type ZodFunctionParseOptions<In extends $ZodFunctionArgs, Out extends $ZodFunctionOut> = {
|
|
4
14
|
input?: In;
|
|
5
15
|
output?: Out;
|
|
6
16
|
inputPath?: PropertyKey | PropertyKey[];
|
|
7
17
|
outputPath?: PropertyKey | PropertyKey[];
|
|
8
18
|
};
|
|
9
|
-
export
|
|
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>>;
|
package/dist/function.js
CHANGED
|
@@ -36,12 +36,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
36
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
37
|
};
|
|
38
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.zodValidatedFunction = zodValidatedFunction;
|
|
39
40
|
exports.zodFunctionSchema = zodFunctionSchema;
|
|
40
41
|
const zod_1 = __importStar(require("zod"));
|
|
41
42
|
const typeGuards_1 = require("./typeGuards");
|
|
42
43
|
const prefixIssuePath_1 = require("./prefixIssuePath");
|
|
44
|
+
const issuePathStartsWith_1 = require("./issuePathStartsWith");
|
|
43
45
|
const is_callable_1 = __importDefault(require("is-callable"));
|
|
44
|
-
|
|
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() } = {}) {
|
|
45
48
|
if (!(0, is_callable_1.default)(func)) {
|
|
46
49
|
throw new zod_1.ZodError([{
|
|
47
50
|
message: `Expected a callable function, but received ${typeof func}`,
|
|
@@ -51,32 +54,114 @@ function zodFunctionParse(func, { inputPath = "args", outputPath = "return", inp
|
|
|
51
54
|
}]);
|
|
52
55
|
}
|
|
53
56
|
const functionFactory = zod_1.default.function({ input, output });
|
|
54
|
-
const wrappedFunction = (setReachedCaller, ...args) => {
|
|
57
|
+
const wrappedFunction = (setReachedCaller, setFinishedCall, ...args) => {
|
|
55
58
|
setReachedCaller(true);
|
|
56
|
-
|
|
59
|
+
const result = func(...args);
|
|
60
|
+
setFinishedCall(true);
|
|
61
|
+
return result;
|
|
57
62
|
};
|
|
58
63
|
return (...args) => {
|
|
59
64
|
// This is how we will differentiate between argument and
|
|
60
65
|
// parameter validation errors
|
|
61
66
|
let reachedCaller = false;
|
|
67
|
+
let finishedCall = false;
|
|
62
68
|
try {
|
|
63
|
-
const implementedFunction = functionFactory.implement(((...args) => wrappedFunction((v) => (reachedCaller = v), ...args)));
|
|
69
|
+
const implementedFunction = functionFactory.implement(((...args) => wrappedFunction((v) => (reachedCaller = v), (v) => (finishedCall = v), ...args)));
|
|
64
70
|
return implementedFunction(...args);
|
|
65
71
|
}
|
|
66
72
|
catch (e) {
|
|
67
73
|
if ((0, typeGuards_1.isZodError)(e)) {
|
|
68
|
-
|
|
74
|
+
if (!reachedCaller || finishedCall)
|
|
75
|
+
e = new zod_1.ZodError(e.issues.map(i => (0, prefixIssuePath_1.prefixZodIssuePath)(i, reachedCaller ? outputPath : inputPath)));
|
|
69
76
|
}
|
|
70
77
|
throw e;
|
|
71
78
|
}
|
|
79
|
+
finally {
|
|
80
|
+
// Reset reachedCaller and finishedCall for the next call
|
|
81
|
+
reachedCaller = false;
|
|
82
|
+
finishedCall = false;
|
|
83
|
+
}
|
|
72
84
|
};
|
|
73
85
|
}
|
|
74
|
-
function zodFunctionSchema(options = {}) {
|
|
86
|
+
function zodFunctionSchema({ trials = [], inputPath = "args", outputPath = "return", ...options } = {}) {
|
|
75
87
|
// Transform the input value using zodFunctionParse
|
|
76
88
|
// so that this schema can be used to validate functions
|
|
77
89
|
return zod_1.default.any().transform((v, ctx) => {
|
|
78
90
|
try {
|
|
79
|
-
|
|
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;
|
|
80
165
|
}
|
|
81
166
|
catch (e) {
|
|
82
167
|
if ((0, typeGuards_1.isZodError)(e)) {
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -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
|
+
}
|