@columnus/shared 0.1.47

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 (206) hide show
  1. package/LICENSE +21 -0
  2. package/dist/apiProfile.d.ts +1072 -0
  3. package/dist/apiProfile.js +4210 -0
  4. package/dist/apiProfile.js.map +1 -0
  5. package/dist/apiProfileSlug.d.ts +11 -0
  6. package/dist/apiProfileSlug.js +39 -0
  7. package/dist/apiProfileSlug.js.map +1 -0
  8. package/dist/apiToken.d.ts +6 -0
  9. package/dist/apiToken.js +35 -0
  10. package/dist/apiToken.js.map +1 -0
  11. package/dist/betterAuthSession.d.ts +8 -0
  12. package/dist/betterAuthSession.js +57 -0
  13. package/dist/betterAuthSession.js.map +1 -0
  14. package/dist/bffHost.d.ts +36 -0
  15. package/dist/bffHost.js +74 -0
  16. package/dist/bffHost.js.map +1 -0
  17. package/dist/bffProtocol.d.ts +1357 -0
  18. package/dist/bffProtocol.js +4362 -0
  19. package/dist/bffProtocol.js.map +1 -0
  20. package/dist/bffRedact.d.ts +30 -0
  21. package/dist/bffRedact.js +55 -0
  22. package/dist/bffRedact.js.map +1 -0
  23. package/dist/ciPreviewEnv.d.ts +49 -0
  24. package/dist/ciPreviewEnv.js +143 -0
  25. package/dist/ciPreviewEnv.js.map +1 -0
  26. package/dist/clipboardTransfer.d.ts +25 -0
  27. package/dist/clipboardTransfer.js +4862 -0
  28. package/dist/clipboardTransfer.js.map +1 -0
  29. package/dist/convexSiteUrl.d.ts +73 -0
  30. package/dist/convexSiteUrl.js +137 -0
  31. package/dist/convexSiteUrl.js.map +1 -0
  32. package/dist/csv.d.ts +54 -0
  33. package/dist/csv.js +5499 -0
  34. package/dist/csv.js.map +1 -0
  35. package/dist/dataTransfer.d.ts +21 -0
  36. package/dist/dataTransfer.js +74 -0
  37. package/dist/dataTransfer.js.map +1 -0
  38. package/dist/dateValues.d.ts +18 -0
  39. package/dist/dateValues.js +73 -0
  40. package/dist/dateValues.js.map +1 -0
  41. package/dist/deployOutput.d.ts +3 -0
  42. package/dist/deployOutput.js +23 -0
  43. package/dist/deployOutput.js.map +1 -0
  44. package/dist/displayLabel.d.ts +13 -0
  45. package/dist/displayLabel.js +4342 -0
  46. package/dist/displayLabel.js.map +1 -0
  47. package/dist/displayTemplateGenerator.d.ts +11 -0
  48. package/dist/displayTemplateGenerator.js +98 -0
  49. package/dist/displayTemplateGenerator.js.map +1 -0
  50. package/dist/displayTypes.d.ts +10 -0
  51. package/dist/displayTypes.js +3 -0
  52. package/dist/displayTypes.js.map +1 -0
  53. package/dist/dotenv.d.ts +8 -0
  54. package/dist/dotenv.js +61 -0
  55. package/dist/dotenv.js.map +1 -0
  56. package/dist/erdLayout.d.ts +27 -0
  57. package/dist/erdLayout.js +78 -0
  58. package/dist/erdLayout.js.map +1 -0
  59. package/dist/fieldTypeFormat.d.ts +5 -0
  60. package/dist/fieldTypeFormat.js +63 -0
  61. package/dist/fieldTypeFormat.js.map +1 -0
  62. package/dist/fieldTypeMeta.d.ts +50 -0
  63. package/dist/fieldTypeMeta.js +84 -0
  64. package/dist/fieldTypeMeta.js.map +1 -0
  65. package/dist/fieldValueEqual.d.ts +4 -0
  66. package/dist/fieldValueEqual.js +58 -0
  67. package/dist/fieldValueEqual.js.map +1 -0
  68. package/dist/importMatch.d.ts +80 -0
  69. package/dist/importMatch.js +5643 -0
  70. package/dist/importMatch.js.map +1 -0
  71. package/dist/index.d.ts +58 -0
  72. package/dist/index.js +10647 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/inferIdentifier.d.ts +18 -0
  75. package/dist/inferIdentifier.js +49 -0
  76. package/dist/inferIdentifier.js.map +1 -0
  77. package/dist/keyboard.d.ts +16 -0
  78. package/dist/keyboard.js +71 -0
  79. package/dist/keyboard.js.map +1 -0
  80. package/dist/manifestDeploy.d.ts +27 -0
  81. package/dist/manifestDeploy.js +16 -0
  82. package/dist/manifestDeploy.js.map +1 -0
  83. package/dist/manifestHash.d.ts +11 -0
  84. package/dist/manifestHash.js +35 -0
  85. package/dist/manifestHash.js.map +1 -0
  86. package/dist/previewDeployName.d.ts +26 -0
  87. package/dist/previewDeployName.js +77 -0
  88. package/dist/previewDeployName.js.map +1 -0
  89. package/dist/proposePolicy.d.ts +17 -0
  90. package/dist/proposePolicy.js +33 -0
  91. package/dist/proposePolicy.js.map +1 -0
  92. package/dist/queryBetween.d.ts +20 -0
  93. package/dist/queryBetween.js +28 -0
  94. package/dist/queryBetween.js.map +1 -0
  95. package/dist/queryExecution.d.ts +5 -0
  96. package/dist/queryExecution.js +58 -0
  97. package/dist/queryExecution.js.map +1 -0
  98. package/dist/queryFieldOps.d.ts +66 -0
  99. package/dist/queryFieldOps.js +138 -0
  100. package/dist/queryFieldOps.js.map +1 -0
  101. package/dist/queryMerge.d.ts +29 -0
  102. package/dist/queryMerge.js +4277 -0
  103. package/dist/queryMerge.js.map +1 -0
  104. package/dist/queryPlan.d.ts +97 -0
  105. package/dist/queryPlan.js +4564 -0
  106. package/dist/queryPlan.js.map +1 -0
  107. package/dist/queryStudio.d.ts +25 -0
  108. package/dist/queryStudio.js +4658 -0
  109. package/dist/queryStudio.js.map +1 -0
  110. package/dist/queryTypes.d.ts +402 -0
  111. package/dist/queryTypes.js +4239 -0
  112. package/dist/queryTypes.js.map +1 -0
  113. package/dist/queryValidators.d.ts +99 -0
  114. package/dist/queryValidators.js +76 -0
  115. package/dist/queryValidators.js.map +1 -0
  116. package/dist/readApiQuery.d.ts +10 -0
  117. package/dist/readApiQuery.js +24 -0
  118. package/dist/readApiQuery.js.map +1 -0
  119. package/dist/recordTableColumns.d.ts +21 -0
  120. package/dist/recordTableColumns.js +4469 -0
  121. package/dist/recordTableColumns.js.map +1 -0
  122. package/dist/refDisplayRequests.d.ts +17 -0
  123. package/dist/refDisplayRequests.js +4877 -0
  124. package/dist/refDisplayRequests.js.map +1 -0
  125. package/dist/refGraph.d.ts +23 -0
  126. package/dist/refGraph.js +102 -0
  127. package/dist/refGraph.js.map +1 -0
  128. package/dist/refsRecompute.d.ts +8 -0
  129. package/dist/refsRecompute.js +12 -0
  130. package/dist/refsRecompute.js.map +1 -0
  131. package/dist/richDoc.d.ts +67 -0
  132. package/dist/richDoc.js +4408 -0
  133. package/dist/richDoc.js.map +1 -0
  134. package/dist/schemaGenerator.d.ts +31 -0
  135. package/dist/schemaGenerator.js +198 -0
  136. package/dist/schemaGenerator.js.map +1 -0
  137. package/dist/schemaShrink.d.ts +74 -0
  138. package/dist/schemaShrink.js +132 -0
  139. package/dist/schemaShrink.js.map +1 -0
  140. package/dist/schemaShrinkValidators.d.ts +72 -0
  141. package/dist/schemaShrinkValidators.js +31 -0
  142. package/dist/schemaShrinkValidators.js.map +1 -0
  143. package/dist/schemaTypes.d.ts +454 -0
  144. package/dist/schemaTypes.js +4557 -0
  145. package/dist/schemaTypes.js.map +1 -0
  146. package/dist/share.d.ts +8 -0
  147. package/dist/share.js +4755 -0
  148. package/dist/share.js.map +1 -0
  149. package/dist/shareApiBridge.d.ts +18 -0
  150. package/dist/shareApiBridge.js +4283 -0
  151. package/dist/shareApiBridge.js.map +1 -0
  152. package/dist/shareGuestPolicy.d.ts +14 -0
  153. package/dist/shareGuestPolicy.js +90 -0
  154. package/dist/shareGuestPolicy.js.map +1 -0
  155. package/dist/shareProposal.d.ts +113 -0
  156. package/dist/shareProposal.js +4810 -0
  157. package/dist/shareProposal.js.map +1 -0
  158. package/dist/shareProposalDiff.d.ts +13 -0
  159. package/dist/shareProposalDiff.js +91 -0
  160. package/dist/shareProposalDiff.js.map +1 -0
  161. package/dist/shareScopes.d.ts +14 -0
  162. package/dist/shareScopes.js +223 -0
  163. package/dist/shareScopes.js.map +1 -0
  164. package/dist/shareTokenCrypto.d.ts +9 -0
  165. package/dist/shareTokenCrypto.js +87 -0
  166. package/dist/shareTokenCrypto.js.map +1 -0
  167. package/dist/shareTokens.d.ts +6 -0
  168. package/dist/shareTokens.js +26 -0
  169. package/dist/shareTokens.js.map +1 -0
  170. package/dist/shareTypes.d.ts +107 -0
  171. package/dist/shareTypes.js +3 -0
  172. package/dist/shareTypes.js.map +1 -0
  173. package/dist/shareValidators.d.ts +168 -0
  174. package/dist/shareValidators.js +124 -0
  175. package/dist/shareValidators.js.map +1 -0
  176. package/dist/shareWizard.d.ts +14 -0
  177. package/dist/shareWizard.js +200 -0
  178. package/dist/shareWizard.js.map +1 -0
  179. package/dist/spaceBundle.d.ts +67 -0
  180. package/dist/spaceBundle.js +4664 -0
  181. package/dist/spaceBundle.js.map +1 -0
  182. package/dist/storageFieldValues.d.ts +10 -0
  183. package/dist/storageFieldValues.js +4421 -0
  184. package/dist/storageFieldValues.js.map +1 -0
  185. package/dist/studioBoot.d.ts +49 -0
  186. package/dist/studioBoot.js +167 -0
  187. package/dist/studioBoot.js.map +1 -0
  188. package/dist/syncClampMembership.d.ts +22 -0
  189. package/dist/syncClampMembership.js +74 -0
  190. package/dist/syncClampMembership.js.map +1 -0
  191. package/dist/tenantHosts.d.ts +30 -0
  192. package/dist/tenantHosts.js +60 -0
  193. package/dist/tenantHosts.js.map +1 -0
  194. package/dist/tenantSecretsCrypto.d.ts +31 -0
  195. package/dist/tenantSecretsCrypto.js +145 -0
  196. package/dist/tenantSecretsCrypto.js.map +1 -0
  197. package/dist/useDebouncedCommit.d.ts +11 -0
  198. package/dist/useDebouncedCommit.js +34 -0
  199. package/dist/useDebouncedCommit.js.map +1 -0
  200. package/dist/useDebouncedValue.d.ts +1 -0
  201. package/dist/useDebouncedValue.js +15 -0
  202. package/dist/useDebouncedValue.js.map +1 -0
  203. package/dist/useModifierHeld.d.ts +2 -0
  204. package/dist/useModifierHeld.js +28 -0
  205. package/dist/useModifierHeld.js.map +1 -0
  206. package/package.json +36 -0
