UNPKG

tailwindcss-taro

Version:

TailwindCSS plugin for Taro4 with Vite/Webpack support - 零配置,开箱即用

1,419 lines (1,403 loc) 145 kB
#!/usr/bin/env node var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; // src/cli/index.ts import { Command } from "commander"; // src/cli/commands/patch.ts import fs from "fs-extra"; import path from "path"; // src/utils/logger.ts var COLORS = { info: "\x1B[36m", // 青色 warn: "\x1B[33m", // 黄色 error: "\x1B[31m", // 红色 success: "\x1B[32m", // 绿色 debug: "\x1B[35m" // 紫色 }; var RESET = "\x1B[0m"; var Logger = class { constructor(verbose = false) { this.verbose = verbose; } info(...args) { if (this.verbose) this.log("info", ...args); } warn(...args) { this.log("warn", ...args); } error(...args) { this.log("error", ...args); } success(...args) { this.log("success", ...args); } debug(...args) { if (this.verbose) this.log("debug", ...args); } log(level, ...args) { const color = COLORS[level] || ""; const prefix = { info: "[INFO]", warn: "[WARN]", error: "[ERROR]", success: "[OK]", debug: "[DEBUG]" }[level]; console.log(`${color}${prefix}${RESET}`, ...args); } }; // src/utils/weapp-postcss-legalizer.ts function legalizeWeappCss(css) { if (!css || typeof css !== "string") { return css || ""; } const logger = new Logger(false); let result = css; try { result = preprocessCss(result); result = handleAtRules(result); result = handleSelectors(result); result = handlePropertyValues(result); result = handleSpecialCharacters(result); result = postprocessCss(result); logger.debug("\u2705 CSS \u5408\u6CD5\u5316\u5B8C\u6210"); } catch (error) { logger.error("\u274C CSS \u5408\u6CD5\u5316\u5931\u8D25:", error); result = basicCleanup(css); } return result; } function preprocessCss(css) { return css.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ").trim(); } function handleAtRules(css) { return css.replace(/@import\s+['"]([^'"]+)['"]\s*;?/g, "").replace(/@media\s+[^{]+{([^}]+)}/g, (match, content) => { const processedContent = handleSelectors(content); return processedContent; }).replace(/@keyframes\s+[^{]+{([^}]+)}/g, "").replace(/@[a-zA-Z-]+\s*[^;{]*;?/g, ""); } function handleSelectors(css) { return css.replace(/:[a-zA-Z-]+/g, "").replace(/::[a-zA-Z-]+/g, "").replace(/\[[^\]]+\]/g, "").replace(/\s*>\s*/g, " ").replace(/\s*\+\s*/g, " ").replace(/\s*~\s*/g, " ").replace(/:\d+/g, "").replace(/:(first|last|only)-(child|of-type)/g, "").replace(/:not\([^)]+\)/g, "").replace(/:is\([^)]+\)/g, "").replace(/:where\([^)]+\)/g, "").replace(/:has\([^)]+\)/g, "").replace(/:empty/g, "").replace(/:root/g, "page").replace(/\*/g, "view").replace(/\s+/g, " ").trim(); } function handlePropertyValues(css) { return css.replace(/calc\([^)]+\)/g, (match) => { return match.replace(/calc\(/g, "").replace(/\)/g, "").replace(/\s*\+\s*/g, "+").replace(/\s*-\s*/g, "-").replace(/\s*\*\s*/g, "*").replace(/\s*\/\s*/g, "/"); }).replace(/var\([^)]+\)/g, "").replace(/linear-gradient\([^)]+\)/g, "#000").replace(/radial-gradient\([^)]+\)/g, "#000").replace(/conic-gradient\([^)]+\)/g, "#000").replace(/url\([^)]+\)/g, "").replace(/rgba\([^)]+\)/g, (match) => { const rgbaMatch = match.match(/rgba?\(([^)]+)\)/); if (rgbaMatch) { const values = rgbaMatch[1].split(",").map((v) => parseFloat(v.trim())); if (values.length >= 3) { const r = Math.round(values[0]); const g = Math.round(values[1]); const b = Math.round(values[2]); return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`; } } return "#000"; }).replace(/hsla?\([^)]+\)/g, "#000").replace(/(\d+(?:\.\d+)?)rem/g, (match, value) => { const remValue = parseFloat(value) * 16; return `${remValue}px`; }).replace(/(\d+(?:\.\d+)?)em/g, (match, value) => { const emValue = parseFloat(value) * 16; return `${emValue}px`; }).replace(/(\d+(?:\.\d+)?)vw/g, (match, value) => { const vwValue = parseFloat(value) * 7.5; return `${vwValue}rpx`; }).replace(/(\d+(?:\.\d+)?)vh/g, (match, value) => { const vhValue = parseFloat(value) * 13.34; return `${vhValue}rpx`; }).replace(/(\d+(?:\.\d+)?)vmin/g, (match, value) => { const vminValue = parseFloat(value) * 7.5; return `${vminValue}rpx`; }).replace(/(\d+(?:\.\d+)?)vmax/g, (match, value) => { const vmaxValue = parseFloat(value) * 13.34; return `${vmaxValue}rpx`; }).replace(/(\d+(?:\.\d+)?)ch/g, (match, value) => { const chValue = parseFloat(value) * 8; return `${chValue}px`; }).replace(/(\d+(?:\.\d+)?)ex/g, (match, value) => { const exValue = parseFloat(value) * 8; return `${exValue}px`; }).replace(/(\d+(?:\.\d+)?)cap/g, (match, value) => { const capValue = parseFloat(value) * 16; return `${capValue}px`; }).replace(/(\d+(?:\.\d+)?)ic/g, (match, value) => { const icValue = parseFloat(value) * 16; return `${icValue}px`; }).replace(/(\d+(?:\.\d+)?)lh/g, (match, value) => { const lhValue = parseFloat(value) * 16; return `${lhValue}px`; }).replace(/(\d+(?:\.\d+)?)rlh/g, (match, value) => { const rlhValue = parseFloat(value) * 16; return `${rlhValue}px`; }).replace(/(\d+(?:\.\d+)?)turn/g, (match, value) => { const turnValue = parseFloat(value) * 360; return `${turnValue}deg`; }).replace(/(\d+(?:\.\d+)?)grad/g, (match, value) => { const gradValue = parseFloat(value) * 0.9; return `${gradValue}deg`; }).replace(/(\d+(?:\.\d+)?)rad/g, (match, value) => { const radValue = parseFloat(value) * 57.2958; return `${radValue}deg`; }); } function handleSpecialCharacters(css) { return css.replace(/\\([0-9a-fA-F]{1,6})\s?/g, (match, hex) => { const charCode = parseInt(hex, 16); return String.fromCharCode(charCode); }).replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => { const charCode = parseInt(hex, 16); return String.fromCharCode(charCode); }).replace(/\\(.)/g, "$1").replace(/[^\x00-\x7F]/g, "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, ""); } function postprocessCss(css) { return css.replace(/[^{}]+{\s*}/g, "").replace(/;+/g, ";").replace(/;(\s*})/g, "$1").replace(/\s+/g, " ").trim(); } function basicCleanup(css) { return css.replace(/[a-zA-Z-]+:\s*(?:var\([^)]+\)|calc\([^)]+\)|linear-gradient\([^)]+\)|radial-gradient\([^)]+\)|conic-gradient\([^)]+\)|url\([^)]+\));?\s*/g, "").replace(/:[a-zA-Z-]+/g, "").replace(/::[a-zA-Z-]+/g, "").replace(/\[[^\]]+\]/g, "").replace(/@[a-zA-Z-]+\s*[^;{]*;?/g, "").replace(/\s+/g, " ").trim(); } // src/utils/escape-weapp-class.ts function escapeWeappClass(className) { if (!className || typeof className !== "string") { return className || ""; } const logger = new Logger(false); let result = className; try { result = preprocessClassName(result); result = handleSpecialCharacters2(result); result = handleNumericPrefix(result); result = handleSpecialPatterns(result); result = handleEscapeSequences(result); result = postprocessClassName(result); if (result !== className) { logger.debug(`\u{1F504} \u7C7B\u540D\u8F6C\u4E49: ${className} \u2192 ${result}`); } } catch (error) { logger.error("\u274C \u7C7B\u540D\u8F6C\u4E49\u5931\u8D25:", error); result = basicEscape(className); } return result; } function preprocessClassName(className) { return className.trim().replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "").replace(/[\u200B-\u200D\uFEFF]/g, ""); } function handleSpecialCharacters2(className) { return className.replace(/\./g, "d").replace(/\//g, "s").replace(/:/g, "c").replace(/;/g, "sc").replace(/=/g, "eq").replace(/\?/g, "q").replace(/!/g, "ex").replace(/@/g, "at").replace(/#/g, "hash").replace(/\$/g, "dollar").replace(/%/g, "percent").replace(/\^/g, "caret").replace(/&/g, "amp").replace(/\*/g, "star").replace(/\(/g, "lp").replace(/\)/g, "rp").replace(/\[/g, "lb").replace(/\]/g, "rb").replace(/\{/g, "lc").replace(/\}/g, "rc").replace(/</g, "lt").replace(/>/g, "gt").replace(/\|/g, "pipe").replace(/\\/g, "backslash").replace(/~/g, "tilde").replace(/`/g, "backtick").replace(/'/g, "quote").replace(/"/g, "dquote").replace(/,/g, "comma").replace(/;/g, "semicolon").replace(/\s+/g, "space").replace(/\t/g, "tab").replace(/\n/g, "newline").replace(/\r/g, "return").replace(/\f/g, "formfeed").replace(/\v/g, "vtab"); } function handleNumericPrefix(className) { if (/^\d/.test(className)) { return "n" + className; } return className; } function handleSpecialPatterns(className) { return className.replace(/^(\d+)\/(\d+)$/, (match, numerator, denominator) => { return `frac${numerator}of${denominator}`; }).replace(/^(\d+)\.(\d+)$/, (match, integer, decimal) => { return `dec${integer}${decimal}`; }).replace(/^-(\d+)$/, (match, number) => { return `neg${number}`; }).replace(/^(\d+)%$/, (match, percentage) => { return `pct${percentage}`; }).replace(/^(\d+)px$/, (match, pixels) => { return `px${pixels}`; }).replace(/^(\d+(?:\.\d+)?)rem$/, (match, rem) => { return `rem${rem.replace(".", "")}`; }).replace(/^(\d+(?:\.\d+)?)em$/, (match, em) => { return `em${em.replace(".", "")}`; }).replace(/^(\d+(?:\.\d+)?)vw$/, (match, vw) => { return `vw${vw.replace(".", "")}`; }).replace(/^(\d+(?:\.\d+)?)vh$/, (match, vh) => { return `vh${vh.replace(".", "")}`; }).replace(/^(\d+(?:\.\d+)?)rpx$/, (match, rpx) => { return `rpx${rpx.replace(".", "")}`; }).replace(/^(\d+(?:\.\d+)?)deg$/, (match, degrees) => { return `deg${degrees.replace(".", "")}`; }).replace(/^(\d+(?:\.\d+)?)rad$/, (match, radians) => { return `rad${radians.replace(".", "")}`; }).replace(/^linear-gradient-/, "lg-").replace(/^radial-gradient-/, "rg-").replace(/^conic-gradient-/, "cg-").replace(/^animate-/, "anim-").replace(/^transition-/, "trans-").replace(/^transform-/, "tf-").replace(/^filter-/, "flt-").replace(/^blend-/, "bl-").replace(/^grid-/, "g-").replace(/^col-/, "c-").replace(/^row-/, "r-").replace(/^flex-/, "f-").replace(/^absolute/, "abs").replace(/^relative/, "rel").replace(/^fixed/, "fix").replace(/^sticky/, "stk").replace(/^block/, "blk").replace(/^inline/, "inl").replace(/^inline-block/, "inlb").replace(/^flex/, "flx").replace(/^grid/, "grd").replace(/^table/, "tbl").replace(/^hidden/, "hdd").replace(/^overflow-/, "ov-").replace(/^visible/, "vis").replace(/^invisible/, "inv").replace(/^opacity-/, "op-").replace(/^z-/, "zidx-"); } function handleEscapeSequences(className) { return className.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => { const charCode = parseInt(hex, 16); return String.fromCharCode(charCode); }).replace(/\\([0-9a-fA-F]{1,6})\s?/g, (match, hex) => { const charCode = parseInt(hex, 16); return String.fromCharCode(charCode); }).replace(/\\([0-7]{1,3})/g, (match, oct) => { const charCode = parseInt(oct, 8); return String.fromCharCode(charCode); }).replace(/\\(.)/g, "$1"); } function postprocessClassName(className) { return className.trim().replace(/_+/g, "_").replace(/^_+|_+$/g, "").replace(/^[^a-zA-Z]/, "cls$&").substring(0, 100); } function basicEscape(className) { return className.replace(/[^a-zA-Z0-9_-]/g, "_").replace(/^[^a-zA-Z]/, "cls$&").substring(0, 100); } // src/cli/commands/patch.ts async function patch(options) { const logger = new Logger(options.verbose); const { platform, dist, runtime, classPatch, selectorPatch } = options; logger.success("\u{1F680} \u5F00\u59CB patch \u6784\u5EFA\u4EA7\u7269..."); logger.info("\u{1F4F1} \u76EE\u6807\u5E73\u53F0:", platform); logger.info("\u{1F4C1} \u6784\u5EFA\u76EE\u5F55:", dist); if (!fs.existsSync(dist)) { throw new Error(`\u6784\u5EFA\u76EE\u5F55\u4E0D\u5B58\u5728: ${dist}`); } const startTime = Date.now(); let processedFiles = 0; let totalSize = 0; let originalSize = 0; if (platform === "weapp") { await processWxssFiles(dist, logger, { processedFiles, totalSize, originalSize }); } if (classPatch) { await processClassNames(dist, logger); } if (selectorPatch) { await processSelectors(dist, logger); } if (runtime) { await addRuntimeSupport(dist, logger); } const totalTime = Date.now() - startTime; logger.success("\u{1F389} Patch \u5B8C\u6210\uFF01"); logger.info(`\u23F1\uFE0F \u603B\u65F6\u95F4: ${totalTime}ms`); } async function processWxssFiles(distPath, logger, stats) { const wxssFiles = await findWxssFiles(distPath); for (const file of wxssFiles) { try { const originalCss = await fs.readFile(file, "utf-8"); const legalCss = legalizeWeappCss(originalCss); await fs.writeFile(file, legalCss); stats.processedFiles++; stats.originalSize += originalCss.length; stats.totalSize += legalCss.length; logger.success(`\u{1F4E6} \u5904\u7406\u6587\u4EF6: ${path.relative(distPath, file)}`); logger.info(`\u{1F4CF} \u539F\u59CB\u5927\u5C0F: ${originalCss.length} \u5B57\u7B26`); logger.info(`\u{1F4CF} \u5904\u7406\u540E: ${legalCss.length} \u5B57\u7B26`); logger.info(`\u{1F4C8} \u538B\u7F29\u7387: ${((1 - legalCss.length / originalCss.length) * 100).toFixed(2)}%`); } catch (error) { logger.error(`\u274C \u5904\u7406\u6587\u4EF6\u5931\u8D25: ${file}`, error); } } } async function processClassNames(distPath, logger) { const jsFiles = await findJsFiles(distPath); for (const file of jsFiles) { try { let content = await fs.readFile(file, "utf-8"); const originalContent = content; content = fixRemovedClassNames(content); if (content !== originalContent) { await fs.writeFile(file, content); logger.success(`\u{1F527} \u4FEE\u590D\u7C7B\u540D: ${path.relative(distPath, file)}`); } } catch (error) { logger.error(`\u274C \u5904\u7406\u7C7B\u540D\u5931\u8D25: ${file}`, error); } } } async function processSelectors(distPath, logger) { const wxssFiles = await findWxssFiles(distPath); for (const file of wxssFiles) { try { let content = await fs.readFile(file, "utf-8"); const originalContent = content; content = fixSelectorCompatibility(content); if (content !== originalContent) { await fs.writeFile(file, content); logger.success(`\u{1F527} \u4FEE\u590D\u9009\u62E9\u5668: ${path.relative(distPath, file)}`); } } catch (error) { logger.error(`\u274C \u5904\u7406\u9009\u62E9\u5668\u5931\u8D25: ${file}`, error); } } } async function addRuntimeSupport(distPath, logger) { const runtimeScript = ` // TailwindCSS Taro \u8FD0\u884C\u65F6\u652F\u6301 (function() { // \u7C7B\u540D\u8F6C\u4E49\u51FD\u6570 window.escapeWeappClass = function(className) { return className.replace(/[^a-zA-Z0-9-_]/g, '_'); }; // \u8FD0\u884C\u65F6\u7C7B\u540D\u6CE8\u5165 window.injectTailwindClass = function(element, className) { if (element && element.className) { const escapedClass = window.escapeWeappClass(className); element.className += ' ' + escapedClass; } }; console.log('\u{1F3A8} TailwindCSS Taro \u8FD0\u884C\u65F6\u652F\u6301\u5DF2\u52A0\u8F7D'); })(); `; const runtimeFile = path.join(distPath, "tailwindcss-taro-runtime.js"); await fs.writeFile(runtimeFile, runtimeScript); logger.success("\u{1F527} \u6DFB\u52A0\u8FD0\u884C\u65F6\u652F\u6301: tailwindcss-taro-runtime.js"); } async function findWxssFiles(dir) { const files = []; async function scan(currentDir) { const items = await fs.readdir(currentDir); for (const item of items) { const fullPath = path.join(currentDir, item); const stat = await fs.stat(fullPath); if (stat.isDirectory()) { await scan(fullPath); } else if (item.endsWith(".wxss")) { files.push(fullPath); } } } await scan(dir); return files; } async function findJsFiles(dir) { const files = []; async function scan(currentDir) { const items = await fs.readdir(currentDir); for (const item of items) { const fullPath = path.join(currentDir, item); const stat = await fs.stat(fullPath); if (stat.isDirectory()) { await scan(fullPath); } else if (item.endsWith(".js") || item.endsWith(".ts")) { files.push(fullPath); } } } await scan(dir); return files; } function fixRemovedClassNames(content) { return content.replace(/className\s*=\s*["']([^"']*)["']/g, (match, className) => { const escapedClasses = className.split(/\s+/).map(escapeWeappClass).join(" "); return `className="${escapedClasses}"`; }).replace(/class\s*=\s*["']([^"']*)["']/g, (match, className) => { const escapedClasses = className.split(/\s+/).map(escapeWeappClass).join(" "); return `class="${escapedClasses}"`; }); } function fixSelectorCompatibility(content) { return content.replace(/:root/g, "page").replace(/\*/g, "view,text").replace(/:[a-z-]+(?=\s*[.{])/g, "").replace(/::[a-z-]+/g, ""); } // node_modules/.pnpm/zod@3.25.73/node_modules/zod/v3/external.js var external_exports = {}; __export(external_exports, { BRAND: () => BRAND, DIRTY: () => DIRTY, EMPTY_PATH: () => EMPTY_PATH, INVALID: () => INVALID, NEVER: () => NEVER, OK: () => OK, ParseStatus: () => ParseStatus, Schema: () => ZodType, ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBigInt: () => ZodBigInt, ZodBoolean: () => ZodBoolean, ZodBranded: () => ZodBranded, ZodCatch: () => ZodCatch, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodEffects: () => ZodEffects, ZodEnum: () => ZodEnum, ZodError: () => ZodError, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, ZodMap: () => ZodMap, ZodNaN: () => ZodNaN, ZodNativeEnum: () => ZodNativeEnum, ZodNever: () => ZodNever, ZodNull: () => ZodNull, ZodNullable: () => ZodNullable, ZodNumber: () => ZodNumber, ZodObject: () => ZodObject, ZodOptional: () => ZodOptional, ZodParsedType: () => ZodParsedType, ZodPipeline: () => ZodPipeline, ZodPromise: () => ZodPromise, ZodReadonly: () => ZodReadonly, ZodRecord: () => ZodRecord, ZodSchema: () => ZodType, ZodSet: () => ZodSet, ZodString: () => ZodString, ZodSymbol: () => ZodSymbol, ZodTransformer: () => ZodEffects, ZodTuple: () => ZodTuple, ZodType: () => ZodType, ZodUndefined: () => ZodUndefined, ZodUnion: () => ZodUnion, ZodUnknown: () => ZodUnknown, ZodVoid: () => ZodVoid, addIssueToContext: () => addIssueToContext, any: () => anyType, array: () => arrayType, bigint: () => bigIntType, boolean: () => booleanType, coerce: () => coerce, custom: () => custom, date: () => dateType, datetimeRegex: () => datetimeRegex, defaultErrorMap: () => en_default, discriminatedUnion: () => discriminatedUnionType, effect: () => effectsType, enum: () => enumType, function: () => functionType, getErrorMap: () => getErrorMap, getParsedType: () => getParsedType, instanceof: () => instanceOfType, intersection: () => intersectionType, isAborted: () => isAborted, isAsync: () => isAsync, isDirty: () => isDirty, isValid: () => isValid, late: () => late, lazy: () => lazyType, literal: () => literalType, makeIssue: () => makeIssue, map: () => mapType, nan: () => nanType, nativeEnum: () => nativeEnumType, never: () => neverType, null: () => nullType, nullable: () => nullableType, number: () => numberType, object: () => objectType, objectUtil: () => objectUtil, oboolean: () => oboolean, onumber: () => onumber, optional: () => optionalType, ostring: () => ostring, pipeline: () => pipelineType, preprocess: () => preprocessType, promise: () => promiseType, quotelessJson: () => quotelessJson, record: () => recordType, set: () => setType, setErrorMap: () => setErrorMap, strictObject: () => strictObjectType, string: () => stringType, symbol: () => symbolType, transformer: () => effectsType, tuple: () => tupleType, undefined: () => undefinedType, union: () => unionType, unknown: () => unknownType, util: () => util, void: () => voidType }); // node_modules/.pnpm/zod@3.25.73/node_modules/zod/v3/helpers/util.js var util; (function(util2) { util2.assertEqual = (_) => { }; function assertIs(_arg) { } util2.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util2.assertNever = assertNever; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e) { return obj[e]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues; util2.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil || (objectUtil = {})); var ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); var getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; // node_modules/.pnpm/zod@3.25.73/node_modules/zod/v3/ZodError.js var ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); var quotelessJson = (obj) => { const json = JSON.stringify(obj, null, 2); return json.replace(/"([^"]+)":/g, "$1:"); }; var ZodError = class _ZodError extends Error { get errors() { return this.issues; } constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } format(_mapper) { const mapper = _mapper || function(issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof _ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { const firstEl = sub.path[0]; fieldErrors[firstEl] = fieldErrors[firstEl] || []; fieldErrors[firstEl].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; // node_modules/.pnpm/zod@3.25.73/node_modules/zod/v3/locales/en.js var errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "bigint") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue); } return { message }; }; var en_default = errorMap; // node_modules/.pnpm/zod@3.25.73/node_modules/zod/v3/errors.js var overrideErrorMap = en_default; function setErrorMap(map) { overrideErrorMap = map; } function getErrorMap() { return overrideErrorMap; } // node_modules/.pnpm/zod@3.25.73/node_modules/zod/v3/helpers/parseUtil.js var makeIssue = (params) => { const { data, path: path2, errorMaps, issueData } = params; const fullPath = [...path2, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; if (issueData.message !== void 0) { return { ...issueData, path: fullPath, message: issueData.message }; } let errorMessage = ""; const maps = errorMaps.filter((m) => !!m).slice().reverse(); for (const map of maps) { errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: errorMessage }; }; var EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map overrideMap === en_default ? void 0 : en_default // then global default map ].filter((x) => !!x) }); ctx.common.issues.push(issue); } var ParseStatus = class _ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs) { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value }); } return _ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } }; var INVALID = Object.freeze({ status: "aborted" }); var DIRTY = (value) => ({ status: "dirty", value }); var OK = (value) => ({ status: "valid", value }); var isAborted = (x) => x.status === "aborted"; var isDirty = (x) => x.status === "dirty"; var isValid = (x) => x.status === "valid"; var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; // node_modules/.pnpm/zod@3.25.73/node_modules/zod/v3/helpers/errorUtil.js var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil || (errorUtil = {})); // node_modules/.pnpm/zod@3.25.73/node_modules/zod/v3/types.js var ParseInputLazyPath = class { constructor(parent, value, path2, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path2; this._key = key; } get path() { if (!this._cachedPath.length) { if (Array.isArray(this._key)) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; var handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error = new ZodError(ctx.common.issues); this._error = error; return this._error; } }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message ?? ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: message ?? required_error ?? ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; return { errorMap: customMap, description }; } var ZodType = class { get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { const ctx = { common: { issues: [], async: params?.async ?? false, contextualErrorMap: params?.errorMap }, path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } "~validate"(data) { const ctx = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; if (!this["~standard"].async) { try { const result = this._parseSync({ data, path: [], parent: ctx }); return isValid(result) ? { value: result.value } : { issues: ctx.common.issues }; } catch (err) { if (err?.message?.toLowerCase()?.includes("encountered")) { this["~standard"].async = true; } ctx.common = { issues: [], async: true }; } } return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues }); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params?.errorMap, async: true }, path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val) }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); this["~standard"] = { version: 1, vendor: "zod", validate: (data) => this["~validate"](data) }; } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; var cuidRegex = /^c[^\s-]{8,}$/i; var cuid2Regex = /^[0-9a-z]+$/; var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; var uuidRegex = /^[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; var nanoidRegex = /^[a-z0-9_-]{21}$/i; var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; var durationRegex = /^[-+]?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)?)??$/; var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; var emojiRegex; var ipv4Regex = /^(?:(?: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])$/; var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; var dateRegexSource = `((\\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])))`; var dateRegex = new RegExp(`^${dateRegexSource}$`); function timeRegexSource(args) { let secondsRegexSource = `[0-5]\\d`; if (args.precision) { secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } else if (args.precision == null) { secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } const secondsQuantifier = args.precision ? "+" : "?"; return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(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}$`); } function isValidIP(ip, version2) { if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { return true; } if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { return true; } return false; } function isValidJWT(jwt, alg) { if (!jwtRegex.test(jwt)) return false; try { const [header] = jwt.split("."); if (!header) return false; const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); const decoded = JSON.parse(atob(base64)); if (typeof decoded !== "object" || decoded === null) return false; if ("typ" in decoded && decoded?.typ !== "JWT") return false; if (!decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } catch { return false; } } function isValidCidr(ip, version2) { if ((version2 === "v4" || !version2) && ipv4Ci