@wildo-ai/zod-decorators 1.0.0 → 1.1.0

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 (98) hide show
  1. package/LICENSE +34 -0
  2. package/dist/esm/.builder.pid +9 -0
  3. package/dist/esm/__mocks__/mime.d.ts.map +1 -1
  4. package/dist/esm/__mocks__/mime.js +1 -1
  5. package/dist/esm/__mocks__/mime.js.map +1 -1
  6. package/dist/esm/commons.d.ts.map +1 -1
  7. package/dist/esm/commons.js +1 -1
  8. package/dist/esm/commons.js.map +1 -1
  9. package/dist/esm/companion-exports.d.ts +8 -0
  10. package/dist/esm/companion-exports.d.ts.map +1 -0
  11. package/dist/esm/companion-exports.js +8 -0
  12. package/dist/esm/companion-exports.js.map +1 -0
  13. package/dist/esm/currencies.shared.schemas.d.ts.map +1 -1
  14. package/dist/esm/currencies.shared.schemas.js +1 -1
  15. package/dist/esm/currencies.shared.schemas.js.map +1 -1
  16. package/dist/esm/files/agent-file-formats.d.ts.map +1 -1
  17. package/dist/esm/files/agent-file-formats.js +1 -1
  18. package/dist/esm/files/agent-file-formats.js.map +1 -1
  19. package/dist/esm/files/extension-nature-map.d.ts +1 -1
  20. package/dist/esm/files/extension-nature-map.d.ts.map +1 -1
  21. package/dist/esm/files/extension-nature-map.js +1 -1
  22. package/dist/esm/files/extension-nature-map.js.map +1 -1
  23. package/dist/esm/files/file-extensions.enum.d.ts.map +1 -1
  24. package/dist/esm/files/file-extensions.enum.js +1 -1
  25. package/dist/esm/files/file-extensions.enum.js.map +1 -1
  26. package/dist/esm/files/mime-registry.d.ts +1 -1
  27. package/dist/esm/files/mime-registry.d.ts.map +1 -1
  28. package/dist/esm/files/mime-registry.js +1 -1
  29. package/dist/esm/files/mime-registry.js.map +1 -1
  30. package/dist/esm/files/unified-registry.d.ts +1 -1
  31. package/dist/esm/files/unified-registry.d.ts.map +1 -1
  32. package/dist/esm/files/unified-registry.js +1 -1
  33. package/dist/esm/files/unified-registry.js.map +1 -1
  34. package/dist/esm/index.d.ts +20 -19
  35. package/dist/esm/index.d.ts.map +1 -1
  36. package/dist/esm/index.js +10 -1
  37. package/dist/esm/index.js.map +1 -1
  38. package/dist/esm/install-bigint-json-encoding.d.ts +80 -0
  39. package/dist/esm/install-bigint-json-encoding.d.ts.map +1 -0
  40. package/dist/esm/install-bigint-json-encoding.js +85 -0
  41. package/dist/esm/install-bigint-json-encoding.js.map +1 -0
  42. package/dist/esm/testing/decorated-test-schemas.d.ts +8 -8
  43. package/dist/esm/testing/decorated-test-schemas.d.ts.map +1 -1
  44. package/dist/esm/testing/decorated-test-schemas.js +1 -1
  45. package/dist/esm/testing/decorated-test-schemas.js.map +1 -1
  46. package/dist/esm/testing.d.ts +1 -1
  47. package/dist/esm/testing.d.ts.map +1 -1
  48. package/dist/esm/testing.js +1 -1
  49. package/dist/esm/testing.js.map +1 -1
  50. package/dist/esm/zod-bigdecimal.d.ts +5 -1
  51. package/dist/esm/zod-bigdecimal.d.ts.map +1 -1
  52. package/dist/esm/zod-bigdecimal.js +4 -1
  53. package/dist/esm/zod-bigdecimal.js.map +1 -1
  54. package/dist/esm/zod-code.d.ts +4 -1
  55. package/dist/esm/zod-code.d.ts.map +1 -1
  56. package/dist/esm/zod-code.js +4 -1
  57. package/dist/esm/zod-code.js.map +1 -1
  58. package/dist/esm/zod-color.d.ts.map +1 -1
  59. package/dist/esm/zod-color.js +1 -1
  60. package/dist/esm/zod-color.js.map +1 -1
  61. package/dist/esm/zod-decorators.types.d.ts +1410 -56
  62. package/dist/esm/zod-decorators.types.d.ts.map +1 -1
  63. package/dist/esm/zod-decorators.types.js +662 -16
  64. package/dist/esm/zod-decorators.types.js.map +1 -1
  65. package/dist/esm/zod-duration.d.ts +8 -4
  66. package/dist/esm/zod-duration.d.ts.map +1 -1
  67. package/dist/esm/zod-duration.js +2 -1
  68. package/dist/esm/zod-duration.js.map +1 -1
  69. package/dist/esm/zod-file.d.ts +75 -14
  70. package/dist/esm/zod-file.d.ts.map +1 -1
  71. package/dist/esm/zod-file.js +151 -8
  72. package/dist/esm/zod-file.js.map +1 -1
  73. package/dist/esm/zod-money.d.ts +18 -3
  74. package/dist/esm/zod-money.d.ts.map +1 -1
  75. package/dist/esm/zod-money.js +4 -1
  76. package/dist/esm/zod-money.js.map +1 -1
  77. package/dist/esm/zod-phone.d.ts +37 -1
  78. package/dist/esm/zod-phone.d.ts.map +1 -1
  79. package/dist/esm/zod-phone.js +66 -5
  80. package/dist/esm/zod-phone.js.map +1 -1
  81. package/dist/esm/zod-range.d.ts +4 -1
  82. package/dist/esm/zod-range.d.ts.map +1 -1
  83. package/dist/esm/zod-range.js +4 -1
  84. package/dist/esm/zod-range.js.map +1 -1
  85. package/dist/esm/zod-utils.shared.d.ts +411 -6
  86. package/dist/esm/zod-utils.shared.d.ts.map +1 -1
  87. package/dist/esm/zod-utils.shared.js +624 -9
  88. package/dist/esm/zod-utils.shared.js.map +1 -1
  89. package/dist/esm/zod-versioned.d.ts +1 -1
  90. package/dist/esm/zod-versioned.d.ts.map +1 -1
  91. package/dist/esm/zod-versioned.js +1 -1
  92. package/dist/esm/zod-versioned.js.map +1 -1
  93. package/dist/esm/zod.module-override.d.ts +458 -68
  94. package/dist/esm/zod.module-override.d.ts.map +1 -1
  95. package/dist/esm/zod.module-override.js +1214 -195
  96. package/dist/esm/zod.module-override.js.map +1 -1
  97. package/dist/tsconfig.build.tsbuildinfo +1 -1
  98. package/package.json +30 -21
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { SCHEMA_METADATA, ZodDecorator } from './zod-decorators.types.js';
2
+ import { RAGChunkingStrategy, SCHEMA_METADATA, ZodDecorator } from './zod-decorators.types.js';
3
3
  const ApplyableTypeAllTypes = ["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodDate", "ZodEnum", "ZodOptional", "ZodArray", "ZodObject"];
4
4
  const ApplyableTypeAllPrimitiveTypes = ["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodDate", "ZodEnum", "ZodOptional"];
5
5
  const ApplyableTypeAllArrayTypes = ["ZodArray"];
