zod-compiler 1.28.0 → 2.0.1

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.
Files changed (97) hide show
  1. package/README.md +176 -148
  2. package/dist/core/codegen/build-path.d.ts +12 -1
  3. package/dist/core/codegen/build-path.d.ts.map +1 -1
  4. package/dist/core/codegen/build-path.js +102 -21
  5. package/dist/core/codegen/build-path.js.map +1 -1
  6. package/dist/core/codegen/context.d.ts +31 -16
  7. package/dist/core/codegen/context.d.ts.map +1 -1
  8. package/dist/core/codegen/context.js +43 -18
  9. package/dist/core/codegen/context.js.map +1 -1
  10. package/dist/core/codegen/emit-issue.d.ts +17 -20
  11. package/dist/core/codegen/emit-issue.d.ts.map +1 -1
  12. package/dist/core/codegen/emit-issue.js +13 -13
  13. package/dist/core/codegen/emit-issue.js.map +1 -1
  14. package/dist/core/codegen/index.d.ts.map +1 -1
  15. package/dist/core/codegen/index.js +9 -7
  16. package/dist/core/codegen/index.js.map +1 -1
  17. package/dist/core/codegen/issue-decls.d.ts +83 -7
  18. package/dist/core/codegen/issue-decls.d.ts.map +1 -1
  19. package/dist/core/codegen/issue-decls.js +93 -10
  20. package/dist/core/codegen/issue-decls.js.map +1 -1
  21. package/dist/core/codegen/schemas/array.js +1 -1
  22. package/dist/core/codegen/schemas/array.js.map +1 -1
  23. package/dist/core/codegen/schemas/bigint.d.ts.map +1 -1
  24. package/dist/core/codegen/schemas/bigint.js +15 -4
  25. package/dist/core/codegen/schemas/bigint.js.map +1 -1
  26. package/dist/core/codegen/schemas/catch.d.ts.map +1 -1
  27. package/dist/core/codegen/schemas/catch.js +3 -2
  28. package/dist/core/codegen/schemas/catch.js.map +1 -1
  29. package/dist/core/codegen/schemas/discriminated-union.d.ts +6 -2
  30. package/dist/core/codegen/schemas/discriminated-union.d.ts.map +1 -1
  31. package/dist/core/codegen/schemas/discriminated-union.js +16 -56
  32. package/dist/core/codegen/schemas/discriminated-union.js.map +1 -1
  33. package/dist/core/codegen/schemas/effect.d.ts.map +1 -1
  34. package/dist/core/codegen/schemas/effect.js +4 -2
  35. package/dist/core/codegen/schemas/effect.js.map +1 -1
  36. package/dist/core/codegen/schemas/file.js +2 -8
  37. package/dist/core/codegen/schemas/file.js.map +1 -1
  38. package/dist/core/codegen/schemas/number.js +4 -3
  39. package/dist/core/codegen/schemas/number.js.map +1 -1
  40. package/dist/core/codegen/schemas/object.d.ts +11 -1
  41. package/dist/core/codegen/schemas/object.d.ts.map +1 -1
  42. package/dist/core/codegen/schemas/object.js +58 -14
  43. package/dist/core/codegen/schemas/object.js.map +1 -1
  44. package/dist/core/codegen/schemas/readonly.d.ts.map +1 -1
  45. package/dist/core/codegen/schemas/readonly.js.map +1 -1
  46. package/dist/core/codegen/schemas/record.d.ts.map +1 -1
  47. package/dist/core/codegen/schemas/record.js +8 -3
  48. package/dist/core/codegen/schemas/record.js.map +1 -1
  49. package/dist/core/codegen/schemas/sizeable.d.ts +49 -3
  50. package/dist/core/codegen/schemas/sizeable.d.ts.map +1 -1
  51. package/dist/core/codegen/schemas/sizeable.js +101 -8
  52. package/dist/core/codegen/schemas/sizeable.js.map +1 -1
  53. package/dist/core/codegen/schemas/string-bool.d.ts +12 -1
  54. package/dist/core/codegen/schemas/string-bool.d.ts.map +1 -1
  55. package/dist/core/codegen/schemas/string-bool.js +19 -4
  56. package/dist/core/codegen/schemas/string-bool.js.map +1 -1
  57. package/dist/core/codegen/schemas/string.d.ts.map +1 -1
  58. package/dist/core/codegen/schemas/string.js +60 -26
  59. package/dist/core/codegen/schemas/string.js.map +1 -1
  60. package/dist/core/codegen/schemas/tuple.d.ts +14 -11
  61. package/dist/core/codegen/schemas/tuple.d.ts.map +1 -1
  62. package/dist/core/codegen/schemas/tuple.js +99 -49
  63. package/dist/core/codegen/schemas/tuple.js.map +1 -1
  64. package/dist/core/codegen/well-known-regex.d.ts +26 -1
  65. package/dist/core/codegen/well-known-regex.d.ts.map +1 -1
  66. package/dist/core/codegen/well-known-regex.js +31 -4
  67. package/dist/core/codegen/well-known-regex.js.map +1 -1
  68. package/dist/core/extract/checks.d.ts.map +1 -1
  69. package/dist/core/extract/checks.js +1 -0
  70. package/dist/core/extract/checks.js.map +1 -1
  71. package/dist/core/extract/extractors/intersection.js +21 -6
  72. package/dist/core/extract/extractors/intersection.js.map +1 -1
  73. package/dist/core/extract/extractors/object.d.ts.map +1 -1
  74. package/dist/core/extract/extractors/object.js +25 -9
  75. package/dist/core/extract/extractors/object.js.map +1 -1
  76. package/dist/core/extract/extractors/optional.d.ts.map +1 -1
  77. package/dist/core/extract/extractors/optional.js +1 -28
  78. package/dist/core/extract/extractors/optional.js.map +1 -1
  79. package/dist/core/extract/extractors/record.js +9 -3
  80. package/dist/core/extract/extractors/record.js.map +1 -1
  81. package/dist/core/extract/extractors/tuple.d.ts.map +1 -1
  82. package/dist/core/extract/extractors/tuple.js +16 -20
  83. package/dist/core/extract/extractors/tuple.js.map +1 -1
  84. package/dist/core/extract/types.d.ts +16 -8
  85. package/dist/core/extract/types.d.ts.map +1 -1
  86. package/dist/core/iife.d.ts +2 -1
  87. package/dist/core/iife.d.ts.map +1 -1
  88. package/dist/core/iife.js +2 -1
  89. package/dist/core/iife.js.map +1 -1
  90. package/dist/core/types.d.ts +70 -21
  91. package/dist/core/types.d.ts.map +1 -1
  92. package/dist/jit.d.ts.map +1 -1
  93. package/dist/jit.js +47 -12
  94. package/dist/jit.js.map +1 -1
  95. package/dist/runtime.d.ts +4 -1
  96. package/dist/runtime.js +14 -11
  97. package/package.json +2 -2
@@ -1,7 +1,7 @@
1
1
  import { declareFastTemps, emitRuntimeHelper, extendPath, hasMutation } from "../context.js";
2
2
  import { emit } from "../emit.js";
3
- import { invalidType } from "../emit-issue.js";
4
- import { ZC_FZ_DECL, ZC_HOP_DECL, ZC_PLAIN_DECL } from "../issue-decls.js";
3
+ import { invalidType, unrecognizedKeys } from "../emit-issue.js";
4
+ import { ZC_FZ_DECL, ZC_HOP_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL } from "../issue-decls.js";
5
5
  //#region src/core/codegen/schemas/record.ts