@@ -0,0 +1,4810 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // packages/@columnus/shared/src/fieldValueEqual.ts
8
+ function bytesToBase64(bytes) {
9
+ let s = "";
10
+ for (const b of bytes) s += String.fromCharCode(b);
11
+ return btoa(s);
12
+ }
13
+ function jsonReplacer(_key, value) {
14
+ if (typeof value === "bigint") return `${value.toString()}n`;
15
+ if (value instanceof Uint8Array) return { __bytes__: bytesToBase64(value) };
16
+ return value;
17
+ }
18
+ function normalizeForCompare(value) {
19
+ if (value === void 0 || value === null) return void 0;
20
+ return value;
21
+ }
22
+ function stableJsonEqual(a, b) {
23
+ try {
24
+ return JSON.stringify(a, jsonReplacer) === JSON.stringify(b, jsonReplacer);
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+ function fieldValuesEqual(a, b) {
30
+ const na = normalizeForCompare(a);
31
+ const nb = normalizeForCompare(b);
32
+ if (Object.is(na, nb)) return true;
33
+ if (na === void 0 && nb === void 0) return true;
34
+ const ta = typeof na;
35
+ const tb = typeof nb;
36
+ if (ta !== tb) {
37
+ if (ta === "bigint" && tb === "string") {
38
+ const naBig = na;
39
+ const nbStr = nb;
40
+ return `${naBig.toString()}n` === nbStr || naBig.toString() === nbStr.replace(/n$/, "");
41
+ }
42
+ if (ta === "string" && tb === "bigint") {
43
+ const naStr = na;
44
+ const nbBig = nb;
45
+ return `${nbBig.toString()}n` === naStr || nbBig.toString() === naStr.replace(/n$/, "");
46
+ }
47
+ return false;
48
+ }
49
+ if (ta === "object" && na !== null && nb !== null) {
50
+ return stableJsonEqual(na, nb);
51
+ }
52
+ return false;
53
+ }
54
+
55
+ // packages/@columnus/shared/src/proposePolicy.ts
56
+ function pickProposalFields(fields, allowedFields) {
57
+ const allowed = allowedFields ? new Set(allowedFields) : null;
58
+ return Object.fromEntries(
59
+ Object.entries(fields).filter(
60
+ ([field]) => !field.startsWith("_") && (!allowed || allowed.has(field))
61
+ )
62
+ );
63
+ }
64
+
65
+ // packages/@columnus/shared/src/refGraph.ts
66
+ function refEdgesForType(type) {
67
+ switch (type.kind) {
68
+ case "id":
69
+ return [{ field: "", targetTable: type.table, array: false }];
70
+ case "array":
71
+ if (type.element.kind === "id") {
72
+ return [{ field: "", targetTable: type.element.table, array: true }];
73
+ }
74
+ return [];
75
+ default:
76
+ return [];
77
+ }
78
+ }
79
+ function refFieldsForTable(table) {
80
+ const edges = [];
81
+ for (const field of table.fields) {
82
+ for (const template of refEdgesForType(field.type)) {
83
+ edges.push({ ...template, field: field.name });
84
+ }
85
+ }
86
+ return edges.sort(
87
+ (a, b) => a.field.localeCompare(b.field) || a.targetTable.localeCompare(b.targetTable)
88
+ );
89
+ }
90
+
91
+ // node_modules/zod/v3/external.js
92
+ var external_exports = {};
93
+ __export(external_exports, {
94
+ BRAND: () => BRAND,
95
+ DIRTY: () => DIRTY,
96
+ EMPTY_PATH: () => EMPTY_PATH,
97
+ INVALID: () => INVALID,
98
+ NEVER: () => NEVER,
99
+ OK: () => OK,
100
+ ParseStatus: () => ParseStatus,
101
+ Schema: () => ZodType,
102
+ ZodAny: () => ZodAny,
103
+ ZodArray: () => ZodArray,
104
+ ZodBigInt: () => ZodBigInt,
105
+ ZodBoolean: () => ZodBoolean,
106
+ ZodBranded: () => ZodBranded,
107
+ ZodCatch: () => ZodCatch,
108
+ ZodDate: () => ZodDate,
109
+ ZodDefault: () => ZodDefault,
110
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
111
+ ZodEffects: () => ZodEffects,
112
+ ZodEnum: () => ZodEnum,
113
+ ZodError: () => ZodError,
114
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
115
+ ZodFunction: () => ZodFunction,
116
+ ZodIntersection: () => ZodIntersection,
117
+ ZodIssueCode: () => ZodIssueCode,
118
+ ZodLazy: () => ZodLazy,
119
+ ZodLiteral: () => ZodLiteral,
120
+ ZodMap: () => ZodMap,
121
+ ZodNaN: () => ZodNaN,
122
+ ZodNativeEnum: () => ZodNativeEnum,
123
+ ZodNever: () => ZodNever,
124
+ ZodNull: () => ZodNull,
125
+ ZodNullable: () => ZodNullable,
126
+ ZodNumber: () => ZodNumber,
127
+ ZodObject: () => ZodObject,
128
+ ZodOptional: () => ZodOptional,
129
+ ZodParsedType: () => ZodParsedType,
130
+ ZodPipeline: () => ZodPipeline,
131
+ ZodPromise: () => ZodPromise,
132
+ ZodReadonly: () => ZodReadonly,
133
+ ZodRecord: () => ZodRecord,
134
+ ZodSchema: () => ZodType,
135
+ ZodSet: () => ZodSet,
136
+ ZodString: () => ZodString,
137
+ ZodSymbol: () => ZodSymbol,
138
+ ZodTransformer: () => ZodEffects,
139
+ ZodTuple: () => ZodTuple,
140
+ ZodType: () => ZodType,
141
+ ZodUndefined: () => ZodUndefined,
142
+ ZodUnion: () => ZodUnion,
143
+ ZodUnknown: () => ZodUnknown,
144
+ ZodVoid: () => ZodVoid,
145
+ addIssueToContext: () => addIssueToContext,
146
+ any: () => anyType,
147
+ array: () => arrayType,
148
+ bigint: () => bigIntType,
149
+ boolean: () => booleanType,
150
+ coerce: () => coerce,
151
+ custom: () => custom,
152
+ date: () => dateType,
153
+ datetimeRegex: () => datetimeRegex,
154
+ defaultErrorMap: () => en_default,
155
+ discriminatedUnion: () => discriminatedUnionType,
156
+ effect: () => effectsType,
157
+ enum: () => enumType,
158
+ function: () => functionType,
159
+ getErrorMap: () => getErrorMap,
160
+ getParsedType: () => getParsedType,
161
+ instanceof: () => instanceOfType,
162
+ intersection: () => intersectionType,
163
+ isAborted: () => isAborted,
164
+ isAsync: () => isAsync,
165
+ isDirty: () => isDirty,
166
+ isValid: () => isValid,
167
+ late: () => late,
168
+ lazy: () => lazyType,
169
+ literal: () => literalType,
170
+ makeIssue: () => makeIssue,
171
+ map: () => mapType,
172
+ nan: () => nanType,
173
+ nativeEnum: () => nativeEnumType,
174
+ never: () => neverType,
175
+ null: () => nullType,
176
+ nullable: () => nullableType,
177
+ number: () => numberType,
178
+ object: () => objectType,
179
+ objectUtil: () => objectUtil,
180
+ oboolean: () => oboolean,
181
+ onumber: () => onumber,
182
+ optional: () => optionalType,
183
+ ostring: () => ostring,
184
+ pipeline: () => pipelineType,
185
+ preprocess: () => preprocessType,
186
+ promise: () => promiseType,
187
+ quotelessJson: () => quotelessJson,
188
+ record: () => recordType,
189
+ set: () => setType,
190
+ setErrorMap: () => setErrorMap,
191
+ strictObject: () => strictObjectType,
192
+ string: () => stringType,
193
+ symbol: () => symbolType,
194
+ transformer: () => effectsType,
195
+ tuple: () => tupleType,
196
+ undefined: () => undefinedType,
197
+ union: () => unionType,
198
+ unknown: () => unknownType,
199
+ util: () => util,
200
+ void: () => voidType
201
+ });
202
+
203
+ // node_modules/zod/v3/helpers/util.js
204
+ var util;
205
+ (function(util2) {
206
+ util2.assertEqual = (_) => {
207
+ };
208
+ function assertIs(_arg) {
209
+ }
210
+ util2.assertIs = assertIs;
211
+ function assertNever(_x) {
212
+ throw new Error();
213
+ }
214
+ util2.assertNever = assertNever;
215
+ util2.arrayToEnum = (items) => {
216
+ const obj = {};
217
+ for (const item of items) {
218
+ obj[item] = item;
219
+ }
220
+ return obj;
221
+ };
222
+ util2.getValidEnumValues = (obj) => {
223
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
224
+ const filtered = {};
225
+ for (const k of validKeys) {
226
+ filtered[k] = obj[k];
227
+ }
228
+ return util2.objectValues(filtered);
229
+ };
230
+ util2.objectValues = (obj) => {
231
+ return util2.objectKeys(obj).map(function(e) {
232
+ return obj[e];
233
+ });
234
+ };
235
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
236
+ const keys = [];
237
+ for (const key in object) {
238
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
239
+ keys.push(key);
240
+ }
241
+ }
242
+ return keys;
243
+ };
244
+ util2.find = (arr, checker) => {
245
+ for (const item of arr) {
246
+ if (checker(item))
247
+ return item;
248
+ }
249
+ return void 0;
250
+ };
251
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
252
+ function joinValues(array, separator = " | ") {
253
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
254
+ }
255
+ util2.joinValues = joinValues;
256
+ util2.jsonStringifyReplacer = (_, value) => {
257
+ if (typeof value === "bigint") {
258
+ return value.toString();
259
+ }
260
+ return value;
261
+ };
262
+ })(util || (util = {}));
263
+ var objectUtil;
264
+ (function(objectUtil2) {
265
+ objectUtil2.mergeShapes = (first, second) => {
266
+ return {
267
+ ...first,
268
+ ...second
269
+ // second overwrites first
270
+ };
271
+ };
272
+ })(objectUtil || (objectUtil = {}));
273
+ var ZodParsedType = util.arrayToEnum([
274
+ "string",
275
+ "nan",
276
+ "number",
277
+ "integer",
278
+ "float",
279
+ "boolean",
280
+ "date",
281
+ "bigint",
282
+ "symbol",
283
+ "function",
284
+ "undefined",
285
+ "null",
286
+ "array",
287
+ "object",
288
+ "unknown",
289
+ "promise",
290
+ "void",
291
+ "never",
292
+ "map",
293
+ "set"
294
+ ]);
295
+ var getParsedType = (data) => {
296
+ const t = typeof data;
297
+ switch (t) {
298
+ case "undefined":
299
+ return ZodParsedType.undefined;
300
+ case "string":
301
+ return ZodParsedType.string;
302
+ case "number":
303
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
304
+ case "boolean":
305
+ return ZodParsedType.boolean;
306
+ case "function":
307
+ return ZodParsedType.function;
308
+ case "bigint":
309
+ return ZodParsedType.bigint;
310
+ case "symbol":
311
+ return ZodParsedType.symbol;
312
+ case "object":
313
+ if (Array.isArray(data)) {
314
+ return ZodParsedType.array;
315
+ }
316
+ if (data === null) {
317
+ return ZodParsedType.null;
318
+ }
319
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
320
+ return ZodParsedType.promise;
321
+ }
322
+ if (typeof Map !== "undefined" && data instanceof Map) {
323
+ return ZodParsedType.map;
324
+ }
325
+ if (typeof Set !== "undefined" && data instanceof Set) {
326
+ return ZodParsedType.set;
327
+ }
328
+ if (typeof Date !== "undefined" && data instanceof Date) {
329
+ return ZodParsedType.date;
330
+ }
331
+ return ZodParsedType.object;
332
+ default:
333
+ return ZodParsedType.unknown;
334
+ }
335
+ };
336
+
337
+ // node_modules/zod/v3/ZodError.js
338
+ var ZodIssueCode = util.arrayToEnum([
339
+ "invalid_type",
340
+ "invalid_literal",
341
+ "custom",
342
+ "invalid_union",
343
+ "invalid_union_discriminator",
344
+ "invalid_enum_value",
345
+ "unrecognized_keys",
346
+ "invalid_arguments",
347
+ "invalid_return_type",
348
+ "invalid_date",
349
+ "invalid_string",
350
+ "too_small",
351
+ "too_big",
352
+ "invalid_intersection_types",
353
+ "not_multiple_of",
354
+ "not_finite"
355
+ ]);
356
+ var quotelessJson = (obj) => {
357
+ const json = JSON.stringify(obj, null, 2);
358
+ return json.replace(/"([^"]+)":/g, "$1:");
359
+ };
360
+ var ZodError = class _ZodError extends Error {
361
+ get errors() {
362
+ return this.issues;
363
+ }
364
+ constructor(issues) {
365
+ super();
366
+ this.issues = [];
367
+ this.addIssue = (sub) => {
368
+ this.issues = [...this.issues, sub];
369
+ };
370
+ this.addIssues = (subs = []) => {
371
+ this.issues = [...this.issues, ...subs];
372
+ };
373
+ const actualProto = new.target.prototype;
374
+ if (Object.setPrototypeOf) {
375
+ Object.setPrototypeOf(this, actualProto);
376
+ } else {
377
+ this.__proto__ = actualProto;
378
+ }
379
+ this.name = "ZodError";
380
+ this.issues = issues;
381
+ }
382
+ format(_mapper) {
383
+ const mapper = _mapper || function(issue) {
384
+ return issue.message;
385
+ };
386
+ const fieldErrors = { _errors: [] };
387
+ const processError = (error) => {
388
+ for (const issue of error.issues) {
389
+ if (issue.code === "invalid_union") {
390
+ issue.unionErrors.map(processError);
391
+ } else if (issue.code === "invalid_return_type") {
392
+ processError(issue.returnTypeError);
393
+ } else if (issue.code === "invalid_arguments") {
394
+ processError(issue.argumentsError);
395
+ } else if (issue.path.length === 0) {
396
+ fieldErrors._errors.push(mapper(issue));
397
+ } else {
398
+ let curr = fieldErrors;
399
+ let i = 0;
400
+ while (i < issue.path.length) {
401
+ const el = issue.path[i];
402
+ const terminal = i === issue.path.length - 1;
403
+ if (!terminal) {
404
+ curr[el] = curr[el] || { _errors: [] };
405
+ } else {
406
+ curr[el] = curr[el] || { _errors: [] };
407
+ curr[el]._errors.push(mapper(issue));
408
+ }
409
+ curr = curr[el];
410
+ i++;
411
+ }
412
+ }
413
+ }
414
+ };
415
+ processError(this);
416
+ return fieldErrors;
417
+ }
418
+ static assert(value) {
419
+ if (!(value instanceof _ZodError)) {
420
+ throw new Error(`Not a ZodError: ${value}`);
421
+ }
422
+ }
423
+ toString() {
424
+ return this.message;
425
+ }
426
+ get message() {
427
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
428
+ }
429
+ get isEmpty() {
430
+ return this.issues.length === 0;
431
+ }
432
+ flatten(mapper = (issue) => issue.message) {
433
+ const fieldErrors = {};
434
+ const formErrors = [];
435
+ for (const sub of this.issues) {
436
+ if (sub.path.length > 0) {
437
+ const firstEl = sub.path[0];
438
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
439
+ fieldErrors[firstEl].push(mapper(sub));
440
+ } else {
441
+ formErrors.push(mapper(sub));
442
+ }
443
+ }
444
+ return { formErrors, fieldErrors };
445
+ }
446
+ get formErrors() {
447
+ return this.flatten();
448
+ }
449
+ };
450
+ ZodError.create = (issues) => {
451
+ const error = new ZodError(issues);
452
+ return error;
453
+ };
454
+
455
+ // node_modules/zod/v3/locales/en.js
456
+ var errorMap = (issue, _ctx) => {
457
+ let message;
458
+ switch (issue.code) {
459
+ case ZodIssueCode.invalid_type:
460
+ if (issue.received === ZodParsedType.undefined) {
461
+ message = "Required";
462
+ } else {
463
+ message = `Expected ${issue.expected}, received ${issue.received}`;
464
+ }
465
+ break;
466
+ case ZodIssueCode.invalid_literal:
467
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
468
+ break;
469
+ case ZodIssueCode.unrecognized_keys:
470
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
471
+ break;
472
+ case ZodIssueCode.invalid_union:
473
+ message = `Invalid input`;
474
+ break;
475
+ case ZodIssueCode.invalid_union_discriminator:
476
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
477
+ break;
478
+ case ZodIssueCode.invalid_enum_value:
479
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
480
+ break;
481
+ case ZodIssueCode.invalid_arguments:
482
+ message = `Invalid function arguments`;
483
+ break;
484
+ case ZodIssueCode.invalid_return_type:
485
+ message = `Invalid function return type`;
486
+ break;
487
+ case ZodIssueCode.invalid_date:
488
+ message = `Invalid date`;
489
+ break;
490
+ case ZodIssueCode.invalid_string:
491
+ if (typeof issue.validation === "object") {
492
+ if ("includes" in issue.validation) {
493
+ message = `Invalid input: must include "${issue.validation.includes}"`;
494
+ if (typeof issue.validation.position === "number") {
495
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
496
+ }
497
+ } else if ("startsWith" in issue.validation) {
498
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
499
+ } else if ("endsWith" in issue.validation) {
500
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
501
+ } else {
502
+ util.assertNever(issue.validation);
503
+ }
504
+ } else if (issue.validation !== "regex") {
505
+ message = `Invalid ${issue.validation}`;
506
+ } else {
507
+ message = "Invalid";
508
+ }
509
+ break;
510
+ case ZodIssueCode.too_small:
511
+ if (issue.type === "array")
512
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
513
+ else if (issue.type === "string")
514
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
515
+ else if (issue.type === "number")
516
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
517
+ else if (issue.type === "bigint")
518
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
519
+ else if (issue.type === "date")
520
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
521
+ else
522
+ message = "Invalid input";
523
+ break;
524
+ case ZodIssueCode.too_big:
525
+ if (issue.type === "array")
526
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
527
+ else if (issue.type === "string")
528
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
529
+ else if (issue.type === "number")
530
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
531
+ else if (issue.type === "bigint")
532
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
533
+ else if (issue.type === "date")
534
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
535
+ else
536
+ message = "Invalid input";
537
+ break;
538
+ case ZodIssueCode.custom:
539
+ message = `Invalid input`;
540
+ break;
541
+ case ZodIssueCode.invalid_intersection_types:
542
+ message = `Intersection results could not be merged`;
543
+ break;
544
+ case ZodIssueCode.not_multiple_of:
545
+ message = `Number must be a multiple of ${issue.multipleOf}`;
546
+ break;
547
+ case ZodIssueCode.not_finite:
548
+ message = "Number must be finite";
549
+ break;
550
+ default:
551
+ message = _ctx.defaultError;
552
+ util.assertNever(issue);
553
+ }
554
+ return { message };
555
+ };
556
+ var en_default = errorMap;
557
+
558
+ // node_modules/zod/v3/errors.js
559
+ var overrideErrorMap = en_default;
560
+ function setErrorMap(map) {
561
+ overrideErrorMap = map;
562
+ }
563
+ function getErrorMap() {
564
+ return overrideErrorMap;
565
+ }
566
+
567
+ // node_modules/zod/v3/helpers/parseUtil.js
568
+ var makeIssue = (params) => {
569
+ const { data, path, errorMaps, issueData } = params;
570
+ const fullPath = [...path, ...issueData.path || []];
571
+ const fullIssue = {
572
+ ...issueData,
573
+ path: fullPath
574
+ };
575
+ if (issueData.message !== void 0) {
576
+ return {
577
+ ...issueData,
578
+ path: fullPath,
579
+ message: issueData.message
580
+ };
581
+ }
582
+ let errorMessage = "";
583
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
584
+ for (const map of maps) {
585
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
586
+ }
587
+ return {
588
+ ...issueData,
589
+ path: fullPath,
590
+ message: errorMessage
591
+ };
592
+ };
593
+ var EMPTY_PATH = [];
594
+ function addIssueToContext(ctx, issueData) {
595
+ const overrideMap = getErrorMap();
596
+ const issue = makeIssue({
597
+ issueData,
598
+ data: ctx.data,
599
+ path: ctx.path,
600
+ errorMaps: [
601
+ ctx.common.contextualErrorMap,
602
+ // contextual error map is first priority
603
+ ctx.schemaErrorMap,
604
+ // then schema-bound map if available
605
+ overrideMap,
606
+ // then global override map
607
+ overrideMap === en_default ? void 0 : en_default
608
+ // then global default map
609
+ ].filter((x) => !!x)
610
+ });
611
+ ctx.common.issues.push(issue);
612
+ }
613
+ var ParseStatus = class _ParseStatus {
614
+ constructor() {
615
+ this.value = "valid";
616
+ }
617
+ dirty() {
618
+ if (this.value === "valid")
619
+ this.value = "dirty";
620
+ }
621
+ abort() {
622
+ if (this.value !== "aborted")
623
+ this.value = "aborted";
624
+ }
625
+ static mergeArray(status, results) {
626
+ const arrayValue = [];
627
+ for (const s of results) {
628
+ if (s.status === "aborted")
629
+ return INVALID;
630
+ if (s.status === "dirty")
631
+ status.dirty();
632
+ arrayValue.push(s.value);
633
+ }
634
+ return { status: status.value, value: arrayValue };
635
+ }
636
+ static async mergeObjectAsync(status, pairs) {
637
+ const syncPairs = [];
638
+ for (const pair of pairs) {
639
+ const key = await pair.key;
640
+ const value = await pair.value;
641
+ syncPairs.push({
642
+ key,
643
+ value
644
+ });
645
+ }
646
+ return _ParseStatus.mergeObjectSync(status, syncPairs);
647
+ }
648
+ static mergeObjectSync(status, pairs) {
649
+ const finalObject = {};
650
+ for (const pair of pairs) {
651
+ const { key, value } = pair;
652
+ if (key.status === "aborted")
653
+ return INVALID;
654
+ if (value.status === "aborted")
655
+ return INVALID;
656
+ if (key.status === "dirty")
657
+ status.dirty();
658
+ if (value.status === "dirty")
659
+ status.dirty();
660
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
661
+ finalObject[key.value] = value.value;
662
+ }
663
+ }
664
+ return { status: status.value, value: finalObject };
665
+ }
666
+ };
667
+ var INVALID = Object.freeze({
668
+ status: "aborted"
669
+ });
670
+ var DIRTY = (value) => ({ status: "dirty", value });
671
+ var OK = (value) => ({ status: "valid", value });
672
+ var isAborted = (x) => x.status === "aborted";
673
+ var isDirty = (x) => x.status === "dirty";
674
+ var isValid = (x) => x.status === "valid";
675
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
676
+
677
+ // node_modules/zod/v3/helpers/errorUtil.js
678
+ var errorUtil;
679
+ (function(errorUtil2) {
680
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
681
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
682
+ })(errorUtil || (errorUtil = {}));
683
+
684
+ // node_modules/zod/v3/types.js
685
+ var ParseInputLazyPath = class {
686
+ constructor(parent, value, path, key) {
687
+ this._cachedPath = [];
688
+ this.parent = parent;
689
+ this.data = value;
690
+ this._path = path;
691
+ this._key = key;
692
+ }
693
+ get path() {
694
+ if (!this._cachedPath.length) {
695
+ if (Array.isArray(this._key)) {
696
+ this._cachedPath.push(...this._path, ...this._key);
697
+ } else {
698
+ this._cachedPath.push(...this._path, this._key);
699
+ }
700
+ }
701
+ return this._cachedPath;
702
+ }
703
+ };
704
+ var handleResult = (ctx, result) => {
705
+ if (isValid(result)) {
706
+ return { success: true, data: result.value };
707
+ } else {
708
+ if (!ctx.common.issues.length) {
709
+ throw new Error("Validation failed but no issues detected.");
710
+ }
711
+ return {
712
+ success: false,
713
+ get error() {
714
+ if (this._error)
715
+ return this._error;
716
+ const error = new ZodError(ctx.common.issues);
717
+ this._error = error;
718
+ return this._error;
719
+ }
720
+ };
721
+ }
722
+ };
723
+ function processCreateParams(params) {
724
+ if (!params)
725
+ return {};
726
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
727
+ if (errorMap2 && (invalid_type_error || required_error)) {
728
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
729
+ }
730
+ if (errorMap2)
731
+ return { errorMap: errorMap2, description };
732
+ const customMap = (iss, ctx) => {
733
+ const { message } = params;
734
+ if (iss.code === "invalid_enum_value") {
735
+ return { message: message ?? ctx.defaultError };
736
+ }
737
+ if (typeof ctx.data === "undefined") {
738
+ return { message: message ?? required_error ?? ctx.defaultError };
739
+ }
740
+ if (iss.code !== "invalid_type")
741
+ return { message: ctx.defaultError };
742
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
743
+ };
744
+ return { errorMap: customMap, description };
745
+ }
746
+ var ZodType = class {
747
+ get description() {
748
+ return this._def.description;
749
+ }
750
+ _getType(input) {
751
+ return getParsedType(input.data);
752
+ }
753
+ _getOrReturnCtx(input, ctx) {
754
+ return ctx || {
755
+ common: input.parent.common,
756
+ data: input.data,
757
+ parsedType: getParsedType(input.data),
758
+ schemaErrorMap: this._def.errorMap,
759
+ path: input.path,
760
+ parent: input.parent
761
+ };
762
+ }
763
+ _processInputParams(input) {
764
+ return {
765
+ status: new ParseStatus(),
766
+ ctx: {
767
+ common: input.parent.common,
768
+ data: input.data,
769
+ parsedType: getParsedType(input.data),
770
+ schemaErrorMap: this._def.errorMap,
771
+ path: input.path,
772
+ parent: input.parent
773
+ }
774
+ };
775
+ }
776
+ _parseSync(input) {
777
+ const result = this._parse(input);
778
+ if (isAsync(result)) {
779
+ throw new Error("Synchronous parse encountered promise.");
780
+ }
781
+ return result;
782
+ }
783
+ _parseAsync(input) {
784
+ const result = this._parse(input);
785
+ return Promise.resolve(result);
786
+ }
787
+ parse(data, params) {
788
+ const result = this.safeParse(data, params);
789
+ if (result.success)
790
+ return result.data;
791
+ throw result.error;
792
+ }
793
+ safeParse(data, params) {
794
+ const ctx = {
795
+ common: {
796
+ issues: [],
797
+ async: params?.async ?? false,
798
+ contextualErrorMap: params?.errorMap
799
+ },
800
+ path: params?.path || [],
801
+ schemaErrorMap: this._def.errorMap,
802
+ parent: null,
803
+ data,
804
+ parsedType: getParsedType(data)
805
+ };
806
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
807
+ return handleResult(ctx, result);
808
+ }
809
+ "~validate"(data) {
810
+ const ctx = {
811
+ common: {
812
+ issues: [],
813
+ async: !!this["~standard"].async
814
+ },
815
+ path: [],
816
+ schemaErrorMap: this._def.errorMap,
817
+ parent: null,
818
+ data,
819
+ parsedType: getParsedType(data)
820
+ };
821
+ if (!this["~standard"].async) {
822
+ try {
823
+ const result = this._parseSync({ data, path: [], parent: ctx });
824
+ return isValid(result) ? {
825
+ value: result.value
826
+ } : {
827
+ issues: ctx.common.issues
828
+ };
829
+ } catch (err) {
830
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
831
+ this["~standard"].async = true;
832
+ }
833
+ ctx.common = {
834
+ issues: [],
835
+ async: true
836
+ };
837
+ }
838
+ }
839
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
840
+ value: result.value
841
+ } : {
842
+ issues: ctx.common.issues
843
+ });
844
+ }
845
+ async parseAsync(data, params) {
846
+ const result = await this.safeParseAsync(data, params);
847
+ if (result.success)
848
+ return result.data;
849
+ throw result.error;
850
+ }
851
+ async safeParseAsync(data, params) {
852
+ const ctx = {
853
+ common: {
854
+ issues: [],
855
+ contextualErrorMap: params?.errorMap,
856
+ async: true
857
+ },
858
+ path: params?.path || [],
859
+ schemaErrorMap: this._def.errorMap,
860
+ parent: null,
861
+ data,
862
+ parsedType: getParsedType(data)
863
+ };
864
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
865
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
866
+ return handleResult(ctx, result);
867
+ }
868
+ refine(check, message) {
869
+ const getIssueProperties = (val) => {
870
+ if (typeof message === "string" || typeof message === "undefined") {
871
+ return { message };
872
+ } else if (typeof message === "function") {
873
+ return message(val);
874
+ } else {
875
+ return message;
876
+ }
877
+ };
878
+ return this._refinement((val, ctx) => {
879
+ const result = check(val);
880
+ const setError = () => ctx.addIssue({
881
+ code: ZodIssueCode.custom,
882
+ ...getIssueProperties(val)
883
+ });
884
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
885
+ return result.then((data) => {
886
+ if (!data) {
887
+ setError();
888
+ return false;
889
+ } else {
890
+ return true;
891
+ }
892
+ });
893
+ }
894
+ if (!result) {
895
+ setError();
896
+ return false;
897
+ } else {
898
+ return true;
899
+ }
900
+ });
901
+ }
902
+ refinement(check, refinementData) {
903
+ return this._refinement((val, ctx) => {
904
+ if (!check(val)) {
905
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
906
+ return false;
907
+ } else {
908
+ return true;
909
+ }
910
+ });
911
+ }
912
+ _refinement(refinement) {
913
+ return new ZodEffects({
914
+ schema: this,
915
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
916
+ effect: { type: "refinement", refinement }
917
+ });
918
+ }
919
+ superRefine(refinement) {
920
+ return this._refinement(refinement);
921
+ }
922
+ constructor(def) {
923
+ this.spa = this.safeParseAsync;
924
+ this._def = def;
925
+ this.parse = this.parse.bind(this);
926
+ this.safeParse = this.safeParse.bind(this);
927
+ this.parseAsync = this.parseAsync.bind(this);
928
+ this.safeParseAsync = this.safeParseAsync.bind(this);
929
+ this.spa = this.spa.bind(this);
930
+ this.refine = this.refine.bind(this);
931
+ this.refinement = this.refinement.bind(this);
932
+ this.superRefine = this.superRefine.bind(this);
933
+ this.optional = this.optional.bind(this);
934
+ this.nullable = this.nullable.bind(this);
935
+ this.nullish = this.nullish.bind(this);
936
+ this.array = this.array.bind(this);
937
+ this.promise = this.promise.bind(this);
938
+ this.or = this.or.bind(this);
939
+ this.and = this.and.bind(this);
940
+ this.transform = this.transform.bind(this);
941
+ this.brand = this.brand.bind(this);
942
+ this.default = this.default.bind(this);
943
+ this.catch = this.catch.bind(this);
944
+ this.describe = this.describe.bind(this);
945
+ this.pipe = this.pipe.bind(this);
946
+ this.readonly = this.readonly.bind(this);
947
+ this.isNullable = this.isNullable.bind(this);
948
+ this.isOptional = this.isOptional.bind(this);
949
+ this["~standard"] = {
950
+ version: 1,
951
+ vendor: "zod",
952
+ validate: (data) => this["~validate"](data)
953
+ };
954
+ }
955
+ optional() {
956
+ return ZodOptional.create(this, this._def);
957
+ }
958
+ nullable() {
959
+ return ZodNullable.create(this, this._def);
960
+ }
961
+ nullish() {
962
+ return this.nullable().optional();
963
+ }
964
+ array() {
965
+ return ZodArray.create(this);
966
+ }
967
+ promise() {
968
+ return ZodPromise.create(this, this._def);
969
+ }
970
+ or(option) {
971
+ return ZodUnion.create([this, option], this._def);
972
+ }
973
+ and(incoming) {
974
+ return ZodIntersection.create(this, incoming, this._def);
975
+ }
976
+ transform(transform) {
977
+ return new ZodEffects({
978
+ ...processCreateParams(this._def),
979
+ schema: this,
980
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
981
+ effect: { type: "transform", transform }
982
+ });
983
+ }
984
+ default(def) {
985
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
986
+ return new ZodDefault({
987
+ ...processCreateParams(this._def),
988
+ innerType: this,
989
+ defaultValue: defaultValueFunc,
990
+ typeName: ZodFirstPartyTypeKind.ZodDefault
991
+ });
992
+ }
993
+ brand() {
994
+ return new ZodBranded({
995
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
996
+ type: this,
997
+ ...processCreateParams(this._def)
998
+ });
999
+ }
1000
+ catch(def) {
1001
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1002
+ return new ZodCatch({
1003
+ ...processCreateParams(this._def),
1004
+ innerType: this,
1005
+ catchValue: catchValueFunc,
1006
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1007
+ });
1008
+ }
1009
+ describe(description) {
1010
+ const This = this.constructor;
1011
+ return new This({
1012
+ ...this._def,
1013
+ description
1014
+ });
1015
+ }
1016
+ pipe(target) {
1017
+ return ZodPipeline.create(this, target);
1018
+ }
1019
+ readonly() {
1020
+ return ZodReadonly.create(this);
1021
+ }
1022
+ isOptional() {
1023
+ return this.safeParse(void 0).success;
1024
+ }
1025
+ isNullable() {
1026
+ return this.safeParse(null).success;
1027
+ }
1028
+ };
1029
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1030
+ var cuid2Regex = /^[0-9a-z]+$/;
1031
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1032
+ var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
1033
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1034
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1035
+ var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1036
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1037
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1038
+ var emojiRegex;
1039
+ var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1040
+ var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
1041
+ var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
1042
+ var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1043
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1044
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1045
+ var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
1046
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
1047
+ function timeRegexSource(args) {
1048
+ let secondsRegexSource = `[0-5]\\d`;
1049
+ if (args.precision) {
1050
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1051
+ } else if (args.precision == null) {
1052
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1053
+ }
1054
+ const secondsQuantifier = args.precision ? "+" : "?";
1055
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1056
+ }
1057
+ function timeRegex(args) {
1058
+ return new RegExp(`^${timeRegexSource(args)}$`);
1059
+ }
1060
+ function datetimeRegex(args) {
1061
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1062
+ const opts = [];
1063
+ opts.push(args.local ? `Z?` : `Z`);
1064
+ if (args.offset)
1065
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1066
+ regex = `${regex}(${opts.join("|")})`;
1067
+ return new RegExp(`^${regex}$`);
1068
+ }
1069
+ function isValidIP(ip, version) {
1070
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1071
+ return true;
1072
+ }
1073
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1074
+ return true;
1075
+ }
1076
+ return false;
1077
+ }
1078
+ function isValidJWT(jwt, alg) {
1079
+ if (!jwtRegex.test(jwt))
1080
+ return false;
1081
+ try {
1082
+ const [header] = jwt.split(".");
1083
+ if (!header)
1084
+ return false;
1085
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1086
+ const decoded = JSON.parse(atob(base64));
1087
+ if (typeof decoded !== "object" || decoded === null)
1088
+ return false;
1089
+ if ("typ" in decoded && decoded?.typ !== "JWT")
1090
+ return false;
1091
+ if (!decoded.alg)
1092
+ return false;
1093
+ if (alg && decoded.alg !== alg)
1094
+ return false;
1095
+ return true;
1096
+ } catch {
1097
+ return false;
1098
+ }
1099
+ }
1100
+ function isValidCidr(ip, version) {
1101
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1102
+ return true;
1103
+ }
1104
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1105
+ return true;
1106
+ }
1107
+ return false;
1108
+ }
1109
+ var ZodString = class _ZodString extends ZodType {
1110
+ _parse(input) {
1111
+ if (this._def.coerce) {
1112
+ input.data = String(input.data);
1113
+ }
1114
+ const parsedType = this._getType(input);
1115
+ if (parsedType !== ZodParsedType.string) {
1116
+ const ctx2 = this._getOrReturnCtx(input);
1117
+ addIssueToContext(ctx2, {
1118
+ code: ZodIssueCode.invalid_type,
1119
+ expected: ZodParsedType.string,
1120
+ received: ctx2.parsedType
1121
+ });
1122
+ return INVALID;
1123
+ }
1124
+ const status = new ParseStatus();
1125
+ let ctx = void 0;
1126
+ for (const check of this._def.checks) {
1127
+ if (check.kind === "min") {
1128
+ if (input.data.length < check.value) {
1129
+ ctx = this._getOrReturnCtx(input, ctx);
1130
+ addIssueToContext(ctx, {
1131
+ code: ZodIssueCode.too_small,
1132
+ minimum: check.value,
1133
+ type: "string",
1134
+ inclusive: true,
1135
+ exact: false,
1136
+ message: check.message
1137
+ });
1138
+ status.dirty();
1139
+ }
1140
+ } else if (check.kind === "max") {
1141
+ if (input.data.length > check.value) {
1142
+ ctx = this._getOrReturnCtx(input, ctx);
1143
+ addIssueToContext(ctx, {
1144
+ code: ZodIssueCode.too_big,
1145
+ maximum: check.value,
1146
+ type: "string",
1147
+ inclusive: true,
1148
+ exact: false,
1149
+ message: check.message
1150
+ });
1151
+ status.dirty();
1152
+ }
1153
+ } else if (check.kind === "length") {
1154
+ const tooBig = input.data.length > check.value;
1155
+ const tooSmall = input.data.length < check.value;
1156
+ if (tooBig || tooSmall) {
1157
+ ctx = this._getOrReturnCtx(input, ctx);
1158
+ if (tooBig) {
1159
+ addIssueToContext(ctx, {
1160
+ code: ZodIssueCode.too_big,
1161
+ maximum: check.value,
1162
+ type: "string",
1163
+ inclusive: true,
1164
+ exact: true,
1165
+ message: check.message
1166
+ });
1167
+ } else if (tooSmall) {
1168
+ addIssueToContext(ctx, {
1169
+ code: ZodIssueCode.too_small,
1170
+ minimum: check.value,
1171
+ type: "string",
1172
+ inclusive: true,
1173
+ exact: true,
1174
+ message: check.message
1175
+ });
1176
+ }
1177
+ status.dirty();
1178
+ }
1179
+ } else if (check.kind === "email") {
1180
+ if (!emailRegex.test(input.data)) {
1181
+ ctx = this._getOrReturnCtx(input, ctx);
1182
+ addIssueToContext(ctx, {
1183
+ validation: "email",
1184
+ code: ZodIssueCode.invalid_string,
1185
+ message: check.message
1186
+ });
1187
+ status.dirty();
1188
+ }
1189
+ } else if (check.kind === "emoji") {
1190
+ if (!emojiRegex) {
1191
+ emojiRegex = new RegExp(_emojiRegex, "u");
1192
+ }
1193
+ if (!emojiRegex.test(input.data)) {
1194
+ ctx = this._getOrReturnCtx(input, ctx);
1195
+ addIssueToContext(ctx, {
1196
+ validation: "emoji",
1197
+ code: ZodIssueCode.invalid_string,
1198
+ message: check.message
1199
+ });
1200
+ status.dirty();
1201
+ }
1202
+ } else if (check.kind === "uuid") {
1203
+ if (!uuidRegex.test(input.data)) {
1204
+ ctx = this._getOrReturnCtx(input, ctx);
1205
+ addIssueToContext(ctx, {
1206
+ validation: "uuid",
1207
+ code: ZodIssueCode.invalid_string,
1208
+ message: check.message
1209
+ });
1210
+ status.dirty();
1211
+ }
1212
+ } else if (check.kind === "nanoid") {
1213
+ if (!nanoidRegex.test(input.data)) {
1214
+ ctx = this._getOrReturnCtx(input, ctx);
1215
+ addIssueToContext(ctx, {
1216
+ validation: "nanoid",
1217
+ code: ZodIssueCode.invalid_string,
1218
+ message: check.message
1219
+ });
1220
+ status.dirty();
1221
+ }
1222
+ } else if (check.kind === "cuid") {
1223
+ if (!cuidRegex.test(input.data)) {
1224
+ ctx = this._getOrReturnCtx(input, ctx);
1225
+ addIssueToContext(ctx, {
1226
+ validation: "cuid",
1227
+ code: ZodIssueCode.invalid_string,
1228
+ message: check.message
1229
+ });
1230
+ status.dirty();
1231
+ }
1232
+ } else if (check.kind === "cuid2") {
1233
+ if (!cuid2Regex.test(input.data)) {
1234
+ ctx = this._getOrReturnCtx(input, ctx);
1235
+ addIssueToContext(ctx, {
1236
+ validation: "cuid2",
1237
+ code: ZodIssueCode.invalid_string,
1238
+ message: check.message
1239
+ });
1240
+ status.dirty();
1241
+ }
1242
+ } else if (check.kind === "ulid") {
1243
+ if (!ulidRegex.test(input.data)) {
1244
+ ctx = this._getOrReturnCtx(input, ctx);
1245
+ addIssueToContext(ctx, {
1246
+ validation: "ulid",
1247
+ code: ZodIssueCode.invalid_string,
1248
+ message: check.message
1249
+ });
1250
+ status.dirty();
1251
+ }
1252
+ } else if (check.kind === "url") {
1253
+ try {
1254
+ new URL(input.data);
1255
+ } catch {
1256
+ ctx = this._getOrReturnCtx(input, ctx);
1257
+ addIssueToContext(ctx, {
1258
+ validation: "url",
1259
+ code: ZodIssueCode.invalid_string,
1260
+ message: check.message
1261
+ });
1262
+ status.dirty();
1263
+ }
1264
+ } else if (check.kind === "regex") {
1265
+ check.regex.lastIndex = 0;
1266
+ const testResult = check.regex.test(input.data);
1267
+ if (!testResult) {
1268
+ ctx = this._getOrReturnCtx(input, ctx);
1269
+ addIssueToContext(ctx, {
1270
+ validation: "regex",
1271
+ code: ZodIssueCode.invalid_string,
1272
+ message: check.message
1273
+ });
1274
+ status.dirty();
1275
+ }
1276
+ } else if (check.kind === "trim") {
1277
+ input.data = input.data.trim();
1278
+ } else if (check.kind === "includes") {
1279
+ if (!input.data.includes(check.value, check.position)) {
1280
+ ctx = this._getOrReturnCtx(input, ctx);
1281
+ addIssueToContext(ctx, {
1282
+ code: ZodIssueCode.invalid_string,
1283
+ validation: { includes: check.value, position: check.position },
1284
+ message: check.message
1285
+ });
1286
+ status.dirty();
1287
+ }
1288
+ } else if (check.kind === "toLowerCase") {
1289
+ input.data = input.data.toLowerCase();
1290
+ } else if (check.kind === "toUpperCase") {
1291
+ input.data = input.data.toUpperCase();
1292
+ } else if (check.kind === "startsWith") {
1293
+ if (!input.data.startsWith(check.value)) {
1294
+ ctx = this._getOrReturnCtx(input, ctx);
1295
+ addIssueToContext(ctx, {
1296
+ code: ZodIssueCode.invalid_string,
1297
+ validation: { startsWith: check.value },
1298
+ message: check.message
1299
+ });
1300
+ status.dirty();
1301
+ }
1302
+ } else if (check.kind === "endsWith") {
1303
+ if (!input.data.endsWith(check.value)) {
1304
+ ctx = this._getOrReturnCtx(input, ctx);
1305
+ addIssueToContext(ctx, {
1306
+ code: ZodIssueCode.invalid_string,
1307
+ validation: { endsWith: check.value },
1308
+ message: check.message
1309
+ });
1310
+ status.dirty();
1311
+ }
1312
+ } else if (check.kind === "datetime") {
1313
+ const regex = datetimeRegex(check);
1314
+ if (!regex.test(input.data)) {
1315
+ ctx = this._getOrReturnCtx(input, ctx);
1316
+ addIssueToContext(ctx, {
1317
+ code: ZodIssueCode.invalid_string,
1318
+ validation: "datetime",
1319
+ message: check.message
1320
+ });
1321
+ status.dirty();
1322
+ }
1323
+ } else if (check.kind === "date") {
1324
+ const regex = dateRegex;
1325
+ if (!regex.test(input.data)) {
1326
+ ctx = this._getOrReturnCtx(input, ctx);
1327
+ addIssueToContext(ctx, {
1328
+ code: ZodIssueCode.invalid_string,
1329
+ validation: "date",
1330
+ message: check.message
1331
+ });
1332
+ status.dirty();
1333
+ }
1334
+ } else if (check.kind === "time") {
1335
+ const regex = timeRegex(check);
1336
+ if (!regex.test(input.data)) {
1337
+ ctx = this._getOrReturnCtx(input, ctx);
1338
+ addIssueToContext(ctx, {
1339
+ code: ZodIssueCode.invalid_string,
1340
+ validation: "time",
1341
+ message: check.message
1342
+ });
1343
+ status.dirty();
1344
+ }
1345
+ } else if (check.kind === "duration") {
1346
+ if (!durationRegex.test(input.data)) {
1347
+ ctx = this._getOrReturnCtx(input, ctx);
1348
+ addIssueToContext(ctx, {
1349
+ validation: "duration",
1350
+ code: ZodIssueCode.invalid_string,
1351
+ message: check.message
1352
+ });
1353
+ status.dirty();
1354
+ }
1355
+ } else if (check.kind === "ip") {
1356
+ if (!isValidIP(input.data, check.version)) {
1357
+ ctx = this._getOrReturnCtx(input, ctx);
1358
+ addIssueToContext(ctx, {
1359
+ validation: "ip",
1360
+ code: ZodIssueCode.invalid_string,
1361
+ message: check.message
1362
+ });
1363
+ status.dirty();
1364
+ }
1365
+ } else if (check.kind === "jwt") {
1366
+ if (!isValidJWT(input.data, check.alg)) {
1367
+ ctx = this._getOrReturnCtx(input, ctx);
1368
+ addIssueToContext(ctx, {
1369
+ validation: "jwt",
1370
+ code: ZodIssueCode.invalid_string,
1371
+ message: check.message
1372
+ });
1373
+ status.dirty();
1374
+ }
1375
+ } else if (check.kind === "cidr") {
1376
+ if (!isValidCidr(input.data, check.version)) {
1377
+ ctx = this._getOrReturnCtx(input, ctx);
1378
+ addIssueToContext(ctx, {
1379
+ validation: "cidr",
1380
+ code: ZodIssueCode.invalid_string,
1381
+ message: check.message
1382
+ });
1383
+ status.dirty();
1384
+ }
1385
+ } else if (check.kind === "base64") {
1386
+ if (!base64Regex.test(input.data)) {
1387
+ ctx = this._getOrReturnCtx(input, ctx);
1388
+ addIssueToContext(ctx, {
1389
+ validation: "base64",
1390
+ code: ZodIssueCode.invalid_string,
1391
+ message: check.message
1392
+ });
1393
+ status.dirty();
1394
+ }
1395
+ } else if (check.kind === "base64url") {
1396
+ if (!base64urlRegex.test(input.data)) {
1397
+ ctx = this._getOrReturnCtx(input, ctx);
1398
+ addIssueToContext(ctx, {
1399
+ validation: "base64url",
1400
+ code: ZodIssueCode.invalid_string,
1401
+ message: check.message
1402
+ });
1403
+ status.dirty();
1404
+ }
1405
+ } else {
1406
+ util.assertNever(check);
1407
+ }
1408
+ }
1409
+ return { status: status.value, value: input.data };
1410
+ }
1411
+ _regex(regex, validation, message) {
1412
+ return this.refinement((data) => regex.test(data), {
1413
+ validation,
1414
+ code: ZodIssueCode.invalid_string,
1415
+ ...errorUtil.errToObj(message)
1416
+ });
1417
+ }
1418
+ _addCheck(check) {
1419
+ return new _ZodString({
1420
+ ...this._def,
1421
+ checks: [...this._def.checks, check]
1422
+ });
1423
+ }
1424
+ email(message) {
1425
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1426
+ }
1427
+ url(message) {
1428
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1429
+ }
1430
+ emoji(message) {
1431
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1432
+ }
1433
+ uuid(message) {
1434
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1435
+ }
1436
+ nanoid(message) {
1437
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1438
+ }
1439
+ cuid(message) {
1440
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1441
+ }
1442
+ cuid2(message) {
1443
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1444
+ }
1445
+ ulid(message) {
1446
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1447
+ }
1448
+ base64(message) {
1449
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1450
+ }
1451
+ base64url(message) {
1452
+ return this._addCheck({
1453
+ kind: "base64url",
1454
+ ...errorUtil.errToObj(message)
1455
+ });
1456
+ }
1457
+ jwt(options) {
1458
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1459
+ }
1460
+ ip(options) {
1461
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1462
+ }
1463
+ cidr(options) {
1464
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1465
+ }
1466
+ datetime(options) {
1467
+ if (typeof options === "string") {
1468
+ return this._addCheck({
1469
+ kind: "datetime",
1470
+ precision: null,
1471
+ offset: false,
1472
+ local: false,
1473
+ message: options
1474
+ });
1475
+ }
1476
+ return this._addCheck({
1477
+ kind: "datetime",
1478
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1479
+ offset: options?.offset ?? false,
1480
+ local: options?.local ?? false,
1481
+ ...errorUtil.errToObj(options?.message)
1482
+ });
1483
+ }
1484
+ date(message) {
1485
+ return this._addCheck({ kind: "date", message });
1486
+ }
1487
+ time(options) {
1488
+ if (typeof options === "string") {
1489
+ return this._addCheck({
1490
+ kind: "time",
1491
+ precision: null,
1492
+ message: options
1493
+ });
1494
+ }
1495
+ return this._addCheck({
1496
+ kind: "time",
1497
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1498
+ ...errorUtil.errToObj(options?.message)
1499
+ });
1500
+ }
1501
+ duration(message) {
1502
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1503
+ }
1504
+ regex(regex, message) {
1505
+ return this._addCheck({
1506
+ kind: "regex",
1507
+ regex,
1508
+ ...errorUtil.errToObj(message)
1509
+ });
1510
+ }
1511
+ includes(value, options) {
1512
+ return this._addCheck({
1513
+ kind: "includes",
1514
+ value,
1515
+ position: options?.position,
1516
+ ...errorUtil.errToObj(options?.message)
1517
+ });
1518
+ }
1519
+ startsWith(value, message) {
1520
+ return this._addCheck({
1521
+ kind: "startsWith",
1522
+ value,
1523
+ ...errorUtil.errToObj(message)
1524
+ });
1525
+ }
1526
+ endsWith(value, message) {
1527
+ return this._addCheck({
1528
+ kind: "endsWith",
1529
+ value,
1530
+ ...errorUtil.errToObj(message)
1531
+ });
1532
+ }
1533
+ min(minLength, message) {
1534
+ return this._addCheck({
1535
+ kind: "min",
1536
+ value: minLength,
1537
+ ...errorUtil.errToObj(message)
1538
+ });
1539
+ }
1540
+ max(maxLength, message) {
1541
+ return this._addCheck({
1542
+ kind: "max",
1543
+ value: maxLength,
1544
+ ...errorUtil.errToObj(message)
1545
+ });
1546
+ }
1547
+ length(len, message) {
1548
+ return this._addCheck({
1549
+ kind: "length",
1550
+ value: len,
1551
+ ...errorUtil.errToObj(message)
1552
+ });
1553
+ }
1554
+ /**
1555
+ * Equivalent to `.min(1)`
1556
+ */
1557
+ nonempty(message) {
1558
+ return this.min(1, errorUtil.errToObj(message));
1559
+ }
1560
+ trim() {
1561
+ return new _ZodString({
1562
+ ...this._def,
1563
+ checks: [...this._def.checks, { kind: "trim" }]
1564
+ });
1565
+ }
1566
+ toLowerCase() {
1567
+ return new _ZodString({
1568
+ ...this._def,
1569
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
1570
+ });
1571
+ }
1572
+ toUpperCase() {
1573
+ return new _ZodString({
1574
+ ...this._def,
1575
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
1576
+ });
1577
+ }
1578
+ get isDatetime() {
1579
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1580
+ }
1581
+ get isDate() {
1582
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1583
+ }
1584
+ get isTime() {
1585
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1586
+ }
1587
+ get isDuration() {
1588
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1589
+ }
1590
+ get isEmail() {
1591
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1592
+ }
1593
+ get isURL() {
1594
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1595
+ }
1596
+ get isEmoji() {
1597
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1598
+ }
1599
+ get isUUID() {
1600
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1601
+ }
1602
+ get isNANOID() {
1603
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1604
+ }
1605
+ get isCUID() {
1606
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1607
+ }
1608
+ get isCUID2() {
1609
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1610
+ }
1611
+ get isULID() {
1612
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1613
+ }
1614
+ get isIP() {
1615
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1616
+ }
1617
+ get isCIDR() {
1618
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
1619
+ }
1620
+ get isBase64() {
1621
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1622
+ }
1623
+ get isBase64url() {
1624
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
1625
+ }
1626
+ get minLength() {
1627
+ let min = null;
1628
+ for (const ch of this._def.checks) {
1629
+ if (ch.kind === "min") {
1630
+ if (min === null || ch.value > min)
1631
+ min = ch.value;
1632
+ }
1633
+ }
1634
+ return min;
1635
+ }
1636
+ get maxLength() {
1637
+ let max = null;
1638
+ for (const ch of this._def.checks) {
1639
+ if (ch.kind === "max") {
1640
+ if (max === null || ch.value < max)
1641
+ max = ch.value;
1642
+ }
1643
+ }
1644
+ return max;
1645
+ }
1646
+ };
1647
+ ZodString.create = (params) => {
1648
+ return new ZodString({
1649
+ checks: [],
1650
+ typeName: ZodFirstPartyTypeKind.ZodString,
1651
+ coerce: params?.coerce ?? false,
1652
+ ...processCreateParams(params)
1653
+ });
1654
+ };
1655
+ function floatSafeRemainder(val, step) {
1656
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1657
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1658
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1659
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1660
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1661
+ return valInt % stepInt / 10 ** decCount;
1662
+ }
1663
+ var ZodNumber = class _ZodNumber extends ZodType {
1664
+ constructor() {
1665
+ super(...arguments);
1666
+ this.min = this.gte;
1667
+ this.max = this.lte;
1668
+ this.step = this.multipleOf;
1669
+ }
1670
+ _parse(input) {
1671
+ if (this._def.coerce) {
1672
+ input.data = Number(input.data);
1673
+ }
1674
+ const parsedType = this._getType(input);
1675
+ if (parsedType !== ZodParsedType.number) {
1676
+ const ctx2 = this._getOrReturnCtx(input);
1677
+ addIssueToContext(ctx2, {
1678
+ code: ZodIssueCode.invalid_type,
1679
+ expected: ZodParsedType.number,
1680
+ received: ctx2.parsedType
1681
+ });
1682
+ return INVALID;
1683
+ }
1684
+ let ctx = void 0;
1685
+ const status = new ParseStatus();
1686
+ for (const check of this._def.checks) {
1687
+ if (check.kind === "int") {
1688
+ if (!util.isInteger(input.data)) {
1689
+ ctx = this._getOrReturnCtx(input, ctx);
1690
+ addIssueToContext(ctx, {
1691
+ code: ZodIssueCode.invalid_type,
1692
+ expected: "integer",
1693
+ received: "float",
1694
+ message: check.message
1695
+ });
1696
+ status.dirty();
1697
+ }
1698
+ } else if (check.kind === "min") {
1699
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1700
+ if (tooSmall) {
1701
+ ctx = this._getOrReturnCtx(input, ctx);
1702
+ addIssueToContext(ctx, {
1703
+ code: ZodIssueCode.too_small,
1704
+ minimum: check.value,
1705
+ type: "number",
1706
+ inclusive: check.inclusive,
1707
+ exact: false,
1708
+ message: check.message
1709
+ });
1710
+ status.dirty();
1711
+ }
1712
+ } else if (check.kind === "max") {
1713
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1714
+ if (tooBig) {
1715
+ ctx = this._getOrReturnCtx(input, ctx);
1716
+ addIssueToContext(ctx, {
1717
+ code: ZodIssueCode.too_big,
1718
+ maximum: check.value,
1719
+ type: "number",
1720
+ inclusive: check.inclusive,
1721
+ exact: false,
1722
+ message: check.message
1723
+ });
1724
+ status.dirty();
1725
+ }
1726
+ } else if (check.kind === "multipleOf") {
1727
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1728
+ ctx = this._getOrReturnCtx(input, ctx);
1729
+ addIssueToContext(ctx, {
1730
+ code: ZodIssueCode.not_multiple_of,
1731
+ multipleOf: check.value,
1732
+ message: check.message
1733
+ });
1734
+ status.dirty();
1735
+ }
1736
+ } else if (check.kind === "finite") {
1737
+ if (!Number.isFinite(input.data)) {
1738
+ ctx = this._getOrReturnCtx(input, ctx);
1739
+ addIssueToContext(ctx, {
1740
+ code: ZodIssueCode.not_finite,
1741
+ message: check.message
1742
+ });
1743
+ status.dirty();
1744
+ }
1745
+ } else {
1746
+ util.assertNever(check);
1747
+ }
1748
+ }
1749
+ return { status: status.value, value: input.data };
1750
+ }
1751
+ gte(value, message) {
1752
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1753
+ }
1754
+ gt(value, message) {
1755
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1756
+ }
1757
+ lte(value, message) {
1758
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1759
+ }
1760
+ lt(value, message) {
1761
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1762
+ }
1763
+ setLimit(kind, value, inclusive, message) {
1764
+ return new _ZodNumber({
1765
+ ...this._def,
1766
+ checks: [
1767
+ ...this._def.checks,
1768
+ {
1769
+ kind,
1770
+ value,
1771
+ inclusive,
1772
+ message: errorUtil.toString(message)
1773
+ }
1774
+ ]
1775
+ });
1776
+ }
1777
+ _addCheck(check) {
1778
+ return new _ZodNumber({
1779
+ ...this._def,
1780
+ checks: [...this._def.checks, check]
1781
+ });
1782
+ }
1783
+ int(message) {
1784
+ return this._addCheck({
1785
+ kind: "int",
1786
+ message: errorUtil.toString(message)
1787
+ });
1788
+ }
1789
+ positive(message) {
1790
+ return this._addCheck({
1791
+ kind: "min",
1792
+ value: 0,
1793
+ inclusive: false,
1794
+ message: errorUtil.toString(message)
1795
+ });
1796
+ }
1797
+ negative(message) {
1798
+ return this._addCheck({
1799
+ kind: "max",
1800
+ value: 0,
1801
+ inclusive: false,
1802
+ message: errorUtil.toString(message)
1803
+ });
1804
+ }
1805
+ nonpositive(message) {
1806
+ return this._addCheck({
1807
+ kind: "max",
1808
+ value: 0,
1809
+ inclusive: true,
1810
+ message: errorUtil.toString(message)
1811
+ });
1812
+ }
1813
+ nonnegative(message) {
1814
+ return this._addCheck({
1815
+ kind: "min",
1816
+ value: 0,
1817
+ inclusive: true,
1818
+ message: errorUtil.toString(message)
1819
+ });
1820
+ }
1821
+ multipleOf(value, message) {
1822
+ return this._addCheck({
1823
+ kind: "multipleOf",
1824
+ value,
1825
+ message: errorUtil.toString(message)
1826
+ });
1827
+ }
1828
+ finite(message) {
1829
+ return this._addCheck({
1830
+ kind: "finite",
1831
+ message: errorUtil.toString(message)
1832
+ });
1833
+ }
1834
+ safe(message) {
1835
+ return this._addCheck({
1836
+ kind: "min",
1837
+ inclusive: true,
1838
+ value: Number.MIN_SAFE_INTEGER,
1839
+ message: errorUtil.toString(message)
1840
+ })._addCheck({
1841
+ kind: "max",
1842
+ inclusive: true,
1843
+ value: Number.MAX_SAFE_INTEGER,
1844
+ message: errorUtil.toString(message)
1845
+ });
1846
+ }
1847
+ get minValue() {
1848
+ let min = null;
1849
+ for (const ch of this._def.checks) {
1850
+ if (ch.kind === "min") {
1851
+ if (min === null || ch.value > min)
1852
+ min = ch.value;
1853
+ }
1854
+ }
1855
+ return min;
1856
+ }
1857
+ get maxValue() {
1858
+ let max = null;
1859
+ for (const ch of this._def.checks) {
1860
+ if (ch.kind === "max") {
1861
+ if (max === null || ch.value < max)
1862
+ max = ch.value;
1863
+ }
1864
+ }
1865
+ return max;
1866
+ }
1867
+ get isInt() {
1868
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1869
+ }
1870
+ get isFinite() {
1871
+ let max = null;
1872
+ let min = null;
1873
+ for (const ch of this._def.checks) {
1874
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1875
+ return true;
1876
+ } else if (ch.kind === "min") {
1877
+ if (min === null || ch.value > min)
1878
+ min = ch.value;
1879
+ } else if (ch.kind === "max") {
1880
+ if (max === null || ch.value < max)
1881
+ max = ch.value;
1882
+ }
1883
+ }
1884
+ return Number.isFinite(min) && Number.isFinite(max);
1885
+ }
1886
+ };
1887
+ ZodNumber.create = (params) => {
1888
+ return new ZodNumber({
1889
+ checks: [],
1890
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1891
+ coerce: params?.coerce || false,
1892
+ ...processCreateParams(params)
1893
+ });
1894
+ };
1895
+ var ZodBigInt = class _ZodBigInt extends ZodType {
1896
+ constructor() {
1897
+ super(...arguments);
1898
+ this.min = this.gte;
1899
+ this.max = this.lte;
1900
+ }
1901
+ _parse(input) {
1902
+ if (this._def.coerce) {
1903
+ try {
1904
+ input.data = BigInt(input.data);
1905
+ } catch {
1906
+ return this._getInvalidInput(input);
1907
+ }
1908
+ }
1909
+ const parsedType = this._getType(input);
1910
+ if (parsedType !== ZodParsedType.bigint) {
1911
+ return this._getInvalidInput(input);
1912
+ }
1913
+ let ctx = void 0;
1914
+ const status = new ParseStatus();
1915
+ for (const check of this._def.checks) {
1916
+ if (check.kind === "min") {
1917
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1918
+ if (tooSmall) {
1919
+ ctx = this._getOrReturnCtx(input, ctx);
1920
+ addIssueToContext(ctx, {
1921
+ code: ZodIssueCode.too_small,
1922
+ type: "bigint",
1923
+ minimum: check.value,
1924
+ inclusive: check.inclusive,
1925
+ message: check.message
1926
+ });
1927
+ status.dirty();
1928
+ }
1929
+ } else if (check.kind === "max") {
1930
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1931
+ if (tooBig) {
1932
+ ctx = this._getOrReturnCtx(input, ctx);
1933
+ addIssueToContext(ctx, {
1934
+ code: ZodIssueCode.too_big,
1935
+ type: "bigint",
1936
+ maximum: check.value,
1937
+ inclusive: check.inclusive,
1938
+ message: check.message
1939
+ });
1940
+ status.dirty();
1941
+ }
1942
+ } else if (check.kind === "multipleOf") {
1943
+ if (input.data % check.value !== BigInt(0)) {
1944
+ ctx = this._getOrReturnCtx(input, ctx);
1945
+ addIssueToContext(ctx, {
1946
+ code: ZodIssueCode.not_multiple_of,
1947
+ multipleOf: check.value,
1948
+ message: check.message
1949
+ });
1950
+ status.dirty();
1951
+ }
1952
+ } else {
1953
+ util.assertNever(check);
1954
+ }
1955
+ }
1956
+ return { status: status.value, value: input.data };
1957
+ }
1958
+ _getInvalidInput(input) {
1959
+ const ctx = this._getOrReturnCtx(input);
1960
+ addIssueToContext(ctx, {
1961
+ code: ZodIssueCode.invalid_type,
1962
+ expected: ZodParsedType.bigint,
1963
+ received: ctx.parsedType
1964
+ });
1965
+ return INVALID;
1966
+ }
1967
+ gte(value, message) {
1968
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1969
+ }
1970
+ gt(value, message) {
1971
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1972
+ }
1973
+ lte(value, message) {
1974
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1975
+ }
1976
+ lt(value, message) {
1977
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1978
+ }
1979
+ setLimit(kind, value, inclusive, message) {
1980
+ return new _ZodBigInt({
1981
+ ...this._def,
1982
+ checks: [
1983
+ ...this._def.checks,
1984
+ {
1985
+ kind,
1986
+ value,
1987
+ inclusive,
1988
+ message: errorUtil.toString(message)
1989
+ }
1990
+ ]
1991
+ });
1992
+ }
1993
+ _addCheck(check) {
1994
+ return new _ZodBigInt({
1995
+ ...this._def,
1996
+ checks: [...this._def.checks, check]
1997
+ });
1998
+ }
1999
+ positive(message) {
2000
+ return this._addCheck({
2001
+ kind: "min",
2002
+ value: BigInt(0),
2003
+ inclusive: false,
2004
+ message: errorUtil.toString(message)
2005
+ });
2006
+ }
2007
+ negative(message) {
2008
+ return this._addCheck({
2009
+ kind: "max",
2010
+ value: BigInt(0),
2011
+ inclusive: false,
2012
+ message: errorUtil.toString(message)
2013
+ });
2014
+ }
2015
+ nonpositive(message) {
2016
+ return this._addCheck({
2017
+ kind: "max",
2018
+ value: BigInt(0),
2019
+ inclusive: true,
2020
+ message: errorUtil.toString(message)
2021
+ });
2022
+ }
2023
+ nonnegative(message) {
2024
+ return this._addCheck({
2025
+ kind: "min",
2026
+ value: BigInt(0),
2027
+ inclusive: true,
2028
+ message: errorUtil.toString(message)
2029
+ });
2030
+ }
2031
+ multipleOf(value, message) {
2032
+ return this._addCheck({
2033
+ kind: "multipleOf",
2034
+ value,
2035
+ message: errorUtil.toString(message)
2036
+ });
2037
+ }
2038
+ get minValue() {
2039
+ let min = null;
2040
+ for (const ch of this._def.checks) {
2041
+ if (ch.kind === "min") {
2042
+ if (min === null || ch.value > min)
2043
+ min = ch.value;
2044
+ }
2045
+ }
2046
+ return min;
2047
+ }
2048
+ get maxValue() {
2049
+ let max = null;
2050
+ for (const ch of this._def.checks) {
2051
+ if (ch.kind === "max") {
2052
+ if (max === null || ch.value < max)
2053
+ max = ch.value;
2054
+ }
2055
+ }
2056
+ return max;
2057
+ }
2058
+ };
2059
+ ZodBigInt.create = (params) => {
2060
+ return new ZodBigInt({
2061
+ checks: [],
2062
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
2063
+ coerce: params?.coerce ?? false,
2064
+ ...processCreateParams(params)
2065
+ });
2066
+ };
2067
+ var ZodBoolean = class extends ZodType {
2068
+ _parse(input) {
2069
+ if (this._def.coerce) {
2070
+ input.data = Boolean(input.data);
2071
+ }
2072
+ const parsedType = this._getType(input);
2073
+ if (parsedType !== ZodParsedType.boolean) {
2074
+ const ctx = this._getOrReturnCtx(input);
2075
+ addIssueToContext(ctx, {
2076
+ code: ZodIssueCode.invalid_type,
2077
+ expected: ZodParsedType.boolean,
2078
+ received: ctx.parsedType
2079
+ });
2080
+ return INVALID;
2081
+ }
2082
+ return OK(input.data);
2083
+ }
2084
+ };
2085
+ ZodBoolean.create = (params) => {
2086
+ return new ZodBoolean({
2087
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2088
+ coerce: params?.coerce || false,
2089
+ ...processCreateParams(params)
2090
+ });
2091
+ };
2092
+ var ZodDate = class _ZodDate extends ZodType {
2093
+ _parse(input) {
2094
+ if (this._def.coerce) {
2095
+ input.data = new Date(input.data);
2096
+ }
2097
+ const parsedType = this._getType(input);
2098
+ if (parsedType !== ZodParsedType.date) {
2099
+ const ctx2 = this._getOrReturnCtx(input);
2100
+ addIssueToContext(ctx2, {
2101
+ code: ZodIssueCode.invalid_type,
2102
+ expected: ZodParsedType.date,
2103
+ received: ctx2.parsedType
2104
+ });
2105
+ return INVALID;
2106
+ }
2107
+ if (Number.isNaN(input.data.getTime())) {
2108
+ const ctx2 = this._getOrReturnCtx(input);
2109
+ addIssueToContext(ctx2, {
2110
+ code: ZodIssueCode.invalid_date
2111
+ });
2112
+ return INVALID;
2113
+ }
2114
+ const status = new ParseStatus();
2115
+ let ctx = void 0;
2116
+ for (const check of this._def.checks) {
2117
+ if (check.kind === "min") {
2118
+ if (input.data.getTime() < check.value) {
2119
+ ctx = this._getOrReturnCtx(input, ctx);
2120
+ addIssueToContext(ctx, {
2121
+ code: ZodIssueCode.too_small,
2122
+ message: check.message,
2123
+ inclusive: true,
2124
+ exact: false,
2125
+ minimum: check.value,
2126
+ type: "date"
2127
+ });
2128
+ status.dirty();
2129
+ }
2130
+ } else if (check.kind === "max") {
2131
+ if (input.data.getTime() > check.value) {
2132
+ ctx = this._getOrReturnCtx(input, ctx);
2133
+ addIssueToContext(ctx, {
2134
+ code: ZodIssueCode.too_big,
2135
+ message: check.message,
2136
+ inclusive: true,
2137
+ exact: false,
2138
+ maximum: check.value,
2139
+ type: "date"
2140
+ });
2141
+ status.dirty();
2142
+ }
2143
+ } else {
2144
+ util.assertNever(check);
2145
+ }
2146
+ }
2147
+ return {
2148
+ status: status.value,
2149
+ value: new Date(input.data.getTime())
2150
+ };
2151
+ }
2152
+ _addCheck(check) {
2153
+ return new _ZodDate({
2154
+ ...this._def,
2155
+ checks: [...this._def.checks, check]
2156
+ });
2157
+ }
2158
+ min(minDate, message) {
2159
+ return this._addCheck({
2160
+ kind: "min",
2161
+ value: minDate.getTime(),
2162
+ message: errorUtil.toString(message)
2163
+ });
2164
+ }
2165
+ max(maxDate, message) {
2166
+ return this._addCheck({
2167
+ kind: "max",
2168
+ value: maxDate.getTime(),
2169
+ message: errorUtil.toString(message)
2170
+ });
2171
+ }
2172
+ get minDate() {
2173
+ let min = null;
2174
+ for (const ch of this._def.checks) {
2175
+ if (ch.kind === "min") {
2176
+ if (min === null || ch.value > min)
2177
+ min = ch.value;
2178
+ }
2179
+ }
2180
+ return min != null ? new Date(min) : null;
2181
+ }
2182
+ get maxDate() {
2183
+ let max = null;
2184
+ for (const ch of this._def.checks) {
2185
+ if (ch.kind === "max") {
2186
+ if (max === null || ch.value < max)
2187
+ max = ch.value;
2188
+ }
2189
+ }
2190
+ return max != null ? new Date(max) : null;
2191
+ }
2192
+ };
2193
+ ZodDate.create = (params) => {
2194
+ return new ZodDate({
2195
+ checks: [],
2196
+ coerce: params?.coerce || false,
2197
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2198
+ ...processCreateParams(params)
2199
+ });
2200
+ };
2201
+ var ZodSymbol = class extends ZodType {
2202
+ _parse(input) {
2203
+ const parsedType = this._getType(input);
2204
+ if (parsedType !== ZodParsedType.symbol) {
2205
+ const ctx = this._getOrReturnCtx(input);
2206
+ addIssueToContext(ctx, {
2207
+ code: ZodIssueCode.invalid_type,
2208
+ expected: ZodParsedType.symbol,
2209
+ received: ctx.parsedType
2210
+ });
2211
+ return INVALID;
2212
+ }
2213
+ return OK(input.data);
2214
+ }
2215
+ };
2216
+ ZodSymbol.create = (params) => {
2217
+ return new ZodSymbol({
2218
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2219
+ ...processCreateParams(params)
2220
+ });
2221
+ };
2222
+ var ZodUndefined = class extends ZodType {
2223
+ _parse(input) {
2224
+ const parsedType = this._getType(input);
2225
+ if (parsedType !== ZodParsedType.undefined) {
2226
+ const ctx = this._getOrReturnCtx(input);
2227
+ addIssueToContext(ctx, {
2228
+ code: ZodIssueCode.invalid_type,
2229
+ expected: ZodParsedType.undefined,
2230
+ received: ctx.parsedType
2231
+ });
2232
+ return INVALID;
2233
+ }
2234
+ return OK(input.data);
2235
+ }
2236
+ };
2237
+ ZodUndefined.create = (params) => {
2238
+ return new ZodUndefined({
2239
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2240
+ ...processCreateParams(params)
2241
+ });
2242
+ };
2243
+ var ZodNull = class extends ZodType {
2244
+ _parse(input) {
2245
+ const parsedType = this._getType(input);
2246
+ if (parsedType !== ZodParsedType.null) {
2247
+ const ctx = this._getOrReturnCtx(input);
2248
+ addIssueToContext(ctx, {
2249
+ code: ZodIssueCode.invalid_type,
2250
+ expected: ZodParsedType.null,
2251
+ received: ctx.parsedType
2252
+ });
2253
+ return INVALID;
2254
+ }
2255
+ return OK(input.data);
2256
+ }
2257
+ };
2258
+ ZodNull.create = (params) => {
2259
+ return new ZodNull({
2260
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2261
+ ...processCreateParams(params)
2262
+ });
2263
+ };
2264
+ var ZodAny = class extends ZodType {
2265
+ constructor() {
2266
+ super(...arguments);
2267
+ this._any = true;
2268
+ }
2269
+ _parse(input) {
2270
+ return OK(input.data);
2271
+ }
2272
+ };
2273
+ ZodAny.create = (params) => {
2274
+ return new ZodAny({
2275
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2276
+ ...processCreateParams(params)
2277
+ });
2278
+ };
2279
+ var ZodUnknown = class extends ZodType {
2280
+ constructor() {
2281
+ super(...arguments);
2282
+ this._unknown = true;
2283
+ }
2284
+ _parse(input) {
2285
+ return OK(input.data);
2286
+ }
2287
+ };
2288
+ ZodUnknown.create = (params) => {
2289
+ return new ZodUnknown({
2290
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2291
+ ...processCreateParams(params)
2292
+ });
2293
+ };
2294
+ var ZodNever = class extends ZodType {
2295
+ _parse(input) {
2296
+ const ctx = this._getOrReturnCtx(input);
2297
+ addIssueToContext(ctx, {
2298
+ code: ZodIssueCode.invalid_type,
2299
+ expected: ZodParsedType.never,
2300
+ received: ctx.parsedType
2301
+ });
2302
+ return INVALID;
2303
+ }
2304
+ };
2305
+ ZodNever.create = (params) => {
2306
+ return new ZodNever({
2307
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2308
+ ...processCreateParams(params)
2309
+ });
2310
+ };
2311
+ var ZodVoid = class extends ZodType {
2312
+ _parse(input) {
2313
+ const parsedType = this._getType(input);
2314
+ if (parsedType !== ZodParsedType.undefined) {
2315
+ const ctx = this._getOrReturnCtx(input);
2316
+ addIssueToContext(ctx, {
2317
+ code: ZodIssueCode.invalid_type,
2318
+ expected: ZodParsedType.void,
2319
+ received: ctx.parsedType
2320
+ });
2321
+ return INVALID;
2322
+ }
2323
+ return OK(input.data);
2324
+ }
2325
+ };
2326
+ ZodVoid.create = (params) => {
2327
+ return new ZodVoid({
2328
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2329
+ ...processCreateParams(params)
2330
+ });
2331
+ };
2332
+ var ZodArray = class _ZodArray extends ZodType {
2333
+ _parse(input) {
2334
+ const { ctx, status } = this._processInputParams(input);
2335
+ const def = this._def;
2336
+ if (ctx.parsedType !== ZodParsedType.array) {
2337
+ addIssueToContext(ctx, {
2338
+ code: ZodIssueCode.invalid_type,
2339
+ expected: ZodParsedType.array,
2340
+ received: ctx.parsedType
2341
+ });
2342
+ return INVALID;
2343
+ }
2344
+ if (def.exactLength !== null) {
2345
+ const tooBig = ctx.data.length > def.exactLength.value;
2346
+ const tooSmall = ctx.data.length < def.exactLength.value;
2347
+ if (tooBig || tooSmall) {
2348
+ addIssueToContext(ctx, {
2349
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2350
+ minimum: tooSmall ? def.exactLength.value : void 0,
2351
+ maximum: tooBig ? def.exactLength.value : void 0,
2352
+ type: "array",
2353
+ inclusive: true,
2354
+ exact: true,
2355
+ message: def.exactLength.message
2356
+ });
2357
+ status.dirty();
2358
+ }
2359
+ }
2360
+ if (def.minLength !== null) {
2361
+ if (ctx.data.length < def.minLength.value) {
2362
+ addIssueToContext(ctx, {
2363
+ code: ZodIssueCode.too_small,
2364
+ minimum: def.minLength.value,
2365
+ type: "array",
2366
+ inclusive: true,
2367
+ exact: false,
2368
+ message: def.minLength.message
2369
+ });
2370
+ status.dirty();
2371
+ }
2372
+ }
2373
+ if (def.maxLength !== null) {
2374
+ if (ctx.data.length > def.maxLength.value) {
2375
+ addIssueToContext(ctx, {
2376
+ code: ZodIssueCode.too_big,
2377
+ maximum: def.maxLength.value,
2378
+ type: "array",
2379
+ inclusive: true,
2380
+ exact: false,
2381
+ message: def.maxLength.message
2382
+ });
2383
+ status.dirty();
2384
+ }
2385
+ }
2386
+ if (ctx.common.async) {
2387
+ return Promise.all([...ctx.data].map((item, i) => {
2388
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2389
+ })).then((result2) => {
2390
+ return ParseStatus.mergeArray(status, result2);
2391
+ });
2392
+ }
2393
+ const result = [...ctx.data].map((item, i) => {
2394
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2395
+ });
2396
+ return ParseStatus.mergeArray(status, result);
2397
+ }
2398
+ get element() {
2399
+ return this._def.type;
2400
+ }
2401
+ min(minLength, message) {
2402
+ return new _ZodArray({
2403
+ ...this._def,
2404
+ minLength: { value: minLength, message: errorUtil.toString(message) }
2405
+ });
2406
+ }
2407
+ max(maxLength, message) {
2408
+ return new _ZodArray({
2409
+ ...this._def,
2410
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
2411
+ });
2412
+ }
2413
+ length(len, message) {
2414
+ return new _ZodArray({
2415
+ ...this._def,
2416
+ exactLength: { value: len, message: errorUtil.toString(message) }
2417
+ });
2418
+ }
2419
+ nonempty(message) {
2420
+ return this.min(1, message);
2421
+ }
2422
+ };
2423
+ ZodArray.create = (schema, params) => {
2424
+ return new ZodArray({
2425
+ type: schema,
2426
+ minLength: null,
2427
+ maxLength: null,
2428
+ exactLength: null,
2429
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2430
+ ...processCreateParams(params)
2431
+ });
2432
+ };
2433
+ function deepPartialify(schema) {
2434
+ if (schema instanceof ZodObject) {
2435
+ const newShape = {};
2436
+ for (const key in schema.shape) {
2437
+ const fieldSchema2 = schema.shape[key];
2438
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema2));
2439
+ }
2440
+ return new ZodObject({
2441
+ ...schema._def,
2442
+ shape: () => newShape
2443
+ });
2444
+ } else if (schema instanceof ZodArray) {
2445
+ return new ZodArray({
2446
+ ...schema._def,
2447
+ type: deepPartialify(schema.element)
2448
+ });
2449
+ } else if (schema instanceof ZodOptional) {
2450
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2451
+ } else if (schema instanceof ZodNullable) {
2452
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2453
+ } else if (schema instanceof ZodTuple) {
2454
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2455
+ } else {
2456
+ return schema;
2457
+ }
2458
+ }
2459
+ var ZodObject = class _ZodObject extends ZodType {
2460
+ constructor() {
2461
+ super(...arguments);
2462
+ this._cached = null;
2463
+ this.nonstrict = this.passthrough;
2464
+ this.augment = this.extend;
2465
+ }
2466
+ _getCached() {
2467
+ if (this._cached !== null)
2468
+ return this._cached;
2469
+ const shape = this._def.shape();
2470
+ const keys = util.objectKeys(shape);
2471
+ this._cached = { shape, keys };
2472
+ return this._cached;
2473
+ }
2474
+ _parse(input) {
2475
+ const parsedType = this._getType(input);
2476
+ if (parsedType !== ZodParsedType.object) {
2477
+ const ctx2 = this._getOrReturnCtx(input);
2478
+ addIssueToContext(ctx2, {
2479
+ code: ZodIssueCode.invalid_type,
2480
+ expected: ZodParsedType.object,
2481
+ received: ctx2.parsedType
2482
+ });
2483
+ return INVALID;
2484
+ }
2485
+ const { status, ctx } = this._processInputParams(input);
2486
+ const { shape, keys: shapeKeys } = this._getCached();
2487
+ const extraKeys = [];
2488
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2489
+ for (const key in ctx.data) {
2490
+ if (!shapeKeys.includes(key)) {
2491
+ extraKeys.push(key);
2492
+ }
2493
+ }
2494
+ }
2495
+ const pairs = [];
2496
+ for (const key of shapeKeys) {
2497
+ const keyValidator = shape[key];
2498
+ const value = ctx.data[key];
2499
+ pairs.push({
2500
+ key: { status: "valid", value: key },
2501
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2502
+ alwaysSet: key in ctx.data
2503
+ });
2504
+ }
2505
+ if (this._def.catchall instanceof ZodNever) {
2506
+ const unknownKeys = this._def.unknownKeys;
2507
+ if (unknownKeys === "passthrough") {
2508
+ for (const key of extraKeys) {
2509
+ pairs.push({
2510
+ key: { status: "valid", value: key },
2511
+ value: { status: "valid", value: ctx.data[key] }
2512
+ });
2513
+ }
2514
+ } else if (unknownKeys === "strict") {
2515
+ if (extraKeys.length > 0) {
2516
+ addIssueToContext(ctx, {
2517
+ code: ZodIssueCode.unrecognized_keys,
2518
+ keys: extraKeys
2519
+ });
2520
+ status.dirty();
2521
+ }
2522
+ } else if (unknownKeys === "strip") ; else {
2523
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2524
+ }
2525
+ } else {
2526
+ const catchall = this._def.catchall;
2527
+ for (const key of extraKeys) {
2528
+ const value = ctx.data[key];
2529
+ pairs.push({
2530
+ key: { status: "valid", value: key },
2531
+ value: catchall._parse(
2532
+ new ParseInputLazyPath(ctx, value, ctx.path, key)
2533
+ //, ctx.child(key), value, getParsedType(value)
2534
+ ),
2535
+ alwaysSet: key in ctx.data
2536
+ });
2537
+ }
2538
+ }
2539
+ if (ctx.common.async) {
2540
+ return Promise.resolve().then(async () => {
2541
+ const syncPairs = [];
2542
+ for (const pair of pairs) {
2543
+ const key = await pair.key;
2544
+ const value = await pair.value;
2545
+ syncPairs.push({
2546
+ key,
2547
+ value,
2548
+ alwaysSet: pair.alwaysSet
2549
+ });
2550
+ }
2551
+ return syncPairs;
2552
+ }).then((syncPairs) => {
2553
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2554
+ });
2555
+ } else {
2556
+ return ParseStatus.mergeObjectSync(status, pairs);
2557
+ }
2558
+ }
2559
+ get shape() {
2560
+ return this._def.shape();
2561
+ }
2562
+ strict(message) {
2563
+ errorUtil.errToObj;
2564
+ return new _ZodObject({
2565
+ ...this._def,
2566
+ unknownKeys: "strict",
2567
+ ...message !== void 0 ? {
2568
+ errorMap: (issue, ctx) => {
2569
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2570
+ if (issue.code === "unrecognized_keys")
2571
+ return {
2572
+ message: errorUtil.errToObj(message).message ?? defaultError
2573
+ };
2574
+ return {
2575
+ message: defaultError
2576
+ };
2577
+ }
2578
+ } : {}
2579
+ });
2580
+ }
2581
+ strip() {
2582
+ return new _ZodObject({
2583
+ ...this._def,
2584
+ unknownKeys: "strip"
2585
+ });
2586
+ }
2587
+ passthrough() {
2588
+ return new _ZodObject({
2589
+ ...this._def,
2590
+ unknownKeys: "passthrough"
2591
+ });
2592
+ }
2593
+ // const AugmentFactory =
2594
+ // <Def extends ZodObjectDef>(def: Def) =>
2595
+ // <Augmentation extends ZodRawShape>(
2596
+ // augmentation: Augmentation
2597
+ // ): ZodObject<
2598
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2599
+ // Def["unknownKeys"],
2600
+ // Def["catchall"]
2601
+ // > => {
2602
+ // return new ZodObject({
2603
+ // ...def,
2604
+ // shape: () => ({
2605
+ // ...def.shape(),
2606
+ // ...augmentation,
2607
+ // }),
2608
+ // }) as any;
2609
+ // };
2610
+ extend(augmentation) {
2611
+ return new _ZodObject({
2612
+ ...this._def,
2613
+ shape: () => ({
2614
+ ...this._def.shape(),
2615
+ ...augmentation
2616
+ })
2617
+ });
2618
+ }
2619
+ /**
2620
+ * Prior to zod@1.0.12 there was a bug in the
2621
+ * inferred type of merged objects. Please
2622
+ * upgrade if you are experiencing issues.
2623
+ */
2624
+ merge(merging) {
2625
+ const merged = new _ZodObject({
2626
+ unknownKeys: merging._def.unknownKeys,
2627
+ catchall: merging._def.catchall,
2628
+ shape: () => ({
2629
+ ...this._def.shape(),
2630
+ ...merging._def.shape()
2631
+ }),
2632
+ typeName: ZodFirstPartyTypeKind.ZodObject
2633
+ });
2634
+ return merged;
2635
+ }
2636
+ // merge<
2637
+ // Incoming extends AnyZodObject,
2638
+ // Augmentation extends Incoming["shape"],
2639
+ // NewOutput extends {
2640
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2641
+ // ? Augmentation[k]["_output"]
2642
+ // : k extends keyof Output
2643
+ // ? Output[k]
2644
+ // : never;
2645
+ // },
2646
+ // NewInput extends {
2647
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2648
+ // ? Augmentation[k]["_input"]
2649
+ // : k extends keyof Input
2650
+ // ? Input[k]
2651
+ // : never;
2652
+ // }
2653
+ // >(
2654
+ // merging: Incoming
2655
+ // ): ZodObject<
2656
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2657
+ // Incoming["_def"]["unknownKeys"],
2658
+ // Incoming["_def"]["catchall"],
2659
+ // NewOutput,
2660
+ // NewInput
2661
+ // > {
2662
+ // const merged: any = new ZodObject({
2663
+ // unknownKeys: merging._def.unknownKeys,
2664
+ // catchall: merging._def.catchall,
2665
+ // shape: () =>
2666
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2667
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2668
+ // }) as any;
2669
+ // return merged;
2670
+ // }
2671
+ setKey(key, schema) {
2672
+ return this.augment({ [key]: schema });
2673
+ }
2674
+ // merge<Incoming extends AnyZodObject>(
2675
+ // merging: Incoming
2676
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2677
+ // ZodObject<
2678
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2679
+ // Incoming["_def"]["unknownKeys"],
2680
+ // Incoming["_def"]["catchall"]
2681
+ // > {
2682
+ // // const mergedShape = objectUtil.mergeShapes(
2683
+ // // this._def.shape(),
2684
+ // // merging._def.shape()
2685
+ // // );
2686
+ // const merged: any = new ZodObject({
2687
+ // unknownKeys: merging._def.unknownKeys,
2688
+ // catchall: merging._def.catchall,
2689
+ // shape: () =>
2690
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2691
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
2692
+ // }) as any;
2693
+ // return merged;
2694
+ // }
2695
+ catchall(index) {
2696
+ return new _ZodObject({
2697
+ ...this._def,
2698
+ catchall: index
2699
+ });
2700
+ }
2701
+ pick(mask) {
2702
+ const shape = {};
2703
+ for (const key of util.objectKeys(mask)) {
2704
+ if (mask[key] && this.shape[key]) {
2705
+ shape[key] = this.shape[key];
2706
+ }
2707
+ }
2708
+ return new _ZodObject({
2709
+ ...this._def,
2710
+ shape: () => shape
2711
+ });
2712
+ }
2713
+ omit(mask) {
2714
+ const shape = {};
2715
+ for (const key of util.objectKeys(this.shape)) {
2716
+ if (!mask[key]) {
2717
+ shape[key] = this.shape[key];
2718
+ }
2719
+ }
2720
+ return new _ZodObject({
2721
+ ...this._def,
2722
+ shape: () => shape
2723
+ });
2724
+ }
2725
+ /**
2726
+ * @deprecated
2727
+ */
2728
+ deepPartial() {
2729
+ return deepPartialify(this);
2730
+ }
2731
+ partial(mask) {
2732
+ const newShape = {};
2733
+ for (const key of util.objectKeys(this.shape)) {
2734
+ const fieldSchema2 = this.shape[key];
2735
+ if (mask && !mask[key]) {
2736
+ newShape[key] = fieldSchema2;
2737
+ } else {
2738
+ newShape[key] = fieldSchema2.optional();
2739
+ }
2740
+ }
2741
+ return new _ZodObject({
2742
+ ...this._def,
2743
+ shape: () => newShape
2744
+ });
2745
+ }
2746
+ required(mask) {
2747
+ const newShape = {};
2748
+ for (const key of util.objectKeys(this.shape)) {
2749
+ if (mask && !mask[key]) {
2750
+ newShape[key] = this.shape[key];
2751
+ } else {
2752
+ const fieldSchema2 = this.shape[key];
2753
+ let newField = fieldSchema2;
2754
+ while (newField instanceof ZodOptional) {
2755
+ newField = newField._def.innerType;
2756
+ }
2757
+ newShape[key] = newField;
2758
+ }
2759
+ }
2760
+ return new _ZodObject({
2761
+ ...this._def,
2762
+ shape: () => newShape
2763
+ });
2764
+ }
2765
+ keyof() {
2766
+ return createZodEnum(util.objectKeys(this.shape));
2767
+ }
2768
+ };
2769
+ ZodObject.create = (shape, params) => {
2770
+ return new ZodObject({
2771
+ shape: () => shape,
2772
+ unknownKeys: "strip",
2773
+ catchall: ZodNever.create(),
2774
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2775
+ ...processCreateParams(params)
2776
+ });
2777
+ };
2778
+ ZodObject.strictCreate = (shape, params) => {
2779
+ return new ZodObject({
2780
+ shape: () => shape,
2781
+ unknownKeys: "strict",
2782
+ catchall: ZodNever.create(),
2783
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2784
+ ...processCreateParams(params)
2785
+ });
2786
+ };
2787
+ ZodObject.lazycreate = (shape, params) => {
2788
+ return new ZodObject({
2789
+ shape,
2790
+ unknownKeys: "strip",
2791
+ catchall: ZodNever.create(),
2792
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2793
+ ...processCreateParams(params)
2794
+ });
2795
+ };
2796
+ var ZodUnion = class extends ZodType {
2797
+ _parse(input) {
2798
+ const { ctx } = this._processInputParams(input);
2799
+ const options = this._def.options;
2800
+ function handleResults(results) {
2801
+ for (const result of results) {
2802
+ if (result.result.status === "valid") {
2803
+ return result.result;
2804
+ }
2805
+ }
2806
+ for (const result of results) {
2807
+ if (result.result.status === "dirty") {
2808
+ ctx.common.issues.push(...result.ctx.common.issues);
2809
+ return result.result;
2810
+ }
2811
+ }
2812
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2813
+ addIssueToContext(ctx, {
2814
+ code: ZodIssueCode.invalid_union,
2815
+ unionErrors
2816
+ });
2817
+ return INVALID;
2818
+ }
2819
+ if (ctx.common.async) {
2820
+ return Promise.all(options.map(async (option) => {
2821
+ const childCtx = {
2822
+ ...ctx,
2823
+ common: {
2824
+ ...ctx.common,
2825
+ issues: []
2826
+ },
2827
+ parent: null
2828
+ };
2829
+ return {
2830
+ result: await option._parseAsync({
2831
+ data: ctx.data,
2832
+ path: ctx.path,
2833
+ parent: childCtx
2834
+ }),
2835
+ ctx: childCtx
2836
+ };
2837
+ })).then(handleResults);
2838
+ } else {
2839
+ let dirty = void 0;
2840
+ const issues = [];
2841
+ for (const option of options) {
2842
+ const childCtx = {
2843
+ ...ctx,
2844
+ common: {
2845
+ ...ctx.common,
2846
+ issues: []
2847
+ },
2848
+ parent: null
2849
+ };
2850
+ const result = option._parseSync({
2851
+ data: ctx.data,
2852
+ path: ctx.path,
2853
+ parent: childCtx
2854
+ });
2855
+ if (result.status === "valid") {
2856
+ return result;
2857
+ } else if (result.status === "dirty" && !dirty) {
2858
+ dirty = { result, ctx: childCtx };
2859
+ }
2860
+ if (childCtx.common.issues.length) {
2861
+ issues.push(childCtx.common.issues);
2862
+ }
2863
+ }
2864
+ if (dirty) {
2865
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2866
+ return dirty.result;
2867
+ }
2868
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
2869
+ addIssueToContext(ctx, {
2870
+ code: ZodIssueCode.invalid_union,
2871
+ unionErrors
2872
+ });
2873
+ return INVALID;
2874
+ }
2875
+ }
2876
+ get options() {
2877
+ return this._def.options;
2878
+ }
2879
+ };
2880
+ ZodUnion.create = (types, params) => {
2881
+ return new ZodUnion({
2882
+ options: types,
2883
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2884
+ ...processCreateParams(params)
2885
+ });
2886
+ };
2887
+ var getDiscriminator = (type) => {
2888
+ if (type instanceof ZodLazy) {
2889
+ return getDiscriminator(type.schema);
2890
+ } else if (type instanceof ZodEffects) {
2891
+ return getDiscriminator(type.innerType());
2892
+ } else if (type instanceof ZodLiteral) {
2893
+ return [type.value];
2894
+ } else if (type instanceof ZodEnum) {
2895
+ return type.options;
2896
+ } else if (type instanceof ZodNativeEnum) {
2897
+ return util.objectValues(type.enum);
2898
+ } else if (type instanceof ZodDefault) {
2899
+ return getDiscriminator(type._def.innerType);
2900
+ } else if (type instanceof ZodUndefined) {
2901
+ return [void 0];
2902
+ } else if (type instanceof ZodNull) {
2903
+ return [null];
2904
+ } else if (type instanceof ZodOptional) {
2905
+ return [void 0, ...getDiscriminator(type.unwrap())];
2906
+ } else if (type instanceof ZodNullable) {
2907
+ return [null, ...getDiscriminator(type.unwrap())];
2908
+ } else if (type instanceof ZodBranded) {
2909
+ return getDiscriminator(type.unwrap());
2910
+ } else if (type instanceof ZodReadonly) {
2911
+ return getDiscriminator(type.unwrap());
2912
+ } else if (type instanceof ZodCatch) {
2913
+ return getDiscriminator(type._def.innerType);
2914
+ } else {
2915
+ return [];
2916
+ }
2917
+ };
2918
+ var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2919
+ _parse(input) {
2920
+ const { ctx } = this._processInputParams(input);
2921
+ if (ctx.parsedType !== ZodParsedType.object) {
2922
+ addIssueToContext(ctx, {
2923
+ code: ZodIssueCode.invalid_type,
2924
+ expected: ZodParsedType.object,
2925
+ received: ctx.parsedType
2926
+ });
2927
+ return INVALID;
2928
+ }
2929
+ const discriminator = this.discriminator;
2930
+ const discriminatorValue = ctx.data[discriminator];
2931
+ const option = this.optionsMap.get(discriminatorValue);
2932
+ if (!option) {
2933
+ addIssueToContext(ctx, {
2934
+ code: ZodIssueCode.invalid_union_discriminator,
2935
+ options: Array.from(this.optionsMap.keys()),
2936
+ path: [discriminator]
2937
+ });
2938
+ return INVALID;
2939
+ }
2940
+ if (ctx.common.async) {
2941
+ return option._parseAsync({
2942
+ data: ctx.data,
2943
+ path: ctx.path,
2944
+ parent: ctx
2945
+ });
2946
+ } else {
2947
+ return option._parseSync({
2948
+ data: ctx.data,
2949
+ path: ctx.path,
2950
+ parent: ctx
2951
+ });
2952
+ }
2953
+ }
2954
+ get discriminator() {
2955
+ return this._def.discriminator;
2956
+ }
2957
+ get options() {
2958
+ return this._def.options;
2959
+ }
2960
+ get optionsMap() {
2961
+ return this._def.optionsMap;
2962
+ }
2963
+ /**
2964
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2965
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2966
+ * have a different value for each object in the union.
2967
+ * @param discriminator the name of the discriminator property
2968
+ * @param types an array of object schemas
2969
+ * @param params
2970
+ */
2971
+ static create(discriminator, options, params) {
2972
+ const optionsMap = /* @__PURE__ */ new Map();
2973
+ for (const type of options) {
2974
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2975
+ if (!discriminatorValues.length) {
2976
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2977
+ }
2978
+ for (const value of discriminatorValues) {
2979
+ if (optionsMap.has(value)) {
2980
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2981
+ }
2982
+ optionsMap.set(value, type);
2983
+ }
2984
+ }
2985
+ return new _ZodDiscriminatedUnion({
2986
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2987
+ discriminator,
2988
+ options,
2989
+ optionsMap,
2990
+ ...processCreateParams(params)
2991
+ });
2992
+ }
2993
+ };
2994
+ function mergeValues(a, b) {
2995
+ const aType = getParsedType(a);
2996
+ const bType = getParsedType(b);
2997
+ if (a === b) {
2998
+ return { valid: true, data: a };
2999
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3000
+ const bKeys = util.objectKeys(b);
3001
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
3002
+ const newObj = { ...a, ...b };
3003
+ for (const key of sharedKeys) {
3004
+ const sharedValue = mergeValues(a[key], b[key]);
3005
+ if (!sharedValue.valid) {
3006
+ return { valid: false };
3007
+ }
3008
+ newObj[key] = sharedValue.data;
3009
+ }
3010
+ return { valid: true, data: newObj };
3011
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3012
+ if (a.length !== b.length) {
3013
+ return { valid: false };
3014
+ }
3015
+ const newArray = [];
3016
+ for (let index = 0; index < a.length; index++) {
3017
+ const itemA = a[index];
3018
+ const itemB = b[index];
3019
+ const sharedValue = mergeValues(itemA, itemB);
3020
+ if (!sharedValue.valid) {
3021
+ return { valid: false };
3022
+ }
3023
+ newArray.push(sharedValue.data);
3024
+ }
3025
+ return { valid: true, data: newArray };
3026
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
3027
+ return { valid: true, data: a };
3028
+ } else {
3029
+ return { valid: false };
3030
+ }
3031
+ }
3032
+ var ZodIntersection = class extends ZodType {
3033
+ _parse(input) {
3034
+ const { status, ctx } = this._processInputParams(input);
3035
+ const handleParsed = (parsedLeft, parsedRight) => {
3036
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3037
+ return INVALID;
3038
+ }
3039
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
3040
+ if (!merged.valid) {
3041
+ addIssueToContext(ctx, {
3042
+ code: ZodIssueCode.invalid_intersection_types
3043
+ });
3044
+ return INVALID;
3045
+ }
3046
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
3047
+ status.dirty();
3048
+ }
3049
+ return { status: status.value, value: merged.data };
3050
+ };
3051
+ if (ctx.common.async) {
3052
+ return Promise.all([
3053
+ this._def.left._parseAsync({
3054
+ data: ctx.data,
3055
+ path: ctx.path,
3056
+ parent: ctx
3057
+ }),
3058
+ this._def.right._parseAsync({
3059
+ data: ctx.data,
3060
+ path: ctx.path,
3061
+ parent: ctx
3062
+ })
3063
+ ]).then(([left, right]) => handleParsed(left, right));
3064
+ } else {
3065
+ return handleParsed(this._def.left._parseSync({
3066
+ data: ctx.data,
3067
+ path: ctx.path,
3068
+ parent: ctx
3069
+ }), this._def.right._parseSync({
3070
+ data: ctx.data,
3071
+ path: ctx.path,
3072
+ parent: ctx
3073
+ }));
3074
+ }
3075
+ }
3076
+ };
3077
+ ZodIntersection.create = (left, right, params) => {
3078
+ return new ZodIntersection({
3079
+ left,
3080
+ right,
3081
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
3082
+ ...processCreateParams(params)
3083
+ });
3084
+ };
3085
+ var ZodTuple = class _ZodTuple extends ZodType {
3086
+ _parse(input) {
3087
+ const { status, ctx } = this._processInputParams(input);
3088
+ if (ctx.parsedType !== ZodParsedType.array) {
3089
+ addIssueToContext(ctx, {
3090
+ code: ZodIssueCode.invalid_type,
3091
+ expected: ZodParsedType.array,
3092
+ received: ctx.parsedType
3093
+ });
3094
+ return INVALID;
3095
+ }
3096
+ if (ctx.data.length < this._def.items.length) {
3097
+ addIssueToContext(ctx, {
3098
+ code: ZodIssueCode.too_small,
3099
+ minimum: this._def.items.length,
3100
+ inclusive: true,
3101
+ exact: false,
3102
+ type: "array"
3103
+ });
3104
+ return INVALID;
3105
+ }
3106
+ const rest = this._def.rest;
3107
+ if (!rest && ctx.data.length > this._def.items.length) {
3108
+ addIssueToContext(ctx, {
3109
+ code: ZodIssueCode.too_big,
3110
+ maximum: this._def.items.length,
3111
+ inclusive: true,
3112
+ exact: false,
3113
+ type: "array"
3114
+ });
3115
+ status.dirty();
3116
+ }
3117
+ const items = [...ctx.data].map((item, itemIndex) => {
3118
+ const schema = this._def.items[itemIndex] || this._def.rest;
3119
+ if (!schema)
3120
+ return null;
3121
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3122
+ }).filter((x) => !!x);
3123
+ if (ctx.common.async) {
3124
+ return Promise.all(items).then((results) => {
3125
+ return ParseStatus.mergeArray(status, results);
3126
+ });
3127
+ } else {
3128
+ return ParseStatus.mergeArray(status, items);
3129
+ }
3130
+ }
3131
+ get items() {
3132
+ return this._def.items;
3133
+ }
3134
+ rest(rest) {
3135
+ return new _ZodTuple({
3136
+ ...this._def,
3137
+ rest
3138
+ });
3139
+ }
3140
+ };
3141
+ ZodTuple.create = (schemas, params) => {
3142
+ if (!Array.isArray(schemas)) {
3143
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3144
+ }
3145
+ return new ZodTuple({
3146
+ items: schemas,
3147
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
3148
+ rest: null,
3149
+ ...processCreateParams(params)
3150
+ });
3151
+ };
3152
+ var ZodRecord = class _ZodRecord extends ZodType {
3153
+ get keySchema() {
3154
+ return this._def.keyType;
3155
+ }
3156
+ get valueSchema() {
3157
+ return this._def.valueType;
3158
+ }
3159
+ _parse(input) {
3160
+ const { status, ctx } = this._processInputParams(input);
3161
+ if (ctx.parsedType !== ZodParsedType.object) {
3162
+ addIssueToContext(ctx, {
3163
+ code: ZodIssueCode.invalid_type,
3164
+ expected: ZodParsedType.object,
3165
+ received: ctx.parsedType
3166
+ });
3167
+ return INVALID;
3168
+ }
3169
+ const pairs = [];
3170
+ const keyType = this._def.keyType;
3171
+ const valueType = this._def.valueType;
3172
+ for (const key in ctx.data) {
3173
+ pairs.push({
3174
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3175
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3176
+ alwaysSet: key in ctx.data
3177
+ });
3178
+ }
3179
+ if (ctx.common.async) {
3180
+ return ParseStatus.mergeObjectAsync(status, pairs);
3181
+ } else {
3182
+ return ParseStatus.mergeObjectSync(status, pairs);
3183
+ }
3184
+ }
3185
+ get element() {
3186
+ return this._def.valueType;
3187
+ }
3188
+ static create(first, second, third) {
3189
+ if (second instanceof ZodType) {
3190
+ return new _ZodRecord({
3191
+ keyType: first,
3192
+ valueType: second,
3193
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3194
+ ...processCreateParams(third)
3195
+ });
3196
+ }
3197
+ return new _ZodRecord({
3198
+ keyType: ZodString.create(),
3199
+ valueType: first,
3200
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3201
+ ...processCreateParams(second)
3202
+ });
3203
+ }
3204
+ };
3205
+ var ZodMap = class extends ZodType {
3206
+ get keySchema() {
3207
+ return this._def.keyType;
3208
+ }
3209
+ get valueSchema() {
3210
+ return this._def.valueType;
3211
+ }
3212
+ _parse(input) {
3213
+ const { status, ctx } = this._processInputParams(input);
3214
+ if (ctx.parsedType !== ZodParsedType.map) {
3215
+ addIssueToContext(ctx, {
3216
+ code: ZodIssueCode.invalid_type,
3217
+ expected: ZodParsedType.map,
3218
+ received: ctx.parsedType
3219
+ });
3220
+ return INVALID;
3221
+ }
3222
+ const keyType = this._def.keyType;
3223
+ const valueType = this._def.valueType;
3224
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3225
+ return {
3226
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3227
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3228
+ };
3229
+ });
3230
+ if (ctx.common.async) {
3231
+ const finalMap = /* @__PURE__ */ new Map();
3232
+ return Promise.resolve().then(async () => {
3233
+ for (const pair of pairs) {
3234
+ const key = await pair.key;
3235
+ const value = await pair.value;
3236
+ if (key.status === "aborted" || value.status === "aborted") {
3237
+ return INVALID;
3238
+ }
3239
+ if (key.status === "dirty" || value.status === "dirty") {
3240
+ status.dirty();
3241
+ }
3242
+ finalMap.set(key.value, value.value);
3243
+ }
3244
+ return { status: status.value, value: finalMap };
3245
+ });
3246
+ } else {
3247
+ const finalMap = /* @__PURE__ */ new Map();
3248
+ for (const pair of pairs) {
3249
+ const key = pair.key;
3250
+ const value = pair.value;
3251
+ if (key.status === "aborted" || value.status === "aborted") {
3252
+ return INVALID;
3253
+ }
3254
+ if (key.status === "dirty" || value.status === "dirty") {
3255
+ status.dirty();
3256
+ }
3257
+ finalMap.set(key.value, value.value);
3258
+ }
3259
+ return { status: status.value, value: finalMap };
3260
+ }
3261
+ }
3262
+ };
3263
+ ZodMap.create = (keyType, valueType, params) => {
3264
+ return new ZodMap({
3265
+ valueType,
3266
+ keyType,
3267
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3268
+ ...processCreateParams(params)
3269
+ });
3270
+ };
3271
+ var ZodSet = class _ZodSet extends ZodType {
3272
+ _parse(input) {
3273
+ const { status, ctx } = this._processInputParams(input);
3274
+ if (ctx.parsedType !== ZodParsedType.set) {
3275
+ addIssueToContext(ctx, {
3276
+ code: ZodIssueCode.invalid_type,
3277
+ expected: ZodParsedType.set,
3278
+ received: ctx.parsedType
3279
+ });
3280
+ return INVALID;
3281
+ }
3282
+ const def = this._def;
3283
+ if (def.minSize !== null) {
3284
+ if (ctx.data.size < def.minSize.value) {
3285
+ addIssueToContext(ctx, {
3286
+ code: ZodIssueCode.too_small,
3287
+ minimum: def.minSize.value,
3288
+ type: "set",
3289
+ inclusive: true,
3290
+ exact: false,
3291
+ message: def.minSize.message
3292
+ });
3293
+ status.dirty();
3294
+ }
3295
+ }
3296
+ if (def.maxSize !== null) {
3297
+ if (ctx.data.size > def.maxSize.value) {
3298
+ addIssueToContext(ctx, {
3299
+ code: ZodIssueCode.too_big,
3300
+ maximum: def.maxSize.value,
3301
+ type: "set",
3302
+ inclusive: true,
3303
+ exact: false,
3304
+ message: def.maxSize.message
3305
+ });
3306
+ status.dirty();
3307
+ }
3308
+ }
3309
+ const valueType = this._def.valueType;
3310
+ function finalizeSet(elements2) {
3311
+ const parsedSet = /* @__PURE__ */ new Set();
3312
+ for (const element of elements2) {
3313
+ if (element.status === "aborted")
3314
+ return INVALID;
3315
+ if (element.status === "dirty")
3316
+ status.dirty();
3317
+ parsedSet.add(element.value);
3318
+ }
3319
+ return { status: status.value, value: parsedSet };
3320
+ }
3321
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3322
+ if (ctx.common.async) {
3323
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3324
+ } else {
3325
+ return finalizeSet(elements);
3326
+ }
3327
+ }
3328
+ min(minSize, message) {
3329
+ return new _ZodSet({
3330
+ ...this._def,
3331
+ minSize: { value: minSize, message: errorUtil.toString(message) }
3332
+ });
3333
+ }
3334
+ max(maxSize, message) {
3335
+ return new _ZodSet({
3336
+ ...this._def,
3337
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
3338
+ });
3339
+ }
3340
+ size(size, message) {
3341
+ return this.min(size, message).max(size, message);
3342
+ }
3343
+ nonempty(message) {
3344
+ return this.min(1, message);
3345
+ }
3346
+ };
3347
+ ZodSet.create = (valueType, params) => {
3348
+ return new ZodSet({
3349
+ valueType,
3350
+ minSize: null,
3351
+ maxSize: null,
3352
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3353
+ ...processCreateParams(params)
3354
+ });
3355
+ };
3356
+ var ZodFunction = class _ZodFunction extends ZodType {
3357
+ constructor() {
3358
+ super(...arguments);
3359
+ this.validate = this.implement;
3360
+ }
3361
+ _parse(input) {
3362
+ const { ctx } = this._processInputParams(input);
3363
+ if (ctx.parsedType !== ZodParsedType.function) {
3364
+ addIssueToContext(ctx, {
3365
+ code: ZodIssueCode.invalid_type,
3366
+ expected: ZodParsedType.function,
3367
+ received: ctx.parsedType
3368
+ });
3369
+ return INVALID;
3370
+ }
3371
+ function makeArgsIssue(args, error) {
3372
+ return makeIssue({
3373
+ data: args,
3374
+ path: ctx.path,
3375
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3376
+ issueData: {
3377
+ code: ZodIssueCode.invalid_arguments,
3378
+ argumentsError: error
3379
+ }
3380
+ });
3381
+ }
3382
+ function makeReturnsIssue(returns, error) {
3383
+ return makeIssue({
3384
+ data: returns,
3385
+ path: ctx.path,
3386
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3387
+ issueData: {
3388
+ code: ZodIssueCode.invalid_return_type,
3389
+ returnTypeError: error
3390
+ }
3391
+ });
3392
+ }
3393
+ const params = { errorMap: ctx.common.contextualErrorMap };
3394
+ const fn = ctx.data;
3395
+ if (this._def.returns instanceof ZodPromise) {
3396
+ const me = this;
3397
+ return OK(async function(...args) {
3398
+ const error = new ZodError([]);
3399
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3400
+ error.addIssue(makeArgsIssue(args, e));
3401
+ throw error;
3402
+ });
3403
+ const result = await Reflect.apply(fn, this, parsedArgs);
3404
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3405
+ error.addIssue(makeReturnsIssue(result, e));
3406
+ throw error;
3407
+ });
3408
+ return parsedReturns;
3409
+ });
3410
+ } else {
3411
+ const me = this;
3412
+ return OK(function(...args) {
3413
+ const parsedArgs = me._def.args.safeParse(args, params);
3414
+ if (!parsedArgs.success) {
3415
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3416
+ }
3417
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3418
+ const parsedReturns = me._def.returns.safeParse(result, params);
3419
+ if (!parsedReturns.success) {
3420
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3421
+ }
3422
+ return parsedReturns.data;
3423
+ });
3424
+ }
3425
+ }
3426
+ parameters() {
3427
+ return this._def.args;
3428
+ }
3429
+ returnType() {
3430
+ return this._def.returns;
3431
+ }
3432
+ args(...items) {
3433
+ return new _ZodFunction({
3434
+ ...this._def,
3435
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
3436
+ });
3437
+ }
3438
+ returns(returnType) {
3439
+ return new _ZodFunction({
3440
+ ...this._def,
3441
+ returns: returnType
3442
+ });
3443
+ }
3444
+ implement(func) {
3445
+ const validatedFunc = this.parse(func);
3446
+ return validatedFunc;
3447
+ }
3448
+ strictImplement(func) {
3449
+ const validatedFunc = this.parse(func);
3450
+ return validatedFunc;
3451
+ }
3452
+ static create(args, returns, params) {
3453
+ return new _ZodFunction({
3454
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3455
+ returns: returns || ZodUnknown.create(),
3456
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3457
+ ...processCreateParams(params)
3458
+ });
3459
+ }
3460
+ };
3461
+ var ZodLazy = class extends ZodType {
3462
+ get schema() {
3463
+ return this._def.getter();
3464
+ }
3465
+ _parse(input) {
3466
+ const { ctx } = this._processInputParams(input);
3467
+ const lazySchema = this._def.getter();
3468
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3469
+ }
3470
+ };
3471
+ ZodLazy.create = (getter, params) => {
3472
+ return new ZodLazy({
3473
+ getter,
3474
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3475
+ ...processCreateParams(params)
3476
+ });
3477
+ };
3478
+ var ZodLiteral = class extends ZodType {
3479
+ _parse(input) {
3480
+ if (input.data !== this._def.value) {
3481
+ const ctx = this._getOrReturnCtx(input);
3482
+ addIssueToContext(ctx, {
3483
+ received: ctx.data,
3484
+ code: ZodIssueCode.invalid_literal,
3485
+ expected: this._def.value
3486
+ });
3487
+ return INVALID;
3488
+ }
3489
+ return { status: "valid", value: input.data };
3490
+ }
3491
+ get value() {
3492
+ return this._def.value;
3493
+ }
3494
+ };
3495
+ ZodLiteral.create = (value, params) => {
3496
+ return new ZodLiteral({
3497
+ value,
3498
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3499
+ ...processCreateParams(params)
3500
+ });
3501
+ };
3502
+ function createZodEnum(values, params) {
3503
+ return new ZodEnum({
3504
+ values,
3505
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3506
+ ...processCreateParams(params)
3507
+ });
3508
+ }
3509
+ var ZodEnum = class _ZodEnum extends ZodType {
3510
+ _parse(input) {
3511
+ if (typeof input.data !== "string") {
3512
+ const ctx = this._getOrReturnCtx(input);
3513
+ const expectedValues = this._def.values;
3514
+ addIssueToContext(ctx, {
3515
+ expected: util.joinValues(expectedValues),
3516
+ received: ctx.parsedType,
3517
+ code: ZodIssueCode.invalid_type
3518
+ });
3519
+ return INVALID;
3520
+ }
3521
+ if (!this._cache) {
3522
+ this._cache = new Set(this._def.values);
3523
+ }
3524
+ if (!this._cache.has(input.data)) {
3525
+ const ctx = this._getOrReturnCtx(input);
3526
+ const expectedValues = this._def.values;
3527
+ addIssueToContext(ctx, {
3528
+ received: ctx.data,
3529
+ code: ZodIssueCode.invalid_enum_value,
3530
+ options: expectedValues
3531
+ });
3532
+ return INVALID;
3533
+ }
3534
+ return OK(input.data);
3535
+ }
3536
+ get options() {
3537
+ return this._def.values;
3538
+ }
3539
+ get enum() {
3540
+ const enumValues = {};
3541
+ for (const val of this._def.values) {
3542
+ enumValues[val] = val;
3543
+ }
3544
+ return enumValues;
3545
+ }
3546
+ get Values() {
3547
+ const enumValues = {};
3548
+ for (const val of this._def.values) {
3549
+ enumValues[val] = val;
3550
+ }
3551
+ return enumValues;
3552
+ }
3553
+ get Enum() {
3554
+ const enumValues = {};
3555
+ for (const val of this._def.values) {
3556
+ enumValues[val] = val;
3557
+ }
3558
+ return enumValues;
3559
+ }
3560
+ extract(values, newDef = this._def) {
3561
+ return _ZodEnum.create(values, {
3562
+ ...this._def,
3563
+ ...newDef
3564
+ });
3565
+ }
3566
+ exclude(values, newDef = this._def) {
3567
+ return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3568
+ ...this._def,
3569
+ ...newDef
3570
+ });
3571
+ }
3572
+ };
3573
+ ZodEnum.create = createZodEnum;
3574
+ var ZodNativeEnum = class extends ZodType {
3575
+ _parse(input) {
3576
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3577
+ const ctx = this._getOrReturnCtx(input);
3578
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3579
+ const expectedValues = util.objectValues(nativeEnumValues);
3580
+ addIssueToContext(ctx, {
3581
+ expected: util.joinValues(expectedValues),
3582
+ received: ctx.parsedType,
3583
+ code: ZodIssueCode.invalid_type
3584
+ });
3585
+ return INVALID;
3586
+ }
3587
+ if (!this._cache) {
3588
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
3589
+ }
3590
+ if (!this._cache.has(input.data)) {
3591
+ const expectedValues = util.objectValues(nativeEnumValues);
3592
+ addIssueToContext(ctx, {
3593
+ received: ctx.data,
3594
+ code: ZodIssueCode.invalid_enum_value,
3595
+ options: expectedValues
3596
+ });
3597
+ return INVALID;
3598
+ }
3599
+ return OK(input.data);
3600
+ }
3601
+ get enum() {
3602
+ return this._def.values;
3603
+ }
3604
+ };
3605
+ ZodNativeEnum.create = (values, params) => {
3606
+ return new ZodNativeEnum({
3607
+ values,
3608
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3609
+ ...processCreateParams(params)
3610
+ });
3611
+ };
3612
+ var ZodPromise = class extends ZodType {
3613
+ unwrap() {
3614
+ return this._def.type;
3615
+ }
3616
+ _parse(input) {
3617
+ const { ctx } = this._processInputParams(input);
3618
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3619
+ addIssueToContext(ctx, {
3620
+ code: ZodIssueCode.invalid_type,
3621
+ expected: ZodParsedType.promise,
3622
+ received: ctx.parsedType
3623
+ });
3624
+ return INVALID;
3625
+ }
3626
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3627
+ return OK(promisified.then((data) => {
3628
+ return this._def.type.parseAsync(data, {
3629
+ path: ctx.path,
3630
+ errorMap: ctx.common.contextualErrorMap
3631
+ });
3632
+ }));
3633
+ }
3634
+ };
3635
+ ZodPromise.create = (schema, params) => {
3636
+ return new ZodPromise({
3637
+ type: schema,
3638
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3639
+ ...processCreateParams(params)
3640
+ });
3641
+ };
3642
+ var ZodEffects = class extends ZodType {
3643
+ innerType() {
3644
+ return this._def.schema;
3645
+ }
3646
+ sourceType() {
3647
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3648
+ }
3649
+ _parse(input) {
3650
+ const { status, ctx } = this._processInputParams(input);
3651
+ const effect = this._def.effect || null;
3652
+ const checkCtx = {
3653
+ addIssue: (arg) => {
3654
+ addIssueToContext(ctx, arg);
3655
+ if (arg.fatal) {
3656
+ status.abort();
3657
+ } else {
3658
+ status.dirty();
3659
+ }
3660
+ },
3661
+ get path() {
3662
+ return ctx.path;
3663
+ }
3664
+ };
3665
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3666
+ if (effect.type === "preprocess") {
3667
+ const processed = effect.transform(ctx.data, checkCtx);
3668
+ if (ctx.common.async) {
3669
+ return Promise.resolve(processed).then(async (processed2) => {
3670
+ if (status.value === "aborted")
3671
+ return INVALID;
3672
+ const result = await this._def.schema._parseAsync({
3673
+ data: processed2,
3674
+ path: ctx.path,
3675
+ parent: ctx
3676
+ });
3677
+ if (result.status === "aborted")
3678
+ return INVALID;
3679
+ if (result.status === "dirty")
3680
+ return DIRTY(result.value);
3681
+ if (status.value === "dirty")
3682
+ return DIRTY(result.value);
3683
+ return result;
3684
+ });
3685
+ } else {
3686
+ if (status.value === "aborted")
3687
+ return INVALID;
3688
+ const result = this._def.schema._parseSync({
3689
+ data: processed,
3690
+ path: ctx.path,
3691
+ parent: ctx
3692
+ });
3693
+ if (result.status === "aborted")
3694
+ return INVALID;
3695
+ if (result.status === "dirty")
3696
+ return DIRTY(result.value);
3697
+ if (status.value === "dirty")
3698
+ return DIRTY(result.value);
3699
+ return result;
3700
+ }
3701
+ }
3702
+ if (effect.type === "refinement") {
3703
+ const executeRefinement = (acc) => {
3704
+ const result = effect.refinement(acc, checkCtx);
3705
+ if (ctx.common.async) {
3706
+ return Promise.resolve(result);
3707
+ }
3708
+ if (result instanceof Promise) {
3709
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3710
+ }
3711
+ return acc;
3712
+ };
3713
+ if (ctx.common.async === false) {
3714
+ const inner = this._def.schema._parseSync({
3715
+ data: ctx.data,
3716
+ path: ctx.path,
3717
+ parent: ctx
3718
+ });
3719
+ if (inner.status === "aborted")
3720
+ return INVALID;
3721
+ if (inner.status === "dirty")
3722
+ status.dirty();
3723
+ executeRefinement(inner.value);
3724
+ return { status: status.value, value: inner.value };
3725
+ } else {
3726
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3727
+ if (inner.status === "aborted")
3728
+ return INVALID;
3729
+ if (inner.status === "dirty")
3730
+ status.dirty();
3731
+ return executeRefinement(inner.value).then(() => {
3732
+ return { status: status.value, value: inner.value };
3733
+ });
3734
+ });
3735
+ }
3736
+ }
3737
+ if (effect.type === "transform") {
3738
+ if (ctx.common.async === false) {
3739
+ const base = this._def.schema._parseSync({
3740
+ data: ctx.data,
3741
+ path: ctx.path,
3742
+ parent: ctx
3743
+ });
3744
+ if (!isValid(base))
3745
+ return INVALID;
3746
+ const result = effect.transform(base.value, checkCtx);
3747
+ if (result instanceof Promise) {
3748
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3749
+ }
3750
+ return { status: status.value, value: result };
3751
+ } else {
3752
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3753
+ if (!isValid(base))
3754
+ return INVALID;
3755
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3756
+ status: status.value,
3757
+ value: result
3758
+ }));
3759
+ });
3760
+ }
3761
+ }
3762
+ util.assertNever(effect);
3763
+ }
3764
+ };
3765
+ ZodEffects.create = (schema, effect, params) => {
3766
+ return new ZodEffects({
3767
+ schema,
3768
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3769
+ effect,
3770
+ ...processCreateParams(params)
3771
+ });
3772
+ };
3773
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3774
+ return new ZodEffects({
3775
+ schema,
3776
+ effect: { type: "preprocess", transform: preprocess },
3777
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3778
+ ...processCreateParams(params)
3779
+ });
3780
+ };
3781
+ var ZodOptional = class extends ZodType {
3782
+ _parse(input) {
3783
+ const parsedType = this._getType(input);
3784
+ if (parsedType === ZodParsedType.undefined) {
3785
+ return OK(void 0);
3786
+ }
3787
+ return this._def.innerType._parse(input);
3788
+ }
3789
+ unwrap() {
3790
+ return this._def.innerType;
3791
+ }
3792
+ };
3793
+ ZodOptional.create = (type, params) => {
3794
+ return new ZodOptional({
3795
+ innerType: type,
3796
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3797
+ ...processCreateParams(params)
3798
+ });
3799
+ };
3800
+ var ZodNullable = class extends ZodType {
3801
+ _parse(input) {
3802
+ const parsedType = this._getType(input);
3803
+ if (parsedType === ZodParsedType.null) {
3804
+ return OK(null);
3805
+ }
3806
+ return this._def.innerType._parse(input);
3807
+ }
3808
+ unwrap() {
3809
+ return this._def.innerType;
3810
+ }
3811
+ };
3812
+ ZodNullable.create = (type, params) => {
3813
+ return new ZodNullable({
3814
+ innerType: type,
3815
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3816
+ ...processCreateParams(params)
3817
+ });
3818
+ };
3819
+ var ZodDefault = class extends ZodType {
3820
+ _parse(input) {
3821
+ const { ctx } = this._processInputParams(input);
3822
+ let data = ctx.data;
3823
+ if (ctx.parsedType === ZodParsedType.undefined) {
3824
+ data = this._def.defaultValue();
3825
+ }
3826
+ return this._def.innerType._parse({
3827
+ data,
3828
+ path: ctx.path,
3829
+ parent: ctx
3830
+ });
3831
+ }
3832
+ removeDefault() {
3833
+ return this._def.innerType;
3834
+ }
3835
+ };
3836
+ ZodDefault.create = (type, params) => {
3837
+ return new ZodDefault({
3838
+ innerType: type,
3839
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3840
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3841
+ ...processCreateParams(params)
3842
+ });
3843
+ };
3844
+ var ZodCatch = class extends ZodType {
3845
+ _parse(input) {
3846
+ const { ctx } = this._processInputParams(input);
3847
+ const newCtx = {
3848
+ ...ctx,
3849
+ common: {
3850
+ ...ctx.common,
3851
+ issues: []
3852
+ }
3853
+ };
3854
+ const result = this._def.innerType._parse({
3855
+ data: newCtx.data,
3856
+ path: newCtx.path,
3857
+ parent: {
3858
+ ...newCtx
3859
+ }
3860
+ });
3861
+ if (isAsync(result)) {
3862
+ return result.then((result2) => {
3863
+ return {
3864
+ status: "valid",
3865
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
3866
+ get error() {
3867
+ return new ZodError(newCtx.common.issues);
3868
+ },
3869
+ input: newCtx.data
3870
+ })
3871
+ };
3872
+ });
3873
+ } else {
3874
+ return {
3875
+ status: "valid",
3876
+ value: result.status === "valid" ? result.value : this._def.catchValue({
3877
+ get error() {
3878
+ return new ZodError(newCtx.common.issues);
3879
+ },
3880
+ input: newCtx.data
3881
+ })
3882
+ };
3883
+ }
3884
+ }
3885
+ removeCatch() {
3886
+ return this._def.innerType;
3887
+ }
3888
+ };
3889
+ ZodCatch.create = (type, params) => {
3890
+ return new ZodCatch({
3891
+ innerType: type,
3892
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
3893
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3894
+ ...processCreateParams(params)
3895
+ });
3896
+ };
3897
+ var ZodNaN = class extends ZodType {
3898
+ _parse(input) {
3899
+ const parsedType = this._getType(input);
3900
+ if (parsedType !== ZodParsedType.nan) {
3901
+ const ctx = this._getOrReturnCtx(input);
3902
+ addIssueToContext(ctx, {
3903
+ code: ZodIssueCode.invalid_type,
3904
+ expected: ZodParsedType.nan,
3905
+ received: ctx.parsedType
3906
+ });
3907
+ return INVALID;
3908
+ }
3909
+ return { status: "valid", value: input.data };
3910
+ }
3911
+ };
3912
+ ZodNaN.create = (params) => {
3913
+ return new ZodNaN({
3914
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
3915
+ ...processCreateParams(params)
3916
+ });
3917
+ };
3918
+ var BRAND = Symbol("zod_brand");
3919
+ var ZodBranded = class extends ZodType {
3920
+ _parse(input) {
3921
+ const { ctx } = this._processInputParams(input);
3922
+ const data = ctx.data;
3923
+ return this._def.type._parse({
3924
+ data,
3925
+ path: ctx.path,
3926
+ parent: ctx
3927
+ });
3928
+ }
3929
+ unwrap() {
3930
+ return this._def.type;
3931
+ }
3932
+ };
3933
+ var ZodPipeline = class _ZodPipeline extends ZodType {
3934
+ _parse(input) {
3935
+ const { status, ctx } = this._processInputParams(input);
3936
+ if (ctx.common.async) {
3937
+ const handleAsync = async () => {
3938
+ const inResult = await this._def.in._parseAsync({
3939
+ data: ctx.data,
3940
+ path: ctx.path,
3941
+ parent: ctx
3942
+ });
3943
+ if (inResult.status === "aborted")
3944
+ return INVALID;
3945
+ if (inResult.status === "dirty") {
3946
+ status.dirty();
3947
+ return DIRTY(inResult.value);
3948
+ } else {
3949
+ return this._def.out._parseAsync({
3950
+ data: inResult.value,
3951
+ path: ctx.path,
3952
+ parent: ctx
3953
+ });
3954
+ }
3955
+ };
3956
+ return handleAsync();
3957
+ } else {
3958
+ const inResult = this._def.in._parseSync({
3959
+ data: ctx.data,
3960
+ path: ctx.path,
3961
+ parent: ctx
3962
+ });
3963
+ if (inResult.status === "aborted")
3964
+ return INVALID;
3965
+ if (inResult.status === "dirty") {
3966
+ status.dirty();
3967
+ return {
3968
+ status: "dirty",
3969
+ value: inResult.value
3970
+ };
3971
+ } else {
3972
+ return this._def.out._parseSync({
3973
+ data: inResult.value,
3974
+ path: ctx.path,
3975
+ parent: ctx
3976
+ });
3977
+ }
3978
+ }
3979
+ }
3980
+ static create(a, b) {
3981
+ return new _ZodPipeline({
3982
+ in: a,
3983
+ out: b,
3984
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
3985
+ });
3986
+ }
3987
+ };
3988
+ var ZodReadonly = class extends ZodType {
3989
+ _parse(input) {
3990
+ const result = this._def.innerType._parse(input);
3991
+ const freeze = (data) => {
3992
+ if (isValid(data)) {
3993
+ data.value = Object.freeze(data.value);
3994
+ }
3995
+ return data;
3996
+ };
3997
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3998
+ }
3999
+ unwrap() {
4000
+ return this._def.innerType;
4001
+ }
4002
+ };
4003
+ ZodReadonly.create = (type, params) => {
4004
+ return new ZodReadonly({
4005
+ innerType: type,
4006
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
4007
+ ...processCreateParams(params)
4008
+ });
4009
+ };
4010
+ function cleanParams(params, data) {
4011
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
4012
+ const p2 = typeof p === "string" ? { message: p } : p;
4013
+ return p2;
4014
+ }
4015
+ function custom(check, _params = {}, fatal) {
4016
+ if (check)
4017
+ return ZodAny.create().superRefine((data, ctx) => {
4018
+ const r = check(data);
4019
+ if (r instanceof Promise) {
4020
+ return r.then((r2) => {
4021
+ if (!r2) {
4022
+ const params = cleanParams(_params, data);
4023
+ const _fatal = params.fatal ?? fatal ?? true;
4024
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4025
+ }
4026
+ });
4027
+ }
4028
+ if (!r) {
4029
+ const params = cleanParams(_params, data);
4030
+ const _fatal = params.fatal ?? fatal ?? true;
4031
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4032
+ }
4033
+ return;
4034
+ });
4035
+ return ZodAny.create();
4036
+ }
4037
+ var late = {
4038
+ object: ZodObject.lazycreate
4039
+ };
4040
+ var ZodFirstPartyTypeKind;
4041
+ (function(ZodFirstPartyTypeKind2) {
4042
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
4043
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
4044
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
4045
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
4046
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
4047
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
4048
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
4049
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
4050
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
4051
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
4052
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
4053
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
4054
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
4055
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
4056
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
4057
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
4058
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4059
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
4060
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
4061
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
4062
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
4063
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
4064
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
4065
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
4066
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
4067
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
4068
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
4069
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
4070
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
4071
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
4072
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
4073
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
4074
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4075
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4076
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4077
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4078
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4079
+ var instanceOfType = (cls, params = {
4080
+ message: `Input not instance of ${cls.name}`
4081
+ }) => custom((data) => data instanceof cls, params);
4082
+ var stringType = ZodString.create;
4083
+ var numberType = ZodNumber.create;
4084
+ var nanType = ZodNaN.create;
4085
+ var bigIntType = ZodBigInt.create;
4086
+ var booleanType = ZodBoolean.create;
4087
+ var dateType = ZodDate.create;
4088
+ var symbolType = ZodSymbol.create;
4089
+ var undefinedType = ZodUndefined.create;
4090
+ var nullType = ZodNull.create;
4091
+ var anyType = ZodAny.create;
4092
+ var unknownType = ZodUnknown.create;
4093
+ var neverType = ZodNever.create;
4094
+ var voidType = ZodVoid.create;
4095
+ var arrayType = ZodArray.create;
4096
+ var objectType = ZodObject.create;
4097
+ var strictObjectType = ZodObject.strictCreate;
4098
+ var unionType = ZodUnion.create;
4099
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
4100
+ var intersectionType = ZodIntersection.create;
4101
+ var tupleType = ZodTuple.create;
4102
+ var recordType = ZodRecord.create;
4103
+ var mapType = ZodMap.create;
4104
+ var setType = ZodSet.create;
4105
+ var functionType = ZodFunction.create;
4106
+ var lazyType = ZodLazy.create;
4107
+ var literalType = ZodLiteral.create;
4108
+ var enumType = ZodEnum.create;
4109
+ var nativeEnumType = ZodNativeEnum.create;
4110
+ var promiseType = ZodPromise.create;
4111
+ var effectsType = ZodEffects.create;
4112
+ var optionalType = ZodOptional.create;
4113
+ var nullableType = ZodNullable.create;
4114
+ var preprocessType = ZodEffects.createWithPreprocess;
4115
+ var pipelineType = ZodPipeline.create;
4116
+ var ostring = () => stringType().optional();
4117
+ var onumber = () => numberType().optional();
4118
+ var oboolean = () => booleanType().optional();
4119
+ var coerce = {
4120
+ string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4121
+ number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4122
+ boolean: ((arg) => ZodBoolean.create({
4123
+ ...arg,
4124
+ coerce: true
4125
+ })),
4126
+ bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4127
+ date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4128
+ };
4129
+ var NEVER = INVALID;
4130
+
4131
+ // packages/@columnus/shared/src/queryFieldOps.ts
4132
+ var PREDICATE_VARIANTS = [
4133
+ {
4134
+ value: "unknown",
4135
+ ops: [
4136
+ { op: "eq", label: "=" },
4137
+ { op: "neq", label: "\u2260" }
4138
+ ]
4139
+ },
4140
+ { value: "unknownArray", ops: [{ op: "in", label: "in" }] },
4141
+ {
4142
+ value: "unknown",
4143
+ ops: [
4144
+ { op: "gt", label: ">" },
4145
+ { op: "gte", label: "\u2265" },
4146
+ { op: "lt", label: "<" },
4147
+ { op: "lte", label: "\u2264" }
4148
+ ]
4149
+ },
4150
+ { value: "between", ops: [{ op: "between", label: "between" }] },
4151
+ {
4152
+ value: "unknownArray",
4153
+ ops: [{ op: "containsAll", label: "contains all" }]
4154
+ }
4155
+ ];
4156
+ var PREDICATE_OPS = PREDICATE_VARIANTS.flatMap(
4157
+ (variant) => variant.ops.map(({ op }) => op)
4158
+ );
4159
+ new Map(
4160
+ PREDICATE_VARIANTS.flatMap((variant) => variant.ops.map(({ op, label }) => [op, label]))
4161
+ );
4162
+
4163
+ // packages/@columnus/shared/src/queryTypes.ts
4164
+ var listAccessKindSchema = external_exports.enum(["table", "index", "search", "idList"]);
4165
+ var listPageKindSchema = external_exports.enum(["paginate", "boundedSort"]);
4166
+ external_exports.enum([
4167
+ "query_invalid",
4168
+ "query_unsupported",
4169
+ "query_unsatisfiable"
4170
+ ]);
4171
+ external_exports.enum(PREDICATE_OPS);
4172
+ var betweenValueSchema = external_exports.object({
4173
+ min: external_exports.unknown(),
4174
+ max: external_exports.unknown()
4175
+ }).refine(
4176
+ (value) => Object.hasOwn(value, "min") && Object.hasOwn(value, "max"),
4177
+ "Between requires min and max"
4178
+ );
4179
+ var predicateSchemas = PREDICATE_VARIANTS.flatMap(
4180
+ (variant) => variant.ops.map(
4181
+ ({ op }) => external_exports.object({
4182
+ field: external_exports.string().min(1),
4183
+ op: external_exports.literal(op),
4184
+ value: variant.value === "unknownArray" ? external_exports.array(external_exports.unknown()) : variant.value === "between" ? betweenValueSchema : external_exports.unknown()
4185
+ })
4186
+ )
4187
+ );
4188
+ var predicateSchema = external_exports.discriminatedUnion(
4189
+ "op",
4190
+ predicateSchemas
4191
+ ).refine(
4192
+ (predicate) => Object.hasOwn(predicate, "value"),
4193
+ "Predicate value is required"
4194
+ );
4195
+ var queryOrderSchema = external_exports.object({
4196
+ field: external_exports.string().min(1),
4197
+ direction: external_exports.enum(["asc", "desc"])
4198
+ });
4199
+ var querySearchSchema = external_exports.object({
4200
+ index: external_exports.string().min(1),
4201
+ query: external_exports.string()
4202
+ });
4203
+ external_exports.object({
4204
+ predicates: external_exports.array(predicateSchema).optional(),
4205
+ order: queryOrderSchema.optional(),
4206
+ search: querySearchSchema.optional(),
4207
+ /** Reserved — rejected by the planner until vector indexes exist in the manifest. */
4208
+ vector: external_exports.unknown().optional(),
4209
+ maxScan: external_exports.number().int().positive().optional(),
4210
+ indexHint: external_exports.string().min(1).optional()
4211
+ });
4212
+ external_exports.object({
4213
+ predicates: external_exports.array(predicateSchema).optional(),
4214
+ order: queryOrderSchema.optional(),
4215
+ search: querySearchSchema.optional()
4216
+ });
4217
+ var listMetaOrderSchema = external_exports.union([
4218
+ queryOrderSchema,
4219
+ external_exports.object({ kind: external_exports.literal("relevance") })
4220
+ ]);
4221
+ external_exports.object({
4222
+ access: listAccessKindSchema,
4223
+ page: listPageKindSchema,
4224
+ order: listMetaOrderSchema.optional(),
4225
+ indexName: external_exports.string().optional(),
4226
+ searchIndexName: external_exports.string().optional(),
4227
+ scanned: external_exports.number().int().nonnegative().optional(),
4228
+ truncated: external_exports.boolean().optional()
4229
+ });
4230
+
4231
+ // packages/@columnus/shared/src/richDoc.ts
4232
+ var RICH_DOC_FORMAT = "blocknote";
4233
+ var RICH_DOC_VERSION = 1;
4234
+ var EMPTY_BLOCK_ID = "00000000-0000-4000-8000-000000000001";
4235
+ function emptyParagraphBlock() {
4236
+ return {
4237
+ id: EMPTY_BLOCK_ID,
4238
+ type: "paragraph",
4239
+ props: {
4240
+ backgroundColor: "default",
4241
+ textColor: "default",
4242
+ textAlignment: "left"
4243
+ },
4244
+ content: [],
4245
+ children: []
4246
+ };
4247
+ }
4248
+ function isBlockNoteEnvelope(parsed) {
4249
+ const p = parsed;
4250
+ return parsed !== null && typeof parsed === "object" && p.format === RICH_DOC_FORMAT && p.version === RICH_DOC_VERSION && Array.isArray(p.blocks);
4251
+ }
4252
+ JSON.stringify({
4253
+ format: RICH_DOC_FORMAT,
4254
+ version: RICH_DOC_VERSION,
4255
+ blocks: [emptyParagraphBlock()]
4256
+ });
4257
+ function isValidRichFieldJson(value) {
4258
+ try {
4259
+ const parsed = JSON.parse(value);
4260
+ if (isBlockNoteEnvelope(parsed)) return parsed.blocks.length > 0;
4261
+ return false;
4262
+ } catch {
4263
+ return false;
4264
+ }
4265
+ }
4266
+
4267
+ // packages/@columnus/shared/src/schemaTypes.ts
4268
+ var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
4269
+ var RESERVED_TABLE_NAMES = /* @__PURE__ */ new Set([
4270
+ "columnus_audit_log",
4271
+ "columnus_spaces",
4272
+ "columnus_manifest",
4273
+ "columnus_display_values",
4274
+ "columnus_api_profiles",
4275
+ "columnus_api_tokens",
4276
+ "columnus_api_outputs",
4277
+ "columnus_api_output_secrets",
4278
+ "columnus_api_sync_routes",
4279
+ "columnus_api_outbox",
4280
+ "columnus_api_delivery"
4281
+ ]);
4282
+ var displayTemplatesSchema = external_exports.object({
4283
+ id: external_exports.string().optional(),
4284
+ preview: external_exports.string().optional()
4285
+ });
4286
+ var TABLE_COLORS = [
4287
+ "brown",
4288
+ "muted-red",
4289
+ "red",
4290
+ "coral",
4291
+ "orange",
4292
+ "amber",
4293
+ "yellow",
4294
+ "gold",
4295
+ "blue",
4296
+ "light-blue",
4297
+ "cyan",
4298
+ "mint",
4299
+ "green",
4300
+ "dark-green",
4301
+ "lime",
4302
+ "light-green",
4303
+ "charcoal",
4304
+ "gray",
4305
+ "mauve",
4306
+ "pink",
4307
+ "purple",
4308
+ "deep-purple",
4309
+ "periwinkle",
4310
+ "lavender"
4311
+ ];
4312
+ var tableColorSchema = external_exports.enum(TABLE_COLORS);
4313
+ var fieldTypeSchema = external_exports.lazy(
4314
+ () => external_exports.discriminatedUnion("kind", [
4315
+ external_exports.object({ kind: external_exports.literal("string") }),
4316
+ external_exports.object({ kind: external_exports.literal("markdown") }),
4317
+ external_exports.object({ kind: external_exports.literal("number") }),
4318
+ external_exports.object({ kind: external_exports.literal("boolean") }),
4319
+ external_exports.object({ kind: external_exports.literal("bigint") }),
4320
+ external_exports.object({ kind: external_exports.literal("null") }),
4321
+ external_exports.object({ kind: external_exports.literal("any") }),
4322
+ external_exports.object({ kind: external_exports.literal("bytes") }),
4323
+ external_exports.object({ kind: external_exports.literal("file") }),
4324
+ external_exports.object({ kind: external_exports.literal("image") }),
4325
+ external_exports.object({ kind: external_exports.literal("date") }),
4326
+ external_exports.object({ kind: external_exports.literal("datetime") }),
4327
+ external_exports.object({ kind: external_exports.literal("id"), table: external_exports.string().regex(IDENT) }),
4328
+ external_exports.object({
4329
+ kind: external_exports.literal("literal"),
4330
+ value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])
4331
+ }),
4332
+ external_exports.object({ kind: external_exports.literal("array"), element: fieldTypeSchema }),
4333
+ external_exports.object({
4334
+ kind: external_exports.literal("object"),
4335
+ fields: external_exports.array(
4336
+ external_exports.object({
4337
+ name: external_exports.string().regex(IDENT),
4338
+ label: external_exports.string().optional(),
4339
+ type: fieldTypeSchema,
4340
+ optional: external_exports.boolean()
4341
+ })
4342
+ )
4343
+ }),
4344
+ external_exports.object({
4345
+ kind: external_exports.literal("union"),
4346
+ options: external_exports.array(fieldTypeSchema).min(2)
4347
+ })
4348
+ ])
4349
+ );
4350
+ var fieldSchema = external_exports.object({
4351
+ name: external_exports.string().regex(IDENT, "must be a valid identifier"),
4352
+ label: external_exports.string().optional(),
4353
+ type: fieldTypeSchema,
4354
+ optional: external_exports.boolean()
4355
+ });
4356
+ var indexSchema = external_exports.object({
4357
+ name: external_exports.string().regex(IDENT),
4358
+ fields: external_exports.array(external_exports.string().regex(IDENT)).min(1)
4359
+ });
4360
+ var searchIndexSchema = external_exports.object({
4361
+ name: external_exports.string().regex(IDENT),
4362
+ searchField: external_exports.string().regex(IDENT),
4363
+ filterFields: external_exports.array(external_exports.string().regex(IDENT)).optional()
4364
+ });
4365
+ var tableSchema = external_exports.object({
4366
+ name: external_exports.string().regex(IDENT).refine((n) => !RESERVED_TABLE_NAMES.has(n), {
4367
+ message: "table name is reserved by the studio"
4368
+ }),
4369
+ label: external_exports.string().optional(),
4370
+ color: tableColorSchema.optional(),
4371
+ fields: external_exports.array(fieldSchema),
4372
+ indexes: external_exports.array(indexSchema).default([]),
4373
+ searchIndexes: external_exports.array(searchIndexSchema).default([]),
4374
+ displayTemplates: displayTemplatesSchema.optional()
4375
+ });
4376
+ external_exports.object({
4377
+ tables: external_exports.array(tableSchema)
4378
+ }).superRefine((manifest, ctx) => {
4379
+ const tableNames = /* @__PURE__ */ new Set();
4380
+ for (const t of manifest.tables) {
4381
+ if (tableNames.has(t.name)) {
4382
+ ctx.addIssue({
4383
+ code: external_exports.ZodIssueCode.custom,
4384
+ message: `duplicate table: ${t.name}`,
4385
+ path: ["tables"]
4386
+ });
4387
+ }
4388
+ tableNames.add(t.name);
4389
+ const fieldNames = /* @__PURE__ */ new Set();
4390
+ for (const f of t.fields) {
4391
+ if (fieldNames.has(f.name)) {
4392
+ ctx.addIssue({
4393
+ code: external_exports.ZodIssueCode.custom,
4394
+ message: `duplicate field in ${t.name}: ${f.name}`,
4395
+ path: ["tables"]
4396
+ });
4397
+ }
4398
+ fieldNames.add(f.name);
4399
+ }
4400
+ }
4401
+ for (const t of manifest.tables) {
4402
+ for (const f of t.fields) {
4403
+ const danglingRef = findDanglingRef(f.type, tableNames);
4404
+ if (danglingRef) {
4405
+ ctx.addIssue({
4406
+ code: external_exports.ZodIssueCode.custom,
4407
+ message: `${t.name}.${f.name} references unknown table: ${danglingRef}`,
4408
+ path: ["tables"]
4409
+ });
4410
+ }
4411
+ }
4412
+ }
4413
+ });
4414
+ function findDanglingRef(t, known) {
4415
+ switch (t.kind) {
4416
+ case "id":
4417
+ return known.has(t.table) ? null : t.table;
4418
+ case "array":
4419
+ return findDanglingRef(t.element, known);
4420
+ case "object":
4421
+ for (const f of t.fields) {
4422
+ const r = findDanglingRef(f.type, known);
4423
+ if (r) return r;
4424
+ }
4425
+ return null;
4426
+ case "union":
4427
+ for (const o of t.options) {
4428
+ const r = findDanglingRef(o, known);
4429
+ if (r) return r;
4430
+ }
4431
+ return null;
4432
+ default:
4433
+ return null;
4434
+ }
4435
+ }
4436
+ function validateFieldValue(value, type, optional) {
4437
+ if (value === void 0 || value === null) {
4438
+ if (optional) return null;
4439
+ if (type.kind === "null") return null;
4440
+ return "Required";
4441
+ }
4442
+ switch (type.kind) {
4443
+ case "string":
4444
+ if (typeof value !== "string") return "Must be a string";
4445
+ if (!optional && value === "") return "Required";
4446
+ return null;
4447
+ case "markdown":
4448
+ if (typeof value !== "string") return "Must be a string";
4449
+ if (!optional && value === "") return "Required";
4450
+ if (value !== "" && !isValidRichFieldJson(value)) return "Invalid markdown document";
4451
+ return null;
4452
+ case "number":
4453
+ case "date":
4454
+ case "datetime":
4455
+ if (typeof value !== "number" || !Number.isFinite(value)) return "Must be a number";
4456
+ return null;
4457
+ case "boolean":
4458
+ return typeof value === "boolean" ? null : "Must be a boolean";
4459
+ case "bigint": {
4460
+ if (typeof value === "bigint") return null;
4461
+ if (typeof value !== "string") return "Must be a bigint";
4462
+ const stripped = value.endsWith("n") ? value.slice(0, -1) : value;
4463
+ if (!/^-?\d+$/.test(stripped)) return "Must be an integer (e.g. 123 or 123n)";
4464
+ return null;
4465
+ }
4466
+ case "id":
4467
+ case "file":
4468
+ case "image":
4469
+ if (typeof value !== "string" || value === "") return "Required";
4470
+ return null;
4471
+ case "literal":
4472
+ return value === type.value ? null : `Must be ${JSON.stringify(type.value)}`;
4473
+ case "any":
4474
+ case "bytes":
4475
+ case "null":
4476
+ return null;
4477
+ case "array": {
4478
+ if (!Array.isArray(value)) return "Must be an array";
4479
+ for (let i = 0; i < value.length; i++) {
4480
+ const err = validateFieldValue(value[i], type.element);
4481
+ if (err) return `Item ${i}: ${err}`;
4482
+ }
4483
+ return null;
4484
+ }
4485
+ case "object": {
4486
+ if (typeof value !== "object" || Array.isArray(value)) return "Must be an object";
4487
+ const v = value;
4488
+ for (const f of type.fields) {
4489
+ const err = validateFieldValue(v[f.name], f.type, f.optional);
4490
+ if (err) return `${f.name}: ${err}`;
4491
+ }
4492
+ return null;
4493
+ }
4494
+ case "union":
4495
+ for (const o of type.options) {
4496
+ if (validateFieldValue(value, o) === null) return null;
4497
+ }
4498
+ return "Does not match any variant";
4499
+ }
4500
+ }
4501
+ function validatePatch(patch, fields) {
4502
+ const errors = {};
4503
+ for (const f of fields) {
4504
+ const err = validateFieldValue(patch[f.name], f.type, f.optional);
4505
+ if (err) errors[f.name] = err;
4506
+ }
4507
+ return errors;
4508
+ }
4509
+
4510
+ // packages/@columnus/shared/src/shareProposal.ts
4511
+ function newProvisionalRowId() {
4512
+ return `new:${crypto.randomUUID()}`;
4513
+ }
4514
+ function provisionalRowKey(table, rowId) {
4515
+ return JSON.stringify([table, rowId]);
4516
+ }
4517
+ function patchLabel(patch) {
4518
+ return `${patch.table}/${patch.rowId}`;
4519
+ }
4520
+ function comparePatches(a, b) {
4521
+ if (a.seq !== b.seq) return a.seq < b.seq ? -1 : 1;
4522
+ if (a._creationTime !== b._creationTime) return a._creationTime < b._creationTime ? -1 : 1;
4523
+ return a.id.localeCompare(b.id);
4524
+ }
4525
+ function findCycle(outgoing, blocked) {
4526
+ const state = /* @__PURE__ */ new Map();
4527
+ const stack = [];
4528
+ const visit = (node) => {
4529
+ state.set(node, "visiting");
4530
+ stack.push(node);
4531
+ for (const next of outgoing[node]) {
4532
+ if (!blocked.has(next)) continue;
4533
+ if (state.get(next) === "visiting") return stack.slice(stack.indexOf(next));
4534
+ if (!state.has(next)) {
4535
+ const cycle = visit(next);
4536
+ if (cycle) return cycle;
4537
+ }
4538
+ }
4539
+ stack.pop();
4540
+ state.set(node, "done");
4541
+ return null;
4542
+ };
4543
+ for (const node of blocked) {
4544
+ if (state.has(node)) continue;
4545
+ const cycle = visit(node);
4546
+ if (cycle) return cycle;
4547
+ }
4548
+ return [];
4549
+ }
4550
+ function referencedProvisionalIds(manifest, patch) {
4551
+ const table = manifest.tables.find((candidate) => candidate.name === patch.table);
4552
+ if (!table) throw new Error(`Unknown proposal table ${patch.table}`);
4553
+ const refs = [];
4554
+ for (const edge of refFieldsForTable(table)) {
4555
+ const value = patch.fields[edge.field];
4556
+ const values = edge.array ? Array.isArray(value) ? value : [] : [value];
4557
+ for (const rowId of values) {
4558
+ if (typeof rowId === "string" && rowId.startsWith("new:")) {
4559
+ refs.push({ table: edge.targetTable, rowId });
4560
+ }
4561
+ }
4562
+ }
4563
+ return refs;
4564
+ }
4565
+ function planProposalPatches(manifest, patches) {
4566
+ for (const patch of patches) {
4567
+ if (!Number.isSafeInteger(patch.seq) || patch.seq < 1) {
4568
+ throw new Error(`Invalid proposal patch sequence for ${patchLabel(patch)}`);
4569
+ }
4570
+ if (patch.rowId.startsWith("new:") && patch.op !== "insert") {
4571
+ throw new Error(`Provisional row ${patchLabel(patch)} must be an insert`);
4572
+ }
4573
+ }
4574
+ const producers = /* @__PURE__ */ new Map();
4575
+ for (let index = 0; index < patches.length; index += 1) {
4576
+ const patch = patches[index];
4577
+ if (patch.op !== "insert" || !patch.rowId.startsWith("new:")) continue;
4578
+ const key = provisionalRowKey(patch.table, patch.rowId);
4579
+ if (producers.has(key)) {
4580
+ throw new Error(`Duplicate provisional row ${patchLabel(patch)}`);
4581
+ }
4582
+ producers.set(key, index);
4583
+ }
4584
+ const outgoing = patches.map(() => /* @__PURE__ */ new Set());
4585
+ const indegree = patches.map(() => 0);
4586
+ let hasDependencies = false;
4587
+ for (let consumer = 0; consumer < patches.length; consumer += 1) {
4588
+ const patch = patches[consumer];
4589
+ for (const ref of referencedProvisionalIds(manifest, patch)) {
4590
+ const producer = producers.get(provisionalRowKey(ref.table, ref.rowId));
4591
+ if (producer === void 0) {
4592
+ throw new Error(
4593
+ `Missing provisional row ${ref.table}/${ref.rowId} referenced by ${patchLabel(patch)}`
4594
+ );
4595
+ }
4596
+ if (!outgoing[producer].has(consumer)) {
4597
+ outgoing[producer].add(consumer);
4598
+ indegree[consumer] += 1;
4599
+ hasDependencies = true;
4600
+ }
4601
+ }
4602
+ }
4603
+ const ready = patches.map((patch, index) => ({ patch, index })).filter(({ index }) => indegree[index] === 0).sort((a, b) => comparePatches(a.patch, b.patch));
4604
+ const orderedPatches = [];
4605
+ while (ready.length > 0) {
4606
+ const current = ready.shift();
4607
+ orderedPatches.push(current.patch);
4608
+ for (const consumer of outgoing[current.index]) {
4609
+ indegree[consumer] -= 1;
4610
+ if (indegree[consumer] === 0) {
4611
+ ready.push({ patch: patches[consumer], index: consumer });
4612
+ ready.sort((a, b) => comparePatches(a.patch, b.patch));
4613
+ }
4614
+ }
4615
+ }
4616
+ if (orderedPatches.length !== patches.length) {
4617
+ const blocked = new Set(indegree.flatMap((value, index) => value > 0 ? [index] : []));
4618
+ const cyclic = findCycle(outgoing, blocked).map((index) => patches[index]).sort(comparePatches).map(patchLabel);
4619
+ throw new Error(`Cyclic provisional references: ${cyclic.join(", ")}`);
4620
+ }
4621
+ return { orderedPatches, hasDependencies };
4622
+ }
4623
+ function prepareProposalPatchesForAccept(manifest, scopes, patches) {
4624
+ const tablesByName = new Map(manifest.tables.map((table) => [table.name, table]));
4625
+ const scopesByTable = new Map(scopes.map((scope) => [scope.table, scope]));
4626
+ const fieldsByTable = /* @__PURE__ */ new Map();
4627
+ const prepared = [];
4628
+ for (const patch of patches) {
4629
+ if (patch.op === "delete") {
4630
+ prepared.push(patch);
4631
+ continue;
4632
+ }
4633
+ const table = tablesByName.get(patch.table);
4634
+ if (!table) throw new Error(`Unknown proposal table ${patch.table}`);
4635
+ const scope = scopesByTable.get(patch.table);
4636
+ let byName = fieldsByTable.get(patch.table);
4637
+ if (!byName) {
4638
+ byName = new Map(table.fields.map((field) => [field.name, field]));
4639
+ fieldsByTable.set(patch.table, byName);
4640
+ }
4641
+ const stripped = Object.fromEntries(
4642
+ Object.entries(pickProposalFields(patch.fields, scope?.allowedFields)).filter(
4643
+ ([field]) => byName.has(field)
4644
+ )
4645
+ );
4646
+ if (patch.op === "update" && Object.keys(stripped).length === 0) continue;
4647
+ const fieldsToCheck = patch.op === "insert" ? table.fields : [...byName.values()].filter((field) => field.name in stripped);
4648
+ const errors = validatePatch(stripped, fieldsToCheck);
4649
+ const first = Object.entries(errors)[0];
4650
+ if (first) {
4651
+ throw new Error(
4652
+ `Proposal patch ${patchLabel(patch)} field "${first[0]}" is invalid: ${first[1]}`
4653
+ );
4654
+ }
4655
+ prepared.push({ ...patch, fields: stripped });
4656
+ }
4657
+ return prepared;
4658
+ }
4659
+ var SYSTEM_FIELDS = /* @__PURE__ */ new Set(["_id", "_creationTime"]);
4660
+ function snapshotBaseFields(op, proposedFields, liveRow) {
4661
+ if (op === "insert" || !liveRow) return void 0;
4662
+ const base = {};
4663
+ if (op === "delete") {
4664
+ for (const [key, value] of Object.entries(liveRow)) {
4665
+ if (!SYSTEM_FIELDS.has(key)) base[key] = value ?? null;
4666
+ }
4667
+ return base;
4668
+ }
4669
+ for (const key of Object.keys(proposedFields)) {
4670
+ base[key] = liveRow[key] ?? null;
4671
+ }
4672
+ return base;
4673
+ }
4674
+ function patchIsStale(patch, liveRow) {
4675
+ const base = patch.baseFields;
4676
+ if (base === void 0 || base === null) return { stale: false };
4677
+ if (patch.op === "insert" || patch.rowId.startsWith("new:")) return { stale: false };
4678
+ if (!liveRow) {
4679
+ return { stale: true, reason: `${patch.table}/${patch.rowId} no longer exists` };
4680
+ }
4681
+ for (const [key, baseValue] of Object.entries(base)) {
4682
+ if (!fieldValuesEqual(baseValue ?? null, liveRow[key] ?? null)) {
4683
+ return {
4684
+ stale: true,
4685
+ reason: `${patch.table}/${patch.rowId} changed since it was proposed (${key})`
4686
+ };
4687
+ }
4688
+ }
4689
+ return { stale: false };
4690
+ }
4691
+ function fieldKeysIntersect(a, b) {
4692
+ const keysA = Object.keys(a ?? {});
4693
+ if (keysA.length === 0) return false;
4694
+ const keysB = new Set(Object.keys(b ?? {}));
4695
+ for (const key of keysA) {
4696
+ if (keysB.has(key)) return true;
4697
+ }
4698
+ return false;
4699
+ }
4700
+ function livePatchesConflict(a, b) {
4701
+ if (a.rowId.startsWith("new:") || b.rowId.startsWith("new:")) return false;
4702
+ if (a.table !== b.table || a.rowId !== b.rowId) return false;
4703
+ if (a.op === "delete" || b.op === "delete") return true;
4704
+ if (a.op === "update" && b.op === "update") {
4705
+ return fieldKeysIntersect(a.fields, b.fields);
4706
+ }
4707
+ return false;
4708
+ }
4709
+ function proposalsConflict(a, b) {
4710
+ for (const patchA of a.patches) {
4711
+ for (const patchB of b.patches) {
4712
+ if (livePatchesConflict(patchA, patchB)) return true;
4713
+ }
4714
+ }
4715
+ return false;
4716
+ }
4717
+ function findOverlappingProposalIds(proposals) {
4718
+ const overlapping = /* @__PURE__ */ new Set();
4719
+ for (let i = 0; i < proposals.length; i += 1) {
4720
+ const left = proposals[i];
4721
+ for (let j = i + 1; j < proposals.length; j += 1) {
4722
+ const right = proposals[j];
4723
+ if (!proposalsConflict(left, right)) continue;
4724
+ overlapping.add(left.id);
4725
+ overlapping.add(right.id);
4726
+ }
4727
+ }
4728
+ return overlapping;
4729
+ }
4730
+ function findProposalIdsOverlappingTarget(target, candidates) {
4731
+ const overlapping = /* @__PURE__ */ new Set();
4732
+ for (const other of candidates) {
4733
+ if (other.id === target.id) continue;
4734
+ if (proposalsConflict(target, other)) overlapping.add(other.id);
4735
+ }
4736
+ return overlapping;
4737
+ }
4738
+ function proposalOverlapsAny(target, candidates) {
4739
+ for (const other of candidates) {
4740
+ if (other.id === target.id) continue;
4741
+ if (proposalsConflict(target, other)) return true;
4742
+ }
4743
+ return false;
4744
+ }
4745
+ function replaceProvisionalReferences(manifest, tableName, fields, createdIds) {
4746
+ const table = manifest.tables.find((candidate) => candidate.name === tableName);
4747
+ if (!table) throw new Error(`Unknown proposal table ${tableName}`);
4748
+ const resolved = { ...fields };
4749
+ const resolveId = (targetTable, rowId) => {
4750
+ if (!rowId.startsWith("new:")) return rowId;
4751
+ const created = createdIds.get(provisionalRowKey(targetTable, rowId));
4752
+ if (!created) throw new Error(`Unresolved provisional row ${targetTable}/${rowId}`);
4753
+ return created;
4754
+ };
4755
+ for (const edge of refFieldsForTable(table)) {
4756
+ const value = fields[edge.field];
4757
+ if (edge.array) {
4758
+ if (!Array.isArray(value)) continue;
4759
+ resolved[edge.field] = value.map(
4760
+ (rowId) => typeof rowId === "string" ? resolveId(edge.targetTable, rowId) : rowId
4761
+ );
4762
+ } else if (typeof value === "string") {
4763
+ resolved[edge.field] = resolveId(edge.targetTable, value);
4764
+ }
4765
+ }
4766
+ return resolved;
4767
+ }
4768
+ var OVERLAP_MESSAGE = "Another pending proposal touches the same rows";
4769
+ async function runAcceptProposalBatch(args) {
4770
+ const { proposalIds, activeProposals, getLiveRow, onAccept, onMissing = "throw" } = args;
4771
+ const multi = proposalIds.length > 1;
4772
+ const byId = new Map(activeProposals.map((proposal) => [proposal.id, proposal]));
4773
+ const overlapping = multi ? findOverlappingProposalIds(
4774
+ activeProposals.map((proposal) => ({ id: proposal.id, patches: proposal.patches }))
4775
+ ) : /* @__PURE__ */ new Set();
4776
+ const outcomes = [];
4777
+ for (const id of proposalIds) {
4778
+ const proposal = byId.get(id);
4779
+ if (!proposal) {
4780
+ if (onMissing === "throw") throw new Error("Active proposal not found");
4781
+ outcomes.push({ id, outcome: "rejected", message: "Proposal not found" });
4782
+ continue;
4783
+ }
4784
+ if (multi && overlapping.has(id)) {
4785
+ outcomes.push({ id, outcome: "skipped_overlap", message: OVERLAP_MESSAGE });
4786
+ continue;
4787
+ }
4788
+ let staleMessage;
4789
+ for (const patch of proposal.patches) {
4790
+ if (patch.op === "insert" || patch.rowId.startsWith("new:")) continue;
4791
+ const liveRow = await Promise.resolve(getLiveRow(patch.table, patch.rowId));
4792
+ const check = patchIsStale(patch, liveRow);
4793
+ if (check.stale) {
4794
+ staleMessage = check.reason ?? "Live data changed since this was proposed";
4795
+ break;
4796
+ }
4797
+ }
4798
+ if (staleMessage) {
4799
+ outcomes.push({ id, outcome: "skipped_stale", message: staleMessage });
4800
+ continue;
4801
+ }
4802
+ await onAccept(id);
4803
+ outcomes.push({ id, outcome: "accepted" });
4804
+ }
4805
+ return outcomes;
4806
+ }
4807
+
4808
+ export { OVERLAP_MESSAGE, findOverlappingProposalIds, findProposalIdsOverlappingTarget, newProvisionalRowId, patchIsStale, planProposalPatches, prepareProposalPatchesForAccept, proposalOverlapsAny, provisionalRowKey, replaceProvisionalReferences, runAcceptProposalBatch, snapshotBaseFields };
4809
+ //# sourceMappingURL=shareProposal.js.map
4810
+ //# sourceMappingURL=shareProposal.js.map