@@ -25,14 +25,117 @@ const ZOD_INSTANCE_METHODS_TO_WRAP = [
25
25
  const ApplyableTypeFormField = [...ApplyableTypeAllPrimitiveTypes, "ZodObject", "ZodArray"];
26
26
  export const ZodDecorator_ApplyableType = {
27
27
  [ZodDecorator.IS_DB_INDEXED]: [...ApplyableTypeAllPrimitiveTypes, "ZodObject"],
28
- [ZodDecorator.IS_FOREIGN_KEY]: ["ZodString"],
28
+ [ZodDecorator.IS_FOREIGN_KEY]: ["ZodString", "ZodOptional"],
29
29
  [ZodDecorator.IS_HIDDEN]: ApplyableTypeFormField,
30
30
  [ZodDecorator.IS_NOT_EDITABLE]: ApplyableTypeFormField,
31
31
  // New decorators - apply to all types since they are schema-level metadata
32
32
  [ZodDecorator.IS_SUMMARY_FIELD]: ApplyableTypeAllTypes,
33
33
  [ZodDecorator.IS_BACKEND_ONLY]: ApplyableTypeAllTypes,
34
+ [ZodDecorator.IS_WRITE_ONLY_SECRET]: ApplyableTypeAllTypes,
35
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET's all-types surface: any field
36
+ // type can hold personal data (a nested `address` object and a `phoneNumbers` array as much as a
37
+ // `fullName` string). Whether a given TREATMENT VALUE fits the field's type (e.g. MASK on a number)
38
+ // is a separate axis, enforced by the resource factory's retention guard, not by this map.
39
+ //
40
+ // ⚠️ This list and the `ZodDecorator_FunctionType.impersonalizeWith` entry + the ZodType prototype
41
+ // installs + the `declare module 'zod'` augmentations are ONE unit — wiring only some of them
42
+ // recreates the P0.3a half-live trap: a non-empty list here alone makes `addChainableMethods`
43
+ // auto-install a generic INSTANCE method on the RESULT of a first decorator, so
44
+ // `z.string().isDBIndexed().impersonalizeWith(t)` works while `z.string().impersonalizeWith(t)`
45
+ // throws (order-dependent `TypeError`). `impersonalize-treatment.test.ts` pins BOTH orders.
46
+ //
47
+ // WHAT THIS LIST DOES AND DOES NOT DETERMINE. It governs the INSTANCE install `addChainableMethods`
48
+ // performs on an already-decorated schema. Whether a BARE schema exposes the method is decided by
49
+ // the PROTOTYPE installs in `ensureZodDecoratorsLoaded`, which are a different set — so list
50
+ // membership is neither necessary nor sufficient:
51
+ // • reachable but NOT listed: ZodRecord / ZodMap / ZodUnion / ZodNullable / ZodDefault
52
+ // (prototype-installed alongside IS_WRITE_ONLY_SECRET, or via the wrapper loop)
53
+ // • reachable but NOT listed, and the case most likely to mislead: EVERY string-format
54
+ // constructor — ZodEmail, ZodUUID, ZodCustomStringFormat, ZodISODateTime, … A format schema's
55
+ // `constructor.name` is `ZodUUID`, which appears in NO list here, so `addChainableMethods`
56
+ // installs nothing on it; it is fully decorated anyway because Zod's `$constructor` copies
57
+ // `ZodStringFormat.prototype`'s keys onto the instance at init. Do NOT treat this map as the
58
+ // authority on what a format type supports — it does not mention them, and never has.
59
+ // • listed but NOT reachable: ZodBigInt — no decorator is prototype-installed on it anywhere, so
60
+ // no decorator (this one included) can start a chain on a bare `z.bigint()`. Its format
61
+ // siblings `z.int64()` / `z.uint64()` inherit that same emptiness (`ZodBigIntFormat.init`
62
+ // calls `ZodBigInt.init`), so they are consistent with it rather than a separate gap.
63
+ //
64
+ // THE LISTED-BUT-UNREACHABLE SET: 65 entries on 2026-08-12, 18 now, and the remainder is a single
65
+ // group kept absent for a SEMANTIC reason. "No app needs it yet" was explicitly rejected as a
66
+ // reason — this is a framework, so a capability the vocabulary claims must exist before the case
67
+ // arrives. Each entry was therefore resolved one of two ways, never left in disagreement:
68
+ //
69
+ // WIRED (the map's claim was right; the surface was missing)
70
+ // • ZodBigInt × 16 — see its prototype block; every other layer already treats bigint as a leaf.
71
+ // • ZodObject `isDBIndexed`/`isHidden`/`isNotEditable` — a composite field is indexable,
72
+ // hideable and non-editable. The TS2320 clash with `z_file()`'s mixin was the only obstacle
73
+ // and it cost nothing to remove, because `DecoratedPrimitiveZodType<T>` is `T & {…}`.
74
+ // • `isBusinessKey` on ZodBoolean/ZodDate — the map says it mirrors IS_DB_INDEXED's primitive
75
+ // set, and that IS on both. A date is a legitimate natural-key component.
76
+ // • ZodOptional `ttl`/`isPassword`/`isOtp`/`isColor`/`businessKeySet` — natural authoring
77
+ // orders. `businessKeySet` additionally learned to unwrap so its field-name validation still
78
+ // runs through the wrapper instead of silently passing.
79
+ // • `showWhen`/`isDraftRelaxed` across every form-field type — see the string surface constant.
80
+ //
81
+ // MAP TIGHTENED (the surface was right; the map claimed support that cannot exist)
82
+ // • IS_DISCRIMINATOR lost ZodBigInt/ZodBoolean/ZodDate — `baseValues` is `string[]`.
83
+ // • OBJECT_BUSINESS_KEY_SET lost ZodRecord/ZodMap — no named fields to validate against.
84
+ //
85
+ // CORRECTLY ABSENT — the 18 that remain, all factory-owned `*UI` / `*Spec`:
86
+ // `moneyUI`/`codeUI`/`fileUI`/`durationUI` on ZodObject, `phoneUI`/`bigDecimalUI`/
87
+ // `foreignKeyUI`/`timeUI` on ZodString, `dateTimeUI` on ZodDate, plus their `*Spec` twins.
88
+ // These belong to `z_money()`, `z_code()`, `z_file()`, `z_duration()`, `z_phone()`,
89
+ // `z_bigdecimal()`, which return an already-decorated schema. A bare `z.object({})` is NOT
90
+ // money, and a bare `z.string()` is not a phone number — installing these would let an author
91
+ // attach a renderer to a value whose shape it cannot read. The entry here is only the coarse
92
+ // gate that lets `addChainableMethods` re-install the method on the factory's own result; the
93
+ // map keys on constructor name and cannot tell `z_money()`'s object from any other.
94
+ // Fluently reachable today: String, Number, Boolean, Date, Enum, Array, Object, Record, Map, Union,
95
+ // Optional, Nullable, Default (+ the string-refinement and format-validator prototypes).
96
+ // NOT reachable: BigInt, Pipe (what `z_phone()` returns), Literal, Tuple, Set, Null, Any,
97
+ // Intersection, Lazy, Readonly, Catch — every one of these carries NO decorators at all, a
98
+ // pre-existing decorator-WIDE gap that is mirrored here rather than special-cased for one decorator.
99
+ // For those, `addImpersonalizeWith(schema, treatment)` needs no prototype method and the treatment
100
+ // reads back normally (pinned for `z_phone` in `impersonalize-treatment.test.ts`).
101
+ [ZodDecorator.IMPERSONALIZE_WITH]: ApplyableTypeAllTypes,
102
+ // Portability provenance — all-types for the same reason as IMPERSONALIZE_WITH above: any field
103
+ // type can be data the subject provided (a nested `address` object and a `phoneNumbers` array as
104
+ // much as a `fullName` string). The list/FunctionType/prototype-install/`declare module`
105
+ // augmentations are ONE unit here too — wiring only some recreates the order-dependent
106
+ // half-live trap documented above.
107
+ [ZodDecorator.PORTABILITY_PROVENANCE]: ApplyableTypeAllTypes,
108
+ // Data categories — all-types for the same reason as the two above: any field type can hold
109
+ // personal data (a nested `address` OBJECT and a `phoneNumbers` ARRAY as much as a `fullName`
110
+ // string). The list/FunctionType/prototype-install/`declare module` augmentations are ONE unit
111
+ // here too — wiring only some recreates the order-dependent half-live trap documented on
112
+ // IMPERSONALIZE_WITH above.
113
+ [ZodDecorator.DATA_CATEGORIES]: ApplyableTypeAllTypes,
114
+ // Audit evidence — all-types for the same reason as the two above: authority and lifecycle state
115
+ // are held in every field shape (`appRoles` is an ARRAY, `status` an ENUM, `suspendedUntil` a
116
+ // DATE, a scope binding an OBJECT). The list/FunctionType/prototype-install/`declare module`
117
+ // augmentations are ONE unit here too — wiring only some recreates the order-dependent half-live
118
+ // trap documented on IMPERSONALIZE_WITH above.
119
+ [ZodDecorator.IS_AUDIT_EVIDENCE]: ApplyableTypeAllTypes,
120
+ // RAG source — deliberately NOT all-types: only TEXT can be a retrieval-corpus source, so the
121
+ // fluent surface is string-backed (plus the wrappers a string field routinely lives under; the
122
+ // string-FORMAT types get the method from the `ZodStringFormat.prototype` install, which — per the
123
+ // long IMPERSONALIZE_WITH note above — never appears in this map). The FILE case does not go
124
+ // through this map at all: `z_file({ ragSource })` registers the decorator on its own result via
125
+ // `addDecorators`, which performs no applicability gating, so a file object carries the metadata
126
+ // without `.ragSource()` ever being installed on ZodObject. The list/FunctionType/prototype-install/
127
+ // `declare module` augmentations are ONE unit here too — wiring only some recreates the
128
+ // order-dependent half-live trap documented on IMPERSONALIZE_WITH above.
129
+ [ZodDecorator.RAG_SOURCE]: ['ZodString', 'ZodOptional', 'ZodNullable', 'ZodDefault'],
34
130
  [ZodDecorator.IS_VIRTUAL]: ApplyableTypeAllTypes,
35
- [ZodDecorator.IS_DISCRIMINATOR]: ApplyableTypeAllPrimitiveTypes, // Only primitives can be discriminators
131
+ // Discriminators are STRING/ENUM-valued, not merely "primitive". `DiscriminatorFieldParams.baseValues`
132
+ // is `string[]` and is documented as auto-detected from ENUM VALUES not covered by variants, so a
133
+ // variant set is a finite list of string-comparable labels. A `ZodDate` cannot supply one, and
134
+ // `ZodBoolean` / `ZodBigInt` cannot express theirs through a `string[]` without a coercion the
135
+ // polymorphism engine never performs. Narrowed 2026-08-12 from `ApplyableTypeAllPrimitiveTypes`,
136
+ // which claimed a support the params model cannot honour — the three removed types were half-live
137
+ // (reachable only after another decorator) and had no prototype install, so nothing regresses.
138
+ [ZodDecorator.IS_DISCRIMINATOR]: ['ZodString', 'ZodNumber', 'ZodEnum', 'ZodOptional'],
36
139
  [ZodDecorator.EXCLUDE_FROM_CREATE]: ApplyableTypeAllTypes,
37
140
  [ZodDecorator.EXCLUDE_FROM_UPDATE]: ApplyableTypeAllTypes,
38
141
  // Database constraint decorators - only strings and numbers can be unique (identifiers, codes, etc.)
@@ -40,6 +143,20 @@ export const ZodDecorator_ApplyableType = {
40
143
  [ZodDecorator.IS_UNIQUE]: ['ZodString', 'ZodNumber', 'ZodOptional'],
41
144
  // Primary key is only for strings (MongoDB _id is always a string or ObjectId)
42
145
  [ZodDecorator.IS_PRIMARY_KEY]: ['ZodString'],
146
+ // Business key marker — applies to any primitive that can carry a stable identity
147
+ // (string keys, numeric discriminators, enum keys). Mirrors `IS_DB_INDEXED`'s primitive
148
+ // base set since business keys are also recursively indexed at the DB layer in Phase 2.
149
+ [ZodDecorator.IS_BUSINESS_KEY]: ApplyableTypeAllPrimitiveTypes,
150
+ // Composite business key — object-level only (analog of OBJECT_UI's applicable types)
151
+ // Composite business key — object-level. NOT `ApplyableTypeAllObjectTypes`: the decorator's whole
152
+ // safety property is validating the named fields against the schema's `shape` at decoration time,
153
+ // and a `ZodRecord` / `ZodMap` has no named fields, so the check would silently pass anything.
154
+ // Claiming support there is worse than omitting it — the author would get a key referencing fields
155
+ // that cannot exist, with no error. `ZodOptional` stays and IS supported: the wrapper's shape is
156
+ // reached by unwrapping (see the `businessKeySet` implementation).
157
+ // Every wrapper that can hold an object and whose inner shape `findObjectShape` can reach —
158
+ // Optional, Nullable and Default all already carry the method at runtime via the wrapper loop.
159
+ [ZodDecorator.OBJECT_BUSINESS_KEY_SET]: ['ZodObject', 'ZodOptional', 'ZodNullable', 'ZodDefault'],
43
160
  // TTL (Time To Live) - only for Date fields (MongoDB TTL indexes work on Date fields)
44
161
  [ZodDecorator.TTL]: ['ZodDate', 'ZodOptional'],
45
162
  // String edit mode convenience decorators - only for strings
@@ -72,25 +189,119 @@ export const ZodDecorator_ApplyableType = {
72
189
  [ZodDecorator.FOREIGN_KEY_UI]: ['ZodString', 'ZodOptional'],
73
190
  [ZodDecorator.ARRAY_UI]: ['ZodArray', 'ZodOptional'],
74
191
  [ZodDecorator.OBJECT_UI]: [...ApplyableTypeAllObjectTypes, 'ZodOptional'],
192
+ // Per-primitive field specification decorators — same type constraints as UI counterparts
193
+ [ZodDecorator.STRING_SPEC]: ['ZodString', 'ZodOptional'],
194
+ [ZodDecorator.NUMBER_SPEC]: ['ZodNumber', 'ZodOptional'],
195
+ [ZodDecorator.BOOLEAN_SPEC]: ['ZodBoolean', 'ZodOptional'],
196
+ [ZodDecorator.DATE_SPEC]: ['ZodDate', 'ZodOptional'],
197
+ [ZodDecorator.DATETIME_SPEC]: ['ZodDate', 'ZodOptional'],
198
+ [ZodDecorator.TIME_SPEC]: ['ZodString', 'ZodOptional'],
199
+ [ZodDecorator.ENUM_SPEC]: ['ZodEnum', 'ZodOptional'],
200
+ [ZodDecorator.MONEY_SPEC]: ['ZodObject', 'ZodOptional'],
201
+ [ZodDecorator.CODE_SPEC]: ['ZodObject', 'ZodOptional'],
202
+ [ZodDecorator.FILE_SPEC]: ['ZodObject', 'ZodOptional'],
203
+ [ZodDecorator.DURATION_SPEC]: ['ZodObject', 'ZodOptional'],
204
+ [ZodDecorator.PHONE_SPEC]: ['ZodString', 'ZodOptional'],
205
+ [ZodDecorator.BIGDECIMAL_SPEC]: ['ZodString', 'ZodOptional'],
206
+ [ZodDecorator.FOREIGN_KEY_SPEC]: ['ZodString', 'ZodOptional'],
207
+ [ZodDecorator.ARRAY_SPEC]: ['ZodArray', 'ZodOptional'],
208
+ [ZodDecorator.OBJECT_SPEC]: [...ApplyableTypeAllObjectTypes, 'ZodOptional'],
75
209
  };
210
+ /**
211
+ * THE decorator surface of a string-backed schema — the single runtime source of truth.
212
+ *
213
+ * A string-format refinement (`z.uuid()`, `z.email()`, `z.hostname()`, `z.iso.datetime()`, …) is a
214
+ * string-backed primitive, so it carries EXACTLY the surface `z.string()` carries. That is not a
215
+ * convenience: it is what the type layer already promises. `declare module 'zod'` below merges the
216
+ * same member list into `ZodString` AND `ZodStringFormat<Format>`, and every refinement type Zod
217
+ * publishes is declared `extends ZodStringFormat<…>` — so `z.uuid().isPrimaryKey()` type-checks.
218
+ * Anything this list omits is a method TypeScript says exists and the prototype does not have.
219
+ *
220
+ * WHY A LIST AND NOT THREE HAND-WRITTEN BLOCKS. Until 2026-08-12 the surface was re-typed by hand at
221
+ * three install sites (the `ZodString` prototype, a named-constructor loop, a format-validator probe)
222
+ * and they had drifted: five decorators — `isPrimaryKey`, `isBusinessKey`, `isPassword`, `isOtp`,
223
+ * `isColor` — reached only `ZodString`, so `z.uuid().isPrimaryKey()` compiled and threw
224
+ * `TypeError: ... is not a function`. Three copies of one list is three chances to forget; one list
225
+ * consumed by one installer makes the divergence unrepresentable rather than merely tested-for.
226
+ * See `.claude/rules/invariant-call-site-enumeration.md` — "prefer making the invariant unbypassable
227
+ * over applying it N times".
228
+ *
229
+ * There are now exactly TWO install sites, `ZodString.prototype` and `ZodStringFormat.prototype`,
230
+ * mirroring the two interfaces one-for-one — see the STEP 3 block in `ensureZodDecoratorsLoaded`
231
+ * for why those two bases are complete and why the per-format lists that used to live there were
232
+ * never the mechanism.
233
+ *
234
+ * KEEP IN SYNC WITH: the `ZodString` and `ZodStringFormat` interfaces in the `declare module 'zod'`
235
+ * block below. `string-format-decorator-parity.contract.test.ts` fails — at type-check time AND at
236
+ * runtime — the moment any of the three disagree.
237
+ */
238
+ const STRING_SCHEMA_DECORATOR_SURFACE = [
239
+ ZodDecorator.IS_DB_INDEXED,
240
+ ZodDecorator.IS_FOREIGN_KEY,
241
+ ZodDecorator.IS_HIDDEN,
242
+ ZodDecorator.IS_NOT_EDITABLE,
243
+ ZodDecorator.IS_SUMMARY_FIELD,
244
+ ZodDecorator.IS_BACKEND_ONLY,
245
+ ZodDecorator.IS_WRITE_ONLY_SECRET,
246
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
247
+ ZodDecorator.IMPERSONALIZE_WITH,
248
+ // Portability provenance — a format validator (`z.email()`, `z.uuid()`) is the shape personal data
249
+ // most often takes, so omitting it here would leave the decorator half-live on exactly those fields.
250
+ ZodDecorator.PORTABILITY_PROVENANCE,
251
+ // Data categories — same argument as PORTABILITY_PROVENANCE directly above: `z.email()` and
252
+ // `z.uuid()` are the shapes personal data most often takes, so omitting the format prototype
253
+ // would leave the decorator half-live on exactly the fields a notice most needs to enumerate.
254
+ ZodDecorator.DATA_CATEGORIES,
255
+ ZodDecorator.IS_AUDIT_EVIDENCE,
256
+ // RAG source — string-backed by nature (only text can be a corpus source), and a format validator
257
+ // is a legitimate carrier: markdown/documentation fields are routinely `z.string()`, but a
258
+ // `z.url()` pointing at authored content is not excluded from being chunked as text.
259
+ ZodDecorator.RAG_SOURCE,
260
+ ZodDecorator.IS_VIRTUAL,
261
+ ZodDecorator.IS_DISCRIMINATOR,
262
+ ZodDecorator.EXCLUDE_FROM_CREATE,
263
+ ZodDecorator.EXCLUDE_FROM_UPDATE,
264
+ // Database constraint decorators — format validators like email/uuid are commonly used as
265
+ // unique identifiers, and `z.uuid().isPrimaryKey()` is the canonical surrogate-key shape.
266
+ ZodDecorator.IS_UNIQUE,
267
+ ZodDecorator.IS_PRIMARY_KEY,
268
+ // Business key marker (data-seeding subsystem) — `z.email().isBusinessKey()` is the canonical
269
+ // natural-key shape, so a format validator is if anything a MORE likely carrier than a bare string.
270
+ ZodDecorator.IS_BUSINESS_KEY,
271
+ // String edit-mode convenience decorators. These belong on refinement types for a mechanical
272
+ // reason, not a stylistic one: each is exactly `stringUI({ edit: { editMode: X } })` plus a marker,
273
+ // and `STRING_UI` itself is already on this surface. Excluding them would mean
274
+ // `z.hex().stringUI({ edit: { editMode: 'color' } })` works while `z.hex().isColor()` throws —
275
+ // the sugar unavailable precisely where the thing it desugars to is available.
276
+ ZodDecorator.IS_PASSWORD,
277
+ ZodDecorator.IS_OTP,
278
+ ZodDecorator.IS_COLOR,
279
+ ZodDecorator.IS_EPHEMERAL,
280
+ ZodDecorator.IS_CRDT,
281
+ // Generic FORM-FIELD decorators. `ZodDecorator_ApplyableType` gives both of these
282
+ // `ApplyableTypeFormField` — every primitive plus object and array — but until 2026-08-12 they
283
+ // were installed on NO primitive prototype, only on the wrapper types, so the natural authoring
284
+ // form `z.string().showWhen({...})` (the shape this decorator's own `ShowWhenParams` JSDoc has
285
+ // always documented) threw while `z.string().isHidden().showWhen({...})` worked. Unlike the
286
+ // `*UI`/`*Spec` pairs below, these two belong to no factory: they are field-level concerns any
287
+ // form field can carry, which is why they are on the shared surface rather than gated.
288
+ ZodDecorator.SHOW_WHEN,
289
+ ZodDecorator.IS_DRAFT_RELAXED,
290
+ // Format validators like uuid/email/url are still string-backed primitives, so platform presets
291
+ // must be able to apply string display/edit policies and author string field specifications.
292
+ ZodDecorator.STRING_UI,
293
+ ZodDecorator.STRING_SPEC,
294
+ ];
76
295
  export const ZodDecorator_FunctionType = {
296
+ /** @wildo_source:part:start zod.decorators.shared-structural-methods facet:layer:shared facet:family:decorator facet:family:method-surface */
77
297
  isDBIndexed: function () { return addDecorators(this, [ZodDecorator.IS_DB_INDEXED]); },
78
298
  isForeignKey: function (params) { return params ? addDecorators(this, [{ ref: ZodDecorator.IS_FOREIGN_KEY, params }]) : addDecorators(this, [ZodDecorator.IS_FOREIGN_KEY]); },
79
- isHidden: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_HIDDEN, params }]); },
80
- isNotEditable: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_NOT_EDITABLE, params }]); },
81
- isSortable: function (params) { return addDecorators(this, [{ ref: ZodDecorator.ARRAY_UI, params: { edit: { isSortable: true, ...params } } }]); },
82
- // String edit mode convenience composites — structural marker + STRING_UI side effect
83
- [ZodDecorator.IS_PASSWORD]: function () { return addDecorators(this, [{ ref: ZodDecorator.IS_PASSWORD, params: undefined }, { ref: ZodDecorator.STRING_UI, params: { edit: { editMode: 'password' } } }]); },
84
- [ZodDecorator.IS_OTP]: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_OTP, params }, { ref: ZodDecorator.STRING_UI, params: { edit: { editMode: 'otp' } } }]); },
85
- [ZodDecorator.IS_COLOR]: function () { return addDecorators(this, [{ ref: ZodDecorator.IS_COLOR, params: undefined }, { ref: ZodDecorator.STRING_UI, params: { edit: { editMode: 'color' } } }]); },
86
- // New decorators for resource derived objects rationalization
87
299
  isSummaryField: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_SUMMARY_FIELD, params }]); },
88
300
  isBackendOnly: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_BACKEND_ONLY, params }]); },
89
- isVirtual: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_VIRTUAL, params }]); },
301
+ isWriteOnlySecret: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_WRITE_ONLY_SECRET, params }]); },
90
302
  isDiscriminator: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_DISCRIMINATOR, params }]); },
91
303
  excludeFromCreate: function () { return addDecorators(this, [ZodDecorator.EXCLUDE_FROM_CREATE]); },
92
304
  excludeFromUpdate: function () { return addDecorators(this, [ZodDecorator.EXCLUDE_FROM_UPDATE]); },
93
- // Database constraint decorators
94
305
  isUnique: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_UNIQUE, params }]); },
95
306
  // isPrimaryKey is a composite decorator: implies excludeFromCreate + isHidden + isUnique(sparse:false) + isDBIndexed
96
307
  isPrimaryKey: function () {
@@ -102,15 +313,114 @@ export const ZodDecorator_FunctionType = {
102
313
  { ref: ZodDecorator.IS_UNIQUE, params: { scope: 'global', sparse: false } },
103
314
  ]);
104
315
  },
316
+ // isBusinessKey is a PURE marker — unlike isPrimaryKey, it does NOT imply
317
+ // excludeFromCreate / isHidden / isUnique. Business keys are user-editable
318
+ // (renames are handled by per-seed `renames: [{ from, to }]` migrators in
319
+ // Phase 4 of the data-seeding subsystem). Indexing is a Phase 2 derivation
320
+ // performed by the seed dispatcher when it materialises composite indexes.
321
+ isBusinessKey: function () {
322
+ return addDecorators(this, [ZodDecorator.IS_BUSINESS_KEY]);
323
+ },
324
+ // businessKeySet is the OBJECT-LEVEL composite analog of isBusinessKey.
325
+ // Validates at decoration time that every named field exists on the
326
+ // underlying ZodObject shape and that the array is non-empty. Mixing
327
+ // field-level isBusinessKey() with object-level businessKeySet([...]) on
328
+ // the same schema is rejected by the seed authoring layer (Phase 1.3) —
329
+ // we keep the decorator itself permissive so that tests can verify the
330
+ // higher-level validator rejects the mix.
331
+ businessKeySet: function (fields, params) {
332
+ if (!Array.isArray(fields) || fields.length === 0) {
333
+ throw new Error(`businessKeySet([...]) requires a non-empty array of field names (received ${JSON.stringify(fields)}).`);
334
+ }
335
+ // Reach the OBJECT shape, unwrapping wrappers on the way. `z.object({…}).optional()` is a
336
+ // legitimate authoring order and its shape lives on the inner type; without this the guard below
337
+ // would find no shape and silently accept field names that do not exist — the decorator would
338
+ // report success while validating nothing.
339
+ const findObjectShape = (candidate, depth = 0) => {
340
+ if (!candidate || depth > 5)
341
+ return undefined;
342
+ const node = candidate;
343
+ const own = node.shape ?? node._zod?.def?.shape;
344
+ if (own && typeof own === 'object')
345
+ return own;
346
+ return findObjectShape(node._zod?.def?.innerType, depth + 1);
347
+ };
348
+ const shape = findObjectShape(this);
349
+ if (shape && typeof shape === 'object') {
350
+ const missing = fields.filter((f) => !(f in shape));
351
+ if (missing.length > 0) {
352
+ throw new Error(`businessKeySet([...]) references field(s) not present in the schema shape: ${missing.join(', ')}.`);
353
+ }
354
+ }
355
+ // `skipRowsMissing` narrows the key it belongs to, so naming a field OUTSIDE the key is not a
356
+ // harmless extra — it would silently scope the constraint by a field the identity never
357
+ // mentions. Rejected at decoration time, where the author can still see both lists.
358
+ const skipRowsMissing = params?.skipRowsMissing;
359
+ if (skipRowsMissing !== undefined) {
360
+ if (!Array.isArray(skipRowsMissing) || skipRowsMissing.length === 0) {
361
+ throw new Error(`businessKeySet([...], { skipRowsMissing }) requires a non-empty array of field names (received ${JSON.stringify(skipRowsMissing)}).`);
362
+ }
363
+ const notInKey = skipRowsMissing.filter((f) => !fields.includes(f));
364
+ if (notInKey.length > 0) {
365
+ throw new Error(`businessKeySet([...], { skipRowsMissing }) names field(s) that are not part of the key: ${notInKey.join(', ')}.`);
366
+ }
367
+ }
368
+ return addDecorators(this, [
369
+ {
370
+ ref: ZodDecorator.OBJECT_BUSINESS_KEY_SET,
371
+ params: {
372
+ fields: [...fields],
373
+ ...(skipRowsMissing ? { skipRowsMissing: [...skipRowsMissing] } : {}),
374
+ ...(params?.conflictMessageReference ? { conflictMessageReference: params.conflictMessageReference } : {}),
375
+ },
376
+ },
377
+ ]);
378
+ },
105
379
  // TTL (Time To Live) - for automatic document expiration in MongoDB