6
6
  /**
7
7
  * `$ZodRecord` gates on `util.isPlainObject`, NOT the looser `util.isObject`
@@ -26,13 +26,17 @@ function slowRecord(ir, g) {
26
26
  ${invalidType(g, "record")}
27
27
  }else{`;
28
28
  if (hasMutation(ir.valueType)) code += `${g.output}={...${g.input}};`;
29
+ code += `${g.output}=${emitRuntimeHelper(g.ctx, "__zcPs", ZC_PROTO_SCRUB_DECL)}(${g.input});`;
29
30
  const keyVar = g.temp("rkey");
30
31
  const keyIssuesVar = g.temp("rki");
31
32
  const keyPath = extendPath(g.path, keyVar);
32
33
  const valExpr = `${g.input}[${keyVar}]`;
33
34
  const hop = emitRuntimeHelper(g.ctx, "__zcHop", ZC_HOP_DECL);
34
35
  const fz = emitRuntimeHelper(g.ctx, "__zcFz", ZC_FZ_DECL);
36
+ const unrecognizedVar = ir.enumerableKeys ? g.temp("ruk") : null;
37
+ const onKeyFailure = unrecognizedVar === null ? `${g.issues}.push({code:"invalid_key",origin:"record",issues:${fz}(${keyIssuesVar}),input:${keyVar},path:${keyPath}${g.typeMsg === void 0 ? "" : `,message:${JSON.stringify(g.typeMsg)}`}});` : `(${unrecognizedVar}=${unrecognizedVar}||[]).push(${keyVar});`;
35
38
  code += emit`
39
+ ${unrecognizedVar === null ? "" : `var ${unrecognizedVar}=null;`}
36
40
  for(var ${keyVar} in ${g.input}){
37
41
  if(!${hop}.call(${g.input},${keyVar}))continue;
38
42
  ${PROTO_SKIP(keyVar)}
@@ -44,7 +48,7 @@ function slowRecord(ir, g) {
44
48
  issues: keyIssuesVar
45
49
  })}
46
50
  if(${keyIssuesVar}.length>0){
47
- ${g.issues}.push({code:"invalid_key",origin:"record",issues:${fz}(${keyIssuesVar}),input:${keyVar},path:${keyPath}${g.typeMsg === void 0 ? "" : `,message:${JSON.stringify(g.typeMsg)}`}});
51
+ ${onKeyFailure}
48
52
  }else{
49
53
  ${g.visit(ir.valueType, {
50
54
  input: valExpr,
@@ -53,6 +57,7 @@ function slowRecord(ir, g) {
53
57
  })}
54
58
  }
55
59
  }
60
+ ${unrecognizedVar === null ? "" : `if(${unrecognizedVar}!==null){${unrecognizedKeys(g, unrecognizedVar)}}`}
56
61
  }`;
57
62
  return `${code}\n`;
58
63
  }
@@ -1 +1 @@
1
- {"version":3,"file":"record.js","names":[],"sources":["../../../../src/core/codegen/schemas/record.ts"],"sourcesContent":["import type { RecordIR, SchemaIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport { declareFastTemps, emitRuntimeHelper, extendPath, hasMutation } from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType } from \"../emit-issue.js\";\nimport { ZC_FZ_DECL, ZC_HOP_DECL, ZC_PLAIN_DECL } from \"../issue-decls.js\";\n\n/**\n * `$ZodRecord` gates on `util.isPlainObject`, NOT the looser `util.isObject`\n * that `$ZodObject` uses — see {@link ZC_PLAIN_DECL} for why the two differ and\n * what accepting the wrong one lets through.\n */\nfunction plainObjectTest(g: SlowGen | FastGen, input: string): string {\n return `${emitRuntimeHelper(g.ctx, \"__zcPlain\", ZC_PLAIN_DECL)}(${input})`;\n}\n\n/**\n * Zod's record walk opens with `if (key === \"__proto__\") continue`, so an own\n * `__proto__` data property (which `JSON.parse('{\"__proto__\":…}')` creates) is\n * neither key-validated nor value-validated nor copied. Without this the\n * compiled walk reported issues zod does not: `z.record(z.string(), z.number())`\n * over such an object raised a SECOND `invalid_type`, and a constrained key\n * schema a second `invalid_key`, for a key zod never looks at.\n */\nconst PROTO_SKIP = (keyVar: string): string => `if(${keyVar}===\"__proto__\")continue;`;\n\nexport function slowRecord(ir: SchemaIR & { type: \"record\" }, g: SlowGen): string {\n let code = emit`\n if(!${plainObjectTest(g, g.input)}){\n ${invalidType(g, \"record\")}\n }else{`;\n\n if (hasMutation(ir.valueType)) {\n code += `${g.output}={...${g.input}};`;\n }\n\n const keyVar = g.temp(\"rkey\");\n const keyIssuesVar = g.temp(\"rki\");\n const keyPath = extendPath(g.path, keyVar);\n const valExpr = `${g.input}[${keyVar}]`;\n // for-in + hasOwnProperty guard instead of Object.keys(): identical\n // own-enumerable string-key set and iteration order, no keys-array\n // allocation. When the value type mutates (coerce/default/.trim()) the clone\n // above has already replaced g.input, so this iterates the clone exactly as\n // the Object.keys form did — the key set is stable (values change, keys\n // don't). Records whose values mutate run this path eagerly, so they get the\n // same speedup the fast path does.\n const hop = emitRuntimeHelper(g.ctx, \"__zcHop\", ZC_HOP_DECL);\n\n // The key is validated at a RELATIVE path and its issues are finalized before\n // being nested, mirroring zod: `issues: keyResult.issues.map(finalizeIssue)`\n // over a payload zod ran fresh. Nested issues never reach the top-level\n // finalization loop (it walks only the outer array), so an unfinalized nest\n // leaked absolute paths and the raw `input` into the reported error.\n const fz = emitRuntimeHelper(g.ctx, \"__zcFz\", ZC_FZ_DECL);\n\n code += emit`\n for(var ${keyVar} in ${g.input}){\n if(!${hop}.call(${g.input},${keyVar}))continue;\n ${PROTO_SKIP(keyVar)}\n var ${keyIssuesVar}=[];\n ${g.visit(ir.keyType, { input: keyVar, output: keyVar, path: \"[]\", issues: keyIssuesVar })}\n if(${keyIssuesVar}.length>0){\n ${g.issues}.push({code:\"invalid_key\",origin:\"record\",issues:${fz}(${keyIssuesVar}),input:${keyVar},path:${keyPath}${g.typeMsg === undefined ? \"\" : `,message:${JSON.stringify(g.typeMsg)}`}});\n }else{\n ${g.visit(ir.valueType, { input: valExpr, output: valExpr, path: keyPath })}\n }\n }\n }`;\n return `${code}\\n`;\n}\n\nexport function fastRecord(ir: RecordIR, g: FastGen): string | null {\n const x = g.input;\n const parts: string[] = [plainObjectTest(g, x)];\n\n // Object.keys only yields strings — a plain unconstrained string key schema\n // is always satisfied, so skip generating its check entirely.\n const plainStringKey =\n ir.keyType.type === \"string\" && ir.keyType.checks.length === 0 && ir.keyType.coerce !== true;\n\n const kv = g.temp(\"rk\");\n const vv = g.temp(\"rv\");\n // Key + value checks share one fresh scope — they live in the same emitted\n // helper function, size-gated independently of the caller.\n const body = g.scoped(kv);\n const keyCheck = plainStringKey ? \"true\" : body.visit(ir.keyType, { input: kv });\n // Hoist o[k] into a loop variable: computed-key lookups don't get V8's load\n // elimination across check boundaries, so each repeated o[k] would re-walk\n // the (often dictionary-mode) object.\n const valCheck = body.visit(ir.valueType, { input: vv });\n if (keyCheck === null || valCheck === null) return null;\n\n const conditions: string[] = [];\n if (keyCheck !== \"true\") conditions.push(keyCheck);\n if (valCheck !== \"true\") conditions.push(valCheck);\n\n if (conditions.length > 0) {\n const helperName = g.temp(\"rf\");\n const valAssign = valCheck !== \"true\" ? `${vv}=o[${kv}];` : \"\";\n // for-in (no Object.keys array allocation) + hasOwnProperty guard. The\n // guard restricts iteration to own enumerable string keys — the exact set\n // Object.keys/the slow path produce — so inherited enumerable props can't\n // make the fast check disagree with the deferred slow walk. Measured 2.9x\n // (5 keys) to 5.8x (20 keys) faster than the Object.keys form; the hoisted\n // __zcHop.call inlines, making the guard ~free vs an unguarded for-in.\n const hop = emitRuntimeHelper(g.ctx, \"__zcHop\", ZC_HOP_DECL);\n g.ctx.preamble.push(\n `function ${helperName}(o){${declareFastTemps(body.scope)}var ${kv},${vv};for(${kv} in o){${PROTO_SKIP(kv)}if(${hop}.call(o,${kv})){${valAssign}if(!(${conditions.join(\"&&\")})){return false;}}}return true;}`,\n );\n parts.push(`${helperName}(${x})`);\n }\n\n return parts.join(\"&&\");\n}\n"],"mappings":";;;;;;;;;;AAYA,SAAS,gBAAgB,GAAsB,OAAuB;CACpE,OAAO,GAAG,kBAAkB,EAAE,KAAK,aAAa,aAAa,EAAE,GAAG,MAAM;AAC1E;;;;;;;;;AAUA,MAAM,cAAc,WAA2B,MAAM,OAAO;AAE5D,SAAgB,WAAW,IAAmC,GAAoB;CAChF,IAAI,OAAO,IAAI;UACP,gBAAgB,GAAG,EAAE,KAAK,EAAE;QAC9B,YAAY,GAAG,QAAQ,EAAE;;CA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AG,CAAC;CAI/E,MAAM,WAAW,KAAK,MAAM,GAAG,WAAW,EAAE,OAAO,GAAG,CAAC;CACvD,IAAI,aAAa,QAAQ,aAAa,MAAM,OAAO;CAEnD,MAAM,aAAuB,CAAC;CAC9B,IAAI,aAAa,QAAQ,WAAW,KAAK,QAAQ;CACjD,IAAI,aAAa,QAAQ,WAAW,KAAK,QAAQ;CAEjD,IAAI,WAAW,SAAS,GAAG;EACzB,MAAM,aAAa,EAAE,KAAK,IAAI;EAC9B,MAAM,YAAY,aAAa,SAAS,GAAG,GAAG,KAAK,GAAG,MAAM;EAO5D,MAAM,MAAM,kBAAkB,EAAE,KAAK,WAAW,WAAW;EAC3D,EAAE,IAAI,SAAS,KACb,YAAY,WAAW,MAAM,iBAAiB,KAAK,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,GAAG,SAAS,WAAW,EAAE,EAAE,KAAK,IAAI,UAAU,GAAG,KAAK,UAAU,OAAO,WAAW,KAAK,IAAI,EAAE,iCAC/K;EACA,MAAM,KAAK,GAAG,WAAW,GAAG,EAAE,EAAE;CAClC;CAEA,OAAO,MAAM,KAAK,IAAI;AACxB"}
1
+ {"version":3,"file":"record.js","names":[],"sources":["../../../../src/core/codegen/schemas/record.ts"],"sourcesContent":["import type { RecordIR, SchemaIR } from \"../../types.js\";\nimport type { FastGen, SlowGen } from \"../context.js\";\nimport { declareFastTemps, emitRuntimeHelper, extendPath, hasMutation } from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { invalidType, unrecognizedKeys } from \"../emit-issue.js\";\nimport { ZC_FZ_DECL, ZC_HOP_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL } from \"../issue-decls.js\";\n\n/**\n * `$ZodRecord` gates on `util.isPlainObject`, NOT the looser `util.isObject`\n * that `$ZodObject` uses — see {@link ZC_PLAIN_DECL} for why the two differ and\n * what accepting the wrong one lets through.\n */\nfunction plainObjectTest(g: SlowGen | FastGen, input: string): string {\n return `${emitRuntimeHelper(g.ctx, \"__zcPlain\", ZC_PLAIN_DECL)}(${input})`;\n}\n\n/**\n * Zod's record walk opens with `if (key === \"__proto__\") continue`, so an own\n * `__proto__` data property (which `JSON.parse('{\"__proto__\":…}')` creates) is\n * neither key-validated nor value-validated nor copied. Without this the\n * compiled walk reported issues zod does not: `z.record(z.string(), z.number())`\n * over such an object raised a SECOND `invalid_type`, and a constrained key\n * schema a second `invalid_key`, for a key zod never looks at.\n */\nconst PROTO_SKIP = (keyVar: string): string => `if(${keyVar}===\"__proto__\")continue;`;\n\nexport function slowRecord(ir: SchemaIR & { type: \"record\" }, g: SlowGen): string {\n let code = emit`\n if(!${plainObjectTest(g, g.input)}){\n ${invalidType(g, \"record\")}\n }else{`;\n\n if (hasMutation(ir.valueType)) {\n code += `${g.output}={...${g.input}};`;\n }\n // PROTO_SKIP keeps `__proto__` out of the WALK; this keeps it out of the\n // OUTPUT, which zod also does — it copies into a fresh `{}` and skips the key\n // (see ZC_PROTO_SCRUB_DECL). Runs before the walk so the loop iterates the\n // same container the caller gets back.\n code += `${g.output}=${emitRuntimeHelper(g.ctx, \"__zcPs\", ZC_PROTO_SCRUB_DECL)}(${g.input});`;\n\n const keyVar = g.temp(\"rkey\");\n const keyIssuesVar = g.temp(\"rki\");\n const keyPath = extendPath(g.path, keyVar);\n const valExpr = `${g.input}[${keyVar}]`;\n // for-in + hasOwnProperty guard instead of Object.keys(): identical\n // own-enumerable string-key set and iteration order, no keys-array\n // allocation. When the value type mutates (coerce/default/.trim()) the clone\n // above has already replaced g.input, so this iterates the clone exactly as\n // the Object.keys form did — the key set is stable (values change, keys\n // don't). Records whose values mutate run this path eagerly, so they get the\n // same speedup the fast path does.\n const hop = emitRuntimeHelper(g.ctx, \"__zcHop\", ZC_HOP_DECL);\n\n // The key is validated at a RELATIVE path and its issues are finalized before\n // being nested, mirroring zod: `issues: keyResult.issues.map(finalizeIssue)`\n // over a payload zod ran fresh. Nested issues never reach the top-level\n // finalization loop (it walks only the outer array), so an unfinalized nest\n // leaked absolute paths and the raw `input` into the reported error.\n const fz = emitRuntimeHelper(g.ctx, \"__zcFz\", ZC_FZ_DECL);\n\n // A key the enumerable key schema rejects is unrecognized, not invalid: zod\n // collects those and pushes ONE `unrecognized_keys` after the walk, so it\n // trails every value issue (see RecordIR.enumerableKeys).\n const unrecognizedVar = ir.enumerableKeys ? g.temp(\"ruk\") : null;\n const onKeyFailure =\n unrecognizedVar === null\n ? `${g.issues}.push({code:\"invalid_key\",origin:\"record\",issues:${fz}(${keyIssuesVar}),input:${keyVar},path:${keyPath}${g.typeMsg === undefined ? \"\" : `,message:${JSON.stringify(g.typeMsg)}`}});`\n : `(${unrecognizedVar}=${unrecognizedVar}||[]).push(${keyVar});`;\n\n code += emit`\n ${unrecognizedVar === null ? \"\" : `var ${unrecognizedVar}=null;`}\n for(var ${keyVar} in ${g.input}){\n if(!${hop}.call(${g.input},${keyVar}))continue;\n ${PROTO_SKIP(keyVar)}\n var ${keyIssuesVar}=[];\n ${g.visit(ir.keyType, { input: keyVar, output: keyVar, path: \"[]\", issues: keyIssuesVar })}\n if(${keyIssuesVar}.length>0){\n ${onKeyFailure}\n }else{\n ${g.visit(ir.valueType, { input: valExpr, output: valExpr, path: keyPath })}\n }\n }\n ${unrecognizedVar === null ? \"\" : `if(${unrecognizedVar}!==null){${unrecognizedKeys(g, unrecognizedVar)}}`}\n }`;\n return `${code}\\n`;\n}\n\nexport function fastRecord(ir: RecordIR, g: FastGen): string | null {\n const x = g.input;\n const parts: string[] = [plainObjectTest(g, x)];\n\n // Object.keys only yields strings — a plain unconstrained string key schema\n // is always satisfied, so skip generating its check entirely.\n const plainStringKey =\n ir.keyType.type === \"string\" && ir.keyType.checks.length === 0 && ir.keyType.coerce !== true;\n\n const kv = g.temp(\"rk\");\n const vv = g.temp(\"rv\");\n // Key + value checks share one fresh scope — they live in the same emitted\n // helper function, size-gated independently of the caller.\n const body = g.scoped(kv);\n const keyCheck = plainStringKey ? \"true\" : body.visit(ir.keyType, { input: kv });\n // Hoist o[k] into a loop variable: computed-key lookups don't get V8's load\n // elimination across check boundaries, so each repeated o[k] would re-walk\n // the (often dictionary-mode) object.\n const valCheck = body.visit(ir.valueType, { input: vv });\n if (keyCheck === null || valCheck === null) return null;\n\n const conditions: string[] = [];\n if (keyCheck !== \"true\") conditions.push(keyCheck);\n if (valCheck !== \"true\") conditions.push(valCheck);\n\n if (conditions.length > 0) {\n const helperName = g.temp(\"rf\");\n const valAssign = valCheck !== \"true\" ? `${vv}=o[${kv}];` : \"\";\n // for-in (no Object.keys array allocation) + hasOwnProperty guard. The\n // guard restricts iteration to own enumerable string keys — the exact set\n // Object.keys/the slow path produce — so inherited enumerable props can't\n // make the fast check disagree with the deferred slow walk. Measured 2.9x\n // (5 keys) to 5.8x (20 keys) faster than the Object.keys form; the hoisted\n // __zcHop.call inlines, making the guard ~free vs an unguarded for-in.\n const hop = emitRuntimeHelper(g.ctx, \"__zcHop\", ZC_HOP_DECL);\n g.ctx.preamble.push(\n `function ${helperName}(o){${declareFastTemps(body.scope)}var ${kv},${vv};for(${kv} in o){${PROTO_SKIP(kv)}if(${hop}.call(o,${kv})){${valAssign}if(!(${conditions.join(\"&&\")})){return false;}}}return true;}`,\n );\n parts.push(`${helperName}(${x})`);\n }\n\n return parts.join(\"&&\");\n}\n"],"mappings":";;;;;;;;;;AAYA,SAAS,gBAAgB,GAAsB,OAAuB;CACpE,OAAO,GAAG,kBAAkB,EAAE,KAAK,aAAa,aAAa,EAAE,GAAG,MAAM;AAC1E;;;;;;;;;AAUA,MAAM,cAAc,WAA2B,MAAM,OAAO;AAE5D,SAAgB,WAAW,IAAmC,GAAoB;CAChF,IAAI,OAAO,IAAI;UACP,gBAAgB,GAAG,EAAE,KAAK,EAAE;QAC9B,YAAY,GAAG,QAAQ,EAAE;;CAG/B,IAAI,YAAY,GAAG,SAAS,GAC1B,QAAQ,GAAG,EAAE,OAAO,OAAO,EAAE,MAAM;CAMrC,QAAQ,GAAG,EAAE,OAA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MAAM,iBACJ,GAAG,QAAQ,SAAS,YAAY,GAAG,QAAQ,OAAO,WAAW,KAAK,GAAG,QAAQ,WAAW;CAE1F,MAAM,KAAK,EAAE,KAAK,IAAI;CACtB,MAAM,KAAK,EAAE,KAAK,IAAI;CAGtB,MAAM,OAAO,EAAE,OAAO,EAAE;CACxB,MAAM,WAAW,iBAAiB,SAAS,KAAK,MAAM,GAAG,SAAS,EAAE,OAAO,GAAG,CAAC;CAI/E,MAAM,WAAW,KAAK,MAAM,GAAG,WAAW,EAAE,OAAO,GAAG,CAAC;CACvD,IAAI,aAAa,QAAQ,aAAa,MAAM,OAAO;CAEnD,MAAM,aAAuB,CAAC;CAC9B,IAAI,aAAa,QAAQ,WAAW,KAAK,QAAQ;CACjD,IAAI,aAAa,QAAQ,WAAW,KAAK,QAAQ;CAEjD,IAAI,WAAW,SAAS,GAAG;EACzB,MAAM,aAAa,EAAE,KAAK,IAAI;EAC9B,MAAM,YAAY,aAAa,SAAS,GAAG,GAAG,KAAK,GAAG,MAAM;EAO5D,MAAM,MAAM,kBAAkB,EAAE,KAAK,WAAW,WAAW;EAC3D,EAAE,IAAI,SAAS,KACb,YAAY,WAAW,MAAM,iBAAiB,KAAK,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,GAAG,SAAS,WAAW,EAAE,EAAE,KAAK,IAAI,UAAU,GAAG,KAAK,UAAU,OAAO,WAAW,KAAK,IAAI,EAAE,iCAC/K;EACA,MAAM,KAAK,GAAG,WAAW,GAAG,EAAE,EAAE;CAClC;CAEA,OAAO,MAAM,KAAK,IAAI;AACxB"}
@@ -1,6 +1,46 @@
1
1
  import { CheckOrEffectIR, FileCheckIR, SetCheckIR } from "../../types.js";
