UNPKG

@duplojs/zod-accelerator

Version:

[![NPM version](https://img.shields.io/npm/v/@duplojs/zod-accelerator)](https://www.npmjs.com/package/@duplojs/zod-accelerator)

1,360 lines (1,315 loc) 57.1 kB
import * as zod from 'zod'; import { ZodError, ZodArray, ZodCatch, ZodDefault, ZodEffects, ZodIntersection, ZodLazy, ZodMap, ZodNullable, ZodObject, ZodOptional, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodSet, ZodTuple, ZodUnion, z } from 'zod'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; class ZodAcceleratorError extends ZodError { passedPath; passedMessage; constructor(passedPath, passedMessage, issue) { super([ { code: "custom", message: `${passedPath} : ${passedMessage}`, path: passedPath === "." ? [] : passedPath.substring(1).split("."), ...issue, }, ]); this.passedPath = passedPath; this.passedMessage = passedMessage; } } const shadowEval = eval; class ZodAcceleratorContent { static replacerList = { $input: "{id}_input", $output: "{id}_output", "$this.": "this.{id}_", $id: "{id}", }; static inc = 0; id = ZodAcceleratorContent.generateId(); content = []; ctx = {}; addContent(...content) { this.content.push(...content.map((value) => { if (typeof value === "string") { return value; } else if (!value || value === true) { return ""; } else if (value instanceof Array) { this.addContext(value[0].ctx); return value[0].exportContent({ path: value[1].path ? this.replacer(value[1].path) : null, input: this.replacer(value[1].input), output: this.replacer(value[1].output), }); } if (value.ctx) { this.addContext(value.ctx); } if (value.content) { return value.content; } return ` if(${value.if ?? "true"}){ return /* cut_execution */ {success: false, error: new ZodAcceleratorError(\`$path\`, "${value.message ?? ""}")}; } `; })); } addContext(ctx) { Object.entries(ctx).forEach(([key, value]) => { if (key.startsWith("duploj$")) { this.ctx[key] = value; } else { this.ctx[`${this.id}_${key}`] = value; } }); } exportContent(params) { const content = this.replacer([ /* js */ `let $input = ${params.input};`, ...this.content, /* js */ `${params.output} = $input;`, ] .join("\n")); if (params.path) { return content.replaceAll("$path", `$path.${params.path}`); } else { return content; } } toFunction() { const functionContent = this.replacer([ "function ($input){", /* js */ "const ZodAcceleratorError = this.ZodAcceleratorError;", ...this.content, /* js */ "return /* cut_execution */ {success: true, data: $input};", "}", ] .join("\n")) .replace(/\$path\.?/g, "."); const fnc = shadowEval(`(${functionContent.includes("await") ? "async " : ""}${functionContent})`); return fnc.bind({ ZodAcceleratorError: ZodAcceleratorError, ...this.ctx, }); } replacer(content) { let remplecedContent = content; Object.entries(ZodAcceleratorContent.replacerList).forEach(([key, value]) => { remplecedContent = remplecedContent.replaceAll(key, value.replace("{id}", this.id)); }); return remplecedContent; } static generateId() { return `duploj$${(this.inc++)}`; } } class ZodAcceleratorParser { buidledParse; get isAsync() { return this.buidledParse.constructor.name === "AsyncFunction"; } constructor(buidledParse) { this.buidledParse = buidledParse; } safeParse(input) { const result = this.buidledParse(input); if (result instanceof Promise) { return { success: false, error: new ZodAcceleratorError(".", "Parse function is async."), }; } return result; } async safeParseAsync(input) { return this.buidledParse(input); } parse(input) { const result = this.safeParse(input); if (result.success) { return result.data; } else { throw result.error; } } async parseAsync(input) { const result = await this.buidledParse(input); if (result.success) { return result.data; } else { throw result.error; } } } function zodSchemaIsAsync(zodSchema, lazyMap = new Set()) { if (lazyMap.has(zodSchema)) { return false; } lazyMap.add(zodSchema); if (zodSchema instanceof ZodArray) { return zodSchemaIsAsync(zodSchema._def.type, lazyMap); } else if (zodSchema instanceof ZodCatch) { return zodSchemaIsAsync(zodSchema._def.innerType, lazyMap); } else if (zodSchema instanceof ZodDefault) { return zodSchemaIsAsync(zodSchema._def.innerType, lazyMap); } else if (zodSchema instanceof ZodEffects) { if ((zodSchema._def.effect.type === "transform" || zodSchema._def.effect.type === "preprocess") && zodSchema._def.effect.transform.constructor.name === "AsyncFunction") { return true; } else if (zodSchema._def.effect.type === "refinement" && zodSchema._def.effect.refinement.constructor.name === "AsyncFunction") { return true; } else if (zodSchemaIsAsync(zodSchema._def.schema, lazyMap)) { return true; } else { const effectFunction = zodSchema._def.effect.type === "refinement" ? zodSchema._def.effect.refinement : zodSchema._def.effect.transform; function anyFunction() { return void 0; } const impossibleErrorProxy = new Proxy(anyFunction, { get() { return impossibleErrorProxy; }, construct() { return impossibleErrorProxy; }, set() { return true; }, apply() { return impossibleErrorProxy; }, }); try { const result = effectFunction(impossibleErrorProxy, { addIssue: () => void undefined, path: [], }); if (result instanceof Promise) { result.catch(() => void undefined); } return result instanceof Promise; } catch { return false; } } } else if (zodSchema instanceof ZodIntersection && (zodSchemaIsAsync(zodSchema._def.left, lazyMap) || zodSchemaIsAsync(zodSchema._def.right, lazyMap))) { return true; } else if (zodSchema instanceof ZodLazy) { return zodSchemaIsAsync(zodSchema._def.getter(), lazyMap); } else if (zodSchema instanceof ZodMap) { return zodSchemaIsAsync(zodSchema._def.keyType, lazyMap) || zodSchemaIsAsync(zodSchema._def.valueType, lazyMap); } else if (zodSchema instanceof ZodNullable) { return zodSchemaIsAsync(zodSchema._def.innerType, lazyMap); } else if (zodSchema instanceof ZodObject) { return !Object.values(zodSchema._def.shape()) .every((value) => !zodSchemaIsAsync(value, lazyMap)); } else if (zodSchema instanceof ZodOptional) { return zodSchemaIsAsync(zodSchema._def.innerType, lazyMap); } else if (zodSchema instanceof ZodPipeline) { return zodSchemaIsAsync(zodSchema._def.in, lazyMap) || zodSchemaIsAsync(zodSchema._def.out, lazyMap); } else if (zodSchema instanceof ZodPromise) { return true; } else if (zodSchema instanceof ZodReadonly) { return zodSchemaIsAsync(zodSchema._def.innerType, lazyMap); } else if (zodSchema instanceof ZodRecord && (zodSchemaIsAsync(zodSchema._def.keyType, lazyMap) || zodSchemaIsAsync(zodSchema._def.valueType, lazyMap))) { return true; } else if (zodSchema instanceof ZodSet) { return zodSchemaIsAsync(zodSchema._def.valueType, lazyMap); } else if (zodSchema instanceof ZodTuple) { return !zodSchema._def.items .every((value) => !zodSchemaIsAsync(value, lazyMap)) || zodSchemaIsAsync(zodSchema._def.rest, lazyMap); } else if (zodSchema instanceof ZodUnion) { return !zodSchema._def.options .every((value) => !zodSchemaIsAsync(value, lazyMap)); } return false; } class ZodAccelerator { static accelerators = []; static zod = z; static findAcceleratorContent(zodSchema, ignoreSchemaAccelerator = false) { for (const accelerator of this.accelerators) { if (zodSchema instanceof accelerator.support) { const zac = new ZodAcceleratorContent(); if (zodSchema.accelerator !== undefined && ignoreSchemaAccelerator === false) { zac.addContext({ zodSchema, }); const isAsync = zodSchemaIsAsync(zodSchema); const parseMethod = isAsync ? "safeParseAsync" : "safeParse"; const mayBeAwait = isAsync ? "await" : ""; zac.addContent(` let $output = ${mayBeAwait} $this.zodSchema.accelerator.${parseMethod}($input); if($output.success === false){ return /* cut_execution */ {success: false, error: new ZodAcceleratorError($output.error.passedPath.replace(".", \`$path.\`), $output.error.passedMessage)} } $input = $output.data; `); return zac; } return accelerator.makeAcceleratorContent(zodSchema, zac); } } throw new Error(`No accelerator found for type: ${zodSchema.constructor.name}`); } static build(zodSchema) { zodSchema.accelerator = new ZodAcceleratorParser(() => ({ success: false, error: new ZodAcceleratorError("", ""), })); const accelerator = new ZodAcceleratorParser(this.findAcceleratorContent(zodSchema, true).toFunction()); zodSchema.accelerator = accelerator; return accelerator; } static autoInstance(zodAccelerator) { ZodAccelerator.accelerators.unshift(new zodAccelerator()); } static injectZod(zod) { this.zod = zod; } } let ZodTypeAccelerator = class ZodTypeAccelerator extends ZodAccelerator { get support() { return ZodAccelerator.zod.ZodType; } makeAcceleratorContent(zodSchema, zac) { const isAsync = zodSchemaIsAsync(zodSchema); const parseMethod = isAsync ? "safeParseAsync" : "safeParse"; const mayBeAwait = isAsync ? "await" : ""; zac.addContent({ content: ` const $output = ${mayBeAwait} $this.zodSchema.${parseMethod}($input); if($output.success === false){ return /* cut_execution */ {success: false, error: new ZodAcceleratorError(\`$path\`, "ZodSchema Fail parse.")}; } $input = $output.data; `, ctx: { zodSchema, }, }); return zac; } }; ZodTypeAccelerator = __decorate([ ZodAccelerator.autoInstance ], ZodTypeAccelerator); var ZodStringAccelerator_1; let ZodStringAccelerator = class ZodStringAccelerator extends ZodAccelerator { static { ZodStringAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodString; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; zac.addContent(def.coerce ? ZodStringAccelerator_1.stringPart.coerce() : ZodStringAccelerator_1.stringPart.typeof(), ...def.checks.map((check) => ZodStringAccelerator_1.stringPart[check.kind]?.(check))); return zac; } static stringPart = { coerce: () => ({ content: /* js */ ` $input = new String($input).valueOf(); `, }), typeof: () => ({ if: /* js */ "(typeof $input !== \"string\")", message: "Input is not a String.", }), min: ({ value }) => ({ if: /* js */ `$input.length < ${value}`, message: `Input String has length less than ${value}.`, }), max: ({ value }) => ({ if: /* js */ `$input.length > ${value}`, message: `Input String has length more than ${value}.`, }), length: ({ value }) => ({ if: /* js */ `$input.length !== ${value}`, message: `Input String has length not equal to ${value}.`, }), email: () => ({ if: /* js */ "!this.duploj$RegexEmail.test($input)", message: "Input string is not an Email.", ctx: { duploj$RegexEmail: /^(?!\.)(?!.*\.\.)([A-Z0-9_+-.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i }, }), url: () => ` try { new URL($input); } catch (error) { return /* cut_execution */ {success: false, error: new ZodAcceleratorError(\`$path\`, "Input String is not an url.")}; } `, emoji: () => ({ if: /* js */ "!this.duploj$RegexEmoji.test($input)", message: "Input String is not an emoji.", ctx: { duploj$RegexEmoji: /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u }, }), uuid: () => ({ if: /* js */ "!this.duploj$RegexUuid.test($input)", message: "Input String is not an uuid.", ctx: { duploj$RegexUuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i }, }), cuid: () => ({ if: /* js */ "!this.duploj$RegexCuid.test($input)", message: "Input String is not an cuid.", ctx: { duploj$RegexCuid: /^c[^\s-]{8,}$/i }, }), includes: ({ value, position }) => ({ if: /* js */ `!$input.includes("${value}", ${position ?? ""})`, message: `Input String not includes ${value}.`, }), cuid2: () => ({ if: /* js */ "!this.duploj$RegexCuid2.test($input)", message: "Input String is not an cuid2.", ctx: { duploj$RegexCuid2: /^[a-z][a-z0-9]*$/ }, }), ulid: () => ({ if: /* js */ "!this.duploj$RegexUlid.test($input)", message: "Input String is not an ulid.", ctx: { duploj$RegexUlid: /^[0-9A-HJKMNP-TV-Z]{26}$/ }, }), startsWith: ({ value }) => ({ if: /* js */ `!$input.startsWith("${value}")`, message: `Input String not starts with ${value}.`, }), endsWith: ({ value }) => ({ if: /* js */ `!$input.endsWith("${value}")`, message: `Input String not ends with ${value}.`, }), regex: ({ regex }) => ({ if: /* js */ "!$this.regexCustom.test($input)", message: `Input String not match with regex ${regex.source}.`, ctx: { regexCustom: regex }, }), trim: () => /* js */ ` $input = $input.trim(); `, toUpperCase: () => /* js */ ` $input = $input.toUpperCase(); `, toLowerCase: () => /* js */ ` $input = $input.toLowerCase(); `, datetime: ({ precision, offset }) => { const ctx = {}; if (precision) { if (offset) { ctx.regexDatetime = shadowEval(`/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$/`); } else { ctx.regexDatetime = shadowEval(`/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${precision}}Z$/`); } } else if (precision === 0) { if (offset) { ctx.regexDatetime = shadowEval("/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$/"); } else { ctx.regexDatetime = shadowEval("/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$/"); } } else if (offset) { ctx.regexDatetime = shadowEval("/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$/"); } else { ctx.regexDatetime = shadowEval("/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/"); } return { if: /* js */ "!$this.regexDatetime.test($input)", message: "Input String is not a datetime.", ctx, }; }, ip: ({ version }) => { if (version === "v4") { return { if: /* js */ "!this.duploj$RegexIpv4.test($input)", message: "Input String is not an ipv4.", ctx: { duploj$RegexIpv4: /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/ }, }; } else if (version === "v6") { return { if: /* js */ "!this.duploj$RegexIpv6.test($input)", message: "Input String is not an ipv6.", ctx: { duploj$RegexIpv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, }, }; } else { return { if: /* js */ "!this.duploj$RegexIpv4.test($input) && !this.duploj$RegexIpv6.test($input)", message: "Input String is not an ipv4 or ipv6.", ctx: { duploj$RegexIpv4: /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/, duploj$RegexIpv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, }, }; } }, }; }; ZodStringAccelerator = ZodStringAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodStringAccelerator); var ZodNumberAccelerator_1; let ZodNumberAccelerator = class ZodNumberAccelerator extends ZodAccelerator { static { ZodNumberAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodNumber; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; zac.addContent(def.coerce ? ZodNumberAccelerator_1.contentPart.coerce() : ZodNumberAccelerator_1.contentPart.typeof(), ...def.checks.map((check) => ZodNumberAccelerator_1.contentPart[check.kind]?.(check))); return zac; } static contentPart = { coerce: () => ` $input = new Number($input).valueOf(); if(Number.isNaN($input)){ return /* cut_execution */ {success: false, error: new ZodAcceleratorError(\`$path\`, "Input is not a Number.")}; } `, typeof: () => ({ if: /* js */ "(typeof $input !== \"number\" || Number.isNaN($input))", message: "Input is not a Number.", }), min: ({ value, inclusive }) => ({ if: /* js */ `$input <${!inclusive ? "=" : ""} ${value}`, message: `Input Number is less ${!inclusive ? "or equal " : ""}than ${value}.`, }), max: ({ value, inclusive }) => ({ if: /* js */ `$input >${!inclusive ? "=" : ""} ${value}`, message: `Input Number is more ${!inclusive ? "or equal " : ""}than ${value}.`, }), int: () => ({ if: /* js */ "!Number.isInteger($input)", message: "Input is not Int.", }), multipleOf: ({ value }) => ({ if: /* js */ `this.duploj$floatSafeRemainder($input, ${value}) !== 0`, message: `Input Number is not multiple of ${value}.`, ctx: { duploj$floatSafeRemainder: ZodNumberAccelerator_1.floatSafeRemainder }, }), finite: () => ({ if: /* js */ "!Number.isFinite($input)", message: "Input Number is not finite.", }), }; static floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); return (valInt % stepInt) / Math.pow(10, decCount); } }; ZodNumberAccelerator = ZodNumberAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodNumberAccelerator); var ZodObjectAccelerator_1; let ZodObjectAccelerator = class ZodObjectAccelerator extends ZodAccelerator { static { ZodObjectAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodObject; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; const shape = def.shape(); zac.addContext({ shape: Object.keys(shape).reduce((pv, cv) => { pv[cv] = true; return pv; }, {}), }); zac.addContent("let $output = {};", ZodObjectAccelerator_1.contentPart.typeof()); Object.entries(shape).forEach(([key, zodSchema]) => { const propsZac = ZodAccelerator.findAcceleratorContent(zodSchema); if (zodSchema instanceof ZodAccelerator.zod.ZodUndefined || zodSchema instanceof ZodAccelerator.zod.ZodVoid || zodSchema instanceof ZodAccelerator.zod.ZodUnknown || zodSchema instanceof ZodAccelerator.zod.ZodAny || zodSchema instanceof ZodAccelerator.zod.ZodOptional || zodSchema instanceof ZodAccelerator.zod.ZodDefault || (zodSchema instanceof ZodAccelerator.zod.ZodLiteral && zodSchema._def.value === undefined)) { zac.addContent([ propsZac, { path: key, input: `$input["${key}"]`, output: "//", }, ], /* js */ ` if(${propsZac.replacer("$input")} != undefined){ $output["${key}"] = ${propsZac.replacer("$input")} } `); } else { zac.addContent([ propsZac, { path: key, input: `$input["${key}"]`, output: `$output["${key}"]`, }, ]); } }); zac.addContent(def.unknownKeys !== "strict" || ZodObjectAccelerator_1.contentPart.strict(), def.unknownKeys !== "passthrough" || ZodObjectAccelerator_1.contentPart.passthrough(), "$input = $output"); return zac; } static contentPart = { typeof: () => ({ if: /* js */ ` typeof $input !== "object" || $input === null || $input instanceof Array || $input instanceof Promise `, message: "Input is not Object.", }), strict: () => ` for(let key in $input){ if(!$this.shape[key]){ return /* cut_execution */ {success: false, error: new ZodAcceleratorError(\`$path.\${key}\`, "Input Object has key to many.")}; } } `, passthrough: () => ` for(let key in $input){ if(!$this.shape[key]){ $output[key] = $input[key]; } } `, }; }; ZodObjectAccelerator = ZodObjectAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodObjectAccelerator); var ZodArrayAccelerator_1; let ZodArrayAccelerator = class ZodArrayAccelerator extends ZodAccelerator { static { ZodArrayAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodArray; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; const zacType = ZodAccelerator.findAcceleratorContent(def.type); zac.addContent("let $output = [];", ZodArrayAccelerator_1.contentPart.typeof(), def.minLength ? ZodArrayAccelerator_1.contentPart.min(def.minLength) : null, def.maxLength ? ZodArrayAccelerator_1.contentPart.max(def.maxLength) : null, def.exactLength ? ZodArrayAccelerator_1.contentPart.exact(def.exactLength) : null, "for(let index = 0; index < $input.length; index++){", [ zacType, { path: "[Array ${index}]", input: "$input[index]", output: "$output[index]", }, ], "}", "$input = $output"); return zac; } static contentPart = { typeof: () => ({ if: /* js */ "!($input instanceof Array)", message: "Input is not Array.", }), min: ({ value }) => ({ if: /* js */ `$input.length < ${value}`, message: `Input Array has length less than ${value}.`, }), max: ({ value }) => ({ if: /* js */ `$input.length > ${value}`, message: `Input Array has length more than ${value}.`, }), exact: ({ value }) => ({ if: /* js */ `$input.length !== ${value}`, message: `Input Array has length not equal to ${value}.`, }), }; }; ZodArrayAccelerator = ZodArrayAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodArrayAccelerator); var ZodEnumAccelerator_1; let ZodEnumAccelerator = class ZodEnumAccelerator extends ZodAccelerator { static { ZodEnumAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodEnum; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; zac.addContent(ZodEnumAccelerator_1.contentPart.enum(def.values)); return zac; } static contentPart = { enum: (values) => ({ if: values.map((value) => `"${value}" !== $input`).join(" && "), message: `Input is not equal to ${values.join(" or ")}.`, }), }; }; ZodEnumAccelerator = ZodEnumAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodEnumAccelerator); var ZodBooleanAccelerator_1; let ZodBooleanAccelerator = class ZodBooleanAccelerator extends ZodAccelerator { static { ZodBooleanAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodBoolean; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; zac.addContent(def.coerce ? ZodBooleanAccelerator_1.contentPart.coerce() : ZodBooleanAccelerator_1.contentPart.typeof()); return zac; } static contentPart = { coerce: () => /* js */ ` $input = Boolean($input).valueOf(); `, typeof: () => ({ if: /* js */ "(typeof $input !== \"boolean\")", message: "Input is not boolean.", }), }; }; ZodBooleanAccelerator = ZodBooleanAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodBooleanAccelerator); let ZodNullableAccelerator$1 = class ZodNullableAccelerator extends ZodAccelerator { get support() { return ZodAccelerator.zod.ZodNullable; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; const zacInnerType = ZodAccelerator.findAcceleratorContent(def.innerType); zac.addContent("if($input !== null){", [ zacInnerType, { path: null, input: "$input", output: "$input", }, ], "}"); return zac; } static contentPart = {}; }; ZodNullableAccelerator$1 = __decorate([ ZodAccelerator.autoInstance ], ZodNullableAccelerator$1); var ZodDateAccelerator_1; let ZodDateAccelerator = class ZodDateAccelerator extends ZodAccelerator { static { ZodDateAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodDate; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; zac.addContent(def.coerce ? ZodDateAccelerator_1.contentPart.coerce() : ZodDateAccelerator_1.contentPart.typeof(), ...def.checks.map((value) => ZodDateAccelerator_1.contentPart[value.kind]?.(value))); return zac; } static contentPart = { coerce: () => ` $input = new Date($input); if(isNaN($input.getTime())){ return /* cut_execution */ {success: false, error: new ZodAcceleratorError(\`$path\`, "Input is invalide Date.")}; } `, typeof: () => ({ if: /* js */ "!($input instanceof Date)", message: "Input is invalide Date.", }), min: ({ value }) => ({ if: /* js */ `$input.getTime() < ${value}`, message: `Input Date is less than ${value}.`, }), max: ({ value }) => ({ if: /* js */ `$input.getTime() > ${value}`, message: `Input Date is more than ${value}.`, }), }; }; ZodDateAccelerator = ZodDateAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodDateAccelerator); var ZodSymbolAccelerator_1; let ZodSymbolAccelerator = class ZodSymbolAccelerator extends ZodAccelerator { static { ZodSymbolAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodSymbol; } makeAcceleratorContent(zodSchema, zac) { zac.addContent(ZodSymbolAccelerator_1.contentPart.typeof()); return zac; } static contentPart = { typeof: () => ({ if: /* js */ "(typeof $input !== \"symbol\")", message: "Input is not a Symbol.", }), }; }; ZodSymbolAccelerator = ZodSymbolAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodSymbolAccelerator); var ZodUndefinedAccelerator_1; let ZodUndefinedAccelerator = class ZodUndefinedAccelerator extends ZodAccelerator { static { ZodUndefinedAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodUndefined; } makeAcceleratorContent(zodSchema, zac) { zac.addContent(ZodUndefinedAccelerator_1.contentPart.typeof()); return zac; } static contentPart = { typeof: () => ({ if: /* js */ "(typeof $input !== \"undefined\")", message: "Input is not Undefined.", }), }; }; ZodUndefinedAccelerator = ZodUndefinedAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodUndefinedAccelerator); var ZodNullAccelerator_1; let ZodNullAccelerator = class ZodNullAccelerator extends ZodAccelerator { static { ZodNullAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodNull; } makeAcceleratorContent(zodSchema, zac) { zac.addContent(ZodNullAccelerator_1.contentPart.typeof()); return zac; } static contentPart = { typeof: () => ({ if: /* js */ "$input !== null", message: "Input is not null.", }), }; }; ZodNullAccelerator = ZodNullAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodNullAccelerator); let ZodAnyAccelerator = class ZodAnyAccelerator extends ZodAccelerator { get support() { return ZodAccelerator.zod.ZodAny; } makeAcceleratorContent(zodSchema, zac) { return zac; } static contentPart = {}; }; ZodAnyAccelerator = __decorate([ ZodAccelerator.autoInstance ], ZodAnyAccelerator); let ZodUnknownAccelerator = class ZodUnknownAccelerator extends ZodAnyAccelerator { get support() { return ZodAccelerator.zod.ZodUnknown; } }; ZodUnknownAccelerator = __decorate([ ZodAccelerator.autoInstance ], ZodUnknownAccelerator); var ZodNeverAccelerator_1; let ZodNeverAccelerator = class ZodNeverAccelerator extends ZodAccelerator { static { ZodNeverAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodNever; } makeAcceleratorContent(zodSchema, zac) { zac.addContent(ZodNeverAccelerator_1.contentPart.typeof()); return zac; } static contentPart = { typeof: () => ({ if: /* js */ "true", message: "Input is not never.", }), }; }; ZodNeverAccelerator = ZodNeverAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodNeverAccelerator); let ZodVoidAccelerator = class ZodVoidAccelerator extends ZodUndefinedAccelerator { get support() { return ZodAccelerator.zod.ZodVoid; } }; ZodVoidAccelerator = __decorate([ ZodAccelerator.autoInstance ], ZodVoidAccelerator); var ZodUnionAccelerator_1; let ZodUnionAccelerator = class ZodUnionAccelerator extends ZodAccelerator { static { ZodUnionAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodUnion; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; zac.addContext({ EMPTY: ZodUnionAccelerator_1.EMPTY, }); zac.addContent("let $output = $this.EMPTY;", "let $id_reasons = {}", "$id_union :{"); def.options.forEach((value, index) => { const childZac = ZodAccelerator.findAcceleratorContent(value); const childZacContent = childZac.exportContent({ path: `[Union ${index}]`, input: zac.replacer("$input"), output: zac.replacer("$output"), }); zac.addContext(childZac.ctx); zac.addContent(`$id_union_child_${index} :{`, childZacContent .split("\n") .map((line) => line.includes("return /* cut_execution */") ? `break $id_union_child_${index};` : line) .join("\n"), "break $id_union;", "}"); }); zac.addContent("}", ZodUnionAccelerator_1.contentPart.checkOutput(), "$input = $output;"); return zac; } static contentPart = { checkOutput: () => ` if($output === $this.EMPTY) { return /* cut_execution */ {success: false, error: new ZodAcceleratorError(\`$path\`, "Input has no correspondence in union.")} } `, }; static EMPTY = Symbol("empty"); }; ZodUnionAccelerator = ZodUnionAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodUnionAccelerator); /* eslint-disable @typescript-eslint/no-unsafe-member-access */ var ZodIntersectionAccelerator_1; let ZodIntersectionAccelerator = class ZodIntersectionAccelerator extends ZodAccelerator { static { ZodIntersectionAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodIntersection; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; zac.addContext({ duploj$mergeValues: ZodIntersectionAccelerator_1.mergeValues, }); zac.addContent( /* js */ ` let $id_left_output; let $id_right_output; `); ["left", "right"].forEach((value) => { zac.addContent([ ZodAccelerator.findAcceleratorContent(def[value]), { path: null, input: "$input", output: `$id_${value}_output`, }, ]); }); zac.addContent(ZodIntersectionAccelerator_1.contentPart.mergeValues()); return zac; } static contentPart = { mergeValues: () => ` let $id_resultMergeValues = this.duploj$mergeValues($id_left_output, $id_right_output, \`$path\`); if(!$id_resultMergeValues.success){ return /* cut_execution */ $id_resultMergeValues; } $input = $id_resultMergeValues.data; `, }; static mergeValues(aa, bb, path) { const aType = zod.getParsedType(aa); const bType = zod.getParsedType(bb); if (aa === bb) { return { success: true, data: aa, }; } else if (aType === zod.ZodParsedType.object && bType === zod.ZodParsedType.object) { const bKeys = Object.keys(bb); const sharedKeys = Object.keys(aa).filter((key) => bKeys.includes(key)); const newObj = { ...aa, ...bb, }; for (const key of sharedKeys) { const result = ZodIntersectionAccelerator_1.mergeValues(aa[key], bb[key], path); if (!result.success) { return result; } newObj[key] = result.data; } return { success: true, data: newObj, }; } else if (aType === zod.ZodParsedType.array && bType === zod.ZodParsedType.array) { if (aa.length !== bb.length) { return { success: false, error: new ZodAcceleratorError(path, "Intersection results could not be merged."), }; } const newArray = []; for (let index = 0; index < aa.length; index++) { const itemA = aa[index]; const itemB = bb[index]; const result = ZodIntersectionAccelerator_1.mergeValues(itemA, itemB, path); if (!result.success) { return result; } newArray.push(result.data); } return { success: true, data: newArray, }; } else if (aType === zod.ZodParsedType.date && bType === zod.ZodParsedType.date && Number(aa) === Number(bb)) { return { success: true, data: aa, }; } else { return { success: false, error: new ZodAcceleratorError(path, "Intersection results could not be merged."), }; } } }; ZodIntersectionAccelerator = ZodIntersectionAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodIntersectionAccelerator); var ZodTupleAccelerator_1; let ZodTupleAccelerator = class ZodTupleAccelerator extends ZodAccelerator { static { ZodTupleAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodTuple; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; zac.addContent("let $output = [];", ZodTupleAccelerator_1.contentPart.typeof(), def.rest ? ZodTupleAccelerator_1.contentPart.min({ value: def.items.length }) : ZodTupleAccelerator_1.contentPart.exact({ value: def.items.length })); def.items.forEach((value, index) => { zac.addContent([ ZodAccelerator.findAcceleratorContent(value), { path: `[Tuple ${index}]`, input: `$input[${index}]`, output: `$output[${index}]`, }, ]); }); if (def.rest) { zac.addContent(`for(let $id_index = ${def.items.length}; $id_index < $input.length; $id_index++){`, [ ZodAccelerator.findAcceleratorContent(def.rest), { path: "[Tuple Rest ${$id_index}]", input: "$input[$id_index]", output: "$output[$id_index]", }, ], "}"); } zac.addContent("$input = $output"); return zac; } static contentPart = { ...ZodArrayAccelerator.contentPart, }; }; ZodTupleAccelerator = ZodTupleAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodTupleAccelerator); var ZodDefaultAccelerator_1; let ZodDefaultAccelerator = class ZodDefaultAccelerator extends ZodAccelerator { static { ZodDefaultAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodDefault; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; const zacInnerType = ZodAccelerator.findAcceleratorContent(def.innerType); zac.addContext({ defaultValue: def.defaultValue, }); zac.addContent(ZodDefaultAccelerator_1.contentPart.default(), "else {", [ zacInnerType, { path: null, input: "$input", output: "$input", }, ], "}"); return zac; } static contentPart = { default: () => /* js */ ` if($input === undefined){ $input = $this.defaultValue() } `, }; }; ZodDefaultAccelerator = ZodDefaultAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodDefaultAccelerator); let ZodNullableAccelerator = class ZodNullableAccelerator extends ZodAccelerator { get support() { return ZodAccelerator.zod.ZodBranded; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; const zacInnerType = ZodAccelerator.findAcceleratorContent(def.type); zac.addContent([ zacInnerType, { path: null, input: "$input", output: "$input", }, ]); return zac; } static contentPart = {}; }; ZodNullableAccelerator = __decorate([ ZodAccelerator.autoInstance ], ZodNullableAccelerator); var ZodNanAccelerator_1; let ZodNanAccelerator = class ZodNanAccelerator extends ZodAccelerator { static { ZodNanAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodNaN; } makeAcceleratorContent(zodSchema, zac) { zac.addContent(ZodNanAccelerator_1.contentPart.typeof(), "$input = NaN;"); return zac; } static contentPart = { typeof: () => ({ if: /* js */ "typeof $input !== 'number' || !isNaN($input)", message: "Input is not NaN.", }), }; }; ZodNanAccelerator = ZodNanAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodNanAccelerator); let ZodOptionalAccelerator = class ZodOptionalAccelerator extends ZodAccelerator { get support() { return ZodAccelerator.zod.ZodOptional; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; const zacInnerType = ZodAccelerator.findAcceleratorContent(def.innerType); zac.addContent("if($input !== undefined){", [ zacInnerType, { path: null, input: "$input", output: "$input", }, ], "}"); return zac; } static contentPart = {}; }; ZodOptionalAccelerator = __decorate([ ZodAccelerator.autoInstance ], ZodOptionalAccelerator); let ZodPipelineAccelerator = class ZodPipelineAccelerator extends ZodAccelerator { get support() { return ZodAccelerator.zod.ZodPipeline; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; const zacIn = ZodAccelerator.findAcceleratorContent(def.in); const zacOut = ZodAccelerator.findAcceleratorContent(def.out); zac.addContent([ zacIn, { path: null, input: "$input", output: "$input", }, ], [ zacOut, { path: null, input: "$input", output: "$input", }, ]); return zac; } static contentPart = {}; }; ZodPipelineAccelerator = __decorate([ ZodAccelerator.autoInstance ], ZodPipelineAccelerator); var ZodCatchAccelerator_1; let ZodCatchAccelerator = class ZodCatchAccelerator extends ZodAccelerator { static { ZodCatchAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodCatch; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; const zacInnerType = ZodAccelerator.findAcceleratorContent(def.innerType); const innerTypeZacContent = zacInnerType.exportContent({ path: null, input: zac.replacer("$input"), output: zac.replacer("$output"), }); zac.addContext({ catchValue: def.catchValue, EMPTY: ZodCatchAccelerator_1.EMPTY, }); zac.addContext(zacInnerType.ctx); zac.addContent("let $output = $this.EMPTY;", "$id_catch :{", innerTypeZacContent .split("\n") .map((line) => line.includes("return /* cut_execution */") ? "break $id_catch;" : line) .join("\n"), "}", ZodCatchAccelerator_1.contentPart.checkOutput(), "$input = $output;"); return zac; } static contentPart = { checkOutput: () => /* js */ ` if($output === $this.EMPTY){ $output = $this.catchValue() } `, }; static EMPTY = Symbol("empty"); }; ZodCatchAccelerator = ZodCatchAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodCatchAccelerator); var ZodRecordAccelerator_1; let ZodRecordAccelerator = class ZodRecordAccelerator extends ZodAccelerator { static { ZodRecordAccelerator_1 = this; } get support() { return ZodAccelerator.zod.ZodRecord; } makeAcceleratorContent(zodSchema, zac) { const def = zodSchema._def; const zacValueType = ZodAccelerator.findAcceleratorContent(def.valueType); let keyType = def.keyType; if (keyType instanceof ZodAccelerator.zod.ZodString) { keyType = new ZodAccelerator.zod.ZodString({ ...keyType._def, coerce: true, }); } const zacKeyType = ZodAccelerator.findAcceleratorContent(keyType); zac.addContent("let $output = {};", ZodRecordAccelerator_1.contentPart.typeof(), "for(let $id_key in $input){", [ zacKeyType, { path: "[Record Key \"${$id_key}\"]", input: "$id_key", output: "$id_key", }, ], [ zacValueType, { path: "[Record Value \"${$id_key}\"]", input: "$input[$id_key]", output: "$output[$id_key]", }, ], "}", "$input = $output"); return zac; } static contentPart = { ...ZodObjectAccelerator.contentPart, }; }; ZodRecordAccelerator = ZodRecordAccelerator_1 = __decorate([ ZodAccelerator.autoInstance ], ZodRecordAccelerator); var ZodLiteralAccelerator_1; let ZodLiteralAccelerator = class ZodL