v2
This commit is contained in:
+57
@@ -0,0 +1,57 @@
|
||||
import * as core from "../core/index.js";
|
||||
import { $ZodError } from "../core/index.js";
|
||||
import * as util from "../core/util.js";
|
||||
/* Prototypes that already carry the lazy helper methods. Seeded with the
|
||||
* intrinsics so that `init` on a foreign object — it accepts any object —
|
||||
* can never install an accessor onto a prototype we do not own. */
|
||||
const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
|
||||
/* Helper methods live as non-enumerable lazy getters on the shared
|
||||
* prototype instead of own properties on every instance. On first
|
||||
* access the getter allocates the per-instance closure and caches it
|
||||
* as a non-enumerable own property, so detached usage still works and
|
||||
* the allocation only happens for methods actually touched. */
|
||||
function _lazyMethod(proto, key, make) {
|
||||
Object.defineProperty(proto, key, {
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
get() {
|
||||
const value = make(this);
|
||||
Object.defineProperty(this, key, { value, configurable: true, writable: true });
|
||||
return value;
|
||||
},
|
||||
set(value) {
|
||||
Object.defineProperty(this, key, { value, configurable: true, writable: true });
|
||||
},
|
||||
});
|
||||
}
|
||||
const initializer = (inst, issues) => {
|
||||
$ZodError.init(inst, issues);
|
||||
inst.name = "ZodError";
|
||||
const proto = Object.getPrototypeOf(inst);
|
||||
if (_installedErrorProtos.has(proto))
|
||||
return;
|
||||
_installedErrorProtos.add(proto);
|
||||
_lazyMethod(proto, "format", (self) => (mapper) => core.formatError(self, mapper));
|
||||
_lazyMethod(proto, "flatten", (self) => (mapper) => core.flattenError(self, mapper));
|
||||
_lazyMethod(proto, "addIssue", (self) => (issue) => {
|
||||
self.issues.push(issue);
|
||||
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
|
||||
});
|
||||
_lazyMethod(proto, "addIssues", (self) => (issues) => {
|
||||
self.issues.push(...issues);
|
||||
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
|
||||
});
|
||||
Object.defineProperty(proto, "isEmpty", {
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
get() {
|
||||
return this.issues.length === 0;
|
||||
},
|
||||
});
|
||||
};
|
||||
export const ZodError = /*@__PURE__*/ core.$constructor("ZodError", initializer);
|
||||
export const ZodRealError = /*@__PURE__*/ core.$constructor("ZodError", initializer, undefined, {
|
||||
Parent: Error,
|
||||
});
|
||||
// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
|
||||
// export type ErrorMapCtx = core.$ZodErrorMapCtx;
|
||||
Reference in New Issue
Block a user