2
- import { SlowGen } from "../context.js";
2
+ import { CodeGenContext, SlowGen } from "../context.js";
3
3
  //#region src/core/codegen/schemas/sizeable.d.ts
4
+ /**
5
+ * String length tests over Unicode CODE POINTS, gated so the count is only
6
+ * paid for when the UTF-16 unit count leaves the verdict in doubt.
7
+ *
8
+ * zod measures `z.string().min()/.max()/.length()` in code points
9
+ * (`util.codePointLength`), so `"😀"` has length 1, and it computes that count
10
+ * only when the unit count could sit on the other side of the bound. A code
11
+ * point is one or two units, so `units/2 <= codePoints <= units` — which pins
12
+ * the doubtful band tighter than zod's own gate without changing a verdict:
13
+ * `min(N)` is settled outside `N <= units < 2*ceil(N)-1` (so `min(1)` stays a
14
+ * plain `length>=1`; see {@link certainlyAtLeast} for the fractional case),
15
+ * `max(N)` outside `N < units <= 2N`, and `length(N)` outside `N <= units <=
16
+ * 2N`. Every test leads with the plain unit comparison, so an ASCII string of
17
+ * ordinary length never reaches the helper.
18
+ *
19
+ * `mayNotBeString` adds the `typeof` guard zod applies (`typeof input ===
20
+ * "string" && …`) for a site whose input is not statically a string — a
21
+ * length check firing on the wrong type through its `when` predicate; an array
22
+ * measures elements, never code points. Only the failure-direction forms take
23
+ * it: `min`/`max`/`equals` are reached solely from `fastStringCheck`, whose
24
+ * input is statically a string.
25
+ */
26
+ declare const stringLengthTests: {
27
+ min(x: string, min: number, ctx: CodeGenContext): string;
28
+ max(x: string, max: number, ctx: CodeGenContext): string;
29
+ equals(x: string, length: number, ctx: CodeGenContext): string;
30
+ /**
31
+ * The FAILING condition of `min`/`max`, with the negation pushed inward so a
32
+ * check with no doubtful band emits the plain comparison the slow path always
33
+ * used (`x.length<1`, not `!(x.length>=1)`).
34
+ */
35
+ minFails(x: string, min: number, ctx: CodeGenContext, mayNotBeString?: boolean): string;
36
+ maxFails(x: string, max: number, ctx: CodeGenContext, mayNotBeString?: boolean): string;
37
+ /**
38
+ * The measured length zod compares in `$ZodCheckLengthEquals` — code points
39
+ * inside the doubtful band, units outside it — for the slow path, which has
40
+ * to know WHICH side of the bound the value fell on.
41
+ */
42
+ measure(x: string, length: number, ctx: CodeGenContext, mayNotBeString?: boolean): string;
43
+ };
4
44
  /**
5
45
  * Length/size checks re-emitted for the branch where the node's TYPE CHECK
6
46
  * ALREADY FAILED.
@@ -30,8 +70,14 @@ import { SlowGen } from "../context.js";
30
70
  *
31
71
  * `origin` is computed at runtime here (see ZC_LENGTH_ORIGIN_DECL), because the
32
72
  * value that reached this branch is by definition not the schema's own type.
73
+ *
74
+ * `mayBeString` is set by a non-string node whose length checks can fire on a
75
+ * string (`z.array(…).min(2)` over `"😀"`): zod then measures it in code
76
+ * points, so those tests take the guarded form of {@link stringLengthTests}. A
77
+ * string node's own failure branch never holds a string and keeps the plain
78
+ * unit comparison.
33
79
  */
