zod-compiler 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +175 -151
- package/dist/core/codegen/build-path.d.ts.map +1 -1
- package/dist/core/codegen/build-path.js +144 -34
- package/dist/core/codegen/build-path.js.map +1 -1
- package/dist/core/codegen/context.d.ts +11 -10
- package/dist/core/codegen/context.d.ts.map +1 -1
- package/dist/core/codegen/context.js.map +1 -1
- package/dist/core/codegen/fast-path.d.ts +3 -1
- package/dist/core/codegen/fast-path.d.ts.map +1 -1
- package/dist/core/codegen/fast-path.js +7 -4
- package/dist/core/codegen/fast-path.js.map +1 -1
- package/dist/core/codegen/index.js +4 -3
- package/dist/core/codegen/index.js.map +1 -1
- package/dist/core/codegen/issue-decls.d.ts +43 -1
- package/dist/core/codegen/issue-decls.d.ts.map +1 -1
- package/dist/core/codegen/issue-decls.js +45 -2
- package/dist/core/codegen/issue-decls.js.map +1 -1
- package/dist/core/codegen/schemas/default.d.ts +10 -0
- package/dist/core/codegen/schemas/default.d.ts.map +1 -1
- package/dist/core/codegen/schemas/default.js +11 -0
- package/dist/core/codegen/schemas/default.js.map +1 -1
- package/dist/core/codegen/schemas/discriminated-union.d.ts +6 -2
- package/dist/core/codegen/schemas/discriminated-union.d.ts.map +1 -1
- package/dist/core/codegen/schemas/discriminated-union.js +14 -55
- package/dist/core/codegen/schemas/discriminated-union.js.map +1 -1
- package/dist/core/codegen/schemas/string-bool.d.ts +12 -1
- package/dist/core/codegen/schemas/string-bool.d.ts.map +1 -1
- package/dist/core/codegen/schemas/string-bool.js +19 -4
- package/dist/core/codegen/schemas/string-bool.js.map +1 -1
- package/dist/core/codegen/schemas/string.d.ts.map +1 -1
- package/dist/core/codegen/schemas/string.js +15 -10
- package/dist/core/codegen/schemas/string.js.map +1 -1
- package/dist/core/codegen/well-known-regex.d.ts +19 -1
- package/dist/core/codegen/well-known-regex.d.ts.map +1 -1
- package/dist/core/codegen/well-known-regex.js +21 -1
- package/dist/core/codegen/well-known-regex.js.map +1 -1
- package/dist/core/iife.d.ts +8 -0
- package/dist/core/iife.d.ts.map +1 -1
- package/dist/core/iife.js +8 -0
- package/dist/core/iife.js.map +1 -1
- package/dist/runtime.d.ts +1 -0
- package/dist/runtime.js +2 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discriminated-union.js","names":[],"sources":["../../../../src/core/codegen/schemas/discriminated-union.ts"],"sourcesContent":["import type { DiscriminatedUnionIR, LiteralValue, ObjectIR, SchemaIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport {\n declareFastTemps,\n emitConstant,\n escapeString,\n extendPath,\n hasMutation,\n literalToJs,\n} from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType } from \"../emit-issue.js\";\n\n/** One `discriminator value → option index` dispatch entry. */\ntype DiscriminatorCase = DiscriminatedUnionIR[\"cases\"][number];\n\nexport function slowDiscriminatedUnion(\n ir: SchemaIR & { type: \"discriminatedUnion\" },\n g: SlowGen,\n): string {\n const discKey = escapeString(ir.discriminator);\n\n let code = emit`\n if(typeof ${g.input}!==\"object\"||${g.input}===null||Array.isArray(${g.input})){\n ${invalidType(g, \"object\", { codeFirst: true })}\n }else{`;\n\n const objVar = g.temp(\"du\");\n code += `var ${objVar}=${g.input};switch(${objVar}[${discKey}]){`;\n\n for (const { value, option: index } of ir.cases) {\n const option = ir.options[index] as SchemaIR;\n code += emit`\n case ${literalToJs(value)}:\n ${g.visit(option, { input: objVar, output: objVar })}\n break;`;\n }\n\n const msgProp = g.typeMsg === undefined ? \"\" : `,message:${JSON.stringify(g.typeMsg)}`;\n // Field for field what $ZodDiscriminatedUnion pushes when no option matches:\n // `{ code, errors: [], note: \"No matching discriminator\", discriminator,\n // options, input, path: [def.discriminator] }`. `options` is\n // `Array.from(disc.value.keys())` — every dispatch value in map insertion\n // order, which is exactly `ir.cases` (option order, then each option's\n // `propValues[discriminator]` in ITS order, so an omittable discriminator\n // lists `undefined` right after its own values). The locale reads the list\n // for \"Invalid discriminator value. Expected 'a' | 'b'\". A fresh array\n // literal per push, as zod allocates one, so consumers never share or\n // mutate a hoisted table.\n const optionsList = ir.cases.map(({ value }) => literalToJs(value)).join(\",\");\n code += emit`\n default:\n ${g.issues}.push({code:\"invalid_union\",errors:[],note:\"No matching discriminator\",discriminator:${discKey},options:[${optionsList}],input:${g.input},path:${extendPath(g.path, discKey)}${msgProp}});\n }`;\n // Propagate option-applied mutations (defaults, coercions, transforms,\n // overwrite checks, stringbool) back to the output location. Each option is\n // visited with output:objVar — a fresh local — so a mutating option's clone is\n // reassigned into objVar and stranded there; without this write-back the caller\n // returns the ORIGINAL input by reference and the mutation is silently lost.\n // Gated on mutation so a pure-validation union stays a zero-write pass-through\n // (objVar still aliases the input). On the no-match/failure paths objVar equals\n // the input, so the write is a harmless self-assignment.\n if (ir.options.some(hasMutation)) {\n code += `${g.output}=${objVar};`;\n }\n code += `}`;\n return `${code}\\n`;\n}\n\n/**\n * Emit an O(1) switch-dispatch fast-check for a discriminated union — real\n * (`z.discriminatedUnion`) or one detected inside a plain `z.union`\n * (see {@link detectUnionDiscriminator}). Both share this so the detected case\n * inherits the size-gating and the per-case guard strip.\n *\n * `discSkipKey` tells each object option to drop its own type-guard and\n * discriminator re-check: the caller's guard (`typeof x===\"object\"&&…` below)\n * already proved object-ness, and the matched switch case has fixed the\n * discriminator value, so re-emitting either is pure redundancy the optimizer\n * only removes when it inlines this helper — which a union large enough to\n * matter won't. Routed through the normal `visit` so size-gated extraction\n * still bounds the switch (the strip survives into any hoisted helper);\n * non-object options ignore the hint and keep their own guard.\n *\n * Returns null if any option is fast-path-ineligible.\n */\nexport function emitFastDiscriminatedSwitch(\n g: FastGen,\n discriminator: string,\n cases: readonly DiscriminatorCase[],\n options: readonly SchemaIR[],\n): string | null {\n const x = g.input;\n const discKey = escapeString(discriminator);\n const helperName = g.temp(\"du\");\n const helperParam = g.temp(\"dx\");\n\n // The switch body is its own function: size-gate the options against the cap\n // in a fresh scope, otherwise many small options accumulate into the caller's\n // scope while this helper itself grows unbounded past the TurboFan budget.\n const body = g.scoped(helperParam);\n const table = stringDispatchTable(cases);\n\n if (table === null) {\n const caseStrs: string[] = [];\n for (const { value, option: index } of cases) {\n const check = body.visit(options[index] as SchemaIR, { discSkipKey: discriminator });\n if (check === null) return null;\n caseStrs.push(`case ${literalToJs(value)}:return ${check};`);\n }\n g.ctx.preamble.push(\n `function ${helperName}(${helperParam}){${declareFastTemps(body.scope)}switch(${helperParam}[${discKey}]){${caseStrs.join(\"\")}default:return false;}}`,\n );\n } else {\n // Dispatch through a string→ordinal table, then switch on the ordinal. V8\n // compiles a switch over STRING labels as sequential `===` comparisons, so\n // the plain form costs ~0.5 ns per preceding case: measured 4.1 ns (2\n // variants), 11.4 (8), 52.1 (80). A dense integer switch becomes a jump\n // table, leaving the lookup flat — 5.9 ns (8) and 15.1 (80), i.e. 1.9x to\n // 3.5x, for a table that adds ~1.3% to a union's generated bytes.\n //\n // `typeof t===\"string\"` is load-bearing: property access would coerce a\n // non-string discriminator (an object's toString, a number) into a key that\n // could hit a case whose own discriminator check the switch has stripped.\n // Strict equality never matched those, so the guard keeps the verdict.\n const caseStrs: string[] = [];\n for (const [optionIndex, ordinal] of table.ordinals) {\n const check = body.visit(options[optionIndex] as SchemaIR, { discSkipKey: discriminator });\n if (check === null) return null;\n caseStrs.push(`case ${ordinal}:return ${check};`);\n }\n const tableVar = emitConstant(g.ctx, \"dt\", table.initializer);\n const t = g.temp(\"dv\");\n g.ctx.preamble.push(\n `function ${helperName}(${helperParam}){${declareFastTemps(body.scope)}var ${t}=${helperParam}[${discKey}];` +\n `switch(typeof ${t}===\"string\"?${tableVar}[${t}]:0){${caseStrs.join(\"\")}default:return false;}}`,\n );\n }\n\n return `typeof ${x}===\"object\"&&${x}!==null&&!Array.isArray(${x})&&${helperName}(${x})`;\n}\n\n/**\n * Minimum case count for ordinal dispatch. Measured crossover is 3: at 2 cases\n * the string switch is one comparison and beats the extra table lookup\n * (4.1 ns vs 4.5), at 3 the table already wins (6.1 vs 4.6).\n */\nconst MIN_TABLE_DISPATCH = 3;\n\n/**\n * Build the `{value: ordinal}` dispatch table for a set of cases, or null when\n * the plain string switch should be kept. Requires every discriminator value to\n * be a string — mixed types would collide once coerced to property keys (`5`\n * and `\"5\"`) — and excludes `__proto__`, which an object literal cannot hold as\n * an own key. Values that select the SAME option share one ordinal, so a\n * multi-value literal emits its check once instead of per value.\n */\nfunction stringDispatchTable(\n cases: readonly DiscriminatorCase[],\n): { initializer: string; ordinals: Map<number, number> } | null {\n if (cases.length < MIN_TABLE_DISPATCH) return null;\n if (!cases.every((c) => typeof c.value === \"string\" && c.value !== \"__proto__\")) return null;\n\n const ordinals = new Map<number, number>();\n const entries: string[] = [];\n for (const { value, option } of cases) {\n let ordinal = ordinals.get(option);\n if (ordinal === undefined) {\n ordinal = ordinals.size + 1;\n ordinals.set(option, ordinal);\n }\n entries.push(`${escapeString(value as string)}:${ordinal}`);\n }\n return { initializer: `{${entries.join(\",\")}}`, ordinals };\n}\n\nexport function fastDiscriminatedUnion(ir: DiscriminatedUnionIR, g: FastGen): string | null {\n return emitFastDiscriminatedSwitch(g, ir.discriminator, ir.cases, ir.options);\n}\n\n/**\n * Minimum option count for rewriting a plain `z.union` to switch dispatch. Below\n * this the switch helper's fixed call overhead loses to a fully-inlined\n * `||`-chain that V8 keeps flat: measured crossover is ~4 options (n=3 can hit\n * 0.6x — a regression — while n=5 is 1.27x and n=32 is 2.34x), so 5 captures the\n * stable wins with margin and never regresses a small union. Real\n * `z.discriminatedUnion` is unaffected — it dispatches via switch by construction\n * regardless of size.\n */\nconst MIN_AUTO_DISCRIMINATE_OPTIONS = 5;\n\n/**\n * Values that switch correctly under `===` (excludes `undefined` and `NaN`).\n *\n * Also excludes a SYMBOL — now that `LiteralIR.values` admits one, this is the\n * guard that keeps it out. A symbol discriminant has no source form, so there\n * is no `case` label to emit for it (`literalToJs` refuses it by type), and the\n * ordinal-table variant is string-keyed besides. Detection bails to the\n * `||`-chain, where the option's own literal check does the right thing by\n * reading the value list off the retained schema.\n */\nfunction isSwitchableDiscriminant(v: LiteralValue): v is string | number | boolean | bigint | null {\n return (\n v === null ||\n typeof v === \"string\" ||\n typeof v === \"boolean\" ||\n typeof v === \"bigint\" ||\n (typeof v === \"number\" && !Number.isNaN(v))\n );\n}\n\n/**\n * Detect whether a plain (untagged) `z.union` is *structurally* a discriminated\n * union, so its fast path can use O(1) switch dispatch instead of probing every\n * arm. Returns the discriminator + dispatch table, or null to keep the\n * `||`-chain.\n *\n * Requires (proving the switch accepts exactly what the `||`-chain would): every\n * option is a plain object that pins one shared key to a REQUIRED literal\n * (`prop.type === \"literal\"` — an optional/non-literal key is rejected), and the\n * literal values are pairwise DISJOINT across options. Disjointness is the crux:\n * it guarantees at most one option can accept any given input, so dispatching to\n * that single option is equivalent to trying them all. Any value shared by two\n * options (ambiguous), a non-switchable value (`undefined`/`NaN`), or a\n * non-object option makes detection bail to the safe `||`-chain.\n *\n * Fast-path only: the slow path keeps `z.union`'s sequential trial and its\n * `invalid_union` error shape, so failure output stays byte-identical to Zod.\n */\nexport function detectUnionDiscriminator(\n options: readonly SchemaIR[],\n): { discriminator: string; cases: DiscriminatorCase[] } | null {\n if (options.length < MIN_AUTO_DISCRIMINATE_OPTIONS) return null;\n const objects: ObjectIR[] = [];\n for (const option of options) {\n if (option.type !== \"object\") return null;\n objects.push(option);\n }\n const first = objects[0];\n if (first === undefined) return null; // unreachable (length checked above)\n\n // Only keys present in the first option can be shared by all; try each.\n candidate: for (const key of Object.keys(first.properties)) {\n const seen = new Set<string | number | boolean | bigint | null>();\n const cases: DiscriminatorCase[] = [];\n for (const [i, object] of objects.entries()) {\n const prop = object.properties[key];\n if (prop === undefined || prop.type !== \"literal\") continue candidate;\n for (const value of prop.values) {\n if (!isSwitchableDiscriminant(value)) continue candidate;\n if (seen.has(value)) continue candidate; // shared value → ambiguous dispatch\n seen.add(value);\n cases.push({ value, option: i });\n }\n }\n return { discriminator: key, cases };\n }\n return null;\n}\n"],"mappings":";;;;AAgBA,SAAgB,uBACd,IACA,GACQ;CACR,MAAM,UAAU,aAAa,GAAG,aAAa;CAE7C,IAAI,OAAO,IAAI;gBACD,EAAE,MAAM,eAAe,EAAE,MAAM,yBAAyB,EAAE,MAAM;QACxE,YAAY,GAAG,UAAU,EAAE,WAAW,KAAK,CAAC,EAAE;;CAGpD,MAAM,SAAS,EAAE,KAAK,IAAI;CAC1B,QAAQ,OAAO,OAAO,GAAG,EAAE,MAAM,UAAU,OAAO,GAAG,QAAQ;CAE7D,KAAK,MAAM,EAAE,OAAO,QAAQ,WAAW,GAAG,OAAO;EAC/C,MAAM,SAAS,GAAG,QAAQ;EAC1B,QAAQ,IAAI;aACH,YAAY,KAAK,EAAE;UACtB,EAAE,MAAM,QAAQ;GAAE,OAAO;GAAQ,QAAQ;EAAO,CAAC,EAAE;;CAE3D;CAEA,MAAM,UAAU,EAAE,YAAY,KAAA,IAAY,KAAK,YAAY,KAAK,UAAU,EAAE,OAAO;CAWnF,MAAM,cAAc,GAAG,MAAM,KAAK,EAAE,YAAY,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG;CAC5E,QAAQ,IAAI;;QAEN,EAAE,OAAO,uFAAuF,QAAQ,YAAY,YAAY,UAAU,EAAE,MAAM,QAAQ,WAAW,EAAE,MAAM,OAAO,IAAI,QAAQ;;CAUtM,IAAI,GAAG,QAAQ,KAAK,WAAW,GAC7B,QAAQ,GAAG,EAAE,OAAO,GAAG,OAAO;CAEhC,QAAQ;CACR,OAAO,GAAG,KAAK;AACjB;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,4BACd,GACA,eACA,OACA,SACe;CACf,MAAM,IAAI,EAAE;CACZ,MAAM,UAAU,aAAa,aAAa;CAC1C,MAAM,aAAa,EAAE,KAAK,IAAI;CAC9B,MAAM,cAAc,EAAE,KAAK,IAAI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AAI,SAAS,KAAA,KAAa,KAAK,SAAS,WAAW,SAAS;GAC5D,KAAK,MAAM,SAAS,KAAK,QAAQ;IAC/B,IAAI,CAAC,yBAAyB,KAAK,GAAG,SAAS;IAC/C,IAAI,KAAK,IAAI,KAAK,GAAG,SAAS;IAC9B,KAAK,IAAI,KAAK;IACd,MAAM,KAAK;KAAE;KAAO,QAAQ;IAAE,CAAC;GACjC;EACF;EACA,OAAO;GAAE,eAAe;GAAK;EAAM;CACrC;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"discriminated-union.js","names":[],"sources":["../../../../src/core/codegen/schemas/discriminated-union.ts"],"sourcesContent":["import type { DiscriminatedUnionIR, LiteralValue, ObjectIR, SchemaIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport {\n declareFastTemps,\n escapeString,\n extendPath,\n hasMutation,\n literalToJs,\n} from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType } from \"../emit-issue.js\";\n\n/** One `discriminator value → option index` dispatch entry. */\ntype DiscriminatorCase = DiscriminatedUnionIR[\"cases\"][number];\n\nexport function slowDiscriminatedUnion(\n ir: SchemaIR & { type: \"discriminatedUnion\" },\n g: SlowGen,\n): string {\n const discKey = escapeString(ir.discriminator);\n\n let code = emit`\n if(typeof ${g.input}!==\"object\"||${g.input}===null||Array.isArray(${g.input})){\n ${invalidType(g, \"object\", { codeFirst: true })}\n }else{`;\n\n const objVar = g.temp(\"du\");\n code += `var ${objVar}=${g.input};switch(${objVar}[${discKey}]){`;\n\n for (const { value, option: index } of ir.cases) {\n const option = ir.options[index] as SchemaIR;\n code += emit`\n case ${literalToJs(value)}:\n ${g.visit(option, { input: objVar, output: objVar })}\n break;`;\n }\n\n const msgProp = g.typeMsg === undefined ? \"\" : `,message:${JSON.stringify(g.typeMsg)}`;\n // Field for field what $ZodDiscriminatedUnion pushes when no option matches:\n // `{ code, errors: [], note: \"No matching discriminator\", discriminator,\n // options, input, path: [def.discriminator] }`. `options` is\n // `Array.from(disc.value.keys())` — every dispatch value in map insertion\n // order, which is exactly `ir.cases` (option order, then each option's\n // `propValues[discriminator]` in ITS order, so an omittable discriminator\n // lists `undefined` right after its own values). The locale reads the list\n // for \"Invalid discriminator value. Expected 'a' | 'b'\". A fresh array\n // literal per push, as zod allocates one, so consumers never share or\n // mutate a hoisted table.\n const optionsList = ir.cases.map(({ value }) => literalToJs(value)).join(\",\");\n code += emit`\n default:\n ${g.issues}.push({code:\"invalid_union\",errors:[],note:\"No matching discriminator\",discriminator:${discKey},options:[${optionsList}],input:${g.input},path:${extendPath(g.path, discKey)}${msgProp}});\n }`;\n // Propagate option-applied mutations (defaults, coercions, transforms,\n // overwrite checks, stringbool) back to the output location. Each option is\n // visited with output:objVar — a fresh local — so a mutating option's clone is\n // reassigned into objVar and stranded there; without this write-back the caller\n // returns the ORIGINAL input by reference and the mutation is silently lost.\n // Gated on mutation so a pure-validation union stays a zero-write pass-through\n // (objVar still aliases the input). On the no-match/failure paths objVar equals\n // the input, so the write is a harmless self-assignment.\n if (ir.options.some(hasMutation)) {\n code += `${g.output}=${objVar};`;\n }\n code += `}`;\n return `${code}\\n`;\n}\n\n/**\n * Emit an O(1) switch-dispatch fast-check for a discriminated union — real\n * (`z.discriminatedUnion`) or one detected inside a plain `z.union`\n * (see {@link detectUnionDiscriminator}). Both share this so the detected case\n * inherits the size-gating and the per-case guard strip.\n *\n * `discSkipKey` tells each object option to drop its own type-guard and\n * discriminator re-check: the caller's guard (`typeof x===\"object\"&&…` below)\n * already proved object-ness, and the matched switch case has fixed the\n * discriminator value, so re-emitting either is pure redundancy the optimizer\n * only removes when it inlines this helper — which a union large enough to\n * matter won't. Routed through the normal `visit` so size-gated extraction\n * still bounds the switch (the strip survives into any hoisted helper);\n * non-object options ignore the hint and keep their own guard.\n *\n * Returns null if any option is fast-path-ineligible.\n */\nexport function emitFastDiscriminatedSwitch(\n g: FastGen,\n discriminator: string,\n cases: readonly DiscriminatorCase[],\n options: readonly SchemaIR[],\n): string | null {\n const x = g.input;\n const discKey = escapeString(discriminator);\n const helperName = g.temp(\"du\");\n const helperParam = g.temp(\"dx\");\n\n // The switch body is its own function: size-gate the options against the cap\n // in a fresh scope, otherwise many small options accumulate into the caller's\n // scope while this helper itself grows unbounded past the TurboFan budget.\n //\n // The switch is over the literal labels themselves. An earlier revision\n // routed three or more string labels through a `{value: ordinal}` table and\n // switched on the ordinal, on the theory that V8 compiles a string switch as\n // sequential comparisons and a dense integer one as a jump table. Measured on\n // V8 13.x (node 24) that is a loss at every size: the table's `t[v]` is a\n // keyed load whose key varies per parse, which goes megamorphic the moment\n // the input rotates through the options, while the string switch stays\n // nearly flat (8.6 ns at 8 cases, 10.1 at 32, 17.3 at 80, rotating input)\n // against the table's 12.9, 15.8 and 20.8. The build path switches the same\n // way (see `buildDispatch`).\n const body = g.scoped(helperParam);\n const caseStrs: string[] = [];\n for (const { value, option: index } of cases) {\n const check = body.visit(options[index] as SchemaIR, { discSkipKey: discriminator });\n if (check === null) return null;\n caseStrs.push(`case ${literalToJs(value)}:return ${check};`);\n }\n g.ctx.preamble.push(\n `function ${helperName}(${helperParam}){${declareFastTemps(body.scope)}switch(${helperParam}[${discKey}]){${caseStrs.join(\"\")}default:return false;}}`,\n );\n\n return `typeof ${x}===\"object\"&&${x}!==null&&!Array.isArray(${x})&&${helperName}(${x})`;\n}\n\nexport function fastDiscriminatedUnion(ir: DiscriminatedUnionIR, g: FastGen): string | null {\n return emitFastDiscriminatedSwitch(g, ir.discriminator, ir.cases, ir.options);\n}\n\n/**\n * Minimum option count for rewriting a plain `z.union` to switch dispatch. Below\n * this the switch helper's fixed call overhead loses to a fully-inlined\n * `||`-chain that V8 keeps flat: measured crossover is ~4 options (n=3 can hit\n * 0.6x — a regression — while n=5 is 1.27x and n=32 is 2.34x), so 5 captures the\n * stable wins with margin and never regresses a small union. Real\n * `z.discriminatedUnion` is unaffected — it dispatches via switch by construction\n * regardless of size.\n */\nconst MIN_AUTO_DISCRIMINATE_OPTIONS = 5;\n\n/**\n * Values that switch correctly under `===` (excludes `undefined` and `NaN`).\n *\n * Also excludes a SYMBOL — now that `LiteralIR.values` admits one, this is the\n * guard that keeps it out. A symbol discriminant has no source form, so there\n * is no `case` label to emit for it (`literalToJs` refuses it by type), and the\n * ordinal-table variant is string-keyed besides. Detection bails to the\n * `||`-chain, where the option's own literal check does the right thing by\n * reading the value list off the retained schema.\n */\nfunction isSwitchableDiscriminant(v: LiteralValue): v is string | number | boolean | bigint | null {\n return (\n v === null ||\n typeof v === \"string\" ||\n typeof v === \"boolean\" ||\n typeof v === \"bigint\" ||\n (typeof v === \"number\" && !Number.isNaN(v))\n );\n}\n\n/**\n * Detect whether a plain (untagged) `z.union` is *structurally* a discriminated\n * union, so its fast path can use O(1) switch dispatch instead of probing every\n * arm. Returns the discriminator + dispatch table, or null to keep the\n * `||`-chain.\n *\n * Requires (proving the switch accepts exactly what the `||`-chain would): every\n * option is a plain object that pins one shared key to a REQUIRED literal\n * (`prop.type === \"literal\"` — an optional/non-literal key is rejected), and the\n * literal values are pairwise DISJOINT across options. Disjointness is the crux:\n * it guarantees at most one option can accept any given input, so dispatching to\n * that single option is equivalent to trying them all. Any value shared by two\n * options (ambiguous), a non-switchable value (`undefined`/`NaN`), or a\n * non-object option makes detection bail to the safe `||`-chain.\n *\n * The slow path is untouched: it keeps `z.union`'s sequential trial and its\n * `invalid_union` error shape, so failure output stays byte-identical to Zod.\n * The fast path and the build path both dispatch on the result — the build\n * path from two options up (`minOptions`), since its options are hosted calls\n * either way and a switch only ever replaces probes with one call; see\n * `buildUnion`.\n */\nexport function detectUnionDiscriminator(\n options: readonly SchemaIR[],\n minOptions: number = MIN_AUTO_DISCRIMINATE_OPTIONS,\n): { discriminator: string; cases: DiscriminatorCase[] } | null {\n if (options.length < minOptions) return null;\n const objects: ObjectIR[] = [];\n for (const option of options) {\n if (option.type !== \"object\") return null;\n objects.push(option);\n }\n const first = objects[0];\n if (first === undefined) return null; // unreachable (length checked above)\n\n // Only keys present in the first option can be shared by all; try each.\n candidate: for (const key of Object.keys(first.properties)) {\n const seen = new Set<string | number | boolean | bigint | null>();\n const cases: DiscriminatorCase[] = [];\n for (const [i, object] of objects.entries()) {\n const prop = object.properties[key];\n if (prop === undefined || prop.type !== \"literal\") continue candidate;\n for (const value of prop.values) {\n if (!isSwitchableDiscriminant(value)) continue candidate;\n if (seen.has(value)) continue candidate; // shared value → ambiguous dispatch\n seen.add(value);\n cases.push({ value, option: i });\n }\n }\n return { discriminator: key, cases };\n }\n return null;\n}\n"],"mappings":";;;;AAeA,SAAgB,uBACd,IACA,GACQ;CACR,MAAM,UAAU,aAAa,GAAG,aAAa;CAE7C,IAAI,OAAO,IAAI;gBACD,EAAE,MAAM,eAAe,EAAE,MAAM,yBAAyB,EAAE,MAAM;QACxE,YAAY,GAAG,UAAU,EAAE,WAAW,KAAK,CAAC,EAAE;;CAGpD,MAAM,SAAS,EAAE,KAAK,IAAI;CAC1B,QAAQ,OAAO,OAAO,GAAG,EAAE,MAAM,UAAU,OAAO,GAAG,QAAQ;CAE7D,KAAK,MAAM,EAAE,OAAO,QAAQ,WAAW,GAAG,OAAO;EAC/C,MAAM,SAAS,GAAG,QAAQ;EAC1B,QAAQ,IAAI;aACH,YAAY,KAAK,EAAE;UACtB,EAAE,MAAM,QAAQ;GAAE,OAAO;GAAQ,QAAQ;EAAO,CAAC,EAAE;;CAE3D;CAEA,MAAM,UAAU,EAAE,YAAY,KAAA,IAAY,KAAK,YAAY,KAAK,UAAU,EAAE,OAAO;CAWnF,MAAM,cAAc,GAAG,MAAM,KAAK,EAAE,YAAY,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG;CAC5E,QAAQ,IAAI;;QAEN,EAAE,OAAO,uFAAuF,QAAQ,YAAY,YAAY,UAAU,EAAE,MAAM,QAAQ,WAAW,EAAE,MAAM,OAAO,IAAI,QAAQ;;CAUtM,IAAI,GAAG,QAAQ,KAAK,WAAW,GAC7B,QAAQ,GAA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;EAC5B,IAAI,OAAO,SAAS,UAAU,OAAO;EACrC,QAAQ,KAAK,MAAM;CACrB;CACA,MAAM,QAAQ,QAAQ;CACtB,IAAI,UAAU,KAAA,GAAW,OAAO;CAGhC,WAAW,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,UAAU,GAAG;EAC1D,MAAM,uBAAO,IAAI,IAA+C;EAChE,MAAM,QAA6B,CAAC;EACpC,KAAK,MAAM,CAAC,GAAG,WAAW,QAAQ,QAAQ,GAAG;GAC3C,MAAM,OAAO,OAAO,WAAW;GAC/B,IAAI,SAAS,KAAA,KAAa,KAAK,SAAS,WAAW,SAAS;GAC5D,KAAK,MAAM,SAAS,KAAK,QAAQ;IAC/B,IAAI,CAAC,yBAAyB,KAAK,GAAG,SAAS;IAC/C,IAAI,KAAK,IAAI,KAAK,GAAG,SAAS;IAC9B,KAAK,IAAI,KAAK;IACd,MAAM,KAAK;KAAE;KAAO,QAAQ;IAAE,CAAC;GACjC;EACF;EACA,OAAO;GAAE,eAAe;GAAK;EAAM;CACrC;CACA,OAAO;AACT"}
|
|
@@ -3,8 +3,19 @@ import { CodeGenContext, SlowGen } from "../context.js";
|
|
|
3
3
|
//#region src/core/codegen/schemas/string-bool.d.ts
|
|
4
4
|
declare function slowStringBool(ir: StringBoolIR, g: SlowGen): string;
|
|
5
5
|
declare function stringBoolUsesInline(ir: StringBoolIR): boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Boolean expression: is `input` verbatim one of an INLINE codec's spellings?
|
|
8
|
+
*
|
|
9
|
+
* The accepted lists come from probing the schema with lowercase candidates
|
|
10
|
+
* (see extractStringBool), so for a case-insensitive codec an exact hit is
|
|
11
|
+
* exactly what `input.toLowerCase()` would have produced — and a handful of
|
|
12
|
+
* `===` on internalized strings is cheaper than the `toLowerCase()` call. The
|
|
13
|
+
* hashed form has no use for this: there the verbatim `Map.get` IS the lookup,
|
|
14
|
+
* retried on the lowercased string only when it misses.
|
|
15
|
+
*/
|
|
16
|
+
declare function stringBoolInlineHit(ir: StringBoolIR, input: string): string;
|
|
6
17
|
/** One lookup distinguishes true, false and absent; shared by hot and issue walks. */
|
|
7
18
|
declare function emitStringBoolMap(ir: StringBoolIR, ctx: CodeGenContext): string;
|
|
8
19
|
//#endregion
|
|
9
|
-
export { emitStringBoolMap, slowStringBool, stringBoolUsesInline };
|
|
20
|
+
export { emitStringBoolMap, slowStringBool, stringBoolInlineHit, stringBoolUsesInline };
|
|
10
21
|
//# sourceMappingURL=string-bool.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string-bool.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/string-bool.ts"],"mappings":";;;iBAMgB,eAAe,IAAI,cAAc,GAAG;
|
|
1
|
+
{"version":3,"file":"string-bool.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/string-bool.ts"],"mappings":";;;iBAMgB,eAAe,IAAI,cAAc,GAAG;iBAyDpC,qBAAqB,IAAI;;;;;;;;;;;iBAczB,oBAAoB,IAAI,cAAc;;iBAKtC,kBAAkB,IAAI,cAAc,KAAK"}
|
|
@@ -9,12 +9,12 @@ function slowStringBool(ir, g) {
|
|
|
9
9
|
${invalidType(g, "string")}
|
|
10
10
|
}else{
|
|
11
11
|
`;
|
|
12
|
-
const normalized = ir.caseSensitive ? g.input : g.temp("sbn");
|
|
13
|
-
if (!ir.caseSensitive) code += `var ${normalized}=${g.input}.toLowerCase();`;
|
|
14
12
|
const allValues = [...ir.truthy, ...ir.falsy];
|
|
15
13
|
const valuesExpr = JSON.stringify(allValues);
|
|
16
14
|
const expectedExtra = "expected:\"stringbool\"";
|
|
17
15
|
if (stringBoolUsesInline(ir)) {
|
|
16
|
+
const normalized = ir.caseSensitive ? g.input : g.temp("sbn");
|
|
17
|
+
if (!ir.caseSensitive) code += `var ${normalized}=${stringBoolInlineHit(ir, g.input)}?${g.input}:${g.input}.toLowerCase();`;
|
|
18
18
|
const truthyCondition = ir.truthy.map((v) => `${normalized}===${escapeString(v)}`).join("||");
|
|
19
19
|
const falsyCondition = ir.falsy.map((v) => `${normalized}===${escapeString(v)}`).join("||");
|
|
20
20
|
code += emit`
|
|
@@ -25,8 +25,10 @@ function slowStringBool(ir, g) {
|
|
|
25
25
|
} else {
|
|
26
26
|
const value = g.temp("sbv");
|
|
27
27
|
const lookup = emitStringBoolMap(ir, g.ctx);
|
|
28
|
+
const lowered = g.temp("sbn");
|
|
29
|
+
const retry = ir.caseSensitive ? "" : `if(${value}===undefined){var ${lowered}=${g.input}.toLowerCase();if(${lowered}!==${g.input}){${value}=${lookup}.get(${lowered});}}`;
|
|
28
30
|
code += emit`
|
|
29
|
-
var ${value}=${lookup}.get(${
|
|
31
|
+
var ${value}=${lookup}.get(${g.input});${retry}
|
|
30
32
|
if(${value}===undefined){${invalidValue(g, valuesExpr, { extra: expectedExtra })}}
|
|
31
33
|
else{${g.output}=${value};}
|
|
32
34
|
`;
|
|
@@ -37,12 +39,25 @@ function slowStringBool(ir, g) {
|
|
|
37
39
|
function stringBoolUsesInline(ir) {
|
|
38
40
|
return ir.truthy.length <= 5 && ir.falsy.length <= 5;
|
|
39
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* Boolean expression: is `input` verbatim one of an INLINE codec's spellings?
|
|
44
|
+
*
|
|
45
|
+
* The accepted lists come from probing the schema with lowercase candidates
|
|
46
|
+
* (see extractStringBool), so for a case-insensitive codec an exact hit is
|
|
47
|
+
* exactly what `input.toLowerCase()` would have produced — and a handful of
|
|
48
|
+
* `===` on internalized strings is cheaper than the `toLowerCase()` call. The
|
|
49
|
+
* hashed form has no use for this: there the verbatim `Map.get` IS the lookup,
|
|
50
|
+
* retried on the lowercased string only when it misses.
|
|
51
|
+
*/
|
|
52
|
+
function stringBoolInlineHit(ir, input) {
|
|
53
|
+
return [...ir.truthy, ...ir.falsy].map((v) => `${input}===${escapeString(v)}`).join("||");
|
|
54
|
+
}
|
|
40
55
|
/** One lookup distinguishes true, false and absent; shared by hot and issue walks. */
|
|
41
56
|
function emitStringBoolMap(ir, ctx) {
|
|
42
57
|
const pairs = [...ir.truthy.map((value) => [value, true]), ...ir.falsy.map((value) => [value, false])];
|
|
43
58
|
return emitConstant(ctx, "map_sb", `new Map(${JSON.stringify(pairs)})`);
|
|
44
59
|
}
|
|
45
60
|
//#endregion
|
|
46
|
-
export { emitStringBoolMap, slowStringBool, stringBoolUsesInline };
|
|
61
|
+
export { emitStringBoolMap, slowStringBool, stringBoolInlineHit, stringBoolUsesInline };
|
|
47
62
|
|
|
48
63
|
//# sourceMappingURL=string-bool.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string-bool.js","names":[],"sources":["../../../../src/core/codegen/schemas/string-bool.ts"],"sourcesContent":["import type { StringBoolIR } from \"../../types.js\";\nimport type { CodeGenContext, SlowGen } from \"../context.js\";\nimport { ENUM_INLINE_THRESHOLD, emitConstant, escapeString } from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType, invalidValue } from \"../emit-issue.js\";\n\nexport function slowStringBool(ir: StringBoolIR, g: SlowGen): string {\n let code = \"\";\n\n // Type check: input must be a string\n code += emit`\n if(typeof ${g.input}!==\"string\"){\n ${invalidType(g, \"string\")}\n }else{\n `;\n\n
|
|
1
|
+
{"version":3,"file":"string-bool.js","names":[],"sources":["../../../../src/core/codegen/schemas/string-bool.ts"],"sourcesContent":["import type { StringBoolIR } from \"../../types.js\";\nimport type { CodeGenContext, SlowGen } from \"../context.js\";\nimport { ENUM_INLINE_THRESHOLD, emitConstant, escapeString } from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType, invalidValue } from \"../emit-issue.js\";\n\nexport function slowStringBool(ir: StringBoolIR, g: SlowGen): string {\n let code = \"\";\n\n // Type check: input must be a string\n code += emit`\n if(typeof ${g.input}!==\"string\"){\n ${invalidType(g, \"string\")}\n }else{\n `;\n\n const allValues = [...ir.truthy, ...ir.falsy];\n const valuesExpr = JSON.stringify(allValues);\n // z.stringbool() is a Codec whose transform pushes\n // `{ code: \"invalid_value\", expected: \"stringbool\", values: [...] }` — the\n // only invalid_value producer that carries an `expected` (enum and literal\n // push `values` alone), and zod's locale keys off it. Both emitted lookups\n // below share this so the two code paths cannot drift apart.\n const expectedExtra = 'expected:\"stringbool\"';\n\n // Compare per-side counts against threshold (not the combined total)\n const useInline = stringBoolUsesInline(ir);\n\n // Case-insensitive matching tries the input VERBATIM before lowercasing it:\n // the accepted spellings are all lowercase, so an exact hit and the\n // lowercased hit are the same string. See buildStringBool for the measured\n // trade; this is the same shape on the eager walk.\n if (useInline) {\n const normalized = ir.caseSensitive ? g.input : g.temp(\"sbn\");\n if (!ir.caseSensitive) {\n code += `var ${normalized}=${stringBoolInlineHit(ir, g.input)}?${g.input}:${g.input}.toLowerCase();`;\n }\n const truthyCondition = ir.truthy.map((v) => `${normalized}===${escapeString(v)}`).join(\"||\");\n const falsyCondition = ir.falsy.map((v) => `${normalized}===${escapeString(v)}`).join(\"||\");\n code += emit`\n if(${truthyCondition}){${g.output}=true;}\n else if(${falsyCondition}){${g.output}=false;}\n else{${invalidValue(g, valuesExpr, { extra: expectedExtra })}}\n `;\n } else {\n const value = g.temp(\"sbv\");\n const lookup = emitStringBoolMap(ir, g.ctx);\n const lowered = g.temp(\"sbn\");\n const retry = ir.caseSensitive\n ? \"\"\n : `if(${value}===undefined){var ${lowered}=${g.input}.toLowerCase();` +\n `if(${lowered}!==${g.input}){${value}=${lookup}.get(${lowered});}}`;\n code += emit`\n var ${value}=${lookup}.get(${g.input});${retry}\n if(${value}===undefined){${invalidValue(g, valuesExpr, { extra: expectedExtra })}}\n else{${g.output}=${value};}\n `;\n }\n\n code += emit`}`;\n return `${code}\\n`;\n}\n\nexport function stringBoolUsesInline(ir: StringBoolIR): boolean {\n return ir.truthy.length <= ENUM_INLINE_THRESHOLD && ir.falsy.length <= ENUM_INLINE_THRESHOLD;\n}\n\n/**\n * Boolean expression: is `input` verbatim one of an INLINE codec's spellings?\n *\n * The accepted lists come from probing the schema with lowercase candidates\n * (see extractStringBool), so for a case-insensitive codec an exact hit is\n * exactly what `input.toLowerCase()` would have produced — and a handful of\n * `===` on internalized strings is cheaper than the `toLowerCase()` call. The\n * hashed form has no use for this: there the verbatim `Map.get` IS the lookup,\n * retried on the lowercased string only when it misses.\n */\nexport function stringBoolInlineHit(ir: StringBoolIR, input: string): string {\n return [...ir.truthy, ...ir.falsy].map((v) => `${input}===${escapeString(v)}`).join(\"||\");\n}\n\n/** One lookup distinguishes true, false and absent; shared by hot and issue walks. */\nexport function emitStringBoolMap(ir: StringBoolIR, ctx: CodeGenContext): string {\n const pairs = [\n ...ir.truthy.map((value) => [value, true]),\n ...ir.falsy.map((value) => [value, false]),\n ];\n return emitConstant(ctx, \"map_sb\", `new Map(${JSON.stringify(pairs)})`);\n}\n"],"mappings":";;;;AAMA,SAAgB,eAAe,IAAkB,GAAoB;CACnE,IAAI,OAAO;CAGX,QAAQ,IAAI;gBACE,EAAE,MAAM;QAChB,YAAY,GAAG,QAAQ,EAAE;;;CAI/B,MAAM,YAAY,CAAC,GAAG,GAAG,QAAQ,GAAG,GAAG,KAAK;CAC5C,MAAM,aAAa,KAAK,UAAU,SAAS;CAM3C,MAAM,gBAAgB;CAStB,IANkB,qBAAqB,EAM3B,GAAG;EACb,MAAM,aAAa,GAAG,gBAAgB,EAAE,QAAQ,EAAE,KAAK,KAAK;EAC5D,IAAI,CAAC,GAAG,eACN,QAAQ,OAAO,WAAW,GAAG,oBAAoB,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,GAAG,EAAE,MAAM;EAEtF,MAAM,kBAAkB,GAAG,OAAO,KAAK,MAAM,GAAG,WAAW,KAAK,aAAa,CAAC,GAAG,CAAC,CAAC,KAAK,IAAI;EAC5F,MAAM,iBAAiB,GAAG,MAAM,KAAK,MAAM,GAAG,WAAW,KAAK,aAAa,CAAC,GAAG,CAAC,CAAC,KAAK,IAAI;EAC1F,QAAQ,IAAI;WACL,gBAAgB,IAAI,EAAE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/core/codegen/schemas/string.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"string.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/string.ts"],"mappings":";;;iBA2GgB,WAAW,IAAI,UAAU,GAAG;;;;;;;;;;;iBAmK5B,gBAAgB,OAAO,SAAS,WAAW,KAAK;iBAuDhD,WAAW,IAAI,UAAU,GAAG"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { EMAIL_REGEX_SOURCE, fastTestSource } from "../well-known-regex.js";
|
|
2
|
-
import { checkPriority, emitEffectCallable, emitEffectFn, emitRegex, emitRegexSourceString, escapeString } from "../context.js";
|
|
1
|
+
import { EMAIL_REGEX_SOURCE, fastTestSource, isDefaultEmailPattern } from "../well-known-regex.js";
|
|
2
|
+
import { checkPriority, emitEffectCallable, emitEffectFn, emitRegex, emitRegexSourceString, emitRuntimeHelper, escapeString } from "../context.js";
|
|
3
3
|
import { emit } from "../emit.js";
|
|
4
4
|
import { invalidFormat, invalidType, tooBig, tooSmall } from "../emit-issue.js";
|
|
5
|
+
import { ZC_EMAIL_DECL } from "../issue-decls.js";
|
|
5
6
|
import { refineCheck, superRefineCheck, superRefineFastTest } from "./effect.js";
|
|
6
7
|
import { stringLengthTests, whenGatedSizeChecks } from "./sizeable.js";
|
|
7
8
|
//#region src/core/codegen/schemas/string.ts
|
|
@@ -163,7 +164,7 @@ function slowString(ir, g) {
|
|
|
163
164
|
code += emit`${g.output}=${emitEffectFn(g.ctx, check.source)}(${g.input});`;
|
|
164
165
|
break;
|
|
165
166
|
case "string_format": {
|
|
166
|
-
let
|
|
167
|
+
let prefix;
|
|
167
168
|
let pattern;
|
|
168
169
|
if (check.format === "url" && !check.pattern) {
|
|
169
170
|
code += slowUrlCheck(check, g);
|
|
@@ -171,22 +172,25 @@ function slowString(ir, g) {
|
|
|
171
172
|
}
|
|
172
173
|
if (check.format === "email") {
|
|
173
174
|
pattern = check.pattern ?? EMAIL_REGEX_SOURCE;
|
|
174
|
-
|
|
175
|
+
prefix = "email";
|
|
175
176
|
} else if (check.format === "regex" && check.pattern) {
|
|
176
177
|
pattern = check.pattern;
|
|
177
|
-
|
|
178
|
+
prefix = "str";
|
|
178
179
|
} else if (check.format === "uuid") {
|
|
179
180
|
pattern = check.pattern ?? "^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$";
|
|
180
|
-
|
|
181
|
+
prefix = "uuid";
|
|
181
182
|
} else if (check.pattern) {
|
|
182
183
|
pattern = check.pattern;
|
|
183
|
-
|
|
184
|
+
prefix = "str";
|
|
184
185
|
} else continue;
|
|
186
|
+
const scanner = isDefaultEmailPattern(pattern, check.patternFlags) ? emitRuntimeHelper(g.ctx, "__zcEmail", ZC_EMAIL_DECL) : null;
|
|
187
|
+
const regexVar = scanner === null ? g.regex(prefix, pattern, check.patternFlags) : null;
|
|
185
188
|
let extra;
|
|
186
|
-
if (!check.bareIssue) extra = `pattern:${!check.patternFlags && fastTestSource(pattern) !== null ? emitRegexSourceString(g.ctx, pattern) : `${regexVar}.toString()`}`;
|
|
189
|
+
if (!check.bareIssue) extra = `pattern:${!check.patternFlags && fastTestSource(pattern) !== null || regexVar === null ? emitRegexSourceString(g.ctx, pattern) : `${regexVar}.toString()`}`;
|
|
190
|
+
const test = regexVar === null ? `${scanner}(${g.input})` : `${regexVar}.test(${g.input})`;
|
|
187
191
|
code += emit`
|
|
188
|
-
${lastIndexReset(regexVar, check.patternFlags)}
|
|
189
|
-
if(!${
|
|
192
|
+
${regexVar === null ? "" : lastIndexReset(regexVar, check.patternFlags)}
|
|
193
|
+
if(!${test}){
|
|
190
194
|
${invalidFormat(g, { expr: escapeString(check.format) }, {
|
|
191
195
|
origin: check.bareIssue ? void 0 : "string",
|
|
192
196
|
extra,
|
|
@@ -232,6 +236,7 @@ function fastStringCheck(check, x, ctx) {
|
|
|
232
236
|
prefix = "re";
|
|
233
237
|
pattern = check.pattern;
|
|
234
238
|
} else return null;
|
|
239
|
+
if (isDefaultEmailPattern(pattern, check.patternFlags)) return `${emitRuntimeHelper(ctx, "__zcEmail", ZC_EMAIL_DECL)}(${x})`;
|
|
235
240
|
const v = emitRegex(ctx, prefix, pattern, check.patternFlags);
|
|
236
241
|
return check.patternFlags && /[gy]/.test(check.patternFlags) ? `((${v}.lastIndex=0),${v}.test(${x}))` : `${v}.test(${x})`;
|
|
237
242
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string.js","names":[],"sources":["../../../../src/core/codegen/schemas/string.ts"],"sourcesContent":["import type { CheckIR, CheckStringFormat, StringIR } from \"../../types.js\";\nimport type { CodeGenContext, FastGen, SlowGen } from \"../context.js\";\nimport {\n checkPriority,\n emitEffectCallable,\n emitEffectFn,\n emitRegex,\n emitRegexSourceString,\n escapeString,\n} from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidFormat, invalidType, tooBig, tooSmall } from \"../emit-issue.js\";\nimport { EMAIL_REGEX_SOURCE, fastTestSource, UUID_REGEX_SOURCE } from \"../well-known-regex.js\";\nimport { refineCheck, superRefineCheck, superRefineFastTest } from \"./effect.js\";\nimport { stringLengthTests, whenGatedSizeChecks } from \"./sizeable.js\";\n\n/** `re.lastIndex=0;` reset statement for stateful (g/y-flagged) regexes. */\nfunction lastIndexReset(regexVar: string, flags: string | undefined): string {\n return flags && /[gy]/.test(flags) ? `${regexVar}.lastIndex=0;` : \"\";\n}\n\n/**\n * `regexes.httpProtocol.source`. `parseURLObject` compares a url check's\n * protocol SOURCE against it — not the schema constructor — so any check whose\n * protocol is spelled this way gets the guard, `z.httpUrl()` or not.\n */\nconst HTTP_PROTOCOL_SOURCE = \"^https?$\";\n\n/**\n * Generate the url check, mirroring $ZodURL semantics:\n * trim → (for an http(s)-protocol check without normalize) require `://` →\n * new URL(trimmed) → optional hostname/protocol regex tests → write back\n * url.href (normalize) or the trimmed input with its tabs and newlines deleted.\n *\n * The `://` guard is `parseURLObject`'s: without it the URL parser accepts\n * `http:example.com`, and its rejection is a distinct issue (`note: \"Invalid\n * URL format\"`, no `pattern`) pushed BEFORE the parser runs. The deletion of\n * `\\t`, `\\n` and `\\r` (`stripTabAndNewline`) matches what the parser itself\n * drops before it reads the host, so the returned value names the host that was\n * validated.\n *\n * $ZodURL is another constructor that OVERRIDES the `??=`-installed default\n * check, so none of the issues below carries `origin` — and the two that do\n * carry a `pattern` use `regex.source`, not the default check's\n * `regex.toString()` (no delimiters, no flags). Both are reproduced verbatim.\n */\nfunction slowUrlCheck(check: CheckStringFormat, g: SlowGen): string {\n const trimmedVar = g.temp(\"ut\");\n const urlVar = g.temp(\"u\");\n let inner = \"\";\n if (check.hostname) {\n const re = g.regex(\"host\", check.hostname, check.hostnameFlags);\n inner += emit`\n ${lastIndexReset(re, check.hostnameFlags)}\n if(!${re}.test(${urlVar}.hostname)){\n ${invalidFormat(g, \"url\", {\n extra: `note:\"Invalid hostname\",pattern:${escapeString(check.hostname)}`,\n message: check.message,\n })}\n }`;\n }\n if (check.protocol) {\n const re = g.regex(\"proto\", check.protocol, check.protocolFlags);\n const protoExpr = `(${urlVar}.protocol.endsWith(\":\")?${urlVar}.protocol.slice(0,-1):${urlVar}.protocol)`;\n inner += emit`\n ${lastIndexReset(re, check.protocolFlags)}\n if(!${re}.test(${protoExpr})){\n ${invalidFormat(g, \"url\", {\n extra: `note:\"Invalid protocol\",pattern:${escapeString(check.protocol)}`,\n message: check.message,\n })}\n }`;\n }\n // Zod writes the value back even when hostname/protocol issues were pushed.\n const stripped = check.normalize\n ? `${urlVar}.href`\n : `${trimmedVar}.replace(${g.regex(\"tnl\", \"[\\\\t\\\\n\\\\r]\", \"g\")},\"\")`;\n inner += `${g.output}=${stripped};`;\n let parse = emit`\n var ${urlVar}=null;\n try{${urlVar}=new URL(${trimmedVar});}catch(_){}\n if(${urlVar}===null){\n ${invalidFormat(g, \"url\", { message: check.message })}\n }else{\n ${inner}\n }`;\n if (!check.normalize && check.protocol === HTTP_PROTOCOL_SOURCE) {\n const re = g.regex(\"httpUrl\", \"^https?:\\\\/\\\\/\", \"i\");\n parse = emit`\n if(!${re}.test(${trimmedVar})){\n ${invalidFormat(g, \"url\", { extra: `note:\"Invalid URL format\"`, message: check.message })}\n }else{\n ${parse}\n }`;\n }\n return emit`\n var ${trimmedVar}=${g.input}.trim();\n ${parse}`;\n}\n\nexport function slowString(ir: StringIR, g: SlowGen): string {\n let code = \"\";\n if (ir.coerce) {\n code += emit`try{${g.output}=String(${g.input});}catch(_){}`;\n }\n code += emit`\n if(typeof ${g.input}!==\"string\"){\n ${invalidType(g, \"string\")}\n ${whenGatedSizeChecks(ir.checks, g, \"length\")}\n }`;\n\n if (ir.checks.length > 0) {\n code += `else{`;\n // Insertion order mirrors zod's issue order for multi-failure inputs;\n // the slow path collects all issues with no short-circuit.\n for (const check of ir.checks) {\n switch (check.kind) {\n // Length is measured in code points where the unit count leaves the\n // verdict in doubt — see stringLengthTests.\n case \"min_length\":\n code += emit`\n if(${stringLengthTests.minFails(g.input, check.minimum, g.ctx)}){\n ${tooSmall(g, check.minimum, \"string\", true, { message: check.message })}\n }`;\n break;\n case \"max_length\":\n code += emit`\n if(${stringLengthTests.maxFails(g.input, check.maximum, g.ctx)}){\n ${tooBig(g, check.maximum, \"string\", true, { message: check.message })}\n }`;\n break;\n case \"length_equals\": {\n const length = g.temp(\"cl\");\n code += emit`\n var ${length}=${stringLengthTests.measure(g.input, check.length, g.ctx)};\n if(${length}<${check.length}){\n ${tooSmall(g, check.length, \"string\", true, { exact: true, message: check.message })}\n }else if(${length}>${check.length}){\n ${tooBig(g, check.length, \"string\", true, { exact: true, message: check.message })}\n }`;\n break;\n }\n // includes/starts_with/ends_with each carry `origin:\"string\"` but NO\n // `pattern`: $ZodCheckIncludes/StartsWith/EndsWith bypass\n // $ZodCheckStringFormat entirely (they init from $ZodCheck and assign\n // `inst._zod.check` directly), and the pattern they build is registered\n // in the bag for JSON Schema only, never put on the issue.\n case \"includes\":\n code += emit`\n if(!${g.input}.includes(${escapeString(check.includes)}${check.position !== undefined ? `,${check.position}` : \"\"})){\n ${invalidFormat(g, \"includes\", { origin: \"string\", extra: `includes:${escapeString(check.includes)}`, message: check.message })}\n }`;\n break;\n case \"starts_with\":\n code += emit`\n if(!${g.input}.startsWith(${escapeString(check.prefix)})){\n ${invalidFormat(g, \"starts_with\", { origin: \"string\", extra: `prefix:${escapeString(check.prefix)}`, message: check.message })}\n }`;\n break;\n case \"ends_with\":\n code += emit`\n if(!${g.input}.endsWith(${escapeString(check.suffix)})){\n ${invalidFormat(g, \"ends_with\", { origin: \"string\", extra: `suffix:${escapeString(check.suffix)}`, message: check.message })}\n }`;\n break;\n case \"refine_effect\":\n code += refineCheck(check, g.input, g);\n break;\n case \"super_refine_effect\":\n code += superRefineCheck(check, g.input, g);\n break;\n case \"overwrite_effect\":\n // $ZodCheckOverwrite: value = tx(value). Later checks read the\n // rewritten value because input aliases the output location.\n code += emit`${g.output}=${emitEffectFn(g.ctx, check.source)}(${g.input});`;\n break;\n case \"string_format\": {\n let regexVar: string;\n let pattern: string;\n // Only the BUILT-IN z.url() gets the URL-parser check, and extraction\n // never gives that one a pattern. A `pattern` on a \"url\"-named check\n // therefore marks a custom format that merely borrowed the name\n // (`z.stringFormat(\"url\", /re/)`); it validates through its own regex,\n // so fall through and compile that instead of the URL parser.\n if (check.format === \"url\" && !check.pattern) {\n code += slowUrlCheck(check, g);\n continue;\n }\n if (check.format === \"email\") {\n pattern = check.pattern ?? EMAIL_REGEX_SOURCE;\n regexVar = g.regex(\"email\", pattern, check.patternFlags);\n } else if (check.format === \"regex\" && check.pattern) {\n pattern = check.pattern;\n regexVar = g.regex(\"str\", pattern, check.patternFlags);\n } else if (check.format === \"uuid\") {\n pattern = check.pattern ?? UUID_REGEX_SOURCE;\n regexVar = g.regex(\"uuid\", pattern, check.patternFlags);\n } else {\n if (check.pattern) {\n pattern = check.pattern;\n regexVar = g.regex(\"str\", pattern, check.patternFlags);\n } else {\n // Extraction guarantees a pattern for non-special formats;\n // defensive skip kept for hand-built IR.\n continue;\n }\n }\n // Zod's invalid_format shape depends on WHICH check instance ran.\n // `$ZodCheckStringFormat.init` installs the default pattern check with\n // `??=`, and that default pushes `origin:\"string\"` + `pattern`. A\n // constructor that OVERRIDES `inst._zod.check` pushes its own issue\n // instead — `$ZodCustomStringFormat` (z.stringFormat/z.hex/z.hostname/\n // z.hash) pushes a bare `{code, format, input}` because it validates\n // through `def.fn` and never reads `def.pattern`. We test the pattern\n // either way, so the issue shape is driven off the extracted flag.\n let extra: string | undefined;\n if (!check.bareIssue) {\n // When emitRegex swapped in a faster equivalent pattern, the runtime\n // regex's toString() would leak the rewrite into the issue. Reference\n // the shared original-pattern string instead (pattern came from\n // RegExp.source, so it matches zod's `.toString()` byte-for-byte).\n const rewritten = !check.patternFlags && fastTestSource(pattern) !== null;\n const patternExpr = rewritten\n ? emitRegexSourceString(g.ctx, pattern)\n : `${regexVar}.toString()`;\n extra = `pattern:${patternExpr}`;\n }\n code += emit`\n ${lastIndexReset(regexVar, check.patternFlags)}\n if(!${regexVar}.test(${g.input})){\n ${invalidFormat(g, { expr: escapeString(check.format) }, { origin: check.bareIssue ? undefined : \"string\", extra, message: check.message })}\n }`;\n break;\n }\n }\n }\n code += `}`;\n }\n\n return `${code}\\n`;\n}\n\n/**\n * Boolean expression testing ONE compiled string check against `x`, or null when\n * the check is not expressible as a pure predicate (`z.url()`, which trims and\n * normalizes, and an unknown format with no pattern).\n *\n * Shared by the fast path — which sorts the checks cheapest-first and joins them\n * with `&&` — and by the build path, which emits them one statement at a time in\n * DECLARATION order so an interleaved `.trim()` rewrite is visible to the checks\n * that follow it (see buildString).\n */\nexport function fastStringCheck(check: CheckIR, x: string, ctx: CodeGenContext): string | null {\n switch (check.kind) {\n case \"min_length\":\n return stringLengthTests.min(x, check.minimum, ctx);\n case \"max_length\":\n return stringLengthTests.max(x, check.maximum, ctx);\n case \"length_equals\":\n return stringLengthTests.equals(x, check.length, ctx);\n case \"includes\":\n return check.position !== undefined\n ? `${x}.includes(${escapeString(check.includes)},${check.position})`\n : `${x}.includes(${escapeString(check.includes)})`;\n case \"starts_with\":\n return `${x}.startsWith(${escapeString(check.prefix)})`;\n case \"ends_with\":\n return `${x}.endsWith(${escapeString(check.suffix)})`;\n case \"string_format\": {\n // URL validation mutates (trims) and uses try/catch — not a predicate.\n // A patterned \"url\" check is a custom format that borrowed the name (see\n // buildString), and its regex IS a predicate.\n if (check.format === \"url\" && !check.pattern) return null;\n let pattern: string;\n let prefix: string;\n if (check.format === \"email\") {\n prefix = \"email\";\n pattern = check.pattern ?? EMAIL_REGEX_SOURCE;\n } else if (check.format === \"uuid\") {\n prefix = \"uuid\";\n pattern = check.pattern ?? UUID_REGEX_SOURCE;\n } else if (check.pattern) {\n prefix = \"re\";\n pattern = check.pattern;\n } else {\n // Unknown format without pattern — can't generate a check\n return null;\n }\n const v = emitRegex(ctx, prefix, pattern, check.patternFlags);\n // Stateful (g/y) regexes need lastIndex reset; comma expression keeps\n // this usable inside the boolean chain.\n return check.patternFlags && /[gy]/.test(check.patternFlags)\n ? `((${v}.lastIndex=0),${v}.test(${x}))`\n : `${v}.test(${x})`;\n }\n default:\n // A check kind this generator does not model (number/bigint/date/set\n // shapes never reach here from a string node).\n return null;\n }\n}\n\nexport function fastString(ir: StringIR, g: FastGen): string | null {\n if (ir.coerce) return null;\n // Overwrite effects rewrite the value — the fast path returns input\n // unchanged, so any mutation makes it ineligible.\n if (ir.checks.some((c) => c.kind === \"overwrite_effect\")) return null;\n\n const x = g.input;\n const parts: string[] = [`typeof ${x}===\"string\"`];\n const checks = ir.checks.filter(\n (c): c is CheckIR => c.kind !== \"refine_effect\" && c.kind !== \"overwrite_effect\",\n );\n\n for (const check of checks.sort(checkPriority)) {\n const expr = fastStringCheck(check, x, g.ctx);\n if (expr === null) return null;\n parts.push(expr);\n }\n\n // Refine effect checks (appended last — run after cheap checks short-circuit)\n for (const check of ir.checks) {\n if (check.kind === \"refine_effect\") {\n parts.push(`${emitEffectCallable(g.ctx, check)}(${x})`);\n } else if (check.kind === \"super_refine_effect\") {\n parts.push(superRefineFastTest(check, x, g));\n }\n }\n\n return parts.join(\"&&\");\n}\n"],"mappings":";;;;;;;;AAiBA,SAAS,eAAe,UAAkB,OAAmC;CAC3E,OAAO,SAAS,OAAO,KAAK,KAAK,IAAI,GAAG,SAAS,iBAAiB;AACpE;;;;;;AAOA,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;AAoB7B,SAAS,aAAa,OAA0B,GAAoB;CAClE,MAAM,aAAa,EAAE,KAAK,IAAI;CAC9B,MAAM,SAAS,EAAE,KAAK,GAAG;CACzB,IAAI,QAAQ;CACZ,IAAI,MAAM,UAAU;EAClB,MAAM,KAAK,EAAE,MAAM,QAAQ,MAAM,UAAU,MAAM,aAAa;EAC9D,SAAS,IAAI;QACT,eAAe,IAAI,MAAM,aAAa,EAAE;YACpC,GAAG,QAAQ,OAAO;UACpB,cAAc,GAAG,OAAO;GACxB,OAAO,mCAAmC,aAAa,MAAM,QAAQ;GACrE,SAAS,MAAM;EACjB,CAAC,EAAE;;CAET;CACA,IAAI,MAAM,UAAU;EAClB,MAAM,KAAK,EAAE,MAAM,SAAS,MAAM,UAAU,MAAM,aAAa;EAC/D,MAAM,YAAY,IAAI,OAAO,0BAA0B,OAAO,wBAAwB,OAAO;EAC7F,SAAS,IAAI;QACT,eAAe,IAAI,MAAM,aAAa,EAAE;YACpC,GAAG,QAAQ,UAAU;UACvB,cAAc,GAAG,OAAO;GACxB,OAAO,mCAAmC,aAAa,MAAM,QAAQ;GACrE,SAAS,MAAM;EACjB,CAAC,EAAE;;CAET;CAEA,MAAM,WAAW,MAAM,YACnB,GAAG,OAAO,SACV,GAAG,WAAW,WAAW,EAAE,MAAM,OAAO,eAAe,GAAG,EAAE;CAChE,SAAS,GAAG,EAAE,OAAO,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AAG;EAC5C,IAAI,SAAS,MAAM,OAAO;EAC1B,MAAM,KAAK,IAAI;CACjB;CAGA,KAAK,MAAM,SAAS,GAAG,QACrB,IAAI,MAAM,SAAS,iBACjB,MAAM,KAAK,GAAG,mBAAmB,EAAE,KAAK,KAAK,EAAE,GAAG,EAAE,EAAE;MACjD,IAAI,MAAM,SAAS,uBACxB,MAAM,KAAK,oBAAoB,OAAO,GAAG,CAAC,CAAC;CAI/C,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
|
1
|
+
{"version":3,"file":"string.js","names":[],"sources":["../../../../src/core/codegen/schemas/string.ts"],"sourcesContent":["import type { CheckIR, CheckStringFormat, StringIR } from \"../../types.js\";\nimport type { CodeGenContext, FastGen, SlowGen } from \"../context.js\";\nimport {\n checkPriority,\n emitEffectCallable,\n emitEffectFn,\n emitRegex,\n emitRegexSourceString,\n emitRuntimeHelper,\n escapeString,\n} from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidFormat, invalidType, tooBig, tooSmall } from \"../emit-issue.js\";\nimport { ZC_EMAIL_DECL } from \"../issue-decls.js\";\nimport {\n EMAIL_REGEX_SOURCE,\n fastTestSource,\n isDefaultEmailPattern,\n UUID_REGEX_SOURCE,\n} from \"../well-known-regex.js\";\nimport { refineCheck, superRefineCheck, superRefineFastTest } from \"./effect.js\";\nimport { stringLengthTests, whenGatedSizeChecks } from \"./sizeable.js\";\n\n/** `re.lastIndex=0;` reset statement for stateful (g/y-flagged) regexes. */\nfunction lastIndexReset(regexVar: string, flags: string | undefined): string {\n return flags && /[gy]/.test(flags) ? `${regexVar}.lastIndex=0;` : \"\";\n}\n\n/**\n * `regexes.httpProtocol.source`. `parseURLObject` compares a url check's\n * protocol SOURCE against it — not the schema constructor — so any check whose\n * protocol is spelled this way gets the guard, `z.httpUrl()` or not.\n */\nconst HTTP_PROTOCOL_SOURCE = \"^https?$\";\n\n/**\n * Generate the url check, mirroring $ZodURL semantics:\n * trim → (for an http(s)-protocol check without normalize) require `://` →\n * new URL(trimmed) → optional hostname/protocol regex tests → write back\n * url.href (normalize) or the trimmed input with its tabs and newlines deleted.\n *\n * The `://` guard is `parseURLObject`'s: without it the URL parser accepts\n * `http:example.com`, and its rejection is a distinct issue (`note: \"Invalid\n * URL format\"`, no `pattern`) pushed BEFORE the parser runs. The deletion of\n * `\\t`, `\\n` and `\\r` (`stripTabAndNewline`) matches what the parser itself\n * drops before it reads the host, so the returned value names the host that was\n * validated.\n *\n * $ZodURL is another constructor that OVERRIDES the `??=`-installed default\n * check, so none of the issues below carries `origin` — and the two that do\n * carry a `pattern` use `regex.source`, not the default check's\n * `regex.toString()` (no delimiters, no flags). Both are reproduced verbatim.\n */\nfunction slowUrlCheck(check: CheckStringFormat, g: SlowGen): string {\n const trimmedVar = g.temp(\"ut\");\n const urlVar = g.temp(\"u\");\n let inner = \"\";\n if (check.hostname) {\n const re = g.regex(\"host\", check.hostname, check.hostnameFlags);\n inner += emit`\n ${lastIndexReset(re, check.hostnameFlags)}\n if(!${re}.test(${urlVar}.hostname)){\n ${invalidFormat(g, \"url\", {\n extra: `note:\"Invalid hostname\",pattern:${escapeString(check.hostname)}`,\n message: check.message,\n })}\n }`;\n }\n if (check.protocol) {\n const re = g.regex(\"proto\", check.protocol, check.protocolFlags);\n const protoExpr = `(${urlVar}.protocol.endsWith(\":\")?${urlVar}.protocol.slice(0,-1):${urlVar}.protocol)`;\n inner += emit`\n ${lastIndexReset(re, check.protocolFlags)}\n if(!${re}.test(${protoExpr})){\n ${invalidFormat(g, \"url\", {\n extra: `note:\"Invalid protocol\",pattern:${escapeString(check.protocol)}`,\n message: check.message,\n })}\n }`;\n }\n // Zod writes the value back even when hostname/protocol issues were pushed.\n const stripped = check.normalize\n ? `${urlVar}.href`\n : `${trimmedVar}.replace(${g.regex(\"tnl\", \"[\\\\t\\\\n\\\\r]\", \"g\")},\"\")`;\n inner += `${g.output}=${stripped};`;\n let parse = emit`\n var ${urlVar}=null;\n try{${urlVar}=new URL(${trimmedVar});}catch(_){}\n if(${urlVar}===null){\n ${invalidFormat(g, \"url\", { message: check.message })}\n }else{\n ${inner}\n }`;\n if (!check.normalize && check.protocol === HTTP_PROTOCOL_SOURCE) {\n const re = g.regex(\"httpUrl\", \"^https?:\\\\/\\\\/\", \"i\");\n parse = emit`\n if(!${re}.test(${trimmedVar})){\n ${invalidFormat(g, \"url\", { extra: `note:\"Invalid URL format\"`, message: check.message })}\n }else{\n ${parse}\n }`;\n }\n return emit`\n var ${trimmedVar}=${g.input}.trim();\n ${parse}`;\n}\n\nexport function slowString(ir: StringIR, g: SlowGen): string {\n let code = \"\";\n if (ir.coerce) {\n code += emit`try{${g.output}=String(${g.input});}catch(_){}`;\n }\n code += emit`\n if(typeof ${g.input}!==\"string\"){\n ${invalidType(g, \"string\")}\n ${whenGatedSizeChecks(ir.checks, g, \"length\")}\n }`;\n\n if (ir.checks.length > 0) {\n code += `else{`;\n // Insertion order mirrors zod's issue order for multi-failure inputs;\n // the slow path collects all issues with no short-circuit.\n for (const check of ir.checks) {\n switch (check.kind) {\n // Length is measured in code points where the unit count leaves the\n // verdict in doubt — see stringLengthTests.\n case \"min_length\":\n code += emit`\n if(${stringLengthTests.minFails(g.input, check.minimum, g.ctx)}){\n ${tooSmall(g, check.minimum, \"string\", true, { message: check.message })}\n }`;\n break;\n case \"max_length\":\n code += emit`\n if(${stringLengthTests.maxFails(g.input, check.maximum, g.ctx)}){\n ${tooBig(g, check.maximum, \"string\", true, { message: check.message })}\n }`;\n break;\n case \"length_equals\": {\n const length = g.temp(\"cl\");\n code += emit`\n var ${length}=${stringLengthTests.measure(g.input, check.length, g.ctx)};\n if(${length}<${check.length}){\n ${tooSmall(g, check.length, \"string\", true, { exact: true, message: check.message })}\n }else if(${length}>${check.length}){\n ${tooBig(g, check.length, \"string\", true, { exact: true, message: check.message })}\n }`;\n break;\n }\n // includes/starts_with/ends_with each carry `origin:\"string\"` but NO\n // `pattern`: $ZodCheckIncludes/StartsWith/EndsWith bypass\n // $ZodCheckStringFormat entirely (they init from $ZodCheck and assign\n // `inst._zod.check` directly), and the pattern they build is registered\n // in the bag for JSON Schema only, never put on the issue.\n case \"includes\":\n code += emit`\n if(!${g.input}.includes(${escapeString(check.includes)}${check.position !== undefined ? `,${check.position}` : \"\"})){\n ${invalidFormat(g, \"includes\", { origin: \"string\", extra: `includes:${escapeString(check.includes)}`, message: check.message })}\n }`;\n break;\n case \"starts_with\":\n code += emit`\n if(!${g.input}.startsWith(${escapeString(check.prefix)})){\n ${invalidFormat(g, \"starts_with\", { origin: \"string\", extra: `prefix:${escapeString(check.prefix)}`, message: check.message })}\n }`;\n break;\n case \"ends_with\":\n code += emit`\n if(!${g.input}.endsWith(${escapeString(check.suffix)})){\n ${invalidFormat(g, \"ends_with\", { origin: \"string\", extra: `suffix:${escapeString(check.suffix)}`, message: check.message })}\n }`;\n break;\n case \"refine_effect\":\n code += refineCheck(check, g.input, g);\n break;\n case \"super_refine_effect\":\n code += superRefineCheck(check, g.input, g);\n break;\n case \"overwrite_effect\":\n // $ZodCheckOverwrite: value = tx(value). Later checks read the\n // rewritten value because input aliases the output location.\n code += emit`${g.output}=${emitEffectFn(g.ctx, check.source)}(${g.input});`;\n break;\n case \"string_format\": {\n let prefix: string;\n let pattern: string;\n // Only the BUILT-IN z.url() gets the URL-parser check, and extraction\n // never gives that one a pattern. A `pattern` on a \"url\"-named check\n // therefore marks a custom format that merely borrowed the name\n // (`z.stringFormat(\"url\", /re/)`); it validates through its own regex,\n // so fall through and compile that instead of the URL parser.\n if (check.format === \"url\" && !check.pattern) {\n code += slowUrlCheck(check, g);\n continue;\n }\n if (check.format === \"email\") {\n pattern = check.pattern ?? EMAIL_REGEX_SOURCE;\n prefix = \"email\";\n } else if (check.format === \"regex\" && check.pattern) {\n pattern = check.pattern;\n prefix = \"str\";\n } else if (check.format === \"uuid\") {\n pattern = check.pattern ?? UUID_REGEX_SOURCE;\n prefix = \"uuid\";\n } else {\n if (check.pattern) {\n pattern = check.pattern;\n prefix = \"str\";\n } else {\n // Extraction guarantees a pattern for non-special formats;\n // defensive skip kept for hand-built IR.\n continue;\n }\n }\n // Zod's default email pattern is tested by the `__zcEmail` scanner, so\n // no RegExp is declared for it at all (see ZC_EMAIL_DECL); the issue\n // below still names the pattern, through the shared source string.\n const scanner = isDefaultEmailPattern(pattern, check.patternFlags)\n ? emitRuntimeHelper(g.ctx, \"__zcEmail\", ZC_EMAIL_DECL)\n : null;\n const regexVar = scanner === null ? g.regex(prefix, pattern, check.patternFlags) : null;\n // Zod's invalid_format shape depends on WHICH check instance ran.\n // `$ZodCheckStringFormat.init` installs the default pattern check with\n // `??=`, and that default pushes `origin:\"string\"` + `pattern`. A\n // constructor that OVERRIDES `inst._zod.check` pushes its own issue\n // instead — `$ZodCustomStringFormat` (z.stringFormat/z.hex/z.hostname/\n // z.hash) pushes a bare `{code, format, input}` because it validates\n // through `def.fn` and never reads `def.pattern`. We test the pattern\n // either way, so the issue shape is driven off the extracted flag.\n let extra: string | undefined;\n if (!check.bareIssue) {\n // When emitRegex swapped in a faster equivalent pattern (or the\n // scanner stands in for the RegExp), the runtime regex's toString()\n // would leak the rewrite into the issue. Reference the shared\n // original-pattern string instead (pattern came from RegExp.source,\n // so it matches zod's `.toString()` byte-for-byte).\n const rewritten = !check.patternFlags && fastTestSource(pattern) !== null;\n const patternExpr =\n rewritten || regexVar === null\n ? emitRegexSourceString(g.ctx, pattern)\n : `${regexVar}.toString()`;\n extra = `pattern:${patternExpr}`;\n }\n const test =\n regexVar === null ? `${scanner}(${g.input})` : `${regexVar}.test(${g.input})`;\n code += emit`\n ${regexVar === null ? \"\" : lastIndexReset(regexVar, check.patternFlags)}\n if(!${test}){\n ${invalidFormat(g, { expr: escapeString(check.format) }, { origin: check.bareIssue ? undefined : \"string\", extra, message: check.message })}\n }`;\n break;\n }\n }\n }\n code += `}`;\n }\n\n return `${code}\\n`;\n}\n\n/**\n * Boolean expression testing ONE compiled string check against `x`, or null when\n * the check is not expressible as a pure predicate (`z.url()`, which trims and\n * normalizes, and an unknown format with no pattern).\n *\n * Shared by the fast path — which sorts the checks cheapest-first and joins them\n * with `&&` — and by the build path, which emits them one statement at a time in\n * DECLARATION order so an interleaved `.trim()` rewrite is visible to the checks\n * that follow it (see buildString).\n */\nexport function fastStringCheck(check: CheckIR, x: string, ctx: CodeGenContext): string | null {\n switch (check.kind) {\n case \"min_length\":\n return stringLengthTests.min(x, check.minimum, ctx);\n case \"max_length\":\n return stringLengthTests.max(x, check.maximum, ctx);\n case \"length_equals\":\n return stringLengthTests.equals(x, check.length, ctx);\n case \"includes\":\n return check.position !== undefined\n ? `${x}.includes(${escapeString(check.includes)},${check.position})`\n : `${x}.includes(${escapeString(check.includes)})`;\n case \"starts_with\":\n return `${x}.startsWith(${escapeString(check.prefix)})`;\n case \"ends_with\":\n return `${x}.endsWith(${escapeString(check.suffix)})`;\n case \"string_format\": {\n // URL validation mutates (trims) and uses try/catch — not a predicate.\n // A patterned \"url\" check is a custom format that borrowed the name (see\n // buildString), and its regex IS a predicate.\n if (check.format === \"url\" && !check.pattern) return null;\n let pattern: string;\n let prefix: string;\n if (check.format === \"email\") {\n prefix = \"email\";\n pattern = check.pattern ?? EMAIL_REGEX_SOURCE;\n } else if (check.format === \"uuid\") {\n prefix = \"uuid\";\n pattern = check.pattern ?? UUID_REGEX_SOURCE;\n } else if (check.pattern) {\n prefix = \"re\";\n pattern = check.pattern;\n } else {\n // Unknown format without pattern — can't generate a check\n return null;\n }\n // Zod's default email pattern runs as a linear scan instead of a RegExp\n // (see ZC_EMAIL_DECL) — a plain call, so it needs no parens either.\n if (isDefaultEmailPattern(pattern, check.patternFlags)) {\n return `${emitRuntimeHelper(ctx, \"__zcEmail\", ZC_EMAIL_DECL)}(${x})`;\n }\n const v = emitRegex(ctx, prefix, pattern, check.patternFlags);\n // Stateful (g/y) regexes need lastIndex reset; comma expression keeps\n // this usable inside the boolean chain.\n return check.patternFlags && /[gy]/.test(check.patternFlags)\n ? `((${v}.lastIndex=0),${v}.test(${x}))`\n : `${v}.test(${x})`;\n }\n default:\n // A check kind this generator does not model (number/bigint/date/set\n // shapes never reach here from a string node).\n return null;\n }\n}\n\nexport function fastString(ir: StringIR, g: FastGen): string | null {\n if (ir.coerce) return null;\n // Overwrite effects rewrite the value — the fast path returns input\n // unchanged, so any mutation makes it ineligible.\n if (ir.checks.some((c) => c.kind === \"overwrite_effect\")) return null;\n\n const x = g.input;\n const parts: string[] = [`typeof ${x}===\"string\"`];\n const checks = ir.checks.filter(\n (c): c is CheckIR => c.kind !== \"refine_effect\" && c.kind !== \"overwrite_effect\",\n );\n\n for (const check of checks.sort(checkPriority)) {\n const expr = fastStringCheck(check, x, g.ctx);\n if (expr === null) return null;\n parts.push(expr);\n }\n\n // Refine effect checks (appended last — run after cheap checks short-circuit)\n for (const check of ir.checks) {\n if (check.kind === \"refine_effect\") {\n parts.push(`${emitEffectCallable(g.ctx, check)}(${x})`);\n } else if (check.kind === \"super_refine_effect\") {\n parts.push(superRefineFastTest(check, x, g));\n }\n }\n\n return parts.join(\"&&\");\n}\n"],"mappings":";;;;;;;;;AAwBA,SAAS,eAAe,UAAkB,OAAmC;CAC3E,OAAO,SAAS,OAAO,KAAK,KAAK,IAAI,GAAG,SAAS,iBAAiB;AACpE;;;;;;AAOA,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;AAoB7B,SAAS,aAAa,OAA0B,GAAoB;CAClE,MAAM,aAAa,EAAE,KAAK,IAAI;CAC9B,MAAM,SAAS,EAAE,KAAK,GAAG;CACzB,IAAI,QAAQ;CACZ,IAAI,MAAM,UAAU;EAClB,MAAM,KAAK,EAAE,MAAM,QAAQ,MAAM,UAAU,MAAM,aAAa;EAC9D,SAAS,IAAI;QACT,eAAe,IAAI,MAAM,aAAa,EAAE;YACpC,GAAG,QAAQ,OAAO;UACpB,cAAc,GAAG,OAAO;GACxB,OAAO,mCAAmC,aAAa,MAAM,QAAQ;GACrE,SAAS,MAAM;EACjB,CAAC,EAAE;;CAET;CAC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sB,SAAS,MAAM,YAAY,GACnD,OAAO,GAAG,kBAAkB,KAAK,aAAa,aAAa,EAAE,GAAG,EAAE;GAEpE,MAAM,IAAI,UAAU,KAAK,QAAQ,SAAS,MAAM,YAAY;GAG5D,OAAO,MAAM,gBAAgB,OAAO,KAAK,MAAM,YAAY,IACvD,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MACnC,GAAG,EAAE,QAAQ,EAAE;EACrB;EACA,SAGE,OAAO;CACX;AACF;AAEA,SAAgB,WAAW,IAAc,GAA2B;CAClE,IAAI,GAAG,QAAQ,OAAO;CAGtB,IAAI,GAAG,OAAO,MAAM,MAAM,EAAE,SAAS,kBAAkB,GAAG,OAAO;CAEjE,MAAM,IAAI,EAAE;CACZ,MAAM,QAAkB,CAAC,UAAU,EAAE,YAAY;CACjD,MAAM,SAAS,GAAG,OAAO,QACtB,MAAoB,EAAE,SAAS,mBAAmB,EAAE,SAAS,kBAChE;CAEA,KAAK,MAAM,SAAS,OAAO,KAAK,aAAa,GAAG;EAC9C,MAAM,OAAO,gBAAgB,OAAO,GAAG,EAAE,GAAG;EAC5C,IAAI,SAAS,MAAM,OAAO;EAC1B,MAAM,KAAK,IAAI;CACjB;CAGA,KAAK,MAAM,SAAS,GAAG,QACrB,IAAI,MAAM,SAAS,iBACjB,MAAM,KAAK,GAAG,mBAAmB,EAAE,KAAK,KAAK,EAAE,GAAG,EAAE,EAAE;MACjD,IAAI,MAAM,SAAS,uBACxB,MAAM,KAAK,oBAAoB,OAAO,GAAG,CAAC,CAAC;CAI/C,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
|
@@ -29,8 +29,26 @@ declare const EMAIL_REGEX_SOURCE: string;
|
|
|
29
29
|
*
|
|
30
30
|
* Equivalence is enforced by tests/core/codegen/email-fast-regex.test.ts
|
|
31
31
|
* (exhaustive short-string sweep + structured cases + random fuzz).
|
|
32
|
+
*
|
|
33
|
+
* Generated code no longer runs this pattern: the flag-less default is tested
|
|
34
|
+
* by the `__zcEmail` scanner instead (see {@link isDefaultEmailPattern} and
|
|
35
|
+
* ZC_EMAIL_DECL in issue-decls.ts). The table entry stays because its `Src`
|
|
36
|
+
* companion is what issue sites report, and so lean mode keeps that string a
|
|
37
|
+
* single bundle-wide constant; the RegExp export itself is simply unreferenced.
|
|
32
38
|
*/
|
|
33
39
|
declare const EMAIL_FAST_REGEX_SOURCE: string;
|
|
40
|
+
/**
|
|
41
|
+
* Is this exactly zod's default email pattern, flag-less?
|
|
42
|
+
*
|
|
43
|
+
* Generated code tests that one pattern with the `__zcEmail` scanner (see
|
|
44
|
+
* ZC_EMAIL_DECL) rather than with either RegExp above, whatever format name
|
|
45
|
+
* the check carries — `z.email()`, `z.string().regex(z.regexes.email)` and a
|
|
46
|
+
* `z.stringFormat("x", z.regexes.email)` all run the same regex in zod and so
|
|
47
|
+
* get the same verdict here. Only the TEST changes: the issue still reports the
|
|
48
|
+
* pattern string, and a flagged copy keeps its RegExp since the flags would be
|
|
49
|
+
* part of what it reports.
|
|
50
|
+
*/
|
|
51
|
+
declare function isDefaultEmailPattern(pattern: string, flags: string | undefined): boolean;
|
|
34
52
|
/** Fallback UUID regex used when the extractor doesn't provide a pattern (e.g. in unit tests). */
|
|
35
53
|
declare const UUID_REGEX_SOURCE = "^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$";
|
|
36
54
|
interface WellKnownRegex {
|
|
@@ -84,5 +102,5 @@ declare function fastTestSource(source: string): string | null;
|
|
|
84
102
|
*/
|
|
85
103
|
declare function wellKnownRegexSourceName(source: string): string | null;
|
|
86
104
|
//#endregion
|
|
87
|
-
export { EMAIL_FAST_REGEX_SOURCE, EMAIL_REGEX_SOURCE, UUID_REGEX_SOURCE, WELL_KNOWN_REGEXES, WellKnownRegex, fastTestSource, lookupFastRegexSource, lookupWellKnownRegex, wellKnownRegexSourceName };
|
|
105
|
+
export { EMAIL_FAST_REGEX_SOURCE, EMAIL_REGEX_SOURCE, UUID_REGEX_SOURCE, WELL_KNOWN_REGEXES, WellKnownRegex, fastTestSource, isDefaultEmailPattern, lookupFastRegexSource, lookupWellKnownRegex, wellKnownRegexSourceName };
|
|
88
106
|
//# sourceMappingURL=well-known-regex.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"well-known-regex.d.ts","names":[],"sources":["../../../src/core/codegen/well-known-regex.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cAqBa
|
|
1
|
+
{"version":3,"file":"well-known-regex.d.ts","names":[],"sources":["../../../src/core/codegen/well-known-regex.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cAqBa;;;;;;;;;;;;;;;;;;;cAoBA;;;;;;;;;;;;iBAaG,sBAAsB,iBAAiB;;cAK1C;UAGI;;EAEf;;EAEA;;;;;;EAMA;;cAGW,6BAA6B;;;;;iBAqE1B,qBAAqB;;;;;;;;;iBAYrB,sBAAsB;;;;;;;;;;;;;;;;iBAmBtB,eAAe;;;;;;;iBAWf,yBAAyB"}
|
|
@@ -30,8 +30,28 @@ const EMAIL_REGEX_SOURCE = String.raw`^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Z
|
|
|
30
30
|
*
|
|
31
31
|
* Equivalence is enforced by tests/core/codegen/email-fast-regex.test.ts
|
|
32
32
|
* (exhaustive short-string sweep + structured cases + random fuzz).
|
|
33
|
+
*
|
|
34
|
+
* Generated code no longer runs this pattern: the flag-less default is tested
|
|
35
|
+
* by the `__zcEmail` scanner instead (see {@link isDefaultEmailPattern} and
|
|
36
|
+
* ZC_EMAIL_DECL in issue-decls.ts). The table entry stays because its `Src`
|
|
37
|
+
* companion is what issue sites report, and so lean mode keeps that string a
|
|
38
|
+
* single bundle-wide constant; the RegExp export itself is simply unreferenced.
|
|
33
39
|
*/
|
|
34
40
|
const EMAIL_FAST_REGEX_SOURCE = String.raw`^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$`;
|
|
41
|
+
/**
|
|
42
|
+
* Is this exactly zod's default email pattern, flag-less?
|
|
43
|
+
*
|
|
44
|
+
* Generated code tests that one pattern with the `__zcEmail` scanner (see
|
|
45
|
+
* ZC_EMAIL_DECL) rather than with either RegExp above, whatever format name
|
|
46
|
+
* the check carries — `z.email()`, `z.string().regex(z.regexes.email)` and a
|
|
47
|
+
* `z.stringFormat("x", z.regexes.email)` all run the same regex in zod and so
|
|
48
|
+
* get the same verdict here. Only the TEST changes: the issue still reports the
|
|
49
|
+
* pattern string, and a flagged copy keeps its RegExp since the flags would be
|
|
50
|
+
* part of what it reports.
|
|
51
|
+
*/
|
|
52
|
+
function isDefaultEmailPattern(pattern, flags) {
|
|
53
|
+
return !flags && pattern === EMAIL_REGEX_SOURCE;
|
|
54
|
+
}
|
|
35
55
|
/** Fallback UUID regex used when the extractor doesn't provide a pattern (e.g. in unit tests). */
|
|
36
56
|
const UUID_REGEX_SOURCE = "^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$";
|
|
37
57
|
const WELL_KNOWN_REGEXES = [
|
|
@@ -160,6 +180,6 @@ function wellKnownRegexSourceName(source) {
|
|
|
160
180
|
return fastTestSource(source) !== null ? `${name}Src` : null;
|
|
161
181
|
}
|
|
162
182
|
//#endregion
|
|
163
|
-
export { EMAIL_FAST_REGEX_SOURCE, EMAIL_REGEX_SOURCE, UUID_REGEX_SOURCE, WELL_KNOWN_REGEXES, fastTestSource, lookupFastRegexSource, lookupWellKnownRegex, wellKnownRegexSourceName };
|
|
183
|
+
export { EMAIL_FAST_REGEX_SOURCE, EMAIL_REGEX_SOURCE, UUID_REGEX_SOURCE, WELL_KNOWN_REGEXES, fastTestSource, isDefaultEmailPattern, lookupFastRegexSource, lookupWellKnownRegex, wellKnownRegexSourceName };
|
|
164
184
|
|
|
165
185
|
//# sourceMappingURL=well-known-regex.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"well-known-regex.js","names":[],"sources":["../../../src/core/codegen/well-known-regex.ts"],"sourcesContent":["/**\n * Well-known regex sources hosted in the virtual module \"virtual:zod-compiler/runtime\".\n *\n * In lean mode (unplugin), `g.regex()` consults this registry and emits a reference\n * like `__zcReEmail` instead of declaring `var __re_email_*=new RegExp(...)`.\n * The bundler then deduplicates the regex literal across all transformed files.\n *\n * Pattern sources are matched verbatim (string equality). Add new entries as Zod\n * exposes additional well-known formats and we want bundle-wide dedup.\n *\n * Verbatim matching means an entry goes STALE SILENTLY when Zod edits a pattern:\n * nothing breaks, the lookup just stops hitting and every transformed file\n * re-declares its own RegExp. The 4.5 bump did exactly that to `cuid`, `ulid`\n * and `iso.datetime` — the last being the ~330-character source this table\n * exists for. tests/core/codegen/well-known-regex.test.ts pins every entry\n * against the live Zod pattern so the next upgrade fails loudly instead.\n */\n\nimport { unrollRepeats } from \"./regex-unroll.js\";\n\n/** Zod v4's email regex source (string.ts uses this directly when format === \"email\"). */\nexport const EMAIL_REGEX_SOURCE = String.raw`^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$`;\n\n/**\n * Behavior-equivalent rewrite of EMAIL_REGEX_SOURCE that runs ~1.45x faster on V8.\n *\n * Zod's pattern fronts two lookaheads; `(?!.*\\.\\.)` re-scans the entire string\n * before matching starts. The rewrite encodes the same constraints structurally:\n * the local part is dot-separated runs of `[A-Za-z0-9_'+-]` (no leading dot, no\n * empty run ⇒ no `..`) ending in `[A-Za-z0-9_+-]`, and the domain grammar already\n * makes `..` impossible (every label starts with an alphanumeric).\n *\n * Equivalence is enforced by tests/core/codegen/email-fast-regex.test.ts\n * (exhaustive short-string sweep + structured cases + random fuzz).\n */\nexport const EMAIL_FAST_REGEX_SOURCE = String.raw`^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$`;\n\n/** Fallback UUID regex used when the extractor doesn't provide a pattern (e.g. in unit tests). */\nexport const UUID_REGEX_SOURCE =\n \"^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$\";\n\nexport interface WellKnownRegex {\n /** Stable virtual-module export name. Always starts with \"__zcRe\". */\n name: string;\n /** Pattern source string (verbatim match against `g.regex()` 2nd argument). */\n source: string;\n /**\n * Behavior-equivalent faster pattern used for the actual `.test()` regex.\n * Issue reporting (`pattern:` field) always uses `source` so generated\n * issues stay byte-identical to zod's.\n */\n testSource?: string;\n}\n\nexport const WELL_KNOWN_REGEXES: readonly WellKnownRegex[] = [\n { name: \"__zcReEmail\", source: EMAIL_REGEX_SOURCE, testSource: EMAIL_FAST_REGEX_SOURCE },\n { name: \"__zcReUuid\", source: UUID_REGEX_SOURCE },\n { name: \"__zcReCuid\", source: \"^[cC][0-9a-z]{6,}$\" },\n { name: \"__zcReCuid2\", source: \"^[0-9a-z]+$\" },\n { name: \"__zcReUlid\", source: \"^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$\" },\n { name: \"__zcReNanoid\", source: \"^[a-zA-Z0-9_-]{21}$\" },\n { name: \"__zcReXid\", source: \"^[0-9a-vA-V]{20}$\" },\n { name: \"__zcReKsuid\", source: \"^[A-Za-z0-9]{27}$\" },\n {\n name: \"__zcReIpv4\",\n source:\n \"^(?:(?: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])$\",\n },\n {\n name: \"__zcReIpv6\",\n source:\n \"^(([0-9a-fA-F]{1,4}:){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}|:))$\",\n },\n {\n name: \"__zcReBase64\",\n source: \"^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$\",\n },\n { name: \"__zcReBase64Url\", source: \"^[A-Za-z0-9_-]*$\" },\n { name: \"__zcReE164\", source: \"^\\\\+[1-9]\\\\d{6,14}$\" },\n {\n name: \"__zcReGuid\",\n source: \"^([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})$\",\n },\n // The ISO family. Zod BUILDS these from the call's options, so only the\n // default spelling is a fixed string — `z.iso.datetime({ offset: true })` or\n // `{ precision: 3 }` produces a different source that simply misses this\n // exact-match table and keeps its per-IIFE declaration. Defaults are worth\n // listing anyway: `z.iso.datetime()` is everywhere in API schemas and its\n // pattern is ~330 characters, so a bundle that repeats it per validator pays\n // for it in bytes and in a RegExp construction per schema at module init.\n {\n name: \"__zcReIsoDate\",\n source:\n \"^(?:(?:\\\\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])))$\",\n },\n { name: \"__zcReIsoTime\", source: \"^(?:[01]\\\\d|2[0-3]):[0-5]\\\\d(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?$\" },\n {\n name: \"__zcReIsoDateTime\",\n source:\n \"^(?:(?:\\\\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])))T(?:(?:[01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d(?:\\\\.\\\\d+)?(?:Z))$\",\n },\n {\n name: \"__zcReIsoDuration\",\n source:\n \"^P(?:(\\\\d+W)|(?!.*W)(?=\\\\d|T\\\\d)(\\\\d+Y)?(\\\\d+M)?(\\\\d+D)?(T(?=\\\\d)(\\\\d+H)?(\\\\d+M)?(\\\\d+([.,]\\\\d+)?S)?)?)$\",\n },\n];\n\nconst SOURCE_TO_NAME: ReadonlyMap<string, string> = new Map(\n WELL_KNOWN_REGEXES.map((r) => [r.source, r.name]),\n);\n\nconst SOURCE_TO_TEST_SOURCE: ReadonlyMap<string, string> = new Map(\n WELL_KNOWN_REGEXES.filter((r) => r.testSource !== undefined).map((r) => [\n r.source,\n r.testSource as string,\n ]),\n);\n\n/**\n * Look up a well-known regex by its pattern source string.\n * Returns the virtual-module export name or null if the pattern is user-defined.\n */\nexport function lookupWellKnownRegex(source: string): string | null {\n return SOURCE_TO_NAME.get(source) ?? null;\n}\n\n/**\n * Look up the hand-written behavior-equivalent test pattern for a regex source.\n * Returns null when no rewrite is registered in {@link WELL_KNOWN_REGEXES}.\n *\n * This is the TABLE lookup only. Codegen calls {@link fastTestSource}, which\n * layers automatic repeat unrolling on top and also covers user-supplied\n * patterns that are in no table.\n */\nexport function lookupFastRegexSource(source: string): string | null {\n return SOURCE_TO_TEST_SOURCE.get(source) ?? null;\n}\n\n/**\n * The pattern a generated `.test()` should actually run for `source`, or null\n * when `source` is already the best form.\n *\n * Two behavior-preserving rewrites compose here: the hand-written table entry\n * above (currently just email), then {@link unrollRepeats}, which turns bounded\n * repeats of single-character atoms into explicit repetition — worth 1.3-3.4x\n * on the string formats everyday schemas use (uuid, guid, ulid, nanoid, xid,\n * ksuid, base64, e164, iso.date). Unrolling runs on the table rewrite when\n * there is one, so the two stack.\n *\n * Callers must apply this only to flag-less regexes (the flagged form would\n * need its flags carried into the reported pattern too) and must keep\n * reporting the ORIGINAL source in issues — see `emitRegexSourceString`.\n */\nexport function fastTestSource(source: string): string | null {\n const tableRewrite = SOURCE_TO_TEST_SOURCE.get(source) ?? null;\n return unrollRepeats(tableRewrite ?? source) ?? tableRewrite;\n}\n\n/**\n * Virtual-module export name for the ORIGINAL `/source/` pattern string of a\n * rewritten well-known regex (e.g. \"__zcReEmailSrc\"). Issue sites reference it\n * so the original pattern stays a single bundle-wide string even though the\n * runtime regex object is built from testSource.\n */\nexport function wellKnownRegexSourceName(source: string): string | null {\n const name = SOURCE_TO_NAME.get(source);\n if (name === undefined) return null;\n return fastTestSource(source) !== null ? `${name}Src` : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,qBAAqB,OAAO,GAAG;;;;;;;;;;;;;AAc5C,MAAa,0BAA0B,OAAO,GAAG;;AAGjD,MAAa,oBACX;AAeF,MAAa,qBAAgD;CAC3D;EAAE,MAAM;EAAe,QAAQ;EAAoB,YAAY;CAAwB;CACvF;EAAE,MAAM;EAA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AAW,OAAO;CAC/B,OAAO,eAAe,MAAM,MAAM,OAAO,GAAG,KAAK,OAAO;AAC1D"}
|
|
1
|
+
{"version":3,"file":"well-known-regex.js","names":[],"sources":["../../../src/core/codegen/well-known-regex.ts"],"sourcesContent":["/**\n * Well-known regex sources hosted in the virtual module \"virtual:zod-compiler/runtime\".\n *\n * In lean mode (unplugin), `g.regex()` consults this registry and emits a reference\n * like `__zcReEmail` instead of declaring `var __re_email_*=new RegExp(...)`.\n * The bundler then deduplicates the regex literal across all transformed files.\n *\n * Pattern sources are matched verbatim (string equality). Add new entries as Zod\n * exposes additional well-known formats and we want bundle-wide dedup.\n *\n * Verbatim matching means an entry goes STALE SILENTLY when Zod edits a pattern:\n * nothing breaks, the lookup just stops hitting and every transformed file\n * re-declares its own RegExp. The 4.5 bump did exactly that to `cuid`, `ulid`\n * and `iso.datetime` — the last being the ~330-character source this table\n * exists for. tests/core/codegen/well-known-regex.test.ts pins every entry\n * against the live Zod pattern so the next upgrade fails loudly instead.\n */\n\nimport { unrollRepeats } from \"./regex-unroll.js\";\n\n/** Zod v4's email regex source (string.ts uses this directly when format === \"email\"). */\nexport const EMAIL_REGEX_SOURCE = String.raw`^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$`;\n\n/**\n * Behavior-equivalent rewrite of EMAIL_REGEX_SOURCE that runs ~1.45x faster on V8.\n *\n * Zod's pattern fronts two lookaheads; `(?!.*\\.\\.)` re-scans the entire string\n * before matching starts. The rewrite encodes the same constraints structurally:\n * the local part is dot-separated runs of `[A-Za-z0-9_'+-]` (no leading dot, no\n * empty run ⇒ no `..`) ending in `[A-Za-z0-9_+-]`, and the domain grammar already\n * makes `..` impossible (every label starts with an alphanumeric).\n *\n * Equivalence is enforced by tests/core/codegen/email-fast-regex.test.ts\n * (exhaustive short-string sweep + structured cases + random fuzz).\n *\n * Generated code no longer runs this pattern: the flag-less default is tested\n * by the `__zcEmail` scanner instead (see {@link isDefaultEmailPattern} and\n * ZC_EMAIL_DECL in issue-decls.ts). The table entry stays because its `Src`\n * companion is what issue sites report, and so lean mode keeps that string a\n * single bundle-wide constant; the RegExp export itself is simply unreferenced.\n */\nexport const EMAIL_FAST_REGEX_SOURCE = String.raw`^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$`;\n\n/**\n * Is this exactly zod's default email pattern, flag-less?\n *\n * Generated code tests that one pattern with the `__zcEmail` scanner (see\n * ZC_EMAIL_DECL) rather than with either RegExp above, whatever format name\n * the check carries — `z.email()`, `z.string().regex(z.regexes.email)` and a\n * `z.stringFormat(\"x\", z.regexes.email)` all run the same regex in zod and so\n * get the same verdict here. Only the TEST changes: the issue still reports the\n * pattern string, and a flagged copy keeps its RegExp since the flags would be\n * part of what it reports.\n */\nexport function isDefaultEmailPattern(pattern: string, flags: string | undefined): boolean {\n return !flags && pattern === EMAIL_REGEX_SOURCE;\n}\n\n/** Fallback UUID regex used when the extractor doesn't provide a pattern (e.g. in unit tests). */\nexport const UUID_REGEX_SOURCE =\n \"^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$\";\n\nexport interface WellKnownRegex {\n /** Stable virtual-module export name. Always starts with \"__zcRe\". */\n name: string;\n /** Pattern source string (verbatim match against `g.regex()` 2nd argument). */\n source: string;\n /**\n * Behavior-equivalent faster pattern used for the actual `.test()` regex.\n * Issue reporting (`pattern:` field) always uses `source` so generated\n * issues stay byte-identical to zod's.\n */\n testSource?: string;\n}\n\nexport const WELL_KNOWN_REGEXES: readonly WellKnownRegex[] = [\n { name: \"__zcReEmail\", source: EMAIL_REGEX_SOURCE, testSource: EMAIL_FAST_REGEX_SOURCE },\n { name: \"__zcReUuid\", source: UUID_REGEX_SOURCE },\n { name: \"__zcReCuid\", source: \"^[cC][0-9a-z]{6,}$\" },\n { name: \"__zcReCuid2\", source: \"^[0-9a-z]+$\" },\n { name: \"__zcReUlid\", source: \"^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$\" },\n { name: \"__zcReNanoid\", source: \"^[a-zA-Z0-9_-]{21}$\" },\n { name: \"__zcReXid\", source: \"^[0-9a-vA-V]{20}$\" },\n { name: \"__zcReKsuid\", source: \"^[A-Za-z0-9]{27}$\" },\n {\n name: \"__zcReIpv4\",\n source:\n \"^(?:(?: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])$\",\n },\n {\n name: \"__zcReIpv6\",\n source:\n \"^(([0-9a-fA-F]{1,4}:){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}|:))$\",\n },\n {\n name: \"__zcReBase64\",\n source: \"^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$\",\n },\n { name: \"__zcReBase64Url\", source: \"^[A-Za-z0-9_-]*$\" },\n { name: \"__zcReE164\", source: \"^\\\\+[1-9]\\\\d{6,14}$\" },\n {\n name: \"__zcReGuid\",\n source: \"^([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})$\",\n },\n // The ISO family. Zod BUILDS these from the call's options, so only the\n // default spelling is a fixed string — `z.iso.datetime({ offset: true })` or\n // `{ precision: 3 }` produces a different source that simply misses this\n // exact-match table and keeps its per-IIFE declaration. Defaults are worth\n // listing anyway: `z.iso.datetime()` is everywhere in API schemas and its\n // pattern is ~330 characters, so a bundle that repeats it per validator pays\n // for it in bytes and in a RegExp construction per schema at module init.\n {\n name: \"__zcReIsoDate\",\n source:\n \"^(?:(?:\\\\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])))$\",\n },\n { name: \"__zcReIsoTime\", source: \"^(?:[01]\\\\d|2[0-3]):[0-5]\\\\d(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?$\" },\n {\n name: \"__zcReIsoDateTime\",\n source:\n \"^(?:(?:\\\\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])))T(?:(?:[01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d(?:\\\\.\\\\d+)?(?:Z))$\",\n },\n {\n name: \"__zcReIsoDuration\",\n source:\n \"^P(?:(\\\\d+W)|(?!.*W)(?=\\\\d|T\\\\d)(\\\\d+Y)?(\\\\d+M)?(\\\\d+D)?(T(?=\\\\d)(\\\\d+H)?(\\\\d+M)?(\\\\d+([.,]\\\\d+)?S)?)?)$\",\n },\n];\n\nconst SOURCE_TO_NAME: ReadonlyMap<string, string> = new Map(\n WELL_KNOWN_REGEXES.map((r) => [r.source, r.name]),\n);\n\nconst SOURCE_TO_TEST_SOURCE: ReadonlyMap<string, string> = new Map(\n WELL_KNOWN_REGEXES.filter((r) => r.testSource !== undefined).map((r) => [\n r.source,\n r.testSource as string,\n ]),\n);\n\n/**\n * Look up a well-known regex by its pattern source string.\n * Returns the virtual-module export name or null if the pattern is user-defined.\n */\nexport function lookupWellKnownRegex(source: string): string | null {\n return SOURCE_TO_NAME.get(source) ?? null;\n}\n\n/**\n * Look up the hand-written behavior-equivalent test pattern for a regex source.\n * Returns null when no rewrite is registered in {@link WELL_KNOWN_REGEXES}.\n *\n * This is the TABLE lookup only. Codegen calls {@link fastTestSource}, which\n * layers automatic repeat unrolling on top and also covers user-supplied\n * patterns that are in no table.\n */\nexport function lookupFastRegexSource(source: string): string | null {\n return SOURCE_TO_TEST_SOURCE.get(source) ?? null;\n}\n\n/**\n * The pattern a generated `.test()` should actually run for `source`, or null\n * when `source` is already the best form.\n *\n * Two behavior-preserving rewrites compose here: the hand-written table entry\n * above (currently just email), then {@link unrollRepeats}, which turns bounded\n * repeats of single-character atoms into explicit repetition — worth 1.3-3.4x\n * on the string formats everyday schemas use (uuid, guid, ulid, nanoid, xid,\n * ksuid, base64, e164, iso.date). Unrolling runs on the table rewrite when\n * there is one, so the two stack.\n *\n * Callers must apply this only to flag-less regexes (the flagged form would\n * need its flags carried into the reported pattern too) and must keep\n * reporting the ORIGINAL source in issues — see `emitRegexSourceString`.\n */\nexport function fastTestSource(source: string): string | null {\n const tableRewrite = SOURCE_TO_TEST_SOURCE.get(source) ?? null;\n return unrollRepeats(tableRewrite ?? source) ?? tableRewrite;\n}\n\n/**\n * Virtual-module export name for the ORIGINAL `/source/` pattern string of a\n * rewritten well-known regex (e.g. \"__zcReEmailSrc\"). Issue sites reference it\n * so the original pattern stays a single bundle-wide string even though the\n * runtime regex object is built from testSource.\n */\nexport function wellKnownRegexSourceName(source: string): string | null {\n const name = SOURCE_TO_NAME.get(source);\n if (name === undefined) return null;\n return fastTestSource(source) !== null ? `${name}Src` : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,qBAAqB,OAAO,GAAG;;;;;;;;;;;;;;;;;;;AAoB5C,MAAa,0BAA0B,OAAO,GAAG;;;;;;;;;;;;AAajD,SAAgB,sBAAsB,SAAiB,OAAoC;CACzF,OAAO,CAAC,SAAS,YAAY;AAC/B;;AAGA,MAAa,oBACX;AAeF,MAAa,qBAAgD;CAC3D;EAAE,MAAM;EAAe,QAAQ;EAAoB,YAAY;CAAwB;CACvF;EAAE,MAAM;EAAc,QAAQ;CAAkB;CAChD;EAAE,MAAM;EAAc,QAAQ;CAAqB;CACnD;EAAE,MAAM;EAAe,QAAQ;CAAc;CAC7C;EAAE,MAAM;EAAc,QAAQ;CAA6C;CAC3E;EAAE,MAAM;EAAgB,QAAQ;CAAsB;CACtD;EAAE,MAAM;EAAa,QAAQ;CAAoB;CACjD;EAAE,MAAM;EAAe,QAAQ;CAAoB;CACnD;EACE,MAAM;EACN,QACE;CACJ;CACA;EACE,MAAM;EACN,QACE;CACJ;CACA;EACE,MAAM;EACN,QAAQ;CACV;CACA;EAAE,MAAM;EAAmB,QAAQ;CAAmB;CACtD;EAAE,MAAM;EAAc,QAAQ;CAAsB;CACpD;EACE,MAAM;EACN,QAAQ;CACV;CAQA;EACE,MAAM;EACN,QACE;CACJ;CACA;EAAE,MAAM;EAAiB,QAAQ;CAA0D;CAC3F;EACE,MAAM;EACN,QACE;CACJ;CACA;EACE,MAAM;EACN,QACE;CACJ;AACF;AAEA,MAAM,iBAA8C,IAAI,IACtD,mBAAmB,KAAK,MAAM,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,CAClD;AAEA,MAAM,wBAAqD,IAAI,IAC7D,mBAAmB,QAAQ,MAAM,EAAE,eAAe,KAAA,CAAS,CAAC,CAAC,KAAK,MAAM,CACtE,EAAE,QACF,EAAE,UACJ,CAAC,CACH;;;;;AAMA,SAAgB,qBAAqB,QAA+B;CAClE,OAAO,eAAe,IAAI,MAAM,KAAK;AACvC;;;;;;;;;AAUA,SAAgB,sBAAsB,QAA+B;CACnE,OAAO,sBAAsB,IAAI,MAAM,KAAK;AAC9C;;;;;;;;;;;;;;;;AAiBA,SAAgB,eAAe,QAA+B;CAC5D,MAAM,eAAe,sBAAsB,IAAI,MAAM,KAAK;CAC1D,OAAO,cAAc,gBAAgB,MAAM,KAAK;AAClD;;;;;;;AAQA,SAAgB,yBAAyB,QAA+B;CACtE,MAAM,OAAO,eAAe,IAAI,MAAM;CACtC,IAAI,SAAS,KAAA,GAAW,OAAO;CAC/B,OAAO,eAAe,MAAM,MAAM,OAAO,GAAG,KAAK,OAAO;AAC1D"}
|
package/dist/core/iife.d.ts
CHANGED
|
@@ -211,6 +211,14 @@ declare const FINZ_DECL = "function __zcFinZ(z,r,i){return new __ZcFailZ(z,r,i);
|
|
|
211
211
|
* Installed with defineProperty rather than assignment: Zod's lazy setter
|
|
212
212
|
* redefines the slot as non-writable, so a second `__zcMkv` on the same schema
|
|
213
213
|
* object — two exports aliasing one schema — would throw under ESM strict mode.
|
|
214
|
+
*
|
|
215
|
+
* A rebuilding schema (no `fc`) reaches `parse()` through `fn`, i.e. through a
|
|
216
|
+
* SafeParseResult unwrapped a line later. Handing the build function over so
|
|
217
|
+
* `parse()` could call it directly was measured and declined: the wrapper is a
|
|
218
|
+
* young-generation bump allocation that V8 elides outright where `fn` inlines,
|
|
219
|
+
* and even across eight schemas sharing this closure — where it cannot — the
|
|
220
|
+
* direct call came out level (41.5 vs 41.8 ns), for a wider signature on every
|
|
221
|
+
* bundle.
|
|
214
222
|
*/
|
|
215
223
|
declare const MK_VALIDATOR_DECL: string;
|
|
216
224
|
/**
|
package/dist/core/iife.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"iife.d.ts","names":[],"sources":["../../src/core/iife.ts"],"mappings":";;;;;;;;cAca;;;;;;;;;;;;;;;;;;;;cAsBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8CA;;;cAUA;;;;;;;;;;;;;;;;;;;;;;;cAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;cA2BA;;cAMA
|
|
1
|
+
{"version":3,"file":"iife.d.ts","names":[],"sources":["../../src/core/iife.ts"],"mappings":";;;;;;;;cAca;;;;;;;;;;;;;;;;;;;;cAsBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8CA;;;cAUA;;;;;;;;;;;;;;;;;;;;;;;cAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;cA2BA;;cAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqGA;;;;;;;;;;;;;;;;;iBA6BG,iBAAiB,QAAQ;;;;;;;;;;;;;iBAgBzB,aACd,oBACA,QAAQ,oBACR;EAAY;EAAiC"}
|
package/dist/core/iife.js
CHANGED
|
@@ -215,6 +215,14 @@ const FINZ_DECL = "function __zcFinZ(z,r,i){return new __ZcFailZ(z,r,i);}";
|
|
|
215
215
|
* Installed with defineProperty rather than assignment: Zod's lazy setter
|
|
216
216
|
* redefines the slot as non-writable, so a second `__zcMkv` on the same schema
|
|
217
217
|
* object — two exports aliasing one schema — would throw under ESM strict mode.
|
|
218
|
+
*
|
|
219
|
+
* A rebuilding schema (no `fc`) reaches `parse()` through `fn`, i.e. through a
|
|
220
|
+
* SafeParseResult unwrapped a line later. Handing the build function over so
|
|
221
|
+
* `parse()` could call it directly was measured and declined: the wrapper is a
|
|
222
|
+
* young-generation bump allocation that V8 elides outright where `fn` inlines,
|
|
223
|
+
* and even across eight schemas sharing this closure — where it cannot — the
|
|
224
|
+
* direct call came out level (41.5 vs 41.8 ns), for a wider signature on every
|
|
225
|
+
* bundle.
|
|
218
226
|
*/
|
|
219
227
|
const MK_VALIDATOR_DECL = "function __zcMkv(fn,schema,fc,is){var w=schema||{};var zpa=w.parseAsync,zspa=w.safeParseAsync;w.parse=fc?function(input){if(fc(input))return input;var r=fn(input);if(r.success)return r.data;throw r.error;}:function(input){var r=fn(input);if(r.success)return r.data;throw r.error;};w.safeParse=fn;w.safeParseAsync=function(input){try{return Promise.resolve(fn(input));}catch(e){if(zspa)return zspa(input);throw e;}};w.parseAsync=fc?function(input){try{if(fc(input))return Promise.resolve(input);var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}}:function(input){try{var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}};w.is=is||function(input){return fn(input).success;};Object.defineProperty(w,\"~standard\",{configurable:true,value:{version:1,vendor:\"zod\",validate:function(input){var r;try{if(fc&&fc(input))return{value:input};r=fn(input);}catch(e){if(zspa)return zspa(input).then(function(q){return q.success?{value:q.data}:{issues:q.error.issues};});throw e;}return r.success?{value:r.data}:{issues:r.error.issues};}}});return w;}";
|
|
220
228
|
function extractFunctionName(functionDef) {
|