zod-to-x
Version:
Multi language types generation from Zod schemas.
80 lines (79 loc) • 2.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Extended = void 0;
exports.extendZod = extendZod;
const v4_1 = require("zod/v4");
function getZod2XConstructor() {
return function (opt, value) {
if (typeof opt === "string" && value !== undefined) {
this._zod2x[opt] = value;
return this;
}
const newItem = this.meta(Object.assign({}, (this.meta() || {})));
newItem._zod2x = typeof opt === "string" ? { typeName: opt } : opt;
return newItem;
};
}
/**
* Extends the Zod library by adding custom methods to its prototypes, enabling
* additional functionality required by the `zod-to-x` package. This function
* must be executed after importing Zod to ensure the extensions are applied
* correctly.
*
* @param zod - The Zod library instance to be extended. This is typically the
* default export or namespace import from the `zod` package.
*
* @remarks
* This function modifies the prototypes of several Zod types, including
* `ZodObject`, `ZodEnum`, `ZodDiscriminatedUnion`, `ZodUnion`, `ZodIntersection`, and `ZodLiteral`.
* It ensures that each type has a `zod2x` method, which is required for the `zod-to-x` package to
* function properly.
*
* Usage:
* ```typescript
* import * as zod from "zod";
* import { extendZod } from "zod-to-x";
*
* extendZod(zod);
* ```
*/
function extendZod(zod /*typeof z ---> any type until solve type incompatibilities*/) {
// Ensure single definitions
if (typeof zod.ZodObject.prototype.zod2x === "undefined") {
zod.ZodObject.prototype.zod2x = getZod2XConstructor();
}
if (typeof zod.ZodEnum.prototype.zod2x === "undefined") {
zod.ZodEnum.prototype.zod2x = getZod2XConstructor();
}
if (typeof zod.ZodUnion.prototype.zod2x === "undefined") {
// Valid also for ZodDiscriminatedUnion
zod.ZodUnion.prototype.zod2x = getZod2XConstructor();
}
if (typeof zod.ZodIntersection.prototype.zod2x === "undefined") {
zod.ZodIntersection.prototype.zod2x = getZod2XConstructor();
}
if (typeof zod.ZodLiteral.prototype.zod2x === "undefined") {
zod.ZodLiteral.prototype.zod2x = function (opt) {
const newItem = this.meta(Object.assign({}, (this.meta() || {})));
newItem._zod2x =
opt instanceof zod.ZodEnum || opt instanceof zod.ZodNativeEnum
? { parentEnum: opt }
: opt;
return newItem;
};
}
Extended.setZ(zod);
}
/**
* Enforcing the same instance of Zod used by user. This resolves Bun incompatibilities.
*/
class Extended {
static getZ() {
return this.zExt;
}
static setZ(zod) {
this.zExt = zod;
}
}
exports.Extended = Extended;
Extended.zExt = v4_1.z;