34
- declare function whenGatedSizeChecks(checks: readonly (CheckOrEffectIR | SetCheckIR | FileCheckIR)[], g: SlowGen, family: "length" | "size"): string;
80
+ declare function whenGatedSizeChecks(checks: readonly (CheckOrEffectIR | SetCheckIR | FileCheckIR)[], g: SlowGen, family: "length" | "size", mayBeString?: boolean): string;
35
81
  //#endregion
36
- export { whenGatedSizeChecks };
82
+ export { stringLengthTests, whenGatedSizeChecks };
37
83
  //# sourceMappingURL=sizeable.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sizeable.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/sizeable.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqCgB,oBACd,kBAAkB,kBAAkB,aAAa,gBACjD,GAAG,SACH"}
1
+ {"version":3,"file":"sizeable.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/sizeable.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;cA4Ca;EACJ,IAAA,WAAM,aAAa,KAAO;EAM1B,IAAA,WAAM,aAAa,KAAO;EAMvB,OAAA,WAAM,gBAAgB,KAAO;;;;;;EAe3B,SAAA,WAAM,aAAa,KAAO,gBAAc;EAOxC,SAAA,WAAM,aAAa,KAAO,gBAAc;;;;;;EAYzC,QAAA,WAAM,gBAAgB,KAAO,gBAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8CxC,oBACd,kBAAkB,kBAAkB,aAAa,gBACjD,GAAG,SACH,2BACA"}
@@ -1,9 +1,94 @@
1
1
  import { emitRuntimeHelper } from "../context.js";
