@matteai/stma 0.2.1

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