106
380
  ttl: function (params) { return addDecorators(this, [{ ref: ZodDecorator.TTL, params }]); },
381
+ /** @wildo_source:part:end zod.decorators.shared-structural-methods */
382
+ // Impersonalization scrub treatment (retention capability). Deliberately declared OUTSIDE the
383
+ // `shared-structural-methods` anchor: the compiled framework-knowledge surface for this decorator
384
+ // is scheduled with its teaching skill in Phase 3 of the retention plan (a capability whose runtime
385
+ // is still being built cannot be taught honestly). Move it inside the anchor when Phase 3 lands.
386
+ //
387
+ // The treatment is REQUIRED (no marker/undefined form) — a field either declares how it is scrubbed
388
+ // or carries no treatment at all. `applySingleDecorator` fails loud on a non-string/blank value, so
389
+ // this method and the `addImpersonalizeWith` helper share one validation chokepoint — which is also
390
+ // where the optional `{ maskValue }` override is normalized and validated.
391
+ impersonalizeWith: function (treatment, options) { return addDecorators(this, [{ ref: ZodDecorator.IMPERSONALIZE_WITH, params: options ? { ...options, treatment } : treatment }]); },
392
+ // Portability provenance — REQUIRED value, validated at the shared `applySingleDecorator`
393
+ // chokepoint so this method and `addPortabilityProvenance` reject the same inputs.
394
+ portabilityProvenance: function (provenance) { return addDecorators(this, [{ ref: ZodDecorator.PORTABILITY_PROVENANCE, params: provenance }]); },
395
+ dataCategories: function (categories) { return addDecorators(this, [{ ref: ZodDecorator.DATA_CATEGORIES, params: categories }]); },
396
+ // Audit evidence — a PURE parameterless marker (the isBusinessKey shape, not the isPrimaryKey
397
+ // shape): it implies no other decorator. Marking a field says only that its before/after values
398
+ // belong on the resource-operation audit event.
399
+ isAuditEvidence: function () { return addDecorators(this, [ZodDecorator.IS_AUDIT_EVIDENCE]); },
400
+ // RAG source (resource-native RAG capability). The config is OPTIONAL — a bare `.ragSource()` is a
401
+ // complete declaration — so unlike impersonalizeWith there is no required-value door to guard;
402
+ // what the shared `applySingleDecorator` chokepoint enforces instead is config validity
403
+ // (chunkSize/chunkOverlap/strategy) and the refused companions (secrets, `.ttl()`), identically
404
+ // for this method and the `addRagSource` helper.
405
+ ragSource: function (config) { return addDecorators(this, [{ ref: ZodDecorator.RAG_SOURCE, params: config }]); },
406
+ isHidden: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_HIDDEN, params }]); },
407
+ isNotEditable: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_NOT_EDITABLE, params }]); },
408
+ isSortable: function (params) { return addDecorators(this, [{ ref: ZodDecorator.ARRAY_UI, params: { edit: { isSortable: true, ...params } } }]); },
409
+ // String edit mode convenience composites — structural marker + STRING_UI side effect
410
+ [ZodDecorator.IS_PASSWORD]: function () { return addDecorators(this, [{ ref: ZodDecorator.IS_PASSWORD, params: undefined }, { ref: ZodDecorator.STRING_UI, params: { edit: { editMode: 'password' } } }]); },
411
+ [ZodDecorator.IS_OTP]: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_OTP, params }, { ref: ZodDecorator.STRING_UI, params: { edit: { editMode: 'otp' } } }]); },
412
+ [ZodDecorator.IS_COLOR]: function () { return addDecorators(this, [{ ref: ZodDecorator.IS_COLOR, params: undefined }, { ref: ZodDecorator.STRING_UI, params: { edit: { editMode: 'color' } } }]); },
413
+ // New decorators for resource derived objects rationalization
414
+ isVirtual: function (params) { return addDecorators(this, [{ ref: ZodDecorator.IS_VIRTUAL, params }]); },
107
415
  isDraftRelaxed: function () { return addDecorators(this, [ZodDecorator.IS_DRAFT_RELAXED]); },
108
416
  // FIX-P5-H1: Conditional visibility decorator
109
417
  showWhen: function (params) { return addDecorators(this, [{ ref: ZodDecorator.SHOW_WHEN, params }]); },
110
418
  // System enum decorator - marks an enum field as using a system-level enum for i18n labelling
111
419
  systemEnum: function (name) { return addDecorators(this, [{ ref: ZodDecorator.SYSTEM_ENUM, params: name }]); },
112
- // Ephemeral field decorator — composite: marks response-only transient data + sets secret display mode + prevents editing
113
- isEphemeral: function () { return addDecorators(this, [{ ref: ZodDecorator.IS_EPHEMERAL, params: undefined }, { ref: ZodDecorator.STRING_UI, params: { display: { displayMode: 'secret' } } }, { ref: ZodDecorator.IS_NOT_EDITABLE, params: undefined }]); },
420
+ // Ephemeral field decorator — composite: marks response-only transient data + sets secret display mode + prevents editing.
421
+ // `initiallyRevealed: true` because an ephemeral value is shown exactly once (one-time reveal) — the caller must read/copy it immediately; the eye toggle still lets them re-hide it.
422
+ // Server-minted, output-only. For a CLIENT-provided secret the server must keep but never echo back, use `.isWriteOnlySecret()` instead (client-writable + masked on read). See WriteOnlySecretFieldParams for the full decision.
423
+ isEphemeral: function () { return addDecorators(this, [{ ref: ZodDecorator.IS_EPHEMERAL, params: undefined }, { ref: ZodDecorator.STRING_UI, params: { display: { displayMode: 'secret', initiallyRevealed: true } } }, { ref: ZodDecorator.IS_NOT_EDITABLE, params: undefined }]); },
114
424
  // CRDT field decorator — boolean marker for future field-level LWW merge
115
425
  isCRDT: function () { return addDecorators(this, [ZodDecorator.IS_CRDT]); },
116
426
  // Unified {primitive}UI decorators — new API
@@ -128,8 +438,25 @@ export const ZodDecorator_FunctionType = {
128
438
  phoneUI: function (params) { return addDecorators(this, [{ ref: ZodDecorator.PHONE_UI, params }]); },
129
439
  bigDecimalUI: function (params) { return addDecorators(this, [{ ref: ZodDecorator.BIGDECIMAL_UI, params }]); },
130
440
  foreignKeyUI: function (params) { return addDecorators(this, [{ ref: ZodDecorator.FOREIGN_KEY_UI, params }]); },
441
+ // Per-primitive field specification decorators (business semantics — companion-only)
442
+ stringSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.STRING_SPEC, params }]); },
443
+ numberSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.NUMBER_SPEC, params }]); },
444
+ booleanSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.BOOLEAN_SPEC, params }]); },
445
+ dateSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.DATE_SPEC, params }]); },
446
+ dateTimeSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.DATETIME_SPEC, params }]); },
447
+ timeSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.TIME_SPEC, params }]); },
448
+ enumSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.ENUM_SPEC, params }]); },
449
+ moneySpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.MONEY_SPEC, params }]); },
450
+ codeSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.CODE_SPEC, params }]); },
451
+ fileSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.FILE_SPEC, params }]); },
452
+ durationSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.DURATION_SPEC, params }]); },
453
+ phoneSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.PHONE_SPEC, params }]); },
454
+ bigDecimalSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.BIGDECIMAL_SPEC, params }]); },
455
+ foreignKeySpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.FOREIGN_KEY_SPEC, params }]); },
131
456
  arrayUI: function (params) { return addDecorators(this, [{ ref: ZodDecorator.ARRAY_UI, params }]); },
457
+ arraySpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.ARRAY_SPEC, params }]); },
132
458
  objectUI: function (params) { return addDecorators(this, [{ ref: ZodDecorator.OBJECT_UI, params }]); },
459
+ objectSpec: function (params) { return addDecorators(this, [{ ref: ZodDecorator.OBJECT_SPEC, params }]); },
133
460
  };
134
461
  // =============================================================================
135
462
  // MAIN ADD UTILITIES