2
2
  import { emit } from "../emit.js";
3
3
  import { tooBig, tooSmall } from "../emit-issue.js";
4
- import { ZC_LENGTH_ORIGIN_DECL, ZC_SIZE_ORIGIN_DECL } from "../issue-decls.js";
4
+ import { ZC_CPL_DECL, ZC_LENGTH_ORIGIN_DECL, ZC_SIZE_ORIGIN_DECL } from "../issue-decls.js";
5
5
  //#region src/core/codegen/schemas/sizeable.ts
6
6
  /**
7
+ * The UTF-16 unit count from which a string is CERTAINLY at least `min` code
8
+ * points, so the count can be skipped.
9
+ *
10
+ * A code point is one or two units, so `codePoints >= ceil(units / 2)`, and
11
+ * that ceiling is an integer: `ceil(units/2) >= min` holds exactly when
12
+ * `ceil(units/2) >= Math.ceil(min)`, i.e. `units >= 2 * ceil(min) - 1`.
13
+ * Rounding `min` up is what makes a FRACTIONAL bound safe — `min(2.5)` is
14
+ * settled at 5 units, not the 4 that `2 * min - 1` would have claimed, where
15
+ * two astral characters are only 2 code points and zod reports `too_small`.
16
+ */
17
+ function certainlyAtLeast(min) {
18
+ return 2 * Math.ceil(min) - 1;
19
+ }
20
+ /**
21
+ * String length tests over Unicode CODE POINTS, gated so the count is only
22
+ * paid for when the UTF-16 unit count leaves the verdict in doubt.
23
+ *
24
+ * zod measures `z.string().min()/.max()/.length()` in code points
25
+ * (`util.codePointLength`), so `"😀"` has length 1, and it computes that count
26
+ * only when the unit count could sit on the other side of the bound. A code
27
+ * point is one or two units, so `units/2 <= codePoints <= units` — which pins
28
+ * the doubtful band tighter than zod's own gate without changing a verdict:
29
+ * `min(N)` is settled outside `N <= units < 2*ceil(N)-1` (so `min(1)` stays a
30
+ * plain `length>=1`; see {@link certainlyAtLeast} for the fractional case),
31
+ * `max(N)` outside `N < units <= 2N`, and `length(N)` outside `N <= units <=
32
+ * 2N`. Every test leads with the plain unit comparison, so an ASCII string of
33
+ * ordinary length never reaches the helper.
34
+ *
35
+ * `mayNotBeString` adds the `typeof` guard zod applies (`typeof input ===
36
+ * "string" && …`) for a site whose input is not statically a string — a
37
+ * length check firing on the wrong type through its `when` predicate; an array
38
+ * measures elements, never code points. Only the failure-direction forms take
39
+ * it: `min`/`max`/`equals` are reached solely from `fastStringCheck`, whose
40
+ * input is statically a string.
41
+ */
42
+ const stringLengthTests = {
43
+ min(x, min, ctx) {
44
+ const units = `${x}.length>=${min}`;
45
+ if (min <= 1) return units;
46
+ const cpl = emitRuntimeHelper(ctx, "__zcCpl", ZC_CPL_DECL);
47
+ return `${units}&&(${x}.length>=${certainlyAtLeast(min)}||${cpl}(${x})>=${min})`;
48
+ },
49
+ max(x, max, ctx) {
50
+ const units = `${x}.length<=${max}`;
51
+ if (max <= 0) return units;
52
+ const cpl = emitRuntimeHelper(ctx, "__zcCpl", ZC_CPL_DECL);
53
+ return `(${units}||(${x}.length<=${2 * max}&&${cpl}(${x})<=${max}))`;
54
+ },
55
+ equals(x, length, ctx) {
56
+ if (length <= 0) return `${x}.length===${length}`;
57
+ const cpl = emitRuntimeHelper(ctx, "__zcCpl", ZC_CPL_DECL);
58
+ if (length === 1) return `(${x}.length===1||(${x}.length===2&&${cpl}(${x})===1))`;
59
+ return `(${x}.length>=${length}&&${x}.length<=${2 * length}&&${cpl}(${x})===${length})`;
60
+ },
61
+ /**
62
+ * The FAILING condition of `min`/`max`, with the negation pushed inward so a
63
+ * check with no doubtful band emits the plain comparison the slow path always
64
+ * used (`x.length<1`, not `!(x.length>=1)`).
65
+ */
66
+ minFails(x, min, ctx, mayNotBeString = false) {
67
+ const units = `${x}.length<${min}`;
68
+ if (min <= 1) return units;
69
+ const cpl = emitRuntimeHelper(ctx, "__zcCpl", ZC_CPL_DECL);
70
+ const guard = mayNotBeString ? `typeof ${x}==="string"&&` : "";
71
+ return `${units}||(${x}.length<${certainlyAtLeast(min)}&&${guard}${cpl}(${x})<${min})`;
72
+ },
73
+ maxFails(x, max, ctx, mayNotBeString = false) {
74
+ const units = `${x}.length>${max}`;
75
+ if (max <= 0) return units;
76
+ const cpl = emitRuntimeHelper(ctx, "__zcCpl", ZC_CPL_DECL);
77
+ const guard = mayNotBeString ? `typeof ${x}!=="string"||` : "";
78
+ return `${units}&&(${x}.length>${2 * max}||${guard}${cpl}(${x})>${max})`;
79
+ },
80
+ /**
81
+ * The measured length zod compares in `$ZodCheckLengthEquals` — code points
82
+ * inside the doubtful band, units outside it — for the slow path, which has
83
+ * to know WHICH side of the bound the value fell on.
84
+ */
85
+ measure(x, length, ctx, mayNotBeString = false) {
86
+ if (length <= 0) return `${x}.length`;
87
+ const cpl = emitRuntimeHelper(ctx, "__zcCpl", ZC_CPL_DECL);
88
+ return `(${mayNotBeString ? `typeof ${x}==="string"&&` : ""}${length === 1 ? `${x}.length===2` : `${x}.length>=${length}&&${x}.length<=${2 * length}`}?${cpl}(${x}):${x}.length)`;
89
+ }
90
+ };
91
+ /**
7
92
  * Length/size checks re-emitted for the branch where the node's TYPE CHECK
8
93
  * ALREADY FAILED.
9
94
  *
@@ -32,8 +117,14 @@ import { ZC_LENGTH_ORIGIN_DECL, ZC_SIZE_ORIGIN_DECL } from "../issue-decls.js";
32
117
  *
33
118
  * `origin` is computed at runtime here (see ZC_LENGTH_ORIGIN_DECL), because the
34
119
  * value that reached this branch is by definition not the schema's own type.
120
+ *
121
+ * `mayBeString` is set by a non-string node whose length checks can fire on a
122
+ * string (`z.array(…).min(2)` over `"😀"`): zod then measures it in code
123
+ * points, so those tests take the guarded form of {@link stringLengthTests}. A
124
+ * string node's own failure branch never holds a string and keeps the plain
125
+ * unit comparison.
35
126
  */
