@statelyai/agent 2.0.0-next.3 → 2.0.0-next.5

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