UNPKG

@settlemint/sdk-utils

Version:

Shared utilities and helper functions for SettleMint SDK modules

1,686 lines (1,667 loc) 546 kB
import "node:module"; import { dirname, join, posix, win32 } from "node:path"; import { greenBright, inverse, magentaBright, redBright, whiteBright, yellowBright } from "yoctocolors"; import { spawn } from "node:child_process"; import isInCi from "is-in-ci"; import yoctoSpinner from "yocto-spinner"; import { Table } from "console-table-printer"; import { config } from "@dotenvx/dotenvx"; import { lstat, readFile, readdir, readlink, realpath, stat, writeFile } from "node:fs/promises"; import { findUp } from "find-up"; import { fileURLToPath } from "node:url"; import { lstatSync, readdir as readdir$1, readdirSync, readlinkSync, realpathSync } from "fs"; import * as actualFS from "node:fs"; import { EventEmitter } from "node:events"; import Stream from "node:stream"; import { StringDecoder } from "node:string_decoder"; import { deepmerge } from "deepmerge-ts"; //#region rolldown:runtime var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); //#endregion //#region src/terminal/should-print.ts /** * Returns true if the terminal should print, false otherwise. * @returns true if the terminal should print, false otherwise. */ function shouldPrint() { return process.env.SETTLEMINT_DISABLE_TERMINAL !== "true"; } //#endregion //#region src/terminal/ascii.ts /** * Prints the SettleMint ASCII art logo to the console in magenta color. * Used for CLI branding and visual identification. * * @example * import { ascii } from "@settlemint/sdk-utils/terminal"; * * // Prints the SettleMint logo * ascii(); */ const ascii = () => { if (!shouldPrint()) { return; } console.log(magentaBright(` _________ __ __ .__ _____ .__ __ / _____/ _____/ |__/ |_| | ____ / \\ |__| _____/ |_ \\_____ \\_/ __ \\ __\\ __\\ | _/ __ \\ / \\ / \\| |/ \\ __\\ / \\ ___/| | | | | |_\\ ___// Y \\ | | \\ | /_________/\\_____>__| |__| |____/\\_____>____|____/__|___|__/__| `)); }; //#endregion //#region src/logging/mask-tokens.ts /** * Masks sensitive SettleMint tokens in output text by replacing them with asterisks. * Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT). * * @param output - The text string that may contain sensitive tokens * @returns The text with any sensitive tokens masked with asterisks * @example * import { maskTokens } from "@settlemint/sdk-utils/terminal"; * * // Masks a token in text * const masked = maskTokens("Token: sm_pat_****"); // "Token: ***" */ const maskTokens = (output) => { return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***"); }; //#endregion //#region src/terminal/cancel.ts /** * Error class used to indicate that the operation was cancelled. * This error is used to signal that the operation should be aborted. */ var CancelError = class extends Error {}; /** * Displays an error message in red inverse text and throws a CancelError. * Used to terminate execution with a visible error message. * Any sensitive tokens in the message are masked before display. * * @param msg - The error message to display * @returns never - Function does not return as it throws an error * @example * import { cancel } from "@settlemint/sdk-utils/terminal"; * * // Exits process with error message * cancel("An error occurred"); */ const cancel = (msg) => { console.log(""); console.log(inverse(redBright(maskTokens(msg)))); console.log(""); throw new CancelError(msg); }; //#endregion //#region src/terminal/execute-command.ts /** * Error class for command execution errors * @extends Error */ var CommandError = class extends Error { /** * Constructs a new CommandError * @param message - The error message * @param code - The exit code of the command * @param output - The output of the command */ constructor(message, code, output) { super(message); this.code = code; this.output = output; } }; /** * Executes a command with the given arguments in a child process. * Pipes stdin to the child process and captures stdout/stderr output. * Masks any sensitive tokens in the output before displaying or returning. * * @param command - The command to execute * @param args - Array of arguments to pass to the command * @param options - Options for customizing command execution * @returns Array of output strings from stdout and stderr * @throws {CommandError} If the process fails to start or exits with non-zero code * @example * import { executeCommand } from "@settlemint/sdk-utils/terminal"; * * // Execute git clone * await executeCommand("git", ["clone", "repo-url"]); * * // Execute silently * await executeCommand("npm", ["install"], { silent: true }); */ async function executeCommand(command, args, options) { const { silent,...spawnOptions } = options ?? {}; const child = spawn(command, args, { ...spawnOptions, env: { ...process.env, ...options?.env } }); process.stdin.pipe(child.stdin); const output = []; return new Promise((resolve, reject) => { child.stdout.on("data", (data) => { const maskedData = maskTokens(data.toString()); if (!silent) { process.stdout.write(maskedData); } output.push(maskedData); }); child.stderr.on("data", (data) => { const maskedData = maskTokens(data.toString()); if (!silent) { process.stderr.write(maskedData); } output.push(maskedData); }); child.on("error", (err) => { process.stdin.unpipe(child.stdin); reject(new CommandError(err.message, "code" in err && typeof err.code === "number" ? err.code : 1, output)); }); child.on("close", (code) => { process.stdin.unpipe(child.stdin); if (code === 0 || code === null || code === 143) { resolve(output); return; } reject(new CommandError(`Command "${command}" exited with code ${code}`, code, output)); }); }); } //#endregion //#region src/terminal/intro.ts /** * Displays an introductory message in magenta text with padding. * Any sensitive tokens in the message are masked before display. * * @param msg - The message to display as introduction * @example * import { intro } from "@settlemint/sdk-utils/terminal"; * * // Display intro message * intro("Starting deployment..."); */ const intro = (msg) => { if (!shouldPrint()) { return; } console.log(""); console.log(magentaBright(maskTokens(msg))); console.log(""); }; //#endregion //#region src/terminal/note.ts /** * Displays a note message with optional warning level formatting. * Regular notes are displayed in normal text, while warnings are shown in yellow. * Any sensitive tokens in the message are masked before display. * * @param message - The message to display as a note * @param level - The note level: "info" (default) or "warn" for warning styling * @example * import { note } from "@settlemint/sdk-utils/terminal"; * * // Display info note * note("Operation completed successfully"); * * // Display warning note * note("Low disk space remaining", "warn"); */ const note = (message, level = "info") => { if (!shouldPrint()) { return; } const maskedMessage = maskTokens(message); console.log(""); if (level === "warn") { console.warn(yellowBright(maskedMessage)); return; } console.log(maskedMessage); }; //#endregion //#region src/terminal/list.ts /** * Displays a list of items in a formatted manner, supporting nested items. * * @param title - The title of the list * @param items - The items to display, can be strings or arrays for nested items * @returns The formatted list * @example * import { list } from "@settlemint/sdk-utils/terminal"; * * // Simple list * list("Use cases", ["use case 1", "use case 2", "use case 3"]); * * // Nested list * list("Providers", [ * "AWS", * ["us-east-1", "eu-west-1"], * "Azure", * ["eastus", "westeurope"] * ]); */ function list(title, items) { const formatItems = (items$1) => { return items$1.map((item) => { if (Array.isArray(item)) { return item.map((subItem) => ` • ${subItem}`).join("\n"); } return ` • ${item}`; }).join("\n"); }; return note(`${title}:\n\n${formatItems(items)}`); } //#endregion //#region src/terminal/outro.ts /** * Displays a closing message in green inverted text with padding. * Any sensitive tokens in the message are masked before display. * * @param msg - The message to display as conclusion * @example * import { outro } from "@settlemint/sdk-utils/terminal"; * * // Display outro message * outro("Deployment completed successfully!"); */ const outro = (msg) => { if (!shouldPrint()) { return; } console.log(""); console.log(inverse(greenBright(maskTokens(msg)))); console.log(""); }; //#endregion //#region src/terminal/spinner.ts /** * Error class used to indicate that the spinner operation failed. * This error is used to signal that the operation should be aborted. */ var SpinnerError = class extends Error { constructor(message, originalError) { super(message); this.originalError = originalError; this.name = "SpinnerError"; } }; /** * Displays a loading spinner while executing an async task. * Shows progress with start/stop messages and handles errors. * Spinner is disabled in CI environments. * * @param options - Configuration options for the spinner * @returns The result from the executed task * @throws Will exit process with code 1 if task fails * @example * import { spinner } from "@settlemint/sdk-utils/terminal"; * * // Show spinner during async task * const result = await spinner({ * startMessage: "Deploying...", * task: async () => { * // Async work here * return "success"; * }, * stopMessage: "Deployed successfully!" * }); */ const spinner = async (options) => { const handleError = (error$37) => { const errorMessage = maskTokens(error$37.message); note(redBright(`${errorMessage}\n\n${error$37.stack}`)); throw new SpinnerError(errorMessage, error$37); }; if (isInCi || !shouldPrint()) { try { return await options.task(); } catch (err) { return handleError(err); } } const spinner$1 = yoctoSpinner({ stream: process.stdout }).start(options.startMessage); try { const result = await options.task(spinner$1); spinner$1.success(options.stopMessage); await new Promise((resolve) => process.nextTick(resolve)); return result; } catch (err) { spinner$1.error(redBright(`${options.startMessage} --> Error!`)); return handleError(err); } }; //#endregion //#region src/string.ts /** * Capitalizes the first letter of a string. * * @param val - The string to capitalize * @returns The input string with its first letter capitalized * * @example * import { capitalizeFirstLetter } from "@settlemint/sdk-utils"; * * const capitalized = capitalizeFirstLetter("hello"); * // Returns: "Hello" */ function capitalizeFirstLetter(val) { return String(val).charAt(0).toUpperCase() + String(val).slice(1); } /** * Converts a camelCase string to a human-readable string. * * @param s - The camelCase string to convert * @returns The human-readable string * * @example * import { camelCaseToWords } from "@settlemint/sdk-utils"; * * const words = camelCaseToWords("camelCaseString"); * // Returns: "Camel Case String" */ function camelCaseToWords(s) { const result = s.replace(/([a-z])([A-Z])/g, "$1 $2"); const withSpaces = result.replace(/([A-Z])([a-z])/g, " $1$2"); const capitalized = capitalizeFirstLetter(withSpaces); return capitalized.replace(/\s+/g, " ").trim(); } /** * Replaces underscores and hyphens with spaces. * * @param s - The string to replace underscores and hyphens with spaces * @returns The input string with underscores and hyphens replaced with spaces * * @example * import { replaceUnderscoresAndHyphensWithSpaces } from "@settlemint/sdk-utils"; * * const result = replaceUnderscoresAndHyphensWithSpaces("Already_Spaced-Second"); * // Returns: "Already Spaced Second" */ function replaceUnderscoresAndHyphensWithSpaces(s) { return s.replace(/[-_]/g, " "); } /** * Truncates a string to a maximum length and appends "..." if it is longer. * * @param value - The string to truncate * @param maxLength - The maximum length of the string * @returns The truncated string or the original string if it is shorter than the maximum length * * @example * import { truncate } from "@settlemint/sdk-utils"; * * const truncated = truncate("Hello, world!", 10); * // Returns: "Hello, wor..." */ function truncate(value, maxLength) { if (value.length <= maxLength) { return value; } return `${value.slice(0, maxLength)}...`; } //#endregion //#region src/terminal/table.ts /** * Displays data in a formatted table in the terminal. * * @param title - Title to display above the table * @param data - Array of objects to display in table format * @example * import { table } from "@settlemint/sdk-utils/terminal"; * * const data = [ * { name: "Item 1", value: 100 }, * { name: "Item 2", value: 200 } * ]; * * table("My Table", data); */ function table(title, data) { if (!shouldPrint()) { return; } note(title); if (!data || data.length === 0) { note("No data to display"); return; } const columnKeys = Object.keys(data[0]); const table$1 = new Table({ columns: columnKeys.map((key) => ({ name: key, title: whiteBright(camelCaseToWords(key)), alignment: "left" })) }); table$1.addRows(data); table$1.printTable(); } //#endregion //#region ../../node_modules/zod/dist/esm/v4/core/core.js function $constructor(name, initializer$2, params) { function init(inst, def) { var _a; Object.defineProperty(inst, "_zod", { value: inst._zod ?? {}, enumerable: false }); (_a = inst._zod).traits ?? (_a.traits = new Set()); inst._zod.traits.add(name); initializer$2(inst, def); for (const k in _.prototype) { if (!(k in inst)) Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); } inst._zod.constr = _; inst._zod.def = def; } const Parent = params?.Parent ?? Object; class Definition extends Parent {} Object.defineProperty(Definition, "name", { value: name }); function _(def) { var _a; const inst = params?.Parent ? new Definition() : this; init(inst, def); (_a = inst._zod).deferred ?? (_a.deferred = []); for (const fn of inst._zod.deferred) { fn(); } return inst; } Object.defineProperty(_, "init", { value: init }); Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { if (params?.Parent && inst instanceof params.Parent) return true; return inst?._zod?.traits?.has(name); } }); Object.defineProperty(_, "name", { value: name }); return _; } const $brand = Symbol("zod_brand"); var $ZodAsyncError = class extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } }; const globalConfig = {}; function config$1(newConfig) { if (newConfig) Object.assign(globalConfig, newConfig); return globalConfig; } //#endregion //#region ../../node_modules/zod/dist/esm/v4/core/util.js var util_exports = {}; __export(util_exports, { BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, Class: () => Class, NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, aborted: () => aborted, allowsEval: () => allowsEval, assert: () => assert, assertEqual: () => assertEqual, assertIs: () => assertIs, assertNever: () => assertNever, assertNotEqual: () => assertNotEqual, assignProp: () => assignProp, cached: () => cached, cleanEnum: () => cleanEnum, cleanRegex: () => cleanRegex, clone: () => clone, createTransparentProxy: () => createTransparentProxy, defineLazy: () => defineLazy, esc: () => esc, escapeRegex: () => escapeRegex, extend: () => extend, finalizeIssue: () => finalizeIssue, floatSafeRemainder: () => floatSafeRemainder, getElementAtPath: () => getElementAtPath, getEnumValues: () => getEnumValues, getLengthableOrigin: () => getLengthableOrigin, getParsedType: () => getParsedType, getSizableOrigin: () => getSizableOrigin, isObject: () => isObject, isPlainObject: () => isPlainObject, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, merge: () => merge, normalizeParams: () => normalizeParams, nullish: () => nullish$1, numKeys: () => numKeys, omit: () => omit, optionalKeys: () => optionalKeys, partial: () => partial, pick: () => pick, prefixIssues: () => prefixIssues, primitiveTypes: () => primitiveTypes, promiseAllObject: () => promiseAllObject, propertyKeyTypes: () => propertyKeyTypes, randomString: () => randomString, required: () => required, stringifyPrimitive: () => stringifyPrimitive, unwrapMessage: () => unwrapMessage }); function assertEqual(val) { return val; } function assertNotEqual(val) { return val; } function assertIs(_arg) {} function assertNever(_x) { throw new Error(); } function assert(_) {} function getEnumValues(entries) { const numericValues = Object.values(entries).filter((v) => typeof v === "number"); const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); return values; } function joinValues(array$1, separator = "|") { return array$1.map((val) => stringifyPrimitive(val)).join(separator); } function jsonStringifyReplacer(_, value) { if (typeof value === "bigint") return value.toString(); return value; } function cached(getter) { const set$1 = false; return { get value() { if (!set$1) { const value = getter(); Object.defineProperty(this, "value", { value }); return value; } throw new Error("cached value already set"); } }; } function nullish$1(input) { return input === null || input === undefined; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } function 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 = Number.parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / 10 ** decCount; } function defineLazy(object$1, key, getter) { const set$1 = false; Object.defineProperty(object$1, key, { get() { if (!set$1) { const value = getter(); object$1[key] = value; return value; } throw new Error("cached value already set"); }, set(v) { Object.defineProperty(object$1, key, { value: v }); }, configurable: true }); } function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true }); } function getElementAtPath(obj, path$1) { if (!path$1) return obj; return path$1.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); const promises = keys.map((key) => promisesObj[key]); return Promise.all(promises).then((results) => { const resolvedObj = {}; for (let i = 0; i < keys.length; i++) { resolvedObj[keys[i]] = results[i]; } return resolvedObj; }); } function randomString(length = 10) { const chars = "abcdefghijklmnopqrstuvwxyz"; let str = ""; for (let i = 0; i < length; i++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } function esc(str) { return JSON.stringify(str); } function isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } const allowsEval = cached(() => { try { const F = Function; new F(""); return true; } catch (_) { return false; } }); function _isObject(o) { return Object.prototype.toString.call(o) === "[object Object]"; } function isPlainObject(o) { if (isObject(o) === false) return false; const ctor = o.constructor; if (ctor === undefined) return true; const prot = ctor.prototype; if (isObject(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } function numKeys(data) { let keyCount = 0; for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { keyCount++; } } return keyCount; } const getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return "undefined"; case "string": return "string"; case "number": return Number.isNaN(data) ? "nan" : "number"; case "boolean": return "boolean"; case "function": return "function"; case "bigint": return "bigint"; case "symbol": return "symbol"; case "object": if (Array.isArray(data)) { return "array"; } if (data === null) { return "null"; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return "promise"; } if (typeof Map !== "undefined" && data instanceof Map) { return "map"; } if (typeof Set !== "undefined" && data instanceof Set) { return "set"; } if (typeof Date !== "undefined" && data instanceof Date) { return "date"; } if (typeof File !== "undefined" && data instanceof File) { return "file"; } return "object"; default: throw new Error(`Unknown data type: ${t}`); } }; const propertyKeyTypes = new Set([ "string", "number", "symbol" ]); const primitiveTypes = new Set([ "string", "number", "bigint", "boolean", "symbol", "undefined" ]); function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function clone(inst, def, params) { const cl = new inst._zod.constr(def ?? inst._zod.def); if (!def || params?.parent) cl._zod.parent = inst; return cl; } function normalizeParams(_params) { const params = _params; if (!params) return {}; if (typeof params === "string") return { error: () => params }; if (params?.message !== undefined) { if (params?.error !== undefined) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return { ...params, error: () => params.error }; return params; } function createTransparentProxy(getter) { let target; return new Proxy({}, { get(_, prop, receiver) { target ?? (target = getter()); return Reflect.get(target, prop, receiver); }, set(_, prop, value, receiver) { target ?? (target = getter()); return Reflect.set(target, prop, value, receiver); }, has(_, prop) { target ?? (target = getter()); return Reflect.has(target, prop); }, deleteProperty(_, prop) { target ?? (target = getter()); return Reflect.deleteProperty(target, prop); }, ownKeys(_) { target ?? (target = getter()); return Reflect.ownKeys(target); }, getOwnPropertyDescriptor(_, prop) { target ?? (target = getter()); return Reflect.getOwnPropertyDescriptor(target, prop); }, defineProperty(_, prop, descriptor) { target ?? (target = getter()); return Reflect.defineProperty(target, prop, descriptor); } }); } function stringifyPrimitive(value) { if (typeof value === "bigint") return value.toString() + "n"; if (typeof value === "string") return `"${value}"`; return `${value}`; } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); } const NUMBER_FORMAT_RANGES = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; const BIGINT_FORMAT_RANGES = { int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] }; function pick(schema, mask) { const newShape = {}; const currDef = schema._zod.def; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; newShape[key] = currDef.shape[key]; } return clone(schema, { ...schema._zod.def, shape: newShape, checks: [] }); } function omit(schema, mask) { const newShape = { ...schema._zod.def.shape }; const currDef = schema._zod.def; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; delete newShape[key]; } return clone(schema, { ...schema._zod.def, shape: newShape, checks: [] }); } function extend(schema, shape) { const def = { ...schema._zod.def, get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); return _shape; }, checks: [] }; return clone(schema, def); } function merge(a, b) { return clone(a, { ...a._zod.def, get shape() { const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; assignProp(this, "shape", _shape); return _shape; }, catchall: b._zod.def.catchall, checks: [] }); } function partial(Class$1, schema, mask) { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in oldShape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = Class$1 ? new Class$1({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } else { for (const key in oldShape) { shape[key] = Class$1 ? new Class$1({ type: "optional", innerType: oldShape[key] }) : oldShape[key]; } } return clone(schema, { ...schema._zod.def, shape, checks: [] }); } function required(Class$1, schema, mask) { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; shape[key] = new Class$1({ type: "nonoptional", innerType: oldShape[key] }); } } else { for (const key in oldShape) { shape[key] = new Class$1({ type: "nonoptional", innerType: oldShape[key] }); } } return clone(schema, { ...schema._zod.def, shape, checks: [] }); } function aborted(x, startIndex = 0) { for (let i = startIndex; i < x.issues.length; i++) { if (x.issues[i].continue !== true) return true; } return false; } function prefixIssues(path$1, issues) { return issues.map((iss) => { var _a; (_a = iss).path ?? (_a.path = []); iss.path.unshift(path$1); return iss; }); } function unwrapMessage(message) { return typeof message === "string" ? message : message?.message; } function finalizeIssue(iss, ctx, config$2) { const full = { ...iss, path: iss.path ?? [] }; if (!iss.message) { const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config$2.customError?.(iss)) ?? unwrapMessage(config$2.localeError?.(iss)) ?? "Invalid input"; full.message = message; } delete full.inst; delete full.continue; if (!ctx?.reportInput) { delete full.input; } return full; } function getSizableOrigin(input) { if (input instanceof Set) return "set"; if (input instanceof Map) return "map"; if (input instanceof File) return "file"; return "unknown"; } function getLengthableOrigin(input) { if (Array.isArray(input)) return "array"; if (typeof input === "string") return "string"; return "unknown"; } function issue(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", input, inst }; } return { ...iss }; } function cleanEnum(obj) { return Object.entries(obj).filter(([k, _]) => { return Number.isNaN(Number.parseInt(k, 10)); }).map((el) => el[1]); } var Class = class { constructor(..._args) {} }; //#endregion //#region ../../node_modules/zod/dist/esm/v4/core/errors.js const initializer$1 = (inst, def) => { inst.name = "$ZodError"; Object.defineProperty(inst, "_zod", { value: inst._zod, enumerable: false }); Object.defineProperty(inst, "issues", { value: def, enumerable: false }); Object.defineProperty(inst, "message", { get() { return JSON.stringify(def, jsonStringifyReplacer, 2); }, enumerable: true }); }; const $ZodError = $constructor("$ZodError", initializer$1); const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error }); function flattenError(error$37, mapper = (issue$1) => issue$1.message) { const fieldErrors = {}; const formErrors = []; for (const sub of error$37.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } function formatError(error$37, _mapper) { const mapper = _mapper || function(issue$1) { return issue$1.message; }; const fieldErrors = { _errors: [] }; const processError = (error$38) => { for (const issue$1 of error$38.issues) { if (issue$1.code === "invalid_union" && issue$1.errors.length) { issue$1.errors.map((issues) => processError({ issues })); } else if (issue$1.code === "invalid_key") { processError({ issues: issue$1.issues }); } else if (issue$1.code === "invalid_element") { processError({ issues: issue$1.issues }); } else if (issue$1.path.length === 0) { fieldErrors._errors.push(mapper(issue$1)); } else { let curr = fieldErrors; let i = 0; while (i < issue$1.path.length) { const el = issue$1.path[i]; const terminal = i === issue$1.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue$1)); } curr = curr[el]; i++; } } } }; processError(error$37); return fieldErrors; } function treeifyError(error$37, _mapper) { const mapper = _mapper || function(issue$1) { return issue$1.message; }; const result = { errors: [] }; const processError = (error$38, path$1 = []) => { var _a, _b; for (const issue$1 of error$38.issues) { if (issue$1.code === "invalid_union" && issue$1.errors.length) { issue$1.errors.map((issues) => processError({ issues }, issue$1.path)); } else if (issue$1.code === "invalid_key") { processError({ issues: issue$1.issues }, issue$1.path); } else if (issue$1.code === "invalid_element") { processError({ issues: issue$1.issues }, issue$1.path); } else { const fullpath = [...path$1, ...issue$1.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue$1)); continue; } let curr = result; let i = 0; while (i < fullpath.length) { const el = fullpath[i]; const terminal = i === fullpath.length - 1; if (typeof el === "string") { curr.properties ?? (curr.properties = {}); (_a = curr.properties)[el] ?? (_a[el] = { errors: [] }); curr = curr.properties[el]; } else { curr.items ?? (curr.items = []); (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); curr = curr.items[el]; } if (terminal) { curr.errors.push(mapper(issue$1)); } i++; } } } }; processError(error$37); return result; } /** Format a ZodError as a human-readable string in the following form. * * From * * ```ts * ZodError { * issues: [ * { * expected: 'string', * code: 'invalid_type', * path: [ 'username' ], * message: 'Invalid input: expected string' * }, * { * expected: 'number', * code: 'invalid_type', * path: [ 'favoriteNumbers', 1 ], * message: 'Invalid input: expected number' * } * ]; * } * ``` * * to * * ``` * username * ✖ Expected number, received string at "username * favoriteNumbers[0] * ✖ Invalid input: expected number * ``` */ function toDotPath(path$1) { const segs = []; for (const seg of path$1) { if (typeof seg === "number") segs.push(`[${seg}]`); else if (typeof seg === "symbol") segs.push(`[${JSON.stringify(String(seg))}]`); else if (/[^\w$]/.test(seg)) segs.push(`[${JSON.stringify(seg)}]`); else { if (segs.length) segs.push("."); segs.push(seg); } } return segs.join(""); } function prettifyError(error$37) { const lines = []; const issues = [...error$37.issues].sort((a, b) => a.path.length - b.path.length); for (const issue$1 of issues) { lines.push(`✖ ${issue$1.message}`); if (issue$1.path?.length) lines.push(` → at ${toDotPath(issue$1.path)}`); } return lines.join("\n"); } //#endregion //#region ../../node_modules/zod/dist/esm/v4/core/parse.js const _parse = (_Err) => (schema, value, _ctx, _params) => { const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } if (result.issues.length) { const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1()))); Error.captureStackTrace(e, _params?.callee); throw e; } return result.value; }; const parse$1 = /* @__PURE__ */ _parse($ZodRealError); const _parseAsync = (_Err) => async (schema, value, _ctx, params) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; if (result.issues.length) { const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1()))); Error.captureStackTrace(e, params?.callee); throw e; } return result.value; }; const parseAsync$1 = /* @__PURE__ */ _parseAsync($ZodRealError); const _safeParse = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } return result.issues.length ? { success: false, error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1()))) } : { success: true, data: result.value }; }; const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError); const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; return result.issues.length ? { success: false, error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1()))) } : { success: true, data: result.value }; }; const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError); //#endregion //#region ../../node_modules/zod/dist/esm/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { _emoji: () => _emoji$1, base64: () => base64$1, base64url: () => base64url$1, bigint: () => bigint$2, boolean: () => boolean$2, browserEmail: () => browserEmail, cidrv4: () => cidrv4$1, cidrv6: () => cidrv6$1, cuid: () => cuid$1, cuid2: () => cuid2$1, date: () => date$3, datetime: () => datetime$1, domain: () => domain, duration: () => duration$1, e164: () => e164$1, email: () => email$1, emoji: () => emoji$1, extendedDuration: () => extendedDuration, guid: () => guid$1, hostname: () => hostname, html5Email: () => html5Email, integer: () => integer, ipv4: () => ipv4$1, ipv6: () => ipv6$1, ksuid: () => ksuid$1, lowercase: () => lowercase, nanoid: () => nanoid$1, null: () => _null$2, number: () => number$2, rfc5322Email: () => rfc5322Email, string: () => string$2, time: () => time$1, ulid: () => ulid$1, undefined: () => _undefined$2, unicodeEmail: () => unicodeEmail, uppercase: () => uppercase, uuid: () => uuid$1, uuid4: () => uuid4, uuid6: () => uuid6, uuid7: () => uuid7, xid: () => xid$1 }); const cuid$1 = /^[cC][^\s-]{8,}$/; const cuid2$1 = /^[0-9a-z]+$/; const ulid$1 = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; const xid$1 = /^[0-9a-vA-V]{20}$/; const ksuid$1 = /^[A-Za-z0-9]{27}$/; const nanoid$1 = /^[a-zA-Z0-9_-]{21}$/; /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; /** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ const guid$1 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; /** Returns a regex for validating an RFC 4122 UUID. * * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ const uuid$1 = (version$1) => { if (!version$1) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version$1}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; const uuid4 = /* @__PURE__ */ uuid$1(4); const uuid6 = /* @__PURE__ */ uuid$1(6); const uuid7 = /* @__PURE__ */ uuid$1(7); /** Practical email validation */ const email$1 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; /** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; /** The classic emailregex.com regex for RFC 5322-compliant emails */ const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; /** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji$1() { return new RegExp(_emoji$1, "u"); } const ipv4$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; const ipv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; const cidrv4$1 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; const cidrv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; const base64$1 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; const base64url$1 = /^[A-Za-z0-9_-]*$/; const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; const e164$1 = /^\+(?:[0-9]){6,14}[0-9]$/; const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; const date$3 = /* @__PURE__ */ new RegExp(`^${dateSource}$`); function timeSource(args) { let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; if (args.precision) { regex = `${regex}\\.\\d{${args.precision}}`; } else if (args.precision == null) { regex = `${regex}(\\.\\d+)?`; } return regex; } function time$1(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime$1(args) { let regex = `${dateSource}T${timeSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}$`); } const string$2 = (params) => { const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); }; const bigint$2 = /^\d+n?$/; const integer = /^\d+$/; const number$2 = /^-?\d+(?:\.\d+)?/i; const boolean$2 = /true|false/i; const _null$2 = /null/i; const _undefined$2 = /undefined/i; const lowercase = /^[^A-Z]*$/; const uppercase = /^[^a-z]*$/; //#endregion //#region ../../node_modules/zod/dist/esm/v4/core/checks.js const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { var _a; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a = inst._zod).onattach ?? (_a.onattach = []); }); const numericOriginMap = { number: "number", bigint: "bigint", object: "date" }; const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst$1) => { const bag = inst$1._zod.bag; const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; if (def.value < curr) { if (def.inclusive) bag.maximum = def.value; else bag.exclusiveMaximum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { return; } payload.issues.push({ origin, code: "too_big", maximum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst$1) => { const bag = inst$1._zod.bag; const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; if (def.value > curr) { if (def.inclusive) bag.minimum = def.value; else bag.exclusiveMinimum = def.value; } }); inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { return; } payload.issues.push({ origin, code: "too_small", minimum: def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.onattach.push((inst$1) => { var _a; (_a = inst$1._zod.bag).multipleOf ?? (_a.multipleOf = def.value); }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; if (isMultiple) return; payload.issues.push({ origin: typeof payload.value, code: "not_multiple_of", divisor: def.value, input: payload.value, inst, continue: !def.abort }); }; }); const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { $ZodCheck.init(inst, def); def.format = def.format || "float64"; const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst$1) => { const bag = inst$1._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; if (isInt) bag.pattern = integer; }); inst._zod.check = (payload) => { const input = payload.value; if (isInt) { if (!Number.isInteger(input)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", input, inst }); return; } if (!Number.isSafeInteger(input)) { if (input > 0) { payload.issues.push({ input, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, continue: !def.abort }); } else { payload.issues.push({ input, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, continue: !def.abort }); } return; } } if (input < minimum) { payload.issues.push({ origin: "number", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "number", input, code: "too_big", maximum, inst }); } }; }); const $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst$1) => { const bag = inst$1._zod.bag; bag.format = def.format; bag.minimum = minimum; bag.maximum = maximum; }); inst._zod.check = (payload) => { const input = payload.value; if (input < minimum) { payload.issues.push({ origin: "bigint", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); } if (input > maximum) { payload.issues.push({ origin: "bigint", input, code: "too_big", maximum, inst }); } }; }); const $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.when = (payload) => { const val = payload.value; return !nullish$1(val) && val.size !== undefined; }; inst._zod.onattach.push((inst$1) => { const curr = inst$1._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst$1._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size <= def.maximum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_big", maximum: def.maximum, input, inst, continue: !def.abort }); }; }); const $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.when = (payload) => { const val = payload.value; return !nullish$1(val) && val.size !== undefined; }; inst._zod.onattach.push((inst$1) => { const curr = inst$1._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst$1._zod.bag.minimum = def.minimum; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size >= def.minimum) return; payload.issues.push({ origin: getSizableOrigin(input), code: "too_small", minimum: def.minimum, input, inst, continue: !def.abort }); }; }); const $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.when = (payload) => { const val = payload.value; return !nullish$1(val) && val.size !== undefined; }; inst._zod.onattach.push((inst$1) => { const bag = inst$1._zod.bag; bag.minimum = def.size; bag.maximum = def.size; bag.size = def.size; }); inst._zod.check = (payload) => { const input = payload.value; const size = input.size; if (size === def.size) return; const tooBig = size > def.size; payload.issues.push({ origin: getSizableOrigin(input), ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, input: payload.value, inst, continue: !def.abort }); }; }); const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.when = (payload) => { const val = payload.value; return !nullish$1(val) && val.length !== undefined; }; inst._zod.onattach.push((inst$1) => { const curr = inst$1._zod.bag.maximum ?? Number.POSITIVE_INFINITY; if (def.maximum < curr) inst$1._zod.bag.maximum = def.maximum; }); inst._zod.check = (payload) => { const input = payload.value; const length = input.length; if (length <= def.maximum) return;