36
- function whenGatedSizeChecks(checks, g, family) {
127
+ function whenGatedSizeChecks(checks, g, family, mayBeString = false) {
37
128
  const KINDS = family === "length" ? /* @__PURE__ */ new Set([
38
129
  "min_length",
39
130
  "max_length",
@@ -51,30 +142,32 @@ function whenGatedSizeChecks(checks, g, family) {
51
142
  for (const check of checks) switch (check.kind) {
52
143
  case "min_length":
53
144
  body += emit`
54
- if(${measure}<${check.minimum}){
145
+ if(${mayBeString ? stringLengthTests.minFails(g.input, check.minimum, g.ctx, true) : `${measure}<${check.minimum}`}){
55
146
  ${tooSmall(g, check.minimum, origin, true, { message: check.message })}
56
147
  }`;
57
148
  break;
58
149
  case "max_length":
59
150
  body += emit`
60
- if(${measure}>${check.maximum}){
151
+ if(${mayBeString ? stringLengthTests.maxFails(g.input, check.maximum, g.ctx, true) : `${measure}>${check.maximum}`}){
61
152
  ${tooBig(g, check.maximum, origin, true, { message: check.message })}
62
153
  }`;
63
154
  break;
64
- case "length_equals":
155
+ case "length_equals": {
156
+ const length = mayBeString ? stringLengthTests.measure(g.input, check.length, g.ctx, true) : measure;
65
157
  body += emit`
66
- if(${measure}<${check.length}){
158
+ if(${length}<${check.length}){
67
159
  ${tooSmall(g, check.length, origin, true, {
68
160
  exact: true,
69
161
  message: check.message
70
162
  })}
71
- }else if(${measure}>${check.length}){
163
+ }else if(${length}>${check.length}){
72
164
  ${tooBig(g, check.length, origin, true, {
73
165
  exact: true,
74
166
  message: check.message
75
167
  })}
76
168
  }`;
77
169
  break;
170
+ }
78
171
  case "min_size":
79
172
  body += emit`
80
173
  if(${measure}<${check.minimum}){
@@ -110,6 +203,6 @@ function whenGatedSizeChecks(checks, g, family) {
110
203
  }`;
111
204
  }
112
205
  //#endregion
113
- export { whenGatedSizeChecks };
206
+ export { stringLengthTests, whenGatedSizeChecks };
114
207
 
115
208
  //# sourceMappingURL=sizeable.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sizeable.js","names":[],"sources":["../../../../src/core/codegen/schemas/sizeable.ts"],"sourcesContent":["import type { CheckOrEffectIR, FileCheckIR, SetCheckIR } from \"../../types.js\";\nimport type { SlowGen } from \"../context.js\";\nimport { emitRuntimeHelper } from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { tooBig, tooSmall } from \"../emit-issue.js\";\nimport { ZC_LENGTH_ORIGIN_DECL, ZC_SIZE_ORIGIN_DECL } from \"../issue-decls.js\";\n\n/**\n * Length/size checks re-emitted for the branch where the node's TYPE CHECK\n * ALREADY FAILED.\n *\n * zod skips a schema's checks once its parse aborted — except the ones carrying\n * a `when` predicate, which `runChecks` consults instead of the abort flag:\n *\n * ```js\n * if (ch._zod.def.when) { if (!ch._zod.def.when(payload)) continue; }\n * else if (isAborted) continue;\n * ```\n *\n * and `$ZodCheckMinLength` & co. install exactly such a predicate —\n * `!nullish(value) && value.length !== undefined` (`.size` for the size family)\n * — so they run on ANY input carrying that property, of any type. Hence\n * `z.string().min(2).safeParse([])` reports TWO issues in zod: the\n * `invalid_type`, and a `too_small` whose `origin` is `\"array\"`, because the\n * empty array satisfied the `when`. Compiled output kept every check inside the\n * matched-type branch and reported only the first. Same for\n * `z.array(…).min(3)` over a short string, `z.set(…).min(2)` over a `Map`, and\n * `z.file().min(2)` over a `Set`.\n *\n * Emitted as a SEPARATE copy in the failure branch rather than hoisted out of\n * both, so the success path — where the origin is statically known and the guard\n * is trivially true — stays byte-for-byte what it was. This is cold code: it\n * runs only for input the node has already rejected.\n *\n * `origin` is computed at runtime here (see ZC_LENGTH_ORIGIN_DECL), because the\n * value that reached this branch is by definition not the schema's own type.\n */\nexport function whenGatedSizeChecks(\n checks: readonly (CheckOrEffectIR | SetCheckIR | FileCheckIR)[],\n g: SlowGen,\n family: \"length\" | \"size\",\n): string {\n const KINDS =\n family === \"length\"\n ? new Set([\"min_length\", \"max_length\", \"length_equals\"])\n : new Set([\"min_size\", \"max_size\", \"size_equals\"]);\n // Checked BEFORE touching the context: `emitRuntimeHelper` pushes its\n // declaration on sight, so asking for the origin helper up front left a dead\n // `__zcLo` in the preamble of every schema with a plain `z.string()` in it.\n if (!checks.some((check) => KINDS.has(check.kind))) return \"\";\n\n const property = family === \"length\" ? \"length\" : \"size\";\n const originHelper =\n family === \"length\"\n ? emitRuntimeHelper(g.ctx, \"__zcLo\", ZC_LENGTH_ORIGIN_DECL)\n : emitRuntimeHelper(g.ctx, \"__zcSo\", ZC_SIZE_ORIGIN_DECL);\n const origin = { expr: `${originHelper}(${g.input})` };\n const measure = `${g.input}.${property}`;\n\n let body = \"\";\n for (const check of checks) {\n // Kept in DECLARATION order: `runChecks` walks the check array, so two\n // failing length checks report in the order they were declared.\n switch (check.kind) {\n case \"min_length\":\n body += emit`\n if(${measure}<${check.minimum}){\n ${tooSmall(g, check.minimum, origin, true, { message: check.message })}\n }`;\n break;\n case \"max_length\":\n body += emit`\n if(${measure}>${check.maximum}){\n ${tooBig(g, check.maximum, origin, true, { message: check.message })}\n }`;\n break;\n case \"length_equals\":\n body += emit`\n if(${measure}<${check.length}){\n ${tooSmall(g, check.length, origin, true, { exact: true, message: check.message })}\n }else if(${measure}>${check.length}){\n ${tooBig(g, check.length, origin, true, { exact: true, message: check.message })}\n }`;\n break;\n case \"min_size\":\n body += emit`\n if(${measure}<${check.minimum}){\n ${tooSmall(g, check.minimum, origin, true, { message: check.message })}\n }`;\n break;\n case \"max_size\":\n body += emit`\n if(${measure}>${check.maximum}){\n ${tooBig(g, check.maximum, origin, true, { message: check.message })}\n }`;\n break;\n case \"size_equals\":\n body += emit`\n if(${measure}<${check.size}){\n ${tooSmall(g, check.size, origin, true, { exact: true, message: check.message })}\n }else if(${measure}>${check.size}){\n ${tooBig(g, check.size, origin, true, { exact: true, message: check.message })}\n }`;\n break;\n default:\n break;\n }\n }\n if (body === \"\") return \"\";\n // zod's own `when`, verbatim: `!util.nullish(value) && value.<prop> !== undefined`.\n return emit`\n if(${g.input}!==undefined&&${g.input}!==null&&${measure}!==undefined){\n ${body}\n }`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,oBACd,QACA,GACA,QACQ;CACR,MAAM,QACJ,WAAW,2BACP,IAAI,IAAI;EAAC;EAAc;EAAc;CAAe,CAAC,oBACrD,IAAI,IAAI;EAAC;EAAY;EAAY;CAAa,CAAC;CAIrD,IAAI,CAAC,OAAO,MAAM,UAAU,MAAM,IAAI,MAAM,IAAI,CAA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AAI;eACL,QAAQ,GAAG,MAAM,KAAK;cACvB,SAAS,GAAG,MAAM,MAAM,QAAQ,MAAM;IAAE,OAAO;IAAM,SAAS,MAAM;GAAQ,CAAC,EAAE;qBACxE,QAAQ,GAAG,MAAM,KAAK;cAC7B,OAAO,GAAG,MAAM,MAAM,QAAQ,MAAM;IAAE,OAAO;IAAM,SAAS,MAAM;GAAQ,CAAC,EAAE;;GAEnF;EACF,SACE;CACJ;CAEF,IAAI,SAAS,IAAI,OAAO;CAExB,OAAO,IAAI;SACJ,EAAE,MAAM,gBAAgB,EAAE,MAAM,WAAW,QAAQ;QACpD,KAAK;;AAEb"}
1
+ {"version":3,"file":"sizeable.js","names":[],"sources":["../../../../src/core/codegen/schemas/sizeable.ts"],"sourcesContent":["import type { CheckOrEffectIR, FileCheckIR, SetCheckIR } from \"../../types.js\";\nimport type { CodeGenContext, SlowGen } from \"../context.js\";\nimport { emitRuntimeHelper } from \"../context.js\";\nimport { emit } from \"../emit.js\";\nimport { tooBig, tooSmall } from \"../emit-issue.js\";\nimport { ZC_CPL_DECL, ZC_LENGTH_ORIGIN_DECL, ZC_SIZE_ORIGIN_DECL } from \"../issue-decls.js\";\n\n/**\n * The UTF-16 unit count from which a string is CERTAINLY at least `min` code\n * points, so the count can be skipped.\n *\n * A code point is one or two units, so `codePoints >= ceil(units / 2)`, and\n * that ceiling is an integer: `ceil(units/2) >= min` holds exactly when\n * `ceil(units/2) >= Math.ceil(min)`, i.e. `units >= 2 * ceil(min) - 1`.\n * Rounding `min` up is what makes a FRACTIONAL bound safe — `min(2.5)` is\n * settled at 5 units, not the 4 that `2 * min - 1` would have claimed, where\n * two astral characters are only 2 code points and zod reports `too_small`.\n */\nfunction certainlyAtLeast(min: number): number {\n return 2 * Math.ceil(min) - 1;\n}\n\n/**\n * String length tests over Unicode CODE POINTS, gated so the count is only\n * paid for when the UTF-16 unit count leaves the verdict in doubt.\n *\n * zod measures `z.string().min()/.max()/.length()` in code points\n * (`util.codePointLength`), so `\"😀\"` has length 1, and it computes that count\n * only when the unit count could sit on the other side of the bound. A code\n * point is one or two units, so `units/2 <= codePoints <= units` — which pins\n * the doubtful band tighter than zod's own gate without changing a verdict:\n * `min(N)` is settled outside `N <= units < 2*ceil(N)-1` (so `min(1)` stays a\n * plain `length>=1`; see {@link certainlyAtLeast} for the fractional case),\n * `max(N)` outside `N < units <= 2N`, and `length(N)` outside `N <= units <=\n * 2N`. Every test leads with the plain unit comparison, so an ASCII string of\n * ordinary length never reaches the helper.\n *\n * `mayNotBeString` adds the `typeof` guard zod applies (`typeof input ===\n * \"string\" && …`) for a site whose input is not statically a string — a\n * length check firing on the wrong type through its `when` predicate; an array\n * measures elements, never code points. Only the failure-direction forms take\n * it: `min`/`max`/`equals` are reached solely from `fastStringCheck`, whose\n * input is statically a string.\n */\nexport const stringLengthTests = {\n min(x: string, min: number, ctx: CodeGenContext): string {\n const units = `${x}.length>=${min}`;\n if (min <= 1) return units;\n const cpl = emitRuntimeHelper(ctx, \"__zcCpl\", ZC_CPL_DECL);\n return `${units}&&(${x}.length>=${certainlyAtLeast(min)}||${cpl}(${x})>=${min})`;\n },\n max(x: string, max: number, ctx: CodeGenContext): string {\n const units = `${x}.length<=${max}`;\n if (max <= 0) return units;\n const cpl = emitRuntimeHelper(ctx, \"__zcCpl\", ZC_CPL_DECL);\n return `(${units}||(${x}.length<=${2 * max}&&${cpl}(${x})<=${max}))`;\n },\n equals(x: string, length: number, ctx: CodeGenContext): string {\n if (length <= 0) return `${x}.length===${length}`;\n const cpl = emitRuntimeHelper(ctx, \"__zcCpl\", ZC_CPL_DECL);\n // A single unit is always one code point, so `length(1)` is only in doubt\n // at exactly two units.\n if (length === 1) {\n return `(${x}.length===1||(${x}.length===2&&${cpl}(${x})===1))`;\n }\n return `(${x}.length>=${length}&&${x}.length<=${2 * length}&&${cpl}(${x})===${length})`;\n },\n /**\n * The FAILING condition of `min`/`max`, with the negation pushed inward so a\n * check with no doubtful band emits the plain comparison the slow path always\n * used (`x.length<1`, not `!(x.length>=1)`).\n */\n minFails(x: string, min: number, ctx: CodeGenContext, mayNotBeString = false): string {\n const units = `${x}.length<${min}`;\n if (min <= 1) return units;\n const cpl = emitRuntimeHelper(ctx, \"__zcCpl\", ZC_CPL_DECL);\n const guard = mayNotBeString ? `typeof ${x}===\"string\"&&` : \"\";\n return `${units}||(${x}.length<${certainlyAtLeast(min)}&&${guard}${cpl}(${x})<${min})`;\n },\n maxFails(x: string, max: number, ctx: CodeGenContext, mayNotBeString = false): string {\n const units = `${x}.length>${max}`;\n if (max <= 0) return units;\n const cpl = emitRuntimeHelper(ctx, \"__zcCpl\", ZC_CPL_DECL);\n const guard = mayNotBeString ? `typeof ${x}!==\"string\"||` : \"\";\n return `${units}&&(${x}.length>${2 * max}||${guard}${cpl}(${x})>${max})`;\n },\n /**\n * The measured length zod compares in `$ZodCheckLengthEquals` — code points\n * inside the doubtful band, units outside it — for the slow path, which has\n * to know WHICH side of the bound the value fell on.\n */\n measure(x: string, length: number, ctx: CodeGenContext, mayNotBeString = false): string {\n if (length <= 0) return `${x}.length`;\n const cpl = emitRuntimeHelper(ctx, \"__zcCpl\", ZC_CPL_DECL);\n const guard = mayNotBeString ? `typeof ${x}===\"string\"&&` : \"\";\n const band =\n length === 1 ? `${x}.length===2` : `${x}.length>=${length}&&${x}.length<=${2 * length}`;\n return `(${guard}${band}?${cpl}(${x}):${x}.length)`;\n },\n};\n\n/**\n * Length/size checks re-emitted for the branch where the node's TYPE CHECK\n * ALREADY FAILED.\n *\n * zod skips a schema's checks once its parse aborted — except the ones carrying\n * a `when` predicate, which `runChecks` consults instead of the abort flag:\n *\n * ```js\n * if (ch._zod.def.when) { if (!ch._zod.def.when(payload)) continue; }\n * else if (isAborted) continue;\n * ```\n *\n * and `$ZodCheckMinLength` & co. install exactly such a predicate —\n * `!nullish(value) && value.length !== undefined` (`.size` for the size family)\n * — so they run on ANY input carrying that property, of any type. Hence\n * `z.string().min(2).safeParse([])` reports TWO issues in zod: the\n * `invalid_type`, and a `too_small` whose `origin` is `\"array\"`, because the\n * empty array satisfied the `when`. Compiled output kept every check inside the\n * matched-type branch and reported only the first. Same for\n * `z.array(…).min(3)` over a short string, `z.set(…).min(2)` over a `Map`, and\n * `z.file().min(2)` over a `Set`.\n *\n * Emitted as a SEPARATE copy in the failure branch rather than hoisted out of\n * both, so the success path — where the origin is statically known and the guard\n * is trivially true — stays byte-for-byte what it was. This is cold code: it\n * runs only for input the node has already rejected.\n *\n * `origin` is computed at runtime here (see ZC_LENGTH_ORIGIN_DECL), because the\n * value that reached this branch is by definition not the schema's own type.\n *\n * `mayBeString` is set by a non-string node whose length checks can fire on a\n * string (`z.array(…).min(2)` over `\"😀\"`): zod then measures it in code\n * points, so those tests take the guarded form of {@link stringLengthTests}. A\n * string node's own failure branch never holds a string and keeps the plain\n * unit comparison.\n */\nexport function whenGatedSizeChecks(\n checks: readonly (CheckOrEffectIR | SetCheckIR | FileCheckIR)[],\n g: SlowGen,\n family: \"length\" | \"size\",\n mayBeString = false,\n): string {\n const KINDS =\n family === \"length\"\n ? new Set([\"min_length\", \"max_length\", \"length_equals\"])\n : new Set([\"min_size\", \"max_size\", \"size_equals\"]);\n // Checked BEFORE touching the context: `emitRuntimeHelper` pushes its\n // declaration on sight, so asking for the origin helper up front left a dead\n // `__zcLo` in the preamble of every schema with a plain `z.string()` in it.\n if (!checks.some((check) => KINDS.has(check.kind))) return \"\";\n\n const property = family === \"length\" ? \"length\" : \"size\";\n const originHelper =\n family === \"length\"\n ? emitRuntimeHelper(g.ctx, \"__zcLo\", ZC_LENGTH_ORIGIN_DECL)\n : emitRuntimeHelper(g.ctx, \"__zcSo\", ZC_SIZE_ORIGIN_DECL);\n const origin = { expr: `${originHelper}(${g.input})` };\n const measure = `${g.input}.${property}`;\n\n let body = \"\";\n for (const check of checks) {\n // Kept in DECLARATION order: `runChecks` walks the check array, so two\n // failing length checks report in the order they were declared.\n switch (check.kind) {\n case \"min_length\":\n body += emit`\n if(${mayBeString ? stringLengthTests.minFails(g.input, check.minimum, g.ctx, true) : `${measure}<${check.minimum}`}){\n ${tooSmall(g, check.minimum, origin, true, { message: check.message })}\n }`;\n break;\n case \"max_length\":\n body += emit`\n if(${mayBeString ? stringLengthTests.maxFails(g.input, check.maximum, g.ctx, true) : `${measure}>${check.maximum}`}){\n ${tooBig(g, check.maximum, origin, true, { message: check.message })}\n }`;\n break;\n case \"length_equals\": {\n const length = mayBeString\n ? stringLengthTests.measure(g.input, check.length, g.ctx, true)\n : measure;\n body += emit`\n if(${length}<${check.length}){\n ${tooSmall(g, check.length, origin, true, { exact: true, message: check.message })}\n }else if(${length}>${check.length}){\n ${tooBig(g, check.length, origin, true, { exact: true, message: check.message })}\n }`;\n break;\n }\n case \"min_size\":\n body += emit`\n if(${measure}<${check.minimum}){\n ${tooSmall(g, check.minimum, origin, true, { message: check.message })}\n }`;\n break;\n case \"max_size\":\n body += emit`\n if(${measure}>${check.maximum}){\n ${tooBig(g, check.maximum, origin, true, { message: check.message })}\n }`;\n break;\n case \"size_equals\":\n body += emit`\n if(${measure}<${check.size}){\n ${tooSmall(g, check.size, origin, true, { exact: true, message: check.message })}\n }else if(${measure}>${check.size}){\n ${tooBig(g, check.size, origin, true, { exact: true, message: check.message })}\n }`;\n break;\n default:\n break;\n }\n }\n if (body === \"\") return \"\";\n // zod's own `when`, verbatim: `!util.nullish(value) && value.<prop> !== undefined`.\n return emit`\n if(${g.input}!==undefined&&${g.input}!==null&&${measure}!==undefined){\n ${body}\n }`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,SAAS,iBAAiB,KAAqB;CAC7C,OAAO,IAAI,KAAK,KAAK,GAAG,IAAI;AAC9B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,oBAAoB;CAC/B,IAAI,GAAW,KAAa,KAA6B;EACvD,MAAM,QAAQ,GAAG,EAAE,WAAW;EAC9B,IAAI,OAAO,GAAG,OAAO;EACrB,MAAM,MAAM,kBAAkB,KAAK,WAAW,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ExB,OAAO,IAAI;SACJ,EAAE,MAAM,gBAAgB,EAAE,MAAM,WAAW,QAAQ;QACpD,KAAK;;AAEb"}
@@ -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;iBA+CpC,qBAAqB,IAAI;;iBAKzB,kBAAkB,IAAI,cAAc,KAAK"}
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(${normalized});
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 // Normalize input for case-insensitive matching\n const normalized = ir.caseSensitive ? g.input : g.temp(\"sbn\");\n if (!ir.caseSensitive) code += `var ${normalized}=${g.input}.toLowerCase();`;\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 if (useInline) {\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 code += emit`\n var ${value}=${lookup}.get(${normalized});\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/** 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;;;CAK/B,MAAM,aAAa,GAAG,gBAAgB,EAAE,QAAQ,EAAE,KAAK,KAAK;CAC5D,IAAI,CAAC,GAAG,eAAe,QAAQ,OAAO,WAAW,GAAG,EAAE,MAAM;CAC5D,MAAM,YAAY,CAAC,GAAG,GAAG,QAAQ,GAAG,GAAG,KAAK;CAC5C,MAAM,aAAa,KAAK,UAAU,SAAS;CAM3C,MAAM,gBAAgB;CAKtB,IAFkB,qBAAqB,EAE3B,GAAG;EACb,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,OAAO;gBACxB,eAAe,IAAI,EAAE,OAAO;aAC/B,aAAa,GAAG,YAAY,EAAE,OAAO,cAAc,CAAC,EAAE;;CAEjE,OAAO;EACL,MAAM,QAAQ,EAAE,KAAK,KAAK;EAC1B,MAAM,SAAS,kBAAkB,IAAI,EAAE,GAAG;EAC1C,QAAQ,IAAI;YACJ,MAAM,GAAG,OAAO,OAAO,WAAW;WACnC,MAAM,gBAAgB,aAAa,GAAG,YAAY,EAAE,OAAO,cAAc,CAAC,EAAE;aAC1E,EAAE,OAAO,GAAG,MAAM;;CAE7B;CAEA,QAAQ,IAAI;CACZ,OAAO,GAAG,KAAK;AACjB;AAEA,SAAgB,qBAAqB,IAA2B;CAC9D,OAAO,GAAG,OAAO,UAAA,KAAmC,GAAG,MAAM,UAAA;AAC/D;;AAGA,SAAgB,kBAAkB,IAAkB,KAA6B;CAC/E,MAAM,QAAQ,CACZ,GAAG,GAAG,OAAO,KAAK,UAAU,CAAC,OAAO,IAAI,CAAC,GACzC,GAAG,GAAG,MAAM,KAAK,UAAU,CAAC,OAAO,KAAK,CAAC,CAC3C;CACA,OAAO,aAAa,KAAK,UAAU,WAAW,KAAK,UAAU,KAAK,EAAE,EAAE;AACxE"}
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,E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B,IAAkB,KAA6B;CAC/E,MAAM,QAAQ,CACZ,GAAG,GAAG,OAAO,KAAK,UAAU,CAAC,OAAO,IAAI,CAAC,GACzC,GAAG,GAAG,MAAM,KAAK,UAAU,CAAC,OAAO,KAAK,CAAC,CAC3C;CACA,OAAO,aAAa,KAAK,UAAU,WAAW,KAAK,UAAU,KAAK,EAAE,EAAE;AACxE"}
@@ -1 +1 @@
1
- {"version":3,"file":"string.d.ts","names":[],"sources":["../../../../src/core/codegen/schemas/string.ts"],"mappings":";;;iBAuEgB,WAAW,IAAI,UAAU,GAAG;;;;;;;;;;;iBAmJ5B,gBAAgB,OAAO,SAAS,WAAW,KAAK;iBAkDhD,WAAW,IAAI,UAAU,GAAG"}
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"}