UNPKG

zod-to-x

Version:

Multi language types generation from Zod schemas.

70 lines (69 loc) 2.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.extendZod = extendZod; function getZod2XConstructor() { return function (opt, value) { if (typeof opt === "string" && value !== undefined) { this._zod2x[opt] = value; return this; } const newItem = new this.constructor(Object.assign({}, this._def)); 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`, `ZodNativeEnum`, `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.ZodNativeEnum.prototype.zod2x === "undefined") { zod.ZodNativeEnum.prototype.zod2x = getZod2XConstructor(); } if (typeof zod.ZodDiscriminatedUnion.prototype.zod2x === "undefined") { zod.ZodDiscriminatedUnion.prototype.zod2x = getZod2XConstructor(); } if (typeof zod.ZodUnion.prototype.zod2x === "undefined") { 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 = new this.constructor(Object.assign({}, this._def)); newItem._zod2x = opt instanceof zod.ZodEnum || opt instanceof zod.ZodNativeEnum ? { parentEnum: opt } : opt; return newItem; }; } }