@@ -209,11 +536,34 @@ function deepCloneValue(value, seen) {
209
536
  * **Use case:** reusable leaf schemas (enums, strings, numbers) with shared visual
210
537
  * config but independent field-level decorators per resource.
211
538
  *
212
- * **Scope limitations:** designed for leaf schemas, NOT for compound types:
213
- * - **`z.object()`:** field schemas inside the shape remain shared references —
214
- * mutating a field's decorators on the clone affects the original.
215
- * - **Wrapper types** (`.optional()`, `.nullable()`, `.array()`, `.pipe()`):
216
- * the inner schema remains shared. Clone the unwrapped schema first, then wrap.
539
+ * **Not required to avoid wrapper leakage.** Decorating a wrapper of a shared leaf
540
+ * (`SharedLeaf.optional().isDBIndexed()`) is safe on its own: the decorator runtime
541
+ * copy-on-writes the wrapper's inner schema before mirroring metadata onto it, so
542
+ * the shared leaf is never written to. Reach for `z_clone` when you want a leaf with
543
+ * DIFFERENT baseline decorators, not as leak protection.
544
+ *
545
+ * **Implementation note:** clones through Zod's own `.clone(def)` with a spread
546
+ * definition. A structural copy (`Object.assign({}, schema)`) cannot work here —
547
+ * `_zod` is a non-enumerable own property, so the copy would omit Zod's internals
548
+ * entirely and every method on it would still act on the ORIGINAL instance
549
+ * (`z_clone(leaf).optional()` would wrap `leaf`, not the clone).
550
+ *
551
+ * **Scope limitation:** the definition is spread SHALLOWLY, so composite members
552
+ * stay shared by reference — `z.object()` shape fields, and a wrapper's own
553
+ * `innerType`. Decorating those members directly still reaches the original; the
554
+ * clone isolates THIS schema's decorators, not its children's.
555
+ *
556
+ * **Related minimal helper:** for the polymorphism engine's specific need —
557
+ * cloning a base-shape field once per variant inside
558
+ * `applyBusinessKeyMarkers` to apply a single decorator without mutating
559
+ * the shared source — see `cloneFieldForBusinessKeyDecoration` in
560
+ * `engine/saas-models/src/resources/utils/resource-polymorphism.schemas.ts`.
561
+ * That helper is a deliberately stripped-down version: it inherits Zod
562
+ * internals via prototype lookup and only shallow-copies `SCHEMA_METADATA`,
563
+ * which is sufficient for the single-decorator mutation pattern used in
564
+ * the polymorphism engine. `z_clone` is the right choice for general-
565
+ * purpose leaf reuse across resources; the polymorphism helper is the
566
+ * right choice when you need MINIMAL isolation in a hot per-variant loop.
217
567
  *
218
568
  * @example
219
569
  * ```ts
@@ -233,43 +583,260 @@ function deepCloneValue(value, seen) {
233
583
  * ```
234
584
  */
235
585
  export function z_clone(schema) {
236
- const clone = Object.assign(Object.create(Object.getPrototypeOf(schema)), schema);
586
+ const definition = schema?._zod?.def ?? schema?.def;
587
+ const nativeClone = schema?.clone;
588
+ if (typeof nativeClone !== 'function' || !definition || typeof definition !== 'object') {
589
+ throw new Error('z_clone requires a Zod schema instance (missing `.clone()` or Zod definition).');
590
+ }
591
+ const clone = nativeClone.call(schema, { ...definition });
237
592
  const metadata = schema[SCHEMA_METADATA];
238
593
  if (metadata) {
239
594
  clone[SCHEMA_METADATA] = deepCloneValue(metadata);
240
595
  }
241
596
  return addChainableMethods(clone);
242
597
  }
598
+ function isPlainObject(value) {
599
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
600
+ }
243
601
  /**
244
- * Deep-merge ENUM_UI decorator params with special handling for the `values` key.
602
+ * Marks an inner schema instance as EXCLUSIVELY OWNED by one wrapper.
603
+ *
604
+ * The value is the owning wrapper instance, not a boolean: ownership is a
605
+ * relation, and a boolean would let a second wrapper mistake someone else's
606
+ * private copy for its own and resume writing into a schema it does not own —
607
+ * reintroducing the very leak this marker exists to close.
608
+ *
609
+ * Deliberately non-enumerable so structural copies (`Object.assign`, spreads,
610
+ * anything that walks own enumerable keys) never inherit an ownership claim
611
+ * that does not belong to them.
612
+ */
613
+ const WRAPPER_OWNED_INNER_SCHEMA = Symbol('wildo.wrapperOwnedInnerSchema');
614
+ /**
615
+ * Resolve the MUTABLE Zod definition object of a schema.
616
+ *
617
+ * Zod 4 stores it at `_zod.def`; the bare `.def` alias is the fallback for
618
+ * schema-like objects that never went through the Zod constructor. Both are
619
+ * read here because `innerType` must be both READ and REWRITTEN through the
620
+ * same object for copy-on-write to take effect.
621
+ */
622
+ function getSchemaDefinition(schema) {
623
+ const def = schema?._zod?.def ?? schema?.def;
624
+ return def && typeof def === 'object' ? def : undefined;
625
+ }
626
+ function getInnerTypeSchema(schema) {
627
+ const innerType = getSchemaDefinition(schema)?.innerType;
628
+ return innerType && typeof innerType === 'object'
629
+ ? innerType
630
+ : undefined;
631
+ }
632
+ /**
633
+ * Produce a private, fully-functional copy of a wrapper's inner schema.
634
+ *
635
+ * Uses Zod's OWN `.clone(def)` rather than a structural copy, because `_zod` is
636
+ * a NON-ENUMERABLE own property: `Object.assign({}, schema)` silently omits it
637
+ * and yields a husk whose every method is still bound to the ORIGINAL instance.
638
+ * Such a husk throws `Cannot read properties of undefined (reading 'optin')`
639
+ * the moment Zod parses through it, and — worse — its `.optional()` would wrap
640
+ * the original rather than the copy. `.clone()` runs the real constructor, so
641
+ * the result carries its own `_zod`, its own parse closures, and the correct
642
+ * subclass (`ZodEmail` stays `ZodEmail`).
643
+ *
644
+ * The definition is SPREAD rather than shared. Zod's argument-less `.clone()`
645
+ * reuses the source `def` object by reference, which would leave the copy's
646
+ * structure aliased to the original — a later `innerType` rewrite on the copy
647
+ * would then reach back into the schema we are trying to protect.
245
648
  *
246
- * - `values` is deep-merged: per-enum-value configs merge individually
247
- * (e.g., adding an icon to a value that already has a color preserves both).
248
- * - All other top-level keys are shallow-replaced (e.g., `displayMode` is atomic).
249
- * - Additive only — you cannot remove a value entry set by a prior call.
250
- * To visually "clear" a property, set it to `undefined` explicitly.
649
+ * Returns `undefined` when no honest private copy can be made, so the caller
650
+ * can fail closed instead of falling back to mutating shared state.
251
651
  */
252
- function deepMergeDisplayParams(existing, incoming) {
652
+ function cloneInnerSchemaForWrapper(innerType) {
653
+ const nativeClone = innerType?.clone;
654
+ const innerDefinition = getSchemaDefinition(innerType);
655
+ if (typeof nativeClone !== 'function' || !innerDefinition) {
656
+ return undefined;
657
+ }
658
+ let cloned;
659
+ try {
660
+ cloned = nativeClone.call(innerType, { ...innerDefinition });
661
+ }
662
+ catch {
663
+ return undefined;
664
+ }
665
+ if (!cloned || cloned === innerType) {
666
+ return undefined;
667
+ }
668
+ // `.clone()` copies the Zod definition, never our decorator symbol — carry the
669
+ // inner's OWN decorators across so the private copy starts semantically identical.
670
+ const existingMetadata = innerType[SCHEMA_METADATA];
671
+ if (existingMetadata) {
672
+ cloned[SCHEMA_METADATA] = { ...existingMetadata };
673
+ }
674
+ // A freshly constructed instance has none of the chainable decorator methods
675
+ // installed as own properties; without this, `unwrapSchema(field).isDBIndexed()`
676
+ // would regress for callers that decorate an unwrapped schema.
677
+ return addChainableMethods(cloned);
678
+ }
679
+ /**
680
+ * Give a wrapper a private inner schema it may safely write field metadata onto.
681
+ *
682
+ * Idempotent per wrapper: the first decorator applied to a given wrapper installs
683
+ * the private copy, every later decorator on that same wrapper recognises its own
684
+ * marker and reuses it, so a decorator chain clones exactly once.
685
+ */
686
+ function ensureWrapperOwnedInnerSchema(wrapper, wrapperDefinition, innerType) {
687
+ if (innerType[WRAPPER_OWNED_INNER_SCHEMA] === wrapper) {
688
+ return innerType;
689
+ }
690
+ const cloned = cloneInnerSchemaForWrapper(innerType);
691
+ if (!cloned) {
692
+ return undefined;
693
+ }
694
+ Object.defineProperty(cloned, WRAPPER_OWNED_INNER_SCHEMA, {
695
+ value: wrapper,
696
+ enumerable: false,
697
+ writable: true,
698
+ configurable: true,
699
+ });
700
+ wrapperDefinition.innerType = cloned;
701
+ return cloned;
702
+ }
703
+ /**
704
+ * Mirror a wrapper's decorator metadata onto the schema it wraps — WITHOUT
705
+ * mutating a schema the wrapper does not own.
706
+ *
707
+ * **Why the mirroring exists.** Decorators are commonly declared on the wrapper
708
+ * (`z.string().optional().isForeignKey()`), while a large family of consumers
709
+ * unwraps first and then reads metadata off the unwrapped schema. Those readers
710
+ * would otherwise see an undecorated leaf.
711
+ *
712
+ * **Why it is copy-on-write.** A wrapper's `innerType` is frequently a SHARED,
713
+ * canonical leaf reused across resources (`TimezoneSchema.default('UTC')` is
714
+ * declared by both the User and the Organization preferences resources). Writing
715
+ * field metadata straight onto that instance published one resource's field
716
+ * decorators onto the shared TYPE, so every other consumer of the leaf silently
717
+ * inherited them — order-dependently, by module import order. Confusing a reusable
718
+ * TYPE with a per-resource FIELD DECLARATION is the root defect; a wrapper may
719
+ * describe its own field, never the type it happens to reuse.
720
+ *
721
+ * The stakes are not cosmetic: `impersonalizeWith` drives the erasure writer, so
722
+ * a leaked treatment scrubs a field its author never marked.
723
+ *
724
+ * **Fail closed.** If no private copy can be made, the mirroring is skipped
725
+ * rather than performed against shared state. The decorator still lives on the
726
+ * wrapper and `getMetadataRecursive` still finds it from there; losing a
727
+ * mirrored read is recoverable, corrupting a shared schema is not.
728
+ */
729
+ function propagateWrapperDecoratorMetadataToInnerSchema(schema, metadata) {
730
+ const wrapperDefinition = getSchemaDefinition(schema);
731
+ const innerType = getInnerTypeSchema(schema);
732
+ if (!wrapperDefinition || !innerType || innerType === schema) {
733
+ return;
734
+ }
735
+ const ownedInnerType = ensureWrapperOwnedInnerSchema(schema, wrapperDefinition, innerType);
736
+ if (!ownedInnerType) {
737
+ return;
738
+ }
739
+ const innerMetadata = ownedInnerType[SCHEMA_METADATA] || {};
740
+ ownedInnerType[SCHEMA_METADATA] = {
741
+ ...innerMetadata,
742
+ ...metadata,
743
+ };
744
+ }
745
+ /**
746
+ * @wildo_source:part:start zod.decorators.chainable-runtime
747
+ *
748
+ * Deep-merge mergeable decorator params with special handling for the `values` key.
749
+ *
750
+ * - Nested plain objects are merged recursively so later decorator calls can
751
+ * augment `display`, `edit`, and similar buckets without dropping earlier data.
752
+ * - `values` is merged per key, preserving existing enum/spec entries while still
753
+ * letting later calls override a nested property of the same entry.
754
+ * - Arrays and non-object values remain atomic and are replaced by the incoming value.
755
+ * - Additive only — to clear a nested property, set it to `undefined` explicitly.
756
+ */
757
+ function deepMergeDecoratorParams(existing, incoming) {
253
758
  const result = { ...existing };
254
759
  for (const [key, value] of Object.entries(incoming)) {
255
- if (key === 'values' &&
256
- value && typeof value === 'object' &&
257
- result[key] && typeof result[key] === 'object') {
258
- const existingValues = result[key];
760
+ const existingValue = result[key];
761
+ if (key === 'values' && isPlainObject(value) && isPlainObject(existingValue)) {
762
+ const existingValues = existingValue;
259
763
  const incomingValues = value;
260
764
  result[key] = { ...existingValues };
261
765
  for (const [enumValue, enumConfig] of Object.entries(incomingValues)) {
262
- result[key][enumValue] = existingValues[enumValue]
263
- ? { ...existingValues[enumValue], ...enumConfig }
264
- : enumConfig;
766
+ const existingEnumConfig = existingValues[enumValue];
767
+ result[key][enumValue] =
768
+ isPlainObject(existingEnumConfig) && isPlainObject(enumConfig)
769
+ ? deepMergeDecoratorParams(existingEnumConfig, enumConfig)
770
+ : enumConfig;
265
771
  }
266
772
  }
773
+ else if (isPlainObject(value) && isPlainObject(existingValue)) {
774
+ result[key] = deepMergeDecoratorParams(existingValue, value);
775
+ }
267
776
  else {
268
777
  result[key] = value;
269
778
  }
270
779
  }
271
780
  return result;
272
781
  }
782
+ /**
783
+ * Decorators that can never share a field with {@link ZodDecorator.RAG_SOURCE}, each with the one
784
+ * sentence that justifies refusing it. ONE table, keyed by the companion, consulted in BOTH
785
+ * application orders by `assertRagSourceCompanionAdmissible` below — the alternative (a check
786
+ * inside each of the five companion methods plus one inside `ragSource`) is six hand-applied
787
+ * copies of one invariant — the failure shape where a fix lands at one of an invariant's N call
788
+ * sites and the other N-1 drift. Because the check lives in
789
+ * `applySingleDecorator`, it also covers every escape hatch (`addRagSource`, `addDecorators`,
790
+ * `z_file({ ragSource })`) for free: there is no door into decorator metadata that bypasses it.
791
+ *
792
+ * ## `TTL` is the one entry this table cannot actually enforce — do not read it as closing DL3
793
+ *
794
+ * Corrected 2026-08-27. `.ttl()`'s applicable types are `['ZodDate','ZodOptional']` and
795
+ * `.ragSource()`'s are `['ZodString','ZodOptional','ZodNullable','ZodDefault']`, so the two
796
+ * essentially cannot land on the SAME field — this row defends a type-impossible pair. The
797
+ * REACHABLE configuration is `expiresAt: z.date().ttl(...)` beside `notes: z.string().ragSource()`:
798
+ * two fields, one resource, one row that MongoDB's TTL monitor deletes whole with no application
799
+ * code running. That is a RESOURCE-level fact and is refused at resource level, at boot, by
800
+ * `ApplicationStartupConfigValidatorService.collectRagSourceRetentionRefusal` (which reads both
801
+ * existing authorities — the RAG field walker and `collectResourceRetentionPolicies` — rather than
802
+ * re-deriving either). The row below is KEPT because it is cheap, correct, and reports the
803
+ * single-field case at authoring time instead of at boot; it is not the control.
804
+ */
805
+ const RAG_SOURCE_REFUSED_COMPANIONS = new Map([
806
+ [ZodDecorator.IS_PASSWORD, 'a password must never enter a retrieval corpus.'],
807
+ [ZodDecorator.IS_OTP, 'a one-time code must never enter a retrieval corpus.'],
808
+ [ZodDecorator.IS_WRITE_ONLY_SECRET, 'a write-only secret must never enter a retrieval corpus.'],
809
+ [ZodDecorator.IS_EPHEMERAL, 'an ephemeral shown-once value must never enter a retrieval corpus.'],
810
+ [
811
+ ZodDecorator.TTL,
812
+ 'MongoDB honours .ttl() natively — rows vanish with no application code running, so derived chunks could never be erased with their parent (resource-rag-capability DL3). ' +
813
+ 'The pair is normally declared on two DIFFERENT fields of one resource, which this field-level check cannot see: that case is refused at boot, per resource, by the startup RAG capability probe. ' +
814
+ 'Both refusals lift when a sweep-cascade reconciles chunk rows against vanished parents.',
815
+ ],
816
+ ]);
817
+ /**
818
+ * Enforce the RAG-source refusal pairs in BOTH orders at the single decorator chokepoint:
819
+ * applying `RAG_SOURCE` to a schema already carrying a refused companion throws, and applying a
820
+ * refused companion to a schema already carrying `RAG_SOURCE` throws the same sentence. Reading
821
+ * `currentMetadata` (the bag this very application is about to write into) is what makes the check
822
+ * order-symmetric: wrapper chains carry their inner metadata forward (`wrapInstanceMethod` copies
823
+ * `SCHEMA_METADATA` across `.optional()` / `.nullable()` / `.default()`), so the earlier
824
+ * declaration is visible from wherever the later one lands.
825
+ */
826
+ function assertRagSourceCompanionAdmissible(decorator, currentMetadata) {
827
+ if (decorator === ZodDecorator.RAG_SOURCE) {
828
+ for (const [companion, reason] of RAG_SOURCE_REFUSED_COMPANIONS) {
829
+ if (currentMetadata[companion] !== undefined) {
830
+ throw new Error(`ragSource() cannot be combined with ${companion}(): ${reason}`);
831
+ }
832
+ }
833
+ return;
834
+ }
835
+ const reason = RAG_SOURCE_REFUSED_COMPANIONS.get(decorator);
836
+ if (reason !== undefined && currentMetadata[ZodDecorator.RAG_SOURCE] !== undefined) {
837
+ throw new Error(`${decorator}() cannot be combined with ragSource(): ${reason}`);
838
+ }
839
+ }
273
840
  function applySingleDecorator(schema, decorator, params) {
274
841
  // Ensure schema exists before accessing Symbol property
275
842
  if (!schema) {
@@ -277,6 +844,9 @@ function applySingleDecorator(schema, decorator, params) {
277
844
  }
278
845
  // Get existing metadata from Symbol property with proper type casting
279
846
  const currentMetadata = schema[SCHEMA_METADATA] || {};
847
+ // Refused RAG-source companions, both orders, before any metadata is written — a refusal that
848
+ // fired after a partial write would leave the schema carrying half of a rejected combination.
849
+ assertRagSourceCompanionAdmissible(decorator, currentMetadata);
280
850
  // Generic updater function resolution: if params is a function, call it with
281
851
  // the current metadata value and use the result. Works for any decorator.
282
852
  let resolvedFromUpdater = false;
@@ -316,6 +886,122 @@ function applySingleDecorator(schema, decorator, params) {
316
886
  case ZodDecorator.IS_BACKEND_ONLY:
317
887
  currentMetadata[ZodDecorator.IS_BACKEND_ONLY] = p ?? true;
318
888
  break;
889
+ case ZodDecorator.IS_WRITE_ONLY_SECRET:
890
+ currentMetadata[ZodDecorator.IS_WRITE_ONLY_SECRET] = p ?? true;
891
+ break;
892
+ case ZodDecorator.IMPERSONALIZE_WITH: {
893
+ // Fail LOUD on a missing / blank treatment. This is the single chokepoint shared by the fluent
894
+ // `.impersonalizeWith(t)` method and the `addImpersonalizeWith(schema, t)` helper, so both doors
895
+ // reject the same inputs. Without it a bare `.impersonalizeWith()` (JS caller, or a TS caller
896
+ // whose value widened to undefined) would store `undefined`, `getImpersonalizeTreatment` would
897
+ // return `undefined`, and the field would read as UNTREATED — a silently unscrubbed personal
898
+ // field, i.e. exactly the PII-leak class this decorator exists to prevent.
899
+ //
900
+ // NORMALIZE HERE, not in the doors. Both authoring forms — the bare `RedactionType` string
901
+ // (the common case) and the `{ treatment, maskValue }` object (a MASK needing a field-specific
902
+ // value) — collapse to the params object before storage, so every reader sees ONE shape and
903
+ // the doors stay dumb pass-throughs. A raw `addDecorators()` caller lands here too.
904
+ const raw = p;
905
+ const normalized = typeof raw === 'string'
906
+ ? { treatment: raw }
907
+ : (raw !== null && typeof raw === 'object' && !Array.isArray(raw))
908
+ ? { ...raw }
909
+ : undefined;
910
+ if (normalized === undefined || typeof normalized.treatment !== 'string' || normalized.treatment.trim().length === 0) {
911
+ throw new Error(`impersonalizeWith(treatment) requires a non-empty RedactionType value (received ${JSON.stringify(raw)}). ` +
912
+ `An untreated field is left intact by the impersonalize writer — declare a treatment or omit the decorator.`);
913
+ }
914
+ // A blank override would write an empty string and erase the distinction between "masked" and
915
+ // "never had a value" — the same class of silent lie the treatment check above prevents.
916
+ // WHETHER a maskValue is legal for this treatment (MASK only) and whether the field's schema
917
+ // ACCEPTS it are both checked by the saas-models boot guard: this layer knows neither
918
+ // `RedactionType` nor the resource's mainSchema.
919
+ if (normalized.maskValue !== undefined && (typeof normalized.maskValue !== 'string' || normalized.maskValue.length === 0)) {
920
+ throw new Error(`impersonalizeWith({ maskValue }) requires a non-empty string (received ${JSON.stringify(normalized.maskValue)}). ` +
921
+ `The mask value is written verbatim in place of the field — omit it to use the framework mask constant.`);
922
+ }
923
+ currentMetadata[ZodDecorator.IMPERSONALIZE_WITH] = normalized;
924
+ break;
925
+ }
926
+ case ZodDecorator.PORTABILITY_PROVENANCE: {
927
+ // Fail LOUD on a missing / blank provenance — the single chokepoint shared by the fluent
928
+ // `.portabilityProvenance(p)` method and the `addPortabilityProvenance(schema, p)` helper.
929
+ //
930
+ // Storing a blank would be worse here than for most decorators. An Art. 20 export treats an
931
+ // UNDECLARED field as a REFUSAL precisely because neither guess is safe (excluding
932
+ // under-delivers a legal right, including over-shares controller-derived data). A silently
933
+ // stored empty string would read back as declared-but-meaningless, converting that deliberate
934
+ // refusal into a fabricated answer about a disclosure boundary.
935
+ //
936
+ // WHETHER the value is a real `DataPortabilityProvenance` member is checked by the saas-models
937
+ // layer, which owns the enum — this layer knows only that a non-empty string was declared.
938
+ const raw = p;
939
+ if (typeof raw !== 'string' || raw.trim().length === 0) {
940
+ throw new Error(`portabilityProvenance(provenance) requires a non-empty DataPortabilityProvenance value (received ${JSON.stringify(raw)}). ` +
941
+ `An undeclared field makes an Art. 20 export refuse rather than guess — declare a provenance or omit the decorator ` +
942
+ `to inherit the resource's portabilityPolicy.defaultProvenance.`);
943
+ }
944
+ currentMetadata[ZodDecorator.PORTABILITY_PROVENANCE] = raw;
945
+ break;
946
+ }
947
+ case ZodDecorator.DATA_CATEGORIES: {
948
+ // NORMALIZE HERE, not in the doors — the impersonalizeWith discipline. A single value (the
949
+ // common case) and an array both store a deduped ARRAY, so every reader sees one shape and
950
+ // `getDataCategories` answers "is this field categorized?" by presence alone.
951
+ //
952
+ // Fail LOUD on an empty declaration. An UNCATEGORIZED field is a legitimate, common state —
953
+ // most fields are not personal data — and the gap report is built on ABSENCE. A stored empty
954
+ // array would read back as declared-with-no-categories, which is invisible to a report
955
+ // looking for absence: the field would be silently excluded from the notice while looking
956
+ // annotated to anyone reading the schema.
957
+ //
958
+ // WHETHER each value is a real `PersonalDataCategory` member is checked by the resource
959
+ // factory's boot guard, which owns the enum — this layer knows only that non-empty strings
960
+ // were declared.
961
+ const raw = p;
962
+ const authored = Array.isArray(raw) ? raw : [raw];
963
+ if (authored.length === 0 || authored.some((value) => typeof value !== 'string' || value.trim().length === 0)) {
964
+ throw new Error(`dataCategories(categories) requires at least one non-empty PersonalDataCategory value (received ${JSON.stringify(raw)}). ` +
965
+ `A field that holds no personal data carries NO declaration — absence is what a category gap report reads. ` +
966
+ `An empty declaration looks annotated and discloses nothing.`);
967
+ }
968
+ currentMetadata[ZodDecorator.DATA_CATEGORIES] = [...new Set(authored)];
969
+ break;
970
+ }
971
+ case ZodDecorator.IS_AUDIT_EVIDENCE:
972
+ currentMetadata[ZodDecorator.IS_AUDIT_EVIDENCE] = true;
973
+ break;
974
+ case ZodDecorator.RAG_SOURCE: {
975
+ // NORMALIZE HERE, not in the doors — the impersonalizeWith discipline. A bare `.ragSource()`
976
+ // (the common case) stores `{}` rather than `true`/`undefined`, so every reader sees ONE
977
+ // shape and `getRagSourceConfig` answers "is this field a source?" by presence alone. The
978
+ // knobs are validated at decoration time because every one of them is otherwise a SILENT
979
+ // runtime misconfiguration: a zero chunkSize or an overlap >= size does not fail — it chunks
980
+ // pathologically (empty chunks, or every chunk repeating its predecessor), which surfaces
981
+ // as bad retrieval quality nobody traces back to the schema.
982
+ const raw = p;
983
+ if (raw !== undefined && (raw === null || typeof raw !== 'object' || Array.isArray(raw))) {
984
+ throw new Error(`ragSource(config?) accepts an optional RagSourceConfiguration object (received ${JSON.stringify(raw)}).`);
985
+ }
986
+ const normalized = raw === undefined ? {} : { ...raw };
987
+ const { chunkingStrategy, chunkSize, chunkOverlap } = normalized;
988
+ const knownStrategies = Object.values(RAGChunkingStrategy);
989
+ if (chunkingStrategy !== undefined && !knownStrategies.includes(chunkingStrategy)) {
990
+ throw new Error(`ragSource({ chunkingStrategy }) must be a RAGChunkingStrategy member (received ${JSON.stringify(chunkingStrategy)}; known: ${knownStrategies.join(', ')}).`);
991
+ }
992
+ if (chunkSize !== undefined && (!Number.isInteger(chunkSize) || chunkSize <= 0)) {
993
+ throw new Error(`ragSource({ chunkSize }) must be a positive integer (received ${JSON.stringify(chunkSize)}).`);
994
+ }
995
+ if (chunkOverlap !== undefined && (!Number.isInteger(chunkOverlap) || chunkOverlap < 0)) {
996
+ throw new Error(`ragSource({ chunkOverlap }) must be a non-negative integer (received ${JSON.stringify(chunkOverlap)}).`);
997
+ }
998
+ if (chunkSize !== undefined && chunkOverlap !== undefined && chunkOverlap >= chunkSize) {
999
+ throw new Error(`ragSource({ chunkSize, chunkOverlap }) requires chunkOverlap < chunkSize (received overlap ${chunkOverlap} >= size ${chunkSize}) — ` +
1000
+ `an overlap that reaches the chunk size makes every chunk repeat its predecessor.`);
1001
+ }
1002
+ currentMetadata[ZodDecorator.RAG_SOURCE] = normalized;
1003
+ break;
1004
+ }
319
1005
  case ZodDecorator.IS_VIRTUAL: {
320
1006
  const vp = rp();
321
1007
  if (!vp?.calculate) {
@@ -339,6 +1025,12 @@ function applySingleDecorator(schema, decorator, params) {
339
1025
  case ZodDecorator.IS_PRIMARY_KEY:
340
1026
  currentMetadata[ZodDecorator.IS_PRIMARY_KEY] = true;
341
1027
  break;
1028
+ case ZodDecorator.IS_BUSINESS_KEY:
1029
+ currentMetadata[ZodDecorator.IS_BUSINESS_KEY] = true;
1030
+ break;
1031
+ case ZodDecorator.OBJECT_BUSINESS_KEY_SET:
1032
+ currentMetadata[ZodDecorator.OBJECT_BUSINESS_KEY_SET] = p;
1033
+ break;
342
1034
  case ZodDecorator.TTL:
343
1035
  currentMetadata[ZodDecorator.TTL] = p;
344
1036
  break;
@@ -366,19 +1058,21 @@ function applySingleDecorator(schema, decorator, params) {
366
1058
  case ZodDecorator.IS_CRDT:
367
1059
  currentMetadata[ZodDecorator.IS_CRDT] = true;
368
1060
  break;
369
- // Unified {primitive}UI decorators — ENUM_UI uses deep merge for per-value configs, all others use shallow replace
1061
+ // Mergeable decorator buckets: primitive UI/spec decorators deep-merge
1062
+ // plain-object params by default, while updater functions still replace
1063
+ // exactly with what they return.
370
1064
  case ZodDecorator.ENUM_UI: {
371
- if (!p) {
372
- currentMetadata[decorator] = true;
1065
+ const existing = currentMetadata[decorator];
1066
+ if (p === undefined) {
1067
+ currentMetadata[decorator] = existing ?? true;
373
1068
  }
374
1069
  else if (resolvedFromUpdater) {
375
1070
  currentMetadata[decorator] = p;
376
1071
  }
377
1072
  else {
378
- const existing = currentMetadata[decorator];
379
1073
  currentMetadata[decorator] =
380
- (existing && typeof existing === 'object')
381
- ? deepMergeDisplayParams(existing, p)
1074
+ isPlainObject(existing) && isPlainObject(p)
1075
+ ? deepMergeDecoratorParams(existing, p)
382
1076
  : p;
383
1077
  }
384
1078
  break;
@@ -397,29 +1091,53 @@ function applySingleDecorator(schema, decorator, params) {
397
1091
  case ZodDecorator.BIGDECIMAL_UI:
398
1092
  case ZodDecorator.FOREIGN_KEY_UI:
399
1093
  case ZodDecorator.ARRAY_UI:
400
- case ZodDecorator.OBJECT_UI: {
401
- if (!p) {
402
- currentMetadata[decorator] = true;
1094
+ case ZodDecorator.OBJECT_UI:
1095
+ case ZodDecorator.STRING_SPEC:
1096
+ case ZodDecorator.NUMBER_SPEC:
1097
+ case ZodDecorator.BOOLEAN_SPEC:
1098
+ case ZodDecorator.DATE_SPEC:
1099
+ case ZodDecorator.DATETIME_SPEC:
1100
+ case ZodDecorator.TIME_SPEC:
1101
+ case ZodDecorator.ENUM_SPEC:
1102
+ case ZodDecorator.MONEY_SPEC:
1103
+ case ZodDecorator.CODE_SPEC:
1104
+ case ZodDecorator.FILE_SPEC:
1105
+ case ZodDecorator.DURATION_SPEC:
1106
+ case ZodDecorator.PHONE_SPEC:
1107
+ case ZodDecorator.BIGDECIMAL_SPEC:
1108
+ case ZodDecorator.FOREIGN_KEY_SPEC:
1109
+ case ZodDecorator.ARRAY_SPEC:
1110
+ case ZodDecorator.OBJECT_SPEC: {
1111
+ const existing = currentMetadata[decorator];
1112
+ if (p === undefined) {
1113
+ currentMetadata[decorator] = existing ?? true;
403
1114
  }
404
1115
  else if (resolvedFromUpdater) {
405
1116
  currentMetadata[decorator] = p;
406
1117
  }
407
1118
  else {
408
- currentMetadata[decorator] = p;
1119
+ currentMetadata[decorator] =
1120
+ isPlainObject(existing) && isPlainObject(p)
1121
+ ? deepMergeDecoratorParams(existing, p)
1122
+ : p;
409
1123
  }
410
1124
  break;
411
1125
  }
412
1126
  }
413
1127
  // Store updated metadata using Symbol
414
1128
  schema[SCHEMA_METADATA] = currentMetadata;
1129
+ propagateWrapperDecoratorMetadataToInnerSchema(schema, currentMetadata);
415
1130
  return addChainableMethods(schema);
416
1131
  }
1132
+ /** @wildo_source:part:end zod.decorators.chainable-runtime */
417
1133
  /**
418
1134
  * Methods that transform object fields and need special handling for field-level metadata.
419
1135
  * These methods create new field wrappers and we need to copy field-level metadata.
420
1136
  */
421
1137
  const OBJECT_FIELD_TRANSFORM_METHODS_SET = new Set(['partial', 'deepPartial', 'required']);
422
1138
  /**
1139
+ * @wildo_source:part:start zod.decorators.chainable-runtime
1140
+ *
423
1141
  * Wraps an instance method to preserve SCHEMA_METADATA when it returns a new instance.
424
1142
  * In Zod v4, methods are on instances not prototypes, so we wrap them individually.
425
1143
  * Also wraps the result's methods to ensure metadata persists through the entire chain.
@@ -522,6 +1240,7 @@ export function addChainableMethods(schema) {
522
1240
  }
523
1241
  return decoratedSchema;
524
1242
  }
1243
+ /** @wildo_source:part:end zod.decorators.chainable-runtime */
525
1244
  // =============================================================================
526
1245
  // ADD DECORATORS
527
1246
  // =============================================================================
@@ -566,6 +1285,158 @@ export function addBackendOnly(schema, params) {
566
1285
  ensureZodDecoratorsLoaded(z);
567
1286
  return addDecorators(schema, [{ ref: ZodDecorator.IS_BACKEND_ONLY, params }]);
568
1287
  }
1288
+ export function addWriteOnlySecret(schema, params) {
1289
+ ensureZodDecoratorsLoaded(z);
1290
+ return addDecorators(schema, [{ ref: ZodDecorator.IS_WRITE_ONLY_SECRET, params }]);
1291
+ }
1292
+ /**
1293
+ * Standalone form of `.impersonalizeWith(treatment)` — declare a field's impersonalization
1294
+ * scrub treatment (a `RedactionType` value).
1295
+ *
1296
+ * The fluent `.impersonalizeWith(treatment)` method is the idiomatic authoring form and is live on
1297
+ * every schema type + wrapper. This helper stays as the programmatic escape hatch for the cases the
1298
+ * fluent form cannot express: decorating a schema held in a variable of an erased/generic type, or
1299
+ * applying a treatment inside a generic transform where `this` is `z.ZodTypeAny`.
1300
+ *
1301
+ * Both doors funnel through `applySingleDecorator`, so both reject a missing/blank treatment
1302
+ * identically. Read the result back with `getImpersonalizeTreatment(schema)`.
1303
+ *
1304
+ * `options.maskValue` overrides the framework mask constant for a `MASK` treatment — required when
1305
+ * the field is a CONSTRAINED string (`z.email()`, `z.uuid()`, `.min(n)`) the default constant cannot
1306
+ * satisfy. See {@link ImpersonalizeFieldParams} for the full contract; read it back with
1307
+ * `getImpersonalizeMaskValue(schema)`.
1308
+ *
1309
+ * @example
1310
+ * // Unconstrained string — the framework mask constant applies.
1311
+ * addImpersonalizeWith(z.string(), RedactionType.MASK)
1312
+ * @example
1313
+ * // Constrained string — the default constant would fail the boot guard, so give it a value the
1314
+ * // field's own schema accepts. `.invalid` is RFC 2606 reserved: never resolvable, never delivered.
1315
+ * addImpersonalizeWith(z.email(), RedactionType.MASK, { maskValue: 'erased@erased.invalid' })
1316
+ */
1317
+ export function addImpersonalizeWith(schema, treatment, options) {
1318
+ ensureZodDecoratorsLoaded(z);
1319
+ return addDecorators(schema, [
1320
+ { ref: ZodDecorator.IMPERSONALIZE_WITH, params: options ? { ...options, treatment } : treatment },
1321
+ ]);
1322
+ }
1323
+ /**
1324
+ * @wildo_source:part:start zod.decorators.rag-source facet:layer:shared facet:family:decorator facet:kind:api facet:audience:app-developer
1325
+ *
1326
+ * Standalone form of `.ragSource(config?)` — declare a field's text a RAG retrieval-corpus source.
1327
+ *
1328
+ * Import from `@wildo-ai/zod-decorators`.
1329
+ *
1330
+ * The fluent `.ragSource()` method is the idiomatic authoring form and is live on every
1331
+ * string-backed type plus the Optional / Nullable / Default wrappers. This helper is the
1332
+ * programmatic escape hatch for schemas held as an erased/generic type, and it is the door
1333
+ * `z_file({ ragSource })` uses to register the SAME decorator on a file schema (a `ZodObject`,
1334
+ * which deliberately carries no fluent `.ragSource()` — see the applicable-types entry).
1335
+ *
1336
+ * Both doors funnel through `applySingleDecorator`, so both validate the config identically and
1337
+ * both enforce the refused companions (`isPassword` / `isOtp` / `isWriteOnlySecret` /
1338
+ * `isEphemeral` / `ttl`) in both application orders. Read the stored config back with
1339
+ * `getRagSourceConfig(schema)`.
1340
+ *
1341
+ * @example
1342
+ * // A complete declaration — framework chunking defaults apply.
1343
+ * addRagSource(z.string())
1344
+ * @example
1345
+ * // Authored chunking for a markdown knowledge field.
1346
+ * addRagSource(z.string(), { chunkingStrategy: RAGChunkingStrategy.MARKDOWN, chunkSize: 1200, chunkOverlap: 150 })
1347
+ */
1348
+ export function addRagSource(schema, config) {
1349
+ ensureZodDecoratorsLoaded(z);
1350
+ return addDecorators(schema, [
1351
+ { ref: ZodDecorator.RAG_SOURCE, params: config },
1352
+ ]);
1353
+ }
1354
+ /** @wildo_source:part:end zod.decorators.rag-source */
1355
+ /**
1356
+ * Standalone form of `.portabilityProvenance(provenance)` — declare where a field's value came
1357
+ * from, for GDPR Art. 20 scoping.
1358
+ *
1359
+ * The fluent method is the idiomatic authoring form and is live on every decorator-reachable Zod
1360
+ * type. This helper exists for the types that carry NO prototype-installed decorators at all
1361
+ * (`z.pipe(...)`, which is what `z_phone()` returns, plus Literal / Tuple / Set / …) and for
1362
+ * applying a provenance inside a generic transform where `this` is `z.ZodTypeAny`.
1363
+ *
1364
+ * Both doors funnel through `applySingleDecorator`, so both reject a missing/blank value
1365
+ * identically. Read the result back with `getPortabilityProvenance(schema)`.
1366
+ *
1367
+ * Omitting the declaration entirely is legitimate and common: the field then inherits its
1368
+ * resource's `portabilityPolicy.defaultProvenance`. Only fields that DIFFER from that default need
1369
+ * a declaration — which is what keeps annotating a resource a one-line cost rather than a per-field
1370
+ * chore.
1371
+ *
1372
+ * @example
1373
+ * // A value the subject typed — in scope for both Art. 15 and Art. 20.
1374
+ * addPortabilityProvenance(z.string(), DataPortabilityProvenance.SUBJECT_PROVIDED)
1375
+ * @example
1376
+ * // A value the controller computed ABOUT the subject — disclosed under Art. 15, excluded from an
1377
+ * // Art. 20 portability bundle.
1378
+ * addPortabilityProvenance(z.number(), DataPortabilityProvenance.DERIVED)
1379
+ */
1380
+ export function addPortabilityProvenance(schema, provenance) {
1381
+ ensureZodDecoratorsLoaded(z);
1382
+ return addDecorators(schema, [
1383
+ { ref: ZodDecorator.PORTABILITY_PROVENANCE, params: provenance },
1384
+ ]);
1385
+ }
1386
+ /**
1387
+ * Standalone form of `.dataCategories(categories)` — declare WHICH KINDS of personal data a field
1388
+ * holds, for the privacy-notice inventory.
1389
+ *
1390
+ * The fluent method is the idiomatic authoring form and is live on every decorator-reachable Zod
1391
+ * type. This helper exists for the types that carry NO prototype-installed decorators at all
1392
+ * (`z.pipe(...)`, which is what `z_phone()` returns, plus Literal / Tuple / Set / …) and for
1393
+ * declaring categories inside a generic transform where `this` is `z.ZodTypeAny`.
1394
+ *
1395
+ * ⚠️ `z_phone()` is the case that makes this helper load-bearing rather than a curiosity: a phone
1396
+ * number is contact detail personal data by definition, and the fluent method cannot reach it.
1397
+ *
1398
+ * Both doors funnel through `applySingleDecorator`, so both reject an empty declaration
1399
+ * identically. Read the result back with `getDataCategories(schema)`.
1400
+ *
1401
+ * @example
1402
+ * // A phone number — the pipe `z_phone()` returns has no fluent surface.
1403
+ * addDataCategories(z_phone(), PersonalDataCategory.CONTACT_DETAILS)
1404
+ * @example
1405
+ * // A field that genuinely spans two categories.
1406
+ * addDataCategories(z.string(), [PersonalDataCategory.USER_CONTENT, PersonalDataCategory.SPECIAL_CATEGORY_HEALTH])
1407
+ *
1408
+ * @wildo_source:part:start zod.decorators.data-categories facet:layer:shared facet:family:decorator facet:kind:api facet:audience:app-developer
1409
+ */
1410
+ export function addDataCategories(schema, categories) {
1411
+ ensureZodDecoratorsLoaded(z);
1412
+ return addDecorators(schema, [
1413
+ { ref: ZodDecorator.DATA_CATEGORIES, params: categories },
1414
+ ]);
1415
+ }
1416
+ /** @wildo_source:part:end zod.decorators.data-categories */
1417
+ /**
1418
+ * Standalone form of `.isAuditEvidence()` — mark a field whose before/after values are recorded on
1419
+ * the `resource_operation_performed` audit event when an operation changes it.
1420
+ *
1421
+ * The fluent method is the idiomatic authoring form and is live on every decorator-reachable Zod
1422
+ * type. This helper exists for the types that carry NO prototype-installed decorators at all
1423
+ * (`z.pipe(...)`, which is what `z_phone()` returns, plus Literal / Tuple / Set / …) and for
1424
+ * marking a field inside a generic transform where `this` is `z.ZodTypeAny`.
1425
+ *
1426
+ * Read the result back with `isAuditEvidenceField(schema)`.
1427
+ *
1428
+ * ⚠️ `z_phone()` is the cautionary case for this decorator specifically: a phone number is personal
1429
+ * data, so reaching for this helper on one is almost always the wrong call. The unreachable-fluent
1430
+ * types are listed here for completeness of the API surface, not as a suggestion.
1431
+ *
1432
+ * @example
1433
+ * // Authority — the values ARE the evidence; a role change without them proves nothing.
1434
+ * addAuditEvidence(z.array(z.string()))
1435
+ */
1436
+ export function addAuditEvidence(schema) {
1437
+ ensureZodDecoratorsLoaded(z);
1438
+ return addDecorators(schema, [ZodDecorator.IS_AUDIT_EVIDENCE]);
1439
+ }
569
1440
  export function addVirtual(schema, params) {
570
1441
  ensureZodDecoratorsLoaded(z);
571
1442
  return addDecorators(schema, [{ ref: ZodDecorator.IS_VIRTUAL, params }]);
@@ -655,7 +1526,7 @@ export function addPrimaryKey(schema) {
655
1526
  * which would lose our SCHEMA_METADATA Symbol. This wrapper copies the metadata.
656
1527
  */
657
1528
  function wrapMethodToPreserveMetadata(originalMethod, methodName) {
658
- return function (...args) {
1529
+ const wrapped = function (...args) {
659
1530
  const originalMetadata = this[SCHEMA_METADATA];
660
1531
  const result = originalMethod.apply(this, args);
661
1532
  // Copy all metadata from original (this) to result if it exists
@@ -665,19 +1536,64 @@ function wrapMethodToPreserveMetadata(originalMethod, methodName) {
665
1536
  }
666
1537
  return result;
667
1538
  };
1539
+ // Deliberately NOT `__metadataWrapped`, which is `wrapInstanceMethod`'s marker. The two wrappers
1540
+ // are not interchangeable — the instance one also runs `copyFieldMetadata` and re-wraps the result
1541
+ // — so sharing a marker would let a prototype wrapper suppress an instance wrapper that does more.
1542
+ wrapped.__prototypeMetadataWrapped = true;
1543
+ return wrapped;
668
1544
  }
669
1545
  /**
670
1546
  * Patches all methods on a prototype that might return new instances,
671
1547
  * ensuring SCHEMA_METADATA is preserved through method chains.
1548
+ *
1549
+ * ⚠️ MEASURED 2026-08-12, zod@4.3.6: this function is currently a COMPLETE NO-OP, and every call to
1550
+ * it is inert. Zod v4 installs schema methods as INSTANCE own properties — `ZodString.prototype`
1551
+ * carries `constructor` and nothing else — so `prototype[methodName]` is `undefined` for every name
1552
+ * passed in and the loop skips all of them. Metadata preservation through `.min()` / `.optional()` /
1553
+ * `.transform()` is done entirely at the instance level by `addChainableMethods` →
1554
+ * `wrapInstanceMethod`, which is what actually works today (verified: metadata survives
1555
+ * `.transform().optional()` and `.array().optional()`).
1556
+ *
1557
+ * It is kept, rather than deleted, because it costs nothing and is the correct behavior if Zod ever
1558
+ * moves methods back onto prototypes — at which point the guard below stops being theoretical, since
1559
+ * `ZodString.prototype` is reached by both the STEP 1 pass and `installStringDecoratorSurface`.
1560
+ * Do NOT cite this function as the reason a decorator survives a chain; it is not.
672
1561
  */
673
1562
  function patchPrototypeMethodsForMetadataPreservation(prototype, methodNames) {
674
1563
  for (const methodName of methodNames) {
675
1564
  const originalMethod = prototype[methodName];
676
- if (typeof originalMethod === 'function') {
677
- prototype[methodName] = wrapMethodToPreserveMetadata(originalMethod, methodName);
678
- }
1565
+ if (typeof originalMethod !== 'function')
1566
+ continue;
1567
+ if (originalMethod.__prototypeMetadataWrapped)
1568
+ continue;
1569
+ prototype[methodName] = wrapMethodToPreserveMetadata(originalMethod, methodName);
679
1570
  }
680
1571
  }
1572
+ /**
1573
+ * Install the WHOLE string decorator surface on one string-backed prototype.
1574
+ *
1575
+ * The only writer of decorator methods onto a string-schema prototype. It has exactly two callers —
1576
+ * `ZodString.prototype` and `ZodStringFormat.prototype` — and routing both through one function is
1577
+ * what makes `STRING_SCHEMA_DECORATOR_SURFACE` a source of truth rather than a copy: a decorator
1578
+ * added to the list reaches `z.string()` and `z.uuid()` in the same edit, and one cannot be given
1579
+ * the method while the other is not.
1580
+ *
1581
+ * Also calls the metadata-preservation patch, matching what each of the three install sites did
1582
+ * before. Note that this call is INERT on zod@4.3.6 — see that function's own docblock; schema
1583
+ * methods live on instances, and `addChainableMethods` is what preserves metadata through a chain.
1584
+ * It is passed through rather than dropped so the two stay coupled if Zod's method placement changes.
1585
+ *
1586
+ * @param prototype - a Zod string-schema prototype (`ZodString.prototype`, `ZodUUID.prototype`, …)
1587
+ * @param methodsToWrap - the instance-returning methods to wrap IF this Zod version puts them on the
1588
+ * prototype at all
1589
+ */
1590
+ function installStringDecoratorSurface(prototype, methodsToWrap) {
1591
+ patchPrototypeMethodsForMetadataPreservation(prototype, methodsToWrap);
1592
+ for (const decorator of STRING_SCHEMA_DECORATOR_SURFACE) {
1593
+ prototype[decorator] = ZodDecorator_FunctionType[decorator];
1594
+ }
1595
+ prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
1596
+ }
681
1597
  /**
682
1598
  * Ensures Zod decorators are applied to a specific Zod instance.
683
1599
  * This is critical when multiple Zod instances exist in the dependency tree.
@@ -752,32 +1668,12 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
752
1668
  // =============================================================================
753
1669
  // STEP 2: Apply decorator methods to Zod prototypes
754
1670
  // =============================================================================
755
- // Apply decorators to this Zod instance
756
- zodInstance.ZodString.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
757
- zodInstance.ZodString.prototype[ZodDecorator.IS_FOREIGN_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_FOREIGN_KEY];
758
- zodInstance.ZodString.prototype[ZodDecorator.IS_HIDDEN] = ZodDecorator_FunctionType[ZodDecorator.IS_HIDDEN];
759
- zodInstance.ZodString.prototype[ZodDecorator.IS_NOT_EDITABLE] = ZodDecorator_FunctionType[ZodDecorator.IS_NOT_EDITABLE];
760
- // New decorators
761
- zodInstance.ZodString.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
762
- zodInstance.ZodString.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
763
- zodInstance.ZodString.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
764
- zodInstance.ZodString.prototype[ZodDecorator.IS_DISCRIMINATOR] = ZodDecorator_FunctionType[ZodDecorator.IS_DISCRIMINATOR];
765
- zodInstance.ZodString.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
766
- zodInstance.ZodString.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
767
- // Database constraint decorators
768
- zodInstance.ZodString.prototype[ZodDecorator.IS_UNIQUE] = ZodDecorator_FunctionType[ZodDecorator.IS_UNIQUE];
769
- zodInstance.ZodString.prototype[ZodDecorator.IS_PRIMARY_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_PRIMARY_KEY];
770
- // String edit mode convenience decorators
771
- zodInstance.ZodString.prototype[ZodDecorator.IS_PASSWORD] = ZodDecorator_FunctionType[ZodDecorator.IS_PASSWORD];
772
- zodInstance.ZodString.prototype[ZodDecorator.IS_OTP] = ZodDecorator_FunctionType[ZodDecorator.IS_OTP];
773
- zodInstance.ZodString.prototype[ZodDecorator.IS_COLOR] = ZodDecorator_FunctionType[ZodDecorator.IS_COLOR];
774
- // Ephemeral field decorator
775
- zodInstance.ZodString.prototype[ZodDecorator.IS_EPHEMERAL] = ZodDecorator_FunctionType[ZodDecorator.IS_EPHEMERAL];
776
- // CRDT field decorator
777
- zodInstance.ZodString.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
778
- // Unified UI decorator
779
- zodInstance.ZodString.prototype[ZodDecorator.STRING_UI] = ZodDecorator_FunctionType[ZodDecorator.STRING_UI];
780
- zodInstance.ZodString.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
1671
+ // Apply decorators to this Zod instance. `ZodString.prototype` takes the SAME surface through the
1672
+ // SAME installer as `ZodStringFormat.prototype` in STEP 3 — that shared call is what keeps
1673
+ // `z.string()` and `z.uuid()` from drifting apart again. This base covers `z.string()` and its
1674
+ // chained forms ONLY; a format type never runs `ZodString.init`, which is the whole point of
1675
+ // STEP 3.
1676
+ installStringDecoratorSurface(zodInstance.ZodString.prototype, zodStringMethodsToWrap);
781
1677
  zodInstance.ZodNumber.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
782
1678
  zodInstance.ZodNumber.prototype[ZodDecorator.IS_FOREIGN_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_FOREIGN_KEY];
783
1679
  zodInstance.ZodNumber.prototype[ZodDecorator.IS_HIDDEN] = ZodDecorator_FunctionType[ZodDecorator.IS_HIDDEN];
@@ -785,17 +1681,65 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
785
1681
  // New decorators
786
1682
  zodInstance.ZodNumber.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
787
1683
  zodInstance.ZodNumber.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1684
+ zodInstance.ZodNumber.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
1685
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
1686
+ zodInstance.ZodNumber.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
1687
+ zodInstance.ZodNumber.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
1688
+ zodInstance.ZodNumber.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
1689
+ zodInstance.ZodNumber.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
788
1690
  zodInstance.ZodNumber.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
789
1691
  zodInstance.ZodNumber.prototype[ZodDecorator.IS_DISCRIMINATOR] = ZodDecorator_FunctionType[ZodDecorator.IS_DISCRIMINATOR];
790
1692
  zodInstance.ZodNumber.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
791
1693
  zodInstance.ZodNumber.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
792
1694
  // Database constraint decorators
793
1695
  zodInstance.ZodNumber.prototype[ZodDecorator.IS_UNIQUE] = ZodDecorator_FunctionType[ZodDecorator.IS_UNIQUE];
1696
+ // Business key marker (data-seeding subsystem)
1697
+ zodInstance.ZodNumber.prototype[ZodDecorator.IS_BUSINESS_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_BUSINESS_KEY];
794
1698
  // CRDT field decorator
795
1699
  zodInstance.ZodNumber.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
796
1700
  // Unified UI decorator
797
1701
  zodInstance.ZodNumber.prototype[ZodDecorator.NUMBER_UI] = ZodDecorator_FunctionType[ZodDecorator.NUMBER_UI];
1702
+ // Field specification decorator
1703
+ zodInstance.ZodNumber.prototype[ZodDecorator.NUMBER_SPEC] = ZodDecorator_FunctionType[ZodDecorator.NUMBER_SPEC];
1704
+ // Generic form-field decorators (conditional visibility / draft relaxation).
1705
+ zodInstance.ZodNumber.prototype[ZodDecorator.SHOW_WHEN] = ZodDecorator_FunctionType[ZodDecorator.SHOW_WHEN];
1706
+ zodInstance.ZodNumber.prototype[ZodDecorator.IS_DRAFT_RELAXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DRAFT_RELAXED];
798
1707
  zodInstance.ZodNumber.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
1708
+ // ZodBigInt — the primitive that carried NO decorator at all until 2026-08-12.
1709
+ //
1710
+ // It is listed in `ApplyableTypeAllTypes` and `ApplyableTypeAllPrimitiveTypes`, and it is a
1711
+ // first-class leaf in every OTHER layer: the Mongoose schema convertor maps it, the DTO builder
1712
+ // coerces it across the network boundary, `install-bigint-json-encoding.ts` exists solely for it,
1713
+ // the MCP JSON-schema emitter handles it, and `z_money()` stores its `amount` as one. The decorator
1714
+ // layer was the single outlier, so an application could not mark a bigint field `isBackendOnly()`,
1715
+ // `excludeFromCreate()`, `impersonalizeWith(...)` or `isDBIndexed()` — all BACKEND concerns that do
1716
+ // not depend on there being a bigint form widget.
1717
+ //
1718
+ // Reached bare via `addChainableMethods` only AFTER another decorator, which was impossible: there
1719
+ // was no first decorator to start the chain. `impersonalize-treatment.test.ts` carried a waiver
1720
+ // saying "drop the waiver if ZodBigInt ever joins the prototype-install block"; this is that.
1721
+ //
1722
+ // No `IS_UNIQUE` / `IS_FOREIGN_KEY` (both are String/Number-scoped in the map), no `IS_DISCRIMINATOR`
1723
+ // (the params model is string/enum-valued — see the map), and no `*UI` / `*Spec` pair, because none
1724
+ // is defined for bigint.
1725
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
1726
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_HIDDEN] = ZodDecorator_FunctionType[ZodDecorator.IS_HIDDEN];
1727
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_NOT_EDITABLE] = ZodDecorator_FunctionType[ZodDecorator.IS_NOT_EDITABLE];
1728
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
1729
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1730
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
1731
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
1732
+ zodInstance.ZodBigInt.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
1733
+ zodInstance.ZodBigInt.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
1734
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
1735
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
1736
+ zodInstance.ZodBigInt.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
1737
+ zodInstance.ZodBigInt.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
1738
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_BUSINESS_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_BUSINESS_KEY];
1739
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
1740
+ zodInstance.ZodBigInt.prototype[ZodDecorator.SHOW_WHEN] = ZodDecorator_FunctionType[ZodDecorator.SHOW_WHEN];
1741
+ zodInstance.ZodBigInt.prototype[ZodDecorator.IS_DRAFT_RELAXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DRAFT_RELAXED];
1742
+ zodInstance.ZodBigInt.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
799
1743
  zodInstance.ZodBoolean.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
800
1744
  zodInstance.ZodBoolean.prototype[ZodDecorator.IS_FOREIGN_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_FOREIGN_KEY];
801
1745
  zodInstance.ZodBoolean.prototype[ZodDecorator.IS_HIDDEN] = ZodDecorator_FunctionType[ZodDecorator.IS_HIDDEN];
@@ -803,6 +1747,12 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
803
1747
  // New decorators
804
1748
  zodInstance.ZodBoolean.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
805
1749
  zodInstance.ZodBoolean.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1750
+ zodInstance.ZodBoolean.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
1751
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
1752
+ zodInstance.ZodBoolean.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
1753
+ zodInstance.ZodBoolean.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
1754
+ zodInstance.ZodBoolean.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
1755
+ zodInstance.ZodBoolean.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
806
1756
  zodInstance.ZodBoolean.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
807
1757
  zodInstance.ZodBoolean.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
808
1758
  zodInstance.ZodBoolean.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
@@ -810,6 +1760,13 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
810
1760
  zodInstance.ZodBoolean.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
811
1761
  // Unified UI decorator
812
1762
  zodInstance.ZodBoolean.prototype[ZodDecorator.BOOLEAN_UI] = ZodDecorator_FunctionType[ZodDecorator.BOOLEAN_UI];
1763
+ // Field specification decorator
1764
+ zodInstance.ZodBoolean.prototype[ZodDecorator.BOOLEAN_SPEC] = ZodDecorator_FunctionType[ZodDecorator.BOOLEAN_SPEC];
1765
+ // Generic form-field decorators (conditional visibility / draft relaxation).
1766
+ zodInstance.ZodBoolean.prototype[ZodDecorator.SHOW_WHEN] = ZodDecorator_FunctionType[ZodDecorator.SHOW_WHEN];
1767
+ zodInstance.ZodBoolean.prototype[ZodDecorator.IS_DRAFT_RELAXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DRAFT_RELAXED];
1768
+ // Business key marker — the map mirrors IS_DB_INDEXED's primitive set, and that IS installed here.
1769
+ zodInstance.ZodBoolean.prototype[ZodDecorator.IS_BUSINESS_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_BUSINESS_KEY];
813
1770
  zodInstance.ZodBoolean.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
814
1771
  zodInstance.ZodDate.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
815
1772
  zodInstance.ZodDate.prototype[ZodDecorator.IS_FOREIGN_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_FOREIGN_KEY];
@@ -818,6 +1775,12 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
818
1775
  // New decorators
819
1776
  zodInstance.ZodDate.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
820
1777
  zodInstance.ZodDate.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1778
+ zodInstance.ZodDate.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
1779
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
1780
+ zodInstance.ZodDate.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
1781
+ zodInstance.ZodDate.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
1782
+ zodInstance.ZodDate.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
1783
+ zodInstance.ZodDate.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
821
1784
  zodInstance.ZodDate.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
822
1785
  zodInstance.ZodDate.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
823
1786
  zodInstance.ZodDate.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
@@ -827,6 +1790,13 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
827
1790
  zodInstance.ZodDate.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
828
1791
  // Unified UI decorator
829
1792
  zodInstance.ZodDate.prototype[ZodDecorator.DATE_UI] = ZodDecorator_FunctionType[ZodDecorator.DATE_UI];
1793
+ // Field specification decorator
1794
+ zodInstance.ZodDate.prototype[ZodDecorator.DATE_SPEC] = ZodDecorator_FunctionType[ZodDecorator.DATE_SPEC];
1795
+ // Generic form-field decorators (conditional visibility / draft relaxation).
1796
+ zodInstance.ZodDate.prototype[ZodDecorator.SHOW_WHEN] = ZodDecorator_FunctionType[ZodDecorator.SHOW_WHEN];
1797
+ zodInstance.ZodDate.prototype[ZodDecorator.IS_DRAFT_RELAXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DRAFT_RELAXED];
1798
+ // Business key marker — a date is a legitimate component of a natural key (e.g. [accountId, statementDate]).
1799
+ zodInstance.ZodDate.prototype[ZodDecorator.IS_BUSINESS_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_BUSINESS_KEY];
830
1800
  zodInstance.ZodDate.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
831
1801
  zodInstance.ZodOptional.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
832
1802
  zodInstance.ZodOptional.prototype[ZodDecorator.IS_FOREIGN_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_FOREIGN_KEY];
@@ -836,13 +1806,33 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
836
1806
  // New decorators
837
1807
  zodInstance.ZodOptional.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
838
1808
  zodInstance.ZodOptional.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1809
+ zodInstance.ZodOptional.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
1810
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
1811
+ zodInstance.ZodOptional.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
1812
+ zodInstance.ZodOptional.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
1813
+ zodInstance.ZodOptional.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
1814
+ zodInstance.ZodOptional.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
1815
+ // RAG source — ZodOptional is the ONE wrapper with a hand-enumerated block (its siblings get every
1816
+ // FunctionType entry from the blanket wrapper loop below), so this line is what keeps
1817
+ // `z.string().optional().ragSource()` from being the order-dependent half-live trap the
1818
+ // ZodOptional.showWhen note further down records.
1819
+ zodInstance.ZodOptional.prototype[ZodDecorator.RAG_SOURCE] = ZodDecorator_FunctionType[ZodDecorator.RAG_SOURCE];
839
1820
  zodInstance.ZodOptional.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
840
1821
  zodInstance.ZodOptional.prototype[ZodDecorator.IS_DISCRIMINATOR] = ZodDecorator_FunctionType[ZodDecorator.IS_DISCRIMINATOR];
841
1822
  zodInstance.ZodOptional.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
842
1823
  zodInstance.ZodOptional.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
843
1824
  // Database constraint decorators - optional wrapper types need isUnique for z.string().isUnique().optional() pattern
844
1825
  zodInstance.ZodOptional.prototype[ZodDecorator.IS_UNIQUE] = ZodDecorator_FunctionType[ZodDecorator.IS_UNIQUE];
1826
+ // Business key marker (data-seeding subsystem) — supports z.string().isBusinessKey().optional() pattern
1827
+ zodInstance.ZodOptional.prototype[ZodDecorator.IS_BUSINESS_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_BUSINESS_KEY];
845
1828
  // Ephemeral field decorator
1829
+ // Conditional visibility. The `ZodOptional` interface below DECLARES `showWhen`, and both sibling
1830
+ // wrappers already carry it at runtime (ZodDefault / ZodNullable get it from the blanket wrapper
1831
+ // loop), so its absence here was an omission, not a policy: `z.string().optional().showWhen(...)`
1832
+ // type-checked and threw, while `z.string().optional().isDBIndexed().showWhen(...)` worked. That
1833
+ // is precisely the order-dependent half-live trap the IMPERSONALIZE_WITH comment at the top of
1834
+ // this file warns about. Found 2026-08-12 by the declared-vs-installed parity contract.
1835
+ zodInstance.ZodOptional.prototype[ZodDecorator.SHOW_WHEN] = ZodDecorator_FunctionType[ZodDecorator.SHOW_WHEN];
846
1836
  zodInstance.ZodOptional.prototype[ZodDecorator.IS_EPHEMERAL] = ZodDecorator_FunctionType[ZodDecorator.IS_EPHEMERAL];
847
1837
  // CRDT field decorator
848
1838
  zodInstance.ZodOptional.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
@@ -852,8 +1842,49 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
852
1842
  zodInstance.ZodOptional.prototype[ZodDecorator.NUMBER_UI] = ZodDecorator_FunctionType[ZodDecorator.NUMBER_UI];
853
1843
  zodInstance.ZodOptional.prototype[ZodDecorator.ENUM_UI] = ZodDecorator_FunctionType[ZodDecorator.ENUM_UI];
854
1844
  zodInstance.ZodOptional.prototype[ZodDecorator.DATE_UI] = ZodDecorator_FunctionType[ZodDecorator.DATE_UI];
1845
+ // The remaining `*_UI` methods MUST also be installed on ZodOptional so an OPTIONAL
1846
+ // field can carry them in a `*.ui-behavior.tsx` `fields` block (e.g.
1847
+ // `avatar.fileUI(...)`). These mirror both the `ZodOptional` type augmentation and the
1848
+ // `ZodDecorator_ApplyableTypes` runtime list — all three must stay in sync, or the type
1849
+ // says the method exists while the prototype lacks it (runtime "X is not a function").
1850
+ zodInstance.ZodOptional.prototype[ZodDecorator.DATETIME_UI] = ZodDecorator_FunctionType[ZodDecorator.DATETIME_UI];
1851
+ zodInstance.ZodOptional.prototype[ZodDecorator.TIME_UI] = ZodDecorator_FunctionType[ZodDecorator.TIME_UI];
1852
+ zodInstance.ZodOptional.prototype[ZodDecorator.MONEY_UI] = ZodDecorator_FunctionType[ZodDecorator.MONEY_UI];
1853
+ zodInstance.ZodOptional.prototype[ZodDecorator.CODE_UI] = ZodDecorator_FunctionType[ZodDecorator.CODE_UI];
1854
+ zodInstance.ZodOptional.prototype[ZodDecorator.FILE_UI] = ZodDecorator_FunctionType[ZodDecorator.FILE_UI];
1855
+ zodInstance.ZodOptional.prototype[ZodDecorator.DURATION_UI] = ZodDecorator_FunctionType[ZodDecorator.DURATION_UI];
1856
+ zodInstance.ZodOptional.prototype[ZodDecorator.PHONE_UI] = ZodDecorator_FunctionType[ZodDecorator.PHONE_UI];
1857
+ zodInstance.ZodOptional.prototype[ZodDecorator.BIGDECIMAL_UI] = ZodDecorator_FunctionType[ZodDecorator.BIGDECIMAL_UI];
1858
+ zodInstance.ZodOptional.prototype[ZodDecorator.FOREIGN_KEY_UI] = ZodDecorator_FunctionType[ZodDecorator.FOREIGN_KEY_UI];
855
1859
  zodInstance.ZodOptional.prototype[ZodDecorator.ARRAY_UI] = ZodDecorator_FunctionType[ZodDecorator.ARRAY_UI];
856
1860
  zodInstance.ZodOptional.prototype[ZodDecorator.OBJECT_UI] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_UI];
1861
+ // Field specification decorators (ZodOptional can wrap any primitive/object)
1862
+ zodInstance.ZodOptional.prototype[ZodDecorator.STRING_SPEC] = ZodDecorator_FunctionType[ZodDecorator.STRING_SPEC];
1863
+ zodInstance.ZodOptional.prototype[ZodDecorator.NUMBER_SPEC] = ZodDecorator_FunctionType[ZodDecorator.NUMBER_SPEC];
1864
+ zodInstance.ZodOptional.prototype[ZodDecorator.BOOLEAN_SPEC] = ZodDecorator_FunctionType[ZodDecorator.BOOLEAN_SPEC];
1865
+ zodInstance.ZodOptional.prototype[ZodDecorator.DATE_SPEC] = ZodDecorator_FunctionType[ZodDecorator.DATE_SPEC];
1866
+ zodInstance.ZodOptional.prototype[ZodDecorator.DATETIME_SPEC] = ZodDecorator_FunctionType[ZodDecorator.DATETIME_SPEC];
1867
+ zodInstance.ZodOptional.prototype[ZodDecorator.TIME_SPEC] = ZodDecorator_FunctionType[ZodDecorator.TIME_SPEC];
1868
+ zodInstance.ZodOptional.prototype[ZodDecorator.ENUM_SPEC] = ZodDecorator_FunctionType[ZodDecorator.ENUM_SPEC];
1869
+ zodInstance.ZodOptional.prototype[ZodDecorator.MONEY_SPEC] = ZodDecorator_FunctionType[ZodDecorator.MONEY_SPEC];
1870
+ zodInstance.ZodOptional.prototype[ZodDecorator.CODE_SPEC] = ZodDecorator_FunctionType[ZodDecorator.CODE_SPEC];
1871
+ zodInstance.ZodOptional.prototype[ZodDecorator.FILE_SPEC] = ZodDecorator_FunctionType[ZodDecorator.FILE_SPEC];
1872
+ zodInstance.ZodOptional.prototype[ZodDecorator.DURATION_SPEC] = ZodDecorator_FunctionType[ZodDecorator.DURATION_SPEC];
1873
+ zodInstance.ZodOptional.prototype[ZodDecorator.PHONE_SPEC] = ZodDecorator_FunctionType[ZodDecorator.PHONE_SPEC];
1874
+ zodInstance.ZodOptional.prototype[ZodDecorator.BIGDECIMAL_SPEC] = ZodDecorator_FunctionType[ZodDecorator.BIGDECIMAL_SPEC];
1875
+ zodInstance.ZodOptional.prototype[ZodDecorator.FOREIGN_KEY_SPEC] = ZodDecorator_FunctionType[ZodDecorator.FOREIGN_KEY_SPEC];
1876
+ zodInstance.ZodOptional.prototype[ZodDecorator.ARRAY_SPEC] = ZodDecorator_FunctionType[ZodDecorator.ARRAY_SPEC];
1877
+ zodInstance.ZodOptional.prototype[ZodDecorator.OBJECT_SPEC] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_SPEC];
1878
+ // Generic form-field decorators (conditional visibility / draft relaxation).
1879
+ zodInstance.ZodOptional.prototype[ZodDecorator.IS_DRAFT_RELAXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DRAFT_RELAXED];
1880
+ // `z.date().optional().ttl()`, `z.string().optional().isPassword()` and
1881
+ // `z.object({…}).optional().businessKeySet([…])` are all natural authoring orders the map already
1882
+ // claims; each was half-live (worked only after another decorator) until 2026-08-12.
1883
+ zodInstance.ZodOptional.prototype[ZodDecorator.TTL] = ZodDecorator_FunctionType[ZodDecorator.TTL];
1884
+ zodInstance.ZodOptional.prototype[ZodDecorator.IS_PASSWORD] = ZodDecorator_FunctionType[ZodDecorator.IS_PASSWORD];
1885
+ zodInstance.ZodOptional.prototype[ZodDecorator.IS_OTP] = ZodDecorator_FunctionType[ZodDecorator.IS_OTP];
1886
+ zodInstance.ZodOptional.prototype[ZodDecorator.IS_COLOR] = ZodDecorator_FunctionType[ZodDecorator.IS_COLOR];
1887
+ zodInstance.ZodOptional.prototype[ZodDecorator.OBJECT_BUSINESS_KEY_SET] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_BUSINESS_KEY_SET];
857
1888
  zodInstance.ZodOptional.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
858
1889
  zodInstance.ZodEnum.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
859
1890
  zodInstance.ZodEnum.prototype[ZodDecorator.IS_FOREIGN_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_FOREIGN_KEY];
@@ -863,14 +1894,27 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
863
1894
  // New decorators
864
1895
  zodInstance.ZodEnum.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
865
1896
  zodInstance.ZodEnum.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1897
+ zodInstance.ZodEnum.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
1898
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
1899
+ zodInstance.ZodEnum.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
1900
+ zodInstance.ZodEnum.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
1901
+ zodInstance.ZodEnum.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
1902
+ zodInstance.ZodEnum.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
866
1903
  zodInstance.ZodEnum.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
867
1904
  zodInstance.ZodEnum.prototype[ZodDecorator.IS_DISCRIMINATOR] = ZodDecorator_FunctionType[ZodDecorator.IS_DISCRIMINATOR];
868
1905
  zodInstance.ZodEnum.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
869
1906
  zodInstance.ZodEnum.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
1907
+ // Business key marker (data-seeding subsystem)
1908
+ zodInstance.ZodEnum.prototype[ZodDecorator.IS_BUSINESS_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_BUSINESS_KEY];
870
1909
  // CRDT field decorator
871
1910
  zodInstance.ZodEnum.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
872
1911
  // Unified UI decorator
873
1912
  zodInstance.ZodEnum.prototype[ZodDecorator.ENUM_UI] = ZodDecorator_FunctionType[ZodDecorator.ENUM_UI];
1913
+ // Field specification decorator
1914
+ zodInstance.ZodEnum.prototype[ZodDecorator.ENUM_SPEC] = ZodDecorator_FunctionType[ZodDecorator.ENUM_SPEC];
1915
+ // Generic form-field decorators (conditional visibility / draft relaxation).
1916
+ zodInstance.ZodEnum.prototype[ZodDecorator.SHOW_WHEN] = ZodDecorator_FunctionType[ZodDecorator.SHOW_WHEN];
1917
+ zodInstance.ZodEnum.prototype[ZodDecorator.IS_DRAFT_RELAXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DRAFT_RELAXED];
874
1918
  zodInstance.ZodEnum.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
875
1919
  zodInstance.ZodArray.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
876
1920
  zodInstance.ZodArray.prototype[ZodDecorator.IS_FOREIGN_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_FOREIGN_KEY];
@@ -881,14 +1925,28 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
881
1925
  // New decorators
882
1926
  zodInstance.ZodArray.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
883
1927
  zodInstance.ZodArray.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1928
+ zodInstance.ZodArray.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
1929
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
1930
+ zodInstance.ZodArray.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
1931
+ zodInstance.ZodArray.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
1932
+ zodInstance.ZodArray.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
1933
+ zodInstance.ZodArray.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
884
1934
  zodInstance.ZodArray.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
885
1935
  zodInstance.ZodArray.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
886
1936
  zodInstance.ZodArray.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
887
1937
  // CRDT field decorator
888
1938
  zodInstance.ZodArray.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
1939
+ // Generic form-field decorators (conditional visibility / draft relaxation).
1940
+ zodInstance.ZodArray.prototype[ZodDecorator.SHOW_WHEN] = ZodDecorator_FunctionType[ZodDecorator.SHOW_WHEN];
1941
+ zodInstance.ZodArray.prototype[ZodDecorator.IS_DRAFT_RELAXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DRAFT_RELAXED];
889
1942
  zodInstance.ZodArray.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
1943
+ zodInstance.ZodArray.prototype[ZodDecorator.ARRAY_SPEC] = ZodDecorator_FunctionType[ZodDecorator.ARRAY_SPEC];
890
1944
  // Wrapper types (ZodDefault, ZodNullable) need ALL decorators for chaining
891
1945
  // e.g. z.date().default(...).excludeFromCreate().isNotEditable().showWhen(...)
1946
+ //
1947
+ // This loop copies EVERY `ZodDecorator_FunctionType` entry, so it automatically covers new fluent
1948
+ // methods (e.g. `impersonalizeWith`) on both wrappers. `.nullish()` needs no entry of its own —
1949
+ // Zod builds it as `.nullable().optional()`, so its OUTER type is ZodOptional, installed above.
892
1950
  for (const wrapperName of ['ZodDefault', 'ZodNullable']) {
893
1951
  const wrapperCtor = zi[wrapperName];
894
1952
  if (wrapperCtor?.prototype) {
@@ -910,6 +1968,12 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
910
1968
  // New decorators
911
1969
  zi.ZodUnion.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
912
1970
  zi.ZodUnion.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1971
+ zi.ZodUnion.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
1972
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
1973
+ zi.ZodUnion.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
1974
+ zi.ZodUnion.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
1975
+ zi.ZodUnion.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
1976
+ zi.ZodUnion.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
913
1977
  zi.ZodUnion.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
914
1978
  zi.ZodUnion.prototype[ZodDecorator.IS_DISCRIMINATOR] = ZodDecorator_FunctionType[ZodDecorator.IS_DISCRIMINATOR];
915
1979
  zi.ZodUnion.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
@@ -921,20 +1985,44 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
921
1985
  // Object / record decorators
922
1986
  if (zi.ZodObject?.prototype) {
923
1987
  zi.ZodObject.prototype[ZodDecorator.OBJECT_UI] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_UI];
1988
+ zi.ZodObject.prototype[ZodDecorator.OBJECT_SPEC] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_SPEC];
924
1989
  zi.ZodObject.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
925
1990
  zi.ZodObject.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1991
+ zi.ZodObject.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
1992
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
1993
+ zi.ZodObject.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
1994
+ zi.ZodObject.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
1995
+ zi.ZodObject.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
1996
+ zi.ZodObject.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
926
1997
  zi.ZodObject.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
927
1998
  zi.ZodObject.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
928
1999
  zi.ZodObject.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
929
2000
  // CRDT field decorator
930
2001
  zi.ZodObject.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
2002
+ // Composite business key (data-seeding subsystem)
2003
+ zi.ZodObject.prototype[ZodDecorator.OBJECT_BUSINESS_KEY_SET] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_BUSINESS_KEY_SET];
2004
+ // Generic form-field decorators (conditional visibility / draft relaxation).
2005
+ zi.ZodObject.prototype[ZodDecorator.SHOW_WHEN] = ZodDecorator_FunctionType[ZodDecorator.SHOW_WHEN];
2006
+ zi.ZodObject.prototype[ZodDecorator.IS_DRAFT_RELAXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DRAFT_RELAXED];
2007
+ // A composite field is indexable, hideable and non-editable like any other. `z_file()` already
2008
+ // declared all three on its own schema type, which is the framework stating that objects carry them.
2009
+ zi.ZodObject.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
2010
+ zi.ZodObject.prototype[ZodDecorator.IS_HIDDEN] = ZodDecorator_FunctionType[ZodDecorator.IS_HIDDEN];
2011
+ zi.ZodObject.prototype[ZodDecorator.IS_NOT_EDITABLE] = ZodDecorator_FunctionType[ZodDecorator.IS_NOT_EDITABLE];
931
2012
  zi.ZodObject.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
932
2013
  }
933
2014
  if (zi.ZodRecord?.prototype) {
934
2015
  zi.ZodRecord.prototype[ZodDecorator.OBJECT_UI] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_UI];
2016
+ zi.ZodRecord.prototype[ZodDecorator.OBJECT_SPEC] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_SPEC];
935
2017
  // New decorators
936
2018
  zi.ZodRecord.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
937
2019
  zi.ZodRecord.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
2020
+ zi.ZodRecord.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
2021
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
2022
+ zi.ZodRecord.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
2023
+ zi.ZodRecord.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
2024
+ zi.ZodRecord.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
2025
+ zi.ZodRecord.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
938
2026
  zi.ZodRecord.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
939
2027
  zi.ZodRecord.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
940
2028
  zi.ZodRecord.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
@@ -953,9 +2041,16 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
953
2041
  zi.ZodMap.prototype[ZodDecorator.IS_HIDDEN] = ZodDecorator_FunctionType[ZodDecorator.IS_HIDDEN];
954
2042
  zi.ZodMap.prototype[ZodDecorator.IS_NOT_EDITABLE] = ZodDecorator_FunctionType[ZodDecorator.IS_NOT_EDITABLE];
955
2043
  zi.ZodMap.prototype[ZodDecorator.OBJECT_UI] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_UI];
2044
+ zi.ZodMap.prototype[ZodDecorator.OBJECT_SPEC] = ZodDecorator_FunctionType[ZodDecorator.OBJECT_SPEC];
956
2045
  // New decorators
957
2046
  zi.ZodMap.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
958
2047
  zi.ZodMap.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
2048
+ zi.ZodMap.prototype[ZodDecorator.IS_WRITE_ONLY_SECRET] = ZodDecorator_FunctionType[ZodDecorator.IS_WRITE_ONLY_SECRET];
2049
+ // Impersonalization scrub treatment — mirrors IS_WRITE_ONLY_SECRET (same all-types surface).
2050
+ zi.ZodMap.prototype[ZodDecorator.IMPERSONALIZE_WITH] = ZodDecorator_FunctionType[ZodDecorator.IMPERSONALIZE_WITH];
2051
+ zi.ZodMap.prototype[ZodDecorator.PORTABILITY_PROVENANCE] = ZodDecorator_FunctionType[ZodDecorator.PORTABILITY_PROVENANCE];
2052
+ zi.ZodMap.prototype[ZodDecorator.DATA_CATEGORIES] = ZodDecorator_FunctionType[ZodDecorator.DATA_CATEGORIES];
2053
+ zi.ZodMap.prototype[ZodDecorator.IS_AUDIT_EVIDENCE] = ZodDecorator_FunctionType[ZodDecorator.IS_AUDIT_EVIDENCE];
959
2054
  zi.ZodMap.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
960
2055
  zi.ZodMap.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
961
2056
  zi.ZodMap.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
@@ -963,131 +2058,55 @@ export function ensureZodDecoratorsLoaded(zodInstance = z) {
963
2058
  zi.ZodMap.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
964
2059
  zi.ZodMap.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
965
2060
  }
966
- // Helper function to add decorators to Zod string refinement types
967
- function addDecoratorsToZodStringRefinement(constructorName) {
968
- const Candidate = zi[constructorName];
969
- if (Candidate && typeof Candidate === 'object' && 'prototype' in Candidate) {
970
- const Constructor = Candidate;
971
- // Patch methods first, then add decorators
972
- patchPrototypeMethodsForMetadataPreservation(Constructor.prototype, zodStringMethodsToWrap);
973
- Constructor.prototype[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
974
- Constructor.prototype[ZodDecorator.IS_FOREIGN_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_FOREIGN_KEY];
975
- Constructor.prototype[ZodDecorator.IS_HIDDEN] = ZodDecorator_FunctionType[ZodDecorator.IS_HIDDEN];
976
- Constructor.prototype[ZodDecorator.IS_NOT_EDITABLE] = ZodDecorator_FunctionType[ZodDecorator.IS_NOT_EDITABLE];
977
- // New decorators
978
- Constructor.prototype[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
979
- Constructor.prototype[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
980
- Constructor.prototype[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
981
- Constructor.prototype[ZodDecorator.IS_DISCRIMINATOR] = ZodDecorator_FunctionType[ZodDecorator.IS_DISCRIMINATOR];
982
- Constructor.prototype[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
983
- Constructor.prototype[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
984
- // Database constraint decorators - format validators like email/uuid are commonly used as unique identifiers
985
- Constructor.prototype[ZodDecorator.IS_UNIQUE] = ZodDecorator_FunctionType[ZodDecorator.IS_UNIQUE];
986
- // Ephemeral field decorator
987
- Constructor.prototype[ZodDecorator.IS_EPHEMERAL] = ZodDecorator_FunctionType[ZodDecorator.IS_EPHEMERAL];
988
- // CRDT field decorator
989
- Constructor.prototype[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
990
- Constructor.prototype.addDecorators = ZodDecorator_FunctionAddDecorators;
991
- }
992
- }
993
- // Add decorator support to Zod string refinement types
994
- addDecoratorsToZodStringRefinement('ZodEmail');
995
- addDecoratorsToZodStringRefinement('ZodUUID');
996
- addDecoratorsToZodStringRefinement('ZodURL');
997
- addDecoratorsToZodStringRefinement('ZodHttpUrl');
998
- addDecoratorsToZodStringRefinement('ZodHostname');
999
- addDecoratorsToZodStringRefinement('ZodEmoji');
1000
- addDecoratorsToZodStringRefinement('ZodBase64');
1001
- addDecoratorsToZodStringRefinement('ZodBase64Url');
1002
- addDecoratorsToZodStringRefinement('ZodHex');
1003
- addDecoratorsToZodStringRefinement('ZodJWT');
1004
- addDecoratorsToZodStringRefinement('ZodNanoId');
1005
- addDecoratorsToZodStringRefinement('ZodCuid');
1006
- addDecoratorsToZodStringRefinement('ZodCuid2');
1007
- addDecoratorsToZodStringRefinement('ZodULID');
1008
- addDecoratorsToZodStringRefinement('ZodIPv4');
1009
- addDecoratorsToZodStringRefinement('ZodIPv6');
1010
- addDecoratorsToZodStringRefinement('ZodMac');
1011
- addDecoratorsToZodStringRefinement('ZodCidrV4');
1012
- addDecoratorsToZodStringRefinement('ZodCidrV6');
1013
- addDecoratorsToZodStringRefinement('ZodHash');
1014
- addDecoratorsToZodStringRefinement('ZodISODate');
1015
- addDecoratorsToZodStringRefinement('ZodISOTime');
1016
- addDecoratorsToZodStringRefinement('ZodISODatetime');
1017
- addDecoratorsToZodStringRefinement('ZodISODateTime');
1018
- addDecoratorsToZodStringRefinement('ZodISODuration');
1019
2061
  // =============================================================================
1020
- // STEP 3: Dynamically patch format validator prototypes
1021
- // In Zod 4, z.email(), z.url() etc. may return schemas whose constructors
1022
- // aren't exposed on the z namespace. We discover them by creating instances.
2062
+ // STEP 3: The string-format refinement types (`z.email()`, `z.uuid()`, `z.hostname()`, `z.iso.*`)
2063
+ //
2064
+ // ONE prototype covers all of them, and it is the same one the type layer names.
2065
+ //
2066
+ // Zod v4 does NOT use prototype inheritance — `Object.getPrototypeOf(z.email())` is
2067
+ // `ZodEmail.prototype`, whose own proto is `Object.prototype`, and Zod's schema methods are
2068
+ // INSTANCE properties. What connects them is an explicit extension hook inside `$constructor`,
2069
+ // commented "support prototype modifications" in Zod's own source: on every `init`, each key of
2070
+ // that trait's prototype is copied onto the instance (`inst[k] = proto[k].bind(inst)`), for each
2071
+ // trait in the chain.
2072
+ //
2073
+ // And the classic init chain is the crux of the original defect (measured, zod@4.3.6):
2074
+ //
2075
+ // ZodEmail.init → $ZodEmail.init + ZodStringFormat.init
2076
+ // ZodStringFormat.init → $ZodStringFormat.init + _ZodString.init
2077
+ // ZodString.init → $ZodString.init + _ZodString.init + the instance methods
2078
+ //
2079
+ // A format type NEVER runs classic `ZodString.init`. So decorators installed only on
2080
+ // `ZodString.prototype` cannot reach `z.email()` at all — which is exactly why `isPrimaryKey`,
2081
+ // `isBusinessKey`, `isPassword`, `isOtp` and `isColor` were absent from every refinement type
2082
+ // while TypeScript declared them, and `z.uuid().isPrimaryKey()` threw.
2083
+ //
2084
+ // `ZodStringFormat` is therefore the single correct base: every string-format type calls its
2085
+ // `init`, including `ZodCustomStringFormat`, which backs `z.hex()`, `z.hostname()` and every
2086
+ // user-defined `z.stringFormat(...)`. Two prototypes, mirroring the two `declare module 'zod'`
2087
+ // interfaces one-for-one.
2088
+ //
2089
+ // WHAT THIS REPLACED, because it is the whole lesson. Until 2026-08-12 this step was 25 hand-listed
2090
+ // constructor names plus 27 hand-listed factory probes. Both lists had rotted and neither was ever
2091
+ // the mechanism: the name loop tested `typeof Candidate === 'object'` on a CLASS (a function), so
2092
+ // all 25 calls were silent no-ops, and at least eleven of the names did not exist in Zod 4
2093
+ // (`ZodHttpUrl`, `ZodHostname`, `ZodHex`, `ZodNanoId`, `ZodCuid`, `ZodCuid2`, `ZodMac`,
2094
+ // `ZodCidrV4`, `ZodCidrV6`, `ZodHash`, `ZodISODatetime`). The probe list, meanwhile, omitted
2095
+ // `hostname`, `hex`, `guid`, `e164`, `mac`, `xid`, `ksuid` and `base64url`, leaving those formats
2096
+ // with ZERO decorators. Verified by removing all 52 calls: parity holds on these two bases alone.
2097
+ // Do NOT reintroduce a per-format list — it is a second enumeration of Zod's format catalogue that
2098
+ // no one will maintain, and `string-format-decorator-parity.contract.test.ts` discovers the real
2099
+ // catalogue from the running Zod and fails loudly if either base ever stops covering it.
1023
2100
  // =============================================================================
1024
- const patchedPrototypes = new Set();
1025
- function patchFormatValidatorPrototype(factoryFn) {
1026
- try {
1027
- const schema = factoryFn();
1028
- const proto = Object.getPrototypeOf(schema);
1029
- // Skip if already patched or if it's ZodString (already handled)
1030
- if (!proto || patchedPrototypes.has(proto))
1031
- return;
1032
- if (proto === zodInstance.ZodString.prototype)
1033
- return;
1034
- // Check if already has decorators
1035
- if (typeof proto[ZodDecorator.IS_DB_INDEXED] === 'function') {
1036
- patchedPrototypes.add(proto);
1037
- return;
1038
- }
1039
- // Patch this prototype
1040
- patchPrototypeMethodsForMetadataPreservation(proto, zodStringMethodsToWrap);
1041
- proto[ZodDecorator.IS_DB_INDEXED] = ZodDecorator_FunctionType[ZodDecorator.IS_DB_INDEXED];
1042
- proto[ZodDecorator.IS_FOREIGN_KEY] = ZodDecorator_FunctionType[ZodDecorator.IS_FOREIGN_KEY];
1043
- proto[ZodDecorator.IS_HIDDEN] = ZodDecorator_FunctionType[ZodDecorator.IS_HIDDEN];
1044
- proto[ZodDecorator.IS_NOT_EDITABLE] = ZodDecorator_FunctionType[ZodDecorator.IS_NOT_EDITABLE];
1045
- // New decorators
1046
- proto[ZodDecorator.IS_SUMMARY_FIELD] = ZodDecorator_FunctionType[ZodDecorator.IS_SUMMARY_FIELD];
1047
- proto[ZodDecorator.IS_BACKEND_ONLY] = ZodDecorator_FunctionType[ZodDecorator.IS_BACKEND_ONLY];
1048
- proto[ZodDecorator.IS_VIRTUAL] = ZodDecorator_FunctionType[ZodDecorator.IS_VIRTUAL];
1049
- proto[ZodDecorator.IS_DISCRIMINATOR] = ZodDecorator_FunctionType[ZodDecorator.IS_DISCRIMINATOR];
1050
- proto[ZodDecorator.EXCLUDE_FROM_CREATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_CREATE];
1051
- proto[ZodDecorator.EXCLUDE_FROM_UPDATE] = ZodDecorator_FunctionType[ZodDecorator.EXCLUDE_FROM_UPDATE];
1052
- // Database constraint decorators - format validators like email/uuid are commonly used as unique identifiers
1053
- proto[ZodDecorator.IS_UNIQUE] = ZodDecorator_FunctionType[ZodDecorator.IS_UNIQUE];
1054
- // Format validators like uuid/email/url are still string-backed primitives,
1055
- // so platform presets must be able to apply string display/edit policies.
1056
- proto[ZodDecorator.STRING_UI] = ZodDecorator_FunctionType[ZodDecorator.STRING_UI];
1057
- // Ephemeral field decorator
1058
- proto[ZodDecorator.IS_EPHEMERAL] = ZodDecorator_FunctionType[ZodDecorator.IS_EPHEMERAL];
1059
- // CRDT field decorator
1060
- proto[ZodDecorator.IS_CRDT] = ZodDecorator_FunctionType[ZodDecorator.IS_CRDT];
1061
- proto.addDecorators = ZodDecorator_FunctionAddDecorators;
1062
- patchedPrototypes.add(proto);
1063
- }
1064
- catch {
1065
- // Factory function might not exist in this Zod version
1066
- }
2101
+ // NOTE the `typeof === 'function'` test. A Zod schema class IS a function; the loop this replaced
2102
+ // tested `typeof === 'object'` and was therefore a no-op at all 25 of its call sites.
2103
+ const stringFormatBase = zi.ZodStringFormat;
2104
+ if (typeof stringFormatBase === 'function' && stringFormatBase.prototype) {
2105
+ installStringDecoratorSurface(stringFormatBase.prototype, zodStringMethodsToWrap);
1067
2106
  }
1068
- // Patch all format validators by creating instances
1069
- patchFormatValidatorPrototype(() => zodInstance.email());
1070
- patchFormatValidatorPrototype(() => zodInstance.url());
1071
- patchFormatValidatorPrototype(() => zodInstance.uuid());
1072
- patchFormatValidatorPrototype(() => zodInstance.cuid());
1073
- patchFormatValidatorPrototype(() => zodInstance.cuid2());
1074
- patchFormatValidatorPrototype(() => zodInstance.ulid());
1075
- patchFormatValidatorPrototype(() => zodInstance.nanoid());
1076
- patchFormatValidatorPrototype(() => zodInstance.base64());
1077
- patchFormatValidatorPrototype(() => zodInstance.jwt());
1078
- patchFormatValidatorPrototype(() => zodInstance.emoji());
1079
- patchFormatValidatorPrototype(() => zodInstance.ipv4());
1080
- patchFormatValidatorPrototype(() => zodInstance.ipv6());
1081
- patchFormatValidatorPrototype(() => zodInstance.cidrv4());
1082
- patchFormatValidatorPrototype(() => zodInstance.cidrv6());
1083
- // Patch z.iso.* format validators
1084
- patchFormatValidatorPrototype(() => zodInstance.iso.datetime());
1085
- patchFormatValidatorPrototype(() => zodInstance.iso.date());
1086
- patchFormatValidatorPrototype(() => zodInstance.iso.time());
1087
- patchFormatValidatorPrototype(() => zodInstance.iso.duration());
1088
2107
  // Note: z.range() is exported as standalone `z_range()` function.
1089
2108
  return zodInstance;
1090
2109
  }
1091
2110
  // Extend the Zod prototypes with the decorator methods (apply to the default imported instance)
1092
2111
  ensureZodDecoratorsLoaded(z);
1093
- //# sourceMappingURL=zod.module-override.js.map
2112
+ //# sourceMappingURL=zod.module-override.js.map