@hasna/testers 0.0.7 → 0.0.10

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.
@@ -11,6 +11,7 @@ var __export = (target, all) => {
11
11
  });
12
12
  };
13
13
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
14
+ var __require = import.meta.require;
14
15
 
15
16
  // src/types/index.ts
16
17
  function scenarioFromRow(row) {
@@ -421,6 +422,168 @@ var init_database = __esm(() => {
421
422
  ];
422
423
  });
423
424
 
425
+ // src/lib/browser-lightpanda.ts
426
+ var exports_browser_lightpanda = {};
427
+ __export(exports_browser_lightpanda, {
428
+ startLightpandaServer: () => startLightpandaServer,
429
+ launchLightpanda: () => launchLightpanda,
430
+ isLightpandaAvailable: () => isLightpandaAvailable,
431
+ installLightpanda: () => installLightpanda,
432
+ getLightpandaPage: () => getLightpandaPage,
433
+ closeLightpanda: () => closeLightpanda
434
+ });
435
+ import { chromium } from "playwright";
436
+ import { spawn } from "child_process";
437
+ function isLightpandaAvailable() {
438
+ try {
439
+ const possiblePaths = [
440
+ `${process.env["HOME"]}/.cache/lightpanda-node/lightpanda`,
441
+ process.env["LIGHTPANDA_EXECUTABLE_PATH"]
442
+ ];
443
+ for (const p of possiblePaths) {
444
+ if (p) {
445
+ try {
446
+ const { existsSync: existsSync2 } = __require("fs");
447
+ if (existsSync2(p))
448
+ return true;
449
+ } catch {
450
+ continue;
451
+ }
452
+ }
453
+ }
454
+ const { execSync } = __require("child_process");
455
+ execSync("lightpanda --version", { stdio: "ignore", timeout: 5000 });
456
+ return true;
457
+ } catch {
458
+ return false;
459
+ }
460
+ }
461
+ function findLightpandaBinary() {
462
+ const envPath = process.env["LIGHTPANDA_EXECUTABLE_PATH"];
463
+ if (envPath)
464
+ return envPath;
465
+ const cachePath = `${process.env["HOME"]}/.cache/lightpanda-node/lightpanda`;
466
+ try {
467
+ const { existsSync: existsSync2 } = __require("fs");
468
+ if (existsSync2(cachePath))
469
+ return cachePath;
470
+ } catch {}
471
+ return "lightpanda";
472
+ }
473
+ async function startLightpandaServer(port) {
474
+ const binary = findLightpandaBinary();
475
+ const cdpPort = port ?? 9222 + Math.floor(Math.random() * 1000);
476
+ return new Promise((resolve, reject) => {
477
+ const proc = spawn(binary, ["serve", "--port", String(cdpPort)], {
478
+ stdio: ["ignore", "pipe", "pipe"]
479
+ });
480
+ let resolved = false;
481
+ const timeout = setTimeout(() => {
482
+ if (!resolved) {
483
+ resolved = true;
484
+ resolve({
485
+ process: proc,
486
+ wsEndpoint: `ws://127.0.0.1:${cdpPort}`
487
+ });
488
+ }
489
+ }, 5000);
490
+ proc.stdout?.on("data", (data) => {
491
+ const output = data.toString();
492
+ if (output.includes("127.0.0.1") || output.includes("listening") || output.includes("DevTools")) {
493
+ if (!resolved) {
494
+ resolved = true;
495
+ clearTimeout(timeout);
496
+ resolve({
497
+ process: proc,
498
+ wsEndpoint: `ws://127.0.0.1:${cdpPort}`
499
+ });
500
+ }
501
+ }
502
+ });
503
+ proc.stderr?.on("data", (data) => {
504
+ const output = data.toString();
505
+ if (output.includes("127.0.0.1") || output.includes("listening")) {
506
+ if (!resolved) {
507
+ resolved = true;
508
+ clearTimeout(timeout);
509
+ resolve({
510
+ process: proc,
511
+ wsEndpoint: `ws://127.0.0.1:${cdpPort}`
512
+ });
513
+ }
514
+ }
515
+ });
516
+ proc.on("error", (err) => {
517
+ clearTimeout(timeout);
518
+ if (!resolved) {
519
+ resolved = true;
520
+ reject(new BrowserError(`Failed to start Lightpanda: ${err.message}. ` + `Install it with: bun install @lightpanda/browser`));
521
+ }
522
+ });
523
+ proc.on("exit", (code) => {
524
+ if (!resolved) {
525
+ resolved = true;
526
+ clearTimeout(timeout);
527
+ reject(new BrowserError(`Lightpanda exited with code ${code}. ` + `Install it with: bun install @lightpanda/browser`));
528
+ }
529
+ });
530
+ });
531
+ }
532
+ async function launchLightpanda(_options) {
533
+ try {
534
+ const { process: proc, wsEndpoint } = await startLightpandaServer();
535
+ lightpandaProcess = proc;
536
+ const browser = await chromium.connectOverCDP(wsEndpoint);
537
+ return browser;
538
+ } catch (error) {
539
+ const message = error instanceof Error ? error.message : String(error);
540
+ throw new BrowserError(`Failed to launch Lightpanda: ${message}`);
541
+ }
542
+ }
543
+ async function getLightpandaPage(browser, options) {
544
+ try {
545
+ const contexts = browser.contexts();
546
+ const context = contexts.length > 0 ? contexts[0] : await browser.newContext({
547
+ viewport: options?.viewport ?? { width: 1280, height: 720 },
548
+ userAgent: options?.userAgent,
549
+ locale: options?.locale
550
+ });
551
+ const page = await context.newPage();
552
+ return page;
553
+ } catch (error) {
554
+ const message = error instanceof Error ? error.message : String(error);
555
+ throw new BrowserError(`Failed to create Lightpanda page: ${message}`);
556
+ }
557
+ }
558
+ async function closeLightpanda(browser) {
559
+ try {
560
+ await browser.close();
561
+ } catch {}
562
+ if (lightpandaProcess) {
563
+ try {
564
+ lightpandaProcess.kill("SIGTERM");
565
+ lightpandaProcess = null;
566
+ } catch {}
567
+ }
568
+ }
569
+ async function installLightpanda() {
570
+ const { execSync } = __require("child_process");
571
+ try {
572
+ execSync("bun install @lightpanda/browser", {
573
+ stdio: "inherit",
574
+ cwd: process.env["HOME"]
575
+ });
576
+ } catch (error) {
577
+ const message = error instanceof Error ? error.message : String(error);
578
+ throw new BrowserError(`Failed to install Lightpanda: ${message}
579
+ ` + `Try manually: bun install @lightpanda/browser`);
580
+ }
581
+ }
582
+ var lightpandaProcess = null;
583
+ var init_browser_lightpanda = __esm(() => {
584
+ init_types();
585
+ });
586
+
424
587
  // src/db/flows.ts
425
588
  var exports_flows = {};
426
589
  __export(exports_flows, {
@@ -454,129 +617,4102 @@ function addDependency(scenarioId, dependsOn) {
454
617
  }
455
618
  }
456
619
  }
457
- db2.query("INSERT OR IGNORE INTO scenario_dependencies (scenario_id, depends_on) VALUES (?, ?)").run(scenarioId, dependsOn);
458
- }
459
- function removeDependency(scenarioId, dependsOn) {
460
- const db2 = getDatabase();
461
- const result = db2.query("DELETE FROM scenario_dependencies WHERE scenario_id = ? AND depends_on = ?").run(scenarioId, dependsOn);
462
- return result.changes > 0;
463
- }
464
- function getDependencies(scenarioId) {
465
- const db2 = getDatabase();
466
- const rows = db2.query("SELECT depends_on FROM scenario_dependencies WHERE scenario_id = ?").all(scenarioId);
467
- return rows.map((r) => r.depends_on);
620
+ db2.query("INSERT OR IGNORE INTO scenario_dependencies (scenario_id, depends_on) VALUES (?, ?)").run(scenarioId, dependsOn);
621
+ }
622
+ function removeDependency(scenarioId, dependsOn) {
623
+ const db2 = getDatabase();
624
+ const result = db2.query("DELETE FROM scenario_dependencies WHERE scenario_id = ? AND depends_on = ?").run(scenarioId, dependsOn);
625
+ return result.changes > 0;
626
+ }
627
+ function getDependencies(scenarioId) {
628
+ const db2 = getDatabase();
629
+ const rows = db2.query("SELECT depends_on FROM scenario_dependencies WHERE scenario_id = ?").all(scenarioId);
630
+ return rows.map((r) => r.depends_on);
631
+ }
632
+ function getDependents(scenarioId) {
633
+ const db2 = getDatabase();
634
+ const rows = db2.query("SELECT scenario_id FROM scenario_dependencies WHERE depends_on = ?").all(scenarioId);
635
+ return rows.map((r) => r.scenario_id);
636
+ }
637
+ function getTransitiveDependencies(scenarioId) {
638
+ const db2 = getDatabase();
639
+ const visited = new Set;
640
+ const queue = [scenarioId];
641
+ while (queue.length > 0) {
642
+ const current = queue.shift();
643
+ const deps = db2.query("SELECT depends_on FROM scenario_dependencies WHERE scenario_id = ?").all(current);
644
+ for (const dep of deps) {
645
+ if (!visited.has(dep.depends_on)) {
646
+ visited.add(dep.depends_on);
647
+ queue.push(dep.depends_on);
648
+ }
649
+ }
650
+ }
651
+ return Array.from(visited);
652
+ }
653
+ function topologicalSort(scenarioIds) {
654
+ const db2 = getDatabase();
655
+ const idSet = new Set(scenarioIds);
656
+ const inDegree = new Map;
657
+ const dependents = new Map;
658
+ for (const id of scenarioIds) {
659
+ inDegree.set(id, 0);
660
+ dependents.set(id, []);
661
+ }
662
+ for (const id of scenarioIds) {
663
+ const deps = db2.query("SELECT depends_on FROM scenario_dependencies WHERE scenario_id = ?").all(id);
664
+ for (const dep of deps) {
665
+ if (idSet.has(dep.depends_on)) {
666
+ inDegree.set(id, (inDegree.get(id) ?? 0) + 1);
667
+ dependents.get(dep.depends_on).push(id);
668
+ }
669
+ }
670
+ }
671
+ const queue = [];
672
+ for (const [id, deg] of inDegree) {
673
+ if (deg === 0)
674
+ queue.push(id);
675
+ }
676
+ const sorted = [];
677
+ while (queue.length > 0) {
678
+ const current = queue.shift();
679
+ sorted.push(current);
680
+ for (const dep of dependents.get(current) ?? []) {
681
+ const newDeg = (inDegree.get(dep) ?? 1) - 1;
682
+ inDegree.set(dep, newDeg);
683
+ if (newDeg === 0)
684
+ queue.push(dep);
685
+ }
686
+ }
687
+ if (sorted.length !== scenarioIds.length) {
688
+ throw new DependencyCycleError("multiple", "multiple");
689
+ }
690
+ return sorted;
691
+ }
692
+ function createFlow(input) {
693
+ const db2 = getDatabase();
694
+ const id = uuid();
695
+ const timestamp = now();
696
+ db2.query(`
697
+ INSERT INTO flows (id, project_id, name, description, scenario_ids, created_at, updated_at)
698
+ VALUES (?, ?, ?, ?, ?, ?, ?)
699
+ `).run(id, input.projectId ?? null, input.name, input.description ?? null, JSON.stringify(input.scenarioIds), timestamp, timestamp);
700
+ return getFlow(id);
701
+ }
702
+ function getFlow(id) {
703
+ const db2 = getDatabase();
704
+ let row = db2.query("SELECT * FROM flows WHERE id = ?").get(id);
705
+ if (row)
706
+ return flowFromRow(row);
707
+ const fullId = resolvePartialId("flows", id);
708
+ if (fullId) {
709
+ row = db2.query("SELECT * FROM flows WHERE id = ?").get(fullId);
710
+ if (row)
711
+ return flowFromRow(row);
712
+ }
713
+ return null;
714
+ }
715
+ function listFlows(projectId) {
716
+ const db2 = getDatabase();
717
+ if (projectId) {
718
+ const rows2 = db2.query("SELECT * FROM flows WHERE project_id = ? ORDER BY created_at DESC").all(projectId);
719
+ return rows2.map(flowFromRow);
720
+ }
721
+ const rows = db2.query("SELECT * FROM flows ORDER BY created_at DESC").all();
722
+ return rows.map(flowFromRow);
723
+ }
724
+ function deleteFlow(id) {
725
+ const db2 = getDatabase();
726
+ const flow = getFlow(id);
727
+ if (!flow)
728
+ return false;
729
+ const result = db2.query("DELETE FROM flows WHERE id = ?").run(flow.id);
730
+ return result.changes > 0;
731
+ }
732
+ var init_flows = __esm(() => {
733
+ init_database();
734
+ init_database();
735
+ init_types();
736
+ });
737
+
738
+ // src/server/index.ts
739
+ import { existsSync as existsSync4 } from "fs";
740
+ import { join as join4 } from "path";
741
+ import { homedir as homedir4 } from "os";
742
+
743
+ // node_modules/zod/v3/external.js
744
+ var exports_external = {};
745
+ __export(exports_external, {
746
+ void: () => voidType,
747
+ util: () => util,
748
+ unknown: () => unknownType,
749
+ union: () => unionType,
750
+ undefined: () => undefinedType,
751
+ tuple: () => tupleType,
752
+ transformer: () => effectsType,
753
+ symbol: () => symbolType,
754
+ string: () => stringType,
755
+ strictObject: () => strictObjectType,
756
+ setErrorMap: () => setErrorMap,
757
+ set: () => setType,
758
+ record: () => recordType,
759
+ quotelessJson: () => quotelessJson,
760
+ promise: () => promiseType,
761
+ preprocess: () => preprocessType,
762
+ pipeline: () => pipelineType,
763
+ ostring: () => ostring,
764
+ optional: () => optionalType,
765
+ onumber: () => onumber,
766
+ oboolean: () => oboolean,
767
+ objectUtil: () => objectUtil,
768
+ object: () => objectType,
769
+ number: () => numberType,
770
+ nullable: () => nullableType,
771
+ null: () => nullType,
772
+ never: () => neverType,
773
+ nativeEnum: () => nativeEnumType,
774
+ nan: () => nanType,
775
+ map: () => mapType,
776
+ makeIssue: () => makeIssue,
777
+ literal: () => literalType,
778
+ lazy: () => lazyType,
779
+ late: () => late,
780
+ isValid: () => isValid,
781
+ isDirty: () => isDirty,
782
+ isAsync: () => isAsync,
783
+ isAborted: () => isAborted,
784
+ intersection: () => intersectionType,
785
+ instanceof: () => instanceOfType,
786
+ getParsedType: () => getParsedType,
787
+ getErrorMap: () => getErrorMap,
788
+ function: () => functionType,
789
+ enum: () => enumType,
790
+ effect: () => effectsType,
791
+ discriminatedUnion: () => discriminatedUnionType,
792
+ defaultErrorMap: () => en_default,
793
+ datetimeRegex: () => datetimeRegex,
794
+ date: () => dateType,
795
+ custom: () => custom,
796
+ coerce: () => coerce,
797
+ boolean: () => booleanType,
798
+ bigint: () => bigIntType,
799
+ array: () => arrayType,
800
+ any: () => anyType,
801
+ addIssueToContext: () => addIssueToContext,
802
+ ZodVoid: () => ZodVoid,
803
+ ZodUnknown: () => ZodUnknown,
804
+ ZodUnion: () => ZodUnion,
805
+ ZodUndefined: () => ZodUndefined,
806
+ ZodType: () => ZodType,
807
+ ZodTuple: () => ZodTuple,
808
+ ZodTransformer: () => ZodEffects,
809
+ ZodSymbol: () => ZodSymbol,
810
+ ZodString: () => ZodString,
811
+ ZodSet: () => ZodSet,
812
+ ZodSchema: () => ZodType,
813
+ ZodRecord: () => ZodRecord,
814
+ ZodReadonly: () => ZodReadonly,
815
+ ZodPromise: () => ZodPromise,
816
+ ZodPipeline: () => ZodPipeline,
817
+ ZodParsedType: () => ZodParsedType,
818
+ ZodOptional: () => ZodOptional,
819
+ ZodObject: () => ZodObject,
820
+ ZodNumber: () => ZodNumber,
821
+ ZodNullable: () => ZodNullable,
822
+ ZodNull: () => ZodNull,
823
+ ZodNever: () => ZodNever,
824
+ ZodNativeEnum: () => ZodNativeEnum,
825
+ ZodNaN: () => ZodNaN,
826
+ ZodMap: () => ZodMap,
827
+ ZodLiteral: () => ZodLiteral,
828
+ ZodLazy: () => ZodLazy,
829
+ ZodIssueCode: () => ZodIssueCode,
830
+ ZodIntersection: () => ZodIntersection,
831
+ ZodFunction: () => ZodFunction,
832
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
833
+ ZodError: () => ZodError,
834
+ ZodEnum: () => ZodEnum,
835
+ ZodEffects: () => ZodEffects,
836
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
837
+ ZodDefault: () => ZodDefault,
838
+ ZodDate: () => ZodDate,
839
+ ZodCatch: () => ZodCatch,
840
+ ZodBranded: () => ZodBranded,
841
+ ZodBoolean: () => ZodBoolean,
842
+ ZodBigInt: () => ZodBigInt,
843
+ ZodArray: () => ZodArray,
844
+ ZodAny: () => ZodAny,
845
+ Schema: () => ZodType,
846
+ ParseStatus: () => ParseStatus,
847
+ OK: () => OK,
848
+ NEVER: () => NEVER,
849
+ INVALID: () => INVALID,
850
+ EMPTY_PATH: () => EMPTY_PATH,
851
+ DIRTY: () => DIRTY,
852
+ BRAND: () => BRAND
853
+ });
854
+
855
+ // node_modules/zod/v3/helpers/util.js
856
+ var util;
857
+ (function(util2) {
858
+ util2.assertEqual = (_) => {};
859
+ function assertIs(_arg) {}
860
+ util2.assertIs = assertIs;
861
+ function assertNever(_x) {
862
+ throw new Error;
863
+ }
864
+ util2.assertNever = assertNever;
865
+ util2.arrayToEnum = (items) => {
866
+ const obj = {};
867
+ for (const item of items) {
868
+ obj[item] = item;
869
+ }
870
+ return obj;
871
+ };
872
+ util2.getValidEnumValues = (obj) => {
873
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
874
+ const filtered = {};
875
+ for (const k of validKeys) {
876
+ filtered[k] = obj[k];
877
+ }
878
+ return util2.objectValues(filtered);
879
+ };
880
+ util2.objectValues = (obj) => {
881
+ return util2.objectKeys(obj).map(function(e) {
882
+ return obj[e];
883
+ });
884
+ };
885
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
886
+ const keys = [];
887
+ for (const key in object) {
888
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
889
+ keys.push(key);
890
+ }
891
+ }
892
+ return keys;
893
+ };
894
+ util2.find = (arr, checker) => {
895
+ for (const item of arr) {
896
+ if (checker(item))
897
+ return item;
898
+ }
899
+ return;
900
+ };
901
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
902
+ function joinValues(array, separator = " | ") {
903
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
904
+ }
905
+ util2.joinValues = joinValues;
906
+ util2.jsonStringifyReplacer = (_, value) => {
907
+ if (typeof value === "bigint") {
908
+ return value.toString();
909
+ }
910
+ return value;
911
+ };
912
+ })(util || (util = {}));
913
+ var objectUtil;
914
+ (function(objectUtil2) {
915
+ objectUtil2.mergeShapes = (first, second) => {
916
+ return {
917
+ ...first,
918
+ ...second
919
+ };
920
+ };
921
+ })(objectUtil || (objectUtil = {}));
922
+ var ZodParsedType = util.arrayToEnum([
923
+ "string",
924
+ "nan",
925
+ "number",
926
+ "integer",
927
+ "float",
928
+ "boolean",
929
+ "date",
930
+ "bigint",
931
+ "symbol",
932
+ "function",
933
+ "undefined",
934
+ "null",
935
+ "array",
936
+ "object",
937
+ "unknown",
938
+ "promise",
939
+ "void",
940
+ "never",
941
+ "map",
942
+ "set"
943
+ ]);
944
+ var getParsedType = (data) => {
945
+ const t = typeof data;
946
+ switch (t) {
947
+ case "undefined":
948
+ return ZodParsedType.undefined;
949
+ case "string":
950
+ return ZodParsedType.string;
951
+ case "number":
952
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
953
+ case "boolean":
954
+ return ZodParsedType.boolean;
955
+ case "function":
956
+ return ZodParsedType.function;
957
+ case "bigint":
958
+ return ZodParsedType.bigint;
959
+ case "symbol":
960
+ return ZodParsedType.symbol;
961
+ case "object":
962
+ if (Array.isArray(data)) {
963
+ return ZodParsedType.array;
964
+ }
965
+ if (data === null) {
966
+ return ZodParsedType.null;
967
+ }
968
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
969
+ return ZodParsedType.promise;
970
+ }
971
+ if (typeof Map !== "undefined" && data instanceof Map) {
972
+ return ZodParsedType.map;
973
+ }
974
+ if (typeof Set !== "undefined" && data instanceof Set) {
975
+ return ZodParsedType.set;
976
+ }
977
+ if (typeof Date !== "undefined" && data instanceof Date) {
978
+ return ZodParsedType.date;
979
+ }
980
+ return ZodParsedType.object;
981
+ default:
982
+ return ZodParsedType.unknown;
983
+ }
984
+ };
985
+
986
+ // node_modules/zod/v3/ZodError.js
987
+ var ZodIssueCode = util.arrayToEnum([
988
+ "invalid_type",
989
+ "invalid_literal",
990
+ "custom",
991
+ "invalid_union",
992
+ "invalid_union_discriminator",
993
+ "invalid_enum_value",
994
+ "unrecognized_keys",
995
+ "invalid_arguments",
996
+ "invalid_return_type",
997
+ "invalid_date",
998
+ "invalid_string",
999
+ "too_small",
1000
+ "too_big",
1001
+ "invalid_intersection_types",
1002
+ "not_multiple_of",
1003
+ "not_finite"
1004
+ ]);
1005
+ var quotelessJson = (obj) => {
1006
+ const json = JSON.stringify(obj, null, 2);
1007
+ return json.replace(/"([^"]+)":/g, "$1:");
1008
+ };
1009
+
1010
+ class ZodError extends Error {
1011
+ get errors() {
1012
+ return this.issues;
1013
+ }
1014
+ constructor(issues) {
1015
+ super();
1016
+ this.issues = [];
1017
+ this.addIssue = (sub) => {
1018
+ this.issues = [...this.issues, sub];
1019
+ };
1020
+ this.addIssues = (subs = []) => {
1021
+ this.issues = [...this.issues, ...subs];
1022
+ };
1023
+ const actualProto = new.target.prototype;
1024
+ if (Object.setPrototypeOf) {
1025
+ Object.setPrototypeOf(this, actualProto);
1026
+ } else {
1027
+ this.__proto__ = actualProto;
1028
+ }
1029
+ this.name = "ZodError";
1030
+ this.issues = issues;
1031
+ }
1032
+ format(_mapper) {
1033
+ const mapper = _mapper || function(issue) {
1034
+ return issue.message;
1035
+ };
1036
+ const fieldErrors = { _errors: [] };
1037
+ const processError = (error) => {
1038
+ for (const issue of error.issues) {
1039
+ if (issue.code === "invalid_union") {
1040
+ issue.unionErrors.map(processError);
1041
+ } else if (issue.code === "invalid_return_type") {
1042
+ processError(issue.returnTypeError);
1043
+ } else if (issue.code === "invalid_arguments") {
1044
+ processError(issue.argumentsError);
1045
+ } else if (issue.path.length === 0) {
1046
+ fieldErrors._errors.push(mapper(issue));
1047
+ } else {
1048
+ let curr = fieldErrors;
1049
+ let i = 0;
1050
+ while (i < issue.path.length) {
1051
+ const el = issue.path[i];
1052
+ const terminal = i === issue.path.length - 1;
1053
+ if (!terminal) {
1054
+ curr[el] = curr[el] || { _errors: [] };
1055
+ } else {
1056
+ curr[el] = curr[el] || { _errors: [] };
1057
+ curr[el]._errors.push(mapper(issue));
1058
+ }
1059
+ curr = curr[el];
1060
+ i++;
1061
+ }
1062
+ }
1063
+ }
1064
+ };
1065
+ processError(this);
1066
+ return fieldErrors;
1067
+ }
1068
+ static assert(value) {
1069
+ if (!(value instanceof ZodError)) {
1070
+ throw new Error(`Not a ZodError: ${value}`);
1071
+ }
1072
+ }
1073
+ toString() {
1074
+ return this.message;
1075
+ }
1076
+ get message() {
1077
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
1078
+ }
1079
+ get isEmpty() {
1080
+ return this.issues.length === 0;
1081
+ }
1082
+ flatten(mapper = (issue) => issue.message) {
1083
+ const fieldErrors = {};
1084
+ const formErrors = [];
1085
+ for (const sub of this.issues) {
1086
+ if (sub.path.length > 0) {
1087
+ const firstEl = sub.path[0];
1088
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
1089
+ fieldErrors[firstEl].push(mapper(sub));
1090
+ } else {
1091
+ formErrors.push(mapper(sub));
1092
+ }
1093
+ }
1094
+ return { formErrors, fieldErrors };
1095
+ }
1096
+ get formErrors() {
1097
+ return this.flatten();
1098
+ }
1099
+ }
1100
+ ZodError.create = (issues) => {
1101
+ const error = new ZodError(issues);
1102
+ return error;
1103
+ };
1104
+
1105
+ // node_modules/zod/v3/locales/en.js
1106
+ var errorMap = (issue, _ctx) => {
1107
+ let message;
1108
+ switch (issue.code) {
1109
+ case ZodIssueCode.invalid_type:
1110
+ if (issue.received === ZodParsedType.undefined) {
1111
+ message = "Required";
1112
+ } else {
1113
+ message = `Expected ${issue.expected}, received ${issue.received}`;
1114
+ }
1115
+ break;
1116
+ case ZodIssueCode.invalid_literal:
1117
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
1118
+ break;
1119
+ case ZodIssueCode.unrecognized_keys:
1120
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
1121
+ break;
1122
+ case ZodIssueCode.invalid_union:
1123
+ message = `Invalid input`;
1124
+ break;
1125
+ case ZodIssueCode.invalid_union_discriminator:
1126
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
1127
+ break;
1128
+ case ZodIssueCode.invalid_enum_value:
1129
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
1130
+ break;
1131
+ case ZodIssueCode.invalid_arguments:
1132
+ message = `Invalid function arguments`;
1133
+ break;
1134
+ case ZodIssueCode.invalid_return_type:
1135
+ message = `Invalid function return type`;
1136
+ break;
1137
+ case ZodIssueCode.invalid_date:
1138
+ message = `Invalid date`;
1139
+ break;
1140
+ case ZodIssueCode.invalid_string:
1141
+ if (typeof issue.validation === "object") {
1142
+ if ("includes" in issue.validation) {
1143
+ message = `Invalid input: must include "${issue.validation.includes}"`;
1144
+ if (typeof issue.validation.position === "number") {
1145
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
1146
+ }
1147
+ } else if ("startsWith" in issue.validation) {
1148
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
1149
+ } else if ("endsWith" in issue.validation) {
1150
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
1151
+ } else {
1152
+ util.assertNever(issue.validation);
1153
+ }
1154
+ } else if (issue.validation !== "regex") {
1155
+ message = `Invalid ${issue.validation}`;
1156
+ } else {
1157
+ message = "Invalid";
1158
+ }
1159
+ break;
1160
+ case ZodIssueCode.too_small:
1161
+ if (issue.type === "array")
1162
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
1163
+ else if (issue.type === "string")
1164
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
1165
+ else if (issue.type === "number")
1166
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1167
+ else if (issue.type === "bigint")
1168
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1169
+ else if (issue.type === "date")
1170
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
1171
+ else
1172
+ message = "Invalid input";
1173
+ break;
1174
+ case ZodIssueCode.too_big:
1175
+ if (issue.type === "array")
1176
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
1177
+ else if (issue.type === "string")
1178
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
1179
+ else if (issue.type === "number")
1180
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1181
+ else if (issue.type === "bigint")
1182
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1183
+ else if (issue.type === "date")
1184
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
1185
+ else
1186
+ message = "Invalid input";
1187
+ break;
1188
+ case ZodIssueCode.custom:
1189
+ message = `Invalid input`;
1190
+ break;
1191
+ case ZodIssueCode.invalid_intersection_types:
1192
+ message = `Intersection results could not be merged`;
1193
+ break;
1194
+ case ZodIssueCode.not_multiple_of:
1195
+ message = `Number must be a multiple of ${issue.multipleOf}`;
1196
+ break;
1197
+ case ZodIssueCode.not_finite:
1198
+ message = "Number must be finite";
1199
+ break;
1200
+ default:
1201
+ message = _ctx.defaultError;
1202
+ util.assertNever(issue);
1203
+ }
1204
+ return { message };
1205
+ };
1206
+ var en_default = errorMap;
1207
+
1208
+ // node_modules/zod/v3/errors.js
1209
+ var overrideErrorMap = en_default;
1210
+ function setErrorMap(map) {
1211
+ overrideErrorMap = map;
1212
+ }
1213
+ function getErrorMap() {
1214
+ return overrideErrorMap;
1215
+ }
1216
+ // node_modules/zod/v3/helpers/parseUtil.js
1217
+ var makeIssue = (params) => {
1218
+ const { data, path, errorMaps, issueData } = params;
1219
+ const fullPath = [...path, ...issueData.path || []];
1220
+ const fullIssue = {
1221
+ ...issueData,
1222
+ path: fullPath
1223
+ };
1224
+ if (issueData.message !== undefined) {
1225
+ return {
1226
+ ...issueData,
1227
+ path: fullPath,
1228
+ message: issueData.message
1229
+ };
1230
+ }
1231
+ let errorMessage = "";
1232
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
1233
+ for (const map of maps) {
1234
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
1235
+ }
1236
+ return {
1237
+ ...issueData,
1238
+ path: fullPath,
1239
+ message: errorMessage
1240
+ };
1241
+ };
1242
+ var EMPTY_PATH = [];
1243
+ function addIssueToContext(ctx, issueData) {
1244
+ const overrideMap = getErrorMap();
1245
+ const issue = makeIssue({
1246
+ issueData,
1247
+ data: ctx.data,
1248
+ path: ctx.path,
1249
+ errorMaps: [
1250
+ ctx.common.contextualErrorMap,
1251
+ ctx.schemaErrorMap,
1252
+ overrideMap,
1253
+ overrideMap === en_default ? undefined : en_default
1254
+ ].filter((x) => !!x)
1255
+ });
1256
+ ctx.common.issues.push(issue);
1257
+ }
1258
+
1259
+ class ParseStatus {
1260
+ constructor() {
1261
+ this.value = "valid";
1262
+ }
1263
+ dirty() {
1264
+ if (this.value === "valid")
1265
+ this.value = "dirty";
1266
+ }
1267
+ abort() {
1268
+ if (this.value !== "aborted")
1269
+ this.value = "aborted";
1270
+ }
1271
+ static mergeArray(status, results) {
1272
+ const arrayValue = [];
1273
+ for (const s of results) {
1274
+ if (s.status === "aborted")
1275
+ return INVALID;
1276
+ if (s.status === "dirty")
1277
+ status.dirty();
1278
+ arrayValue.push(s.value);
1279
+ }
1280
+ return { status: status.value, value: arrayValue };
1281
+ }
1282
+ static async mergeObjectAsync(status, pairs) {
1283
+ const syncPairs = [];
1284
+ for (const pair of pairs) {
1285
+ const key = await pair.key;
1286
+ const value = await pair.value;
1287
+ syncPairs.push({
1288
+ key,
1289
+ value
1290
+ });
1291
+ }
1292
+ return ParseStatus.mergeObjectSync(status, syncPairs);
1293
+ }
1294
+ static mergeObjectSync(status, pairs) {
1295
+ const finalObject = {};
1296
+ for (const pair of pairs) {
1297
+ const { key, value } = pair;
1298
+ if (key.status === "aborted")
1299
+ return INVALID;
1300
+ if (value.status === "aborted")
1301
+ return INVALID;
1302
+ if (key.status === "dirty")
1303
+ status.dirty();
1304
+ if (value.status === "dirty")
1305
+ status.dirty();
1306
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1307
+ finalObject[key.value] = value.value;
1308
+ }
1309
+ }
1310
+ return { status: status.value, value: finalObject };
1311
+ }
1312
+ }
1313
+ var INVALID = Object.freeze({
1314
+ status: "aborted"
1315
+ });
1316
+ var DIRTY = (value) => ({ status: "dirty", value });
1317
+ var OK = (value) => ({ status: "valid", value });
1318
+ var isAborted = (x) => x.status === "aborted";
1319
+ var isDirty = (x) => x.status === "dirty";
1320
+ var isValid = (x) => x.status === "valid";
1321
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1322
+ // node_modules/zod/v3/helpers/errorUtil.js
1323
+ var errorUtil;
1324
+ (function(errorUtil2) {
1325
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1326
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
1327
+ })(errorUtil || (errorUtil = {}));
1328
+
1329
+ // node_modules/zod/v3/types.js
1330
+ class ParseInputLazyPath {
1331
+ constructor(parent, value, path, key) {
1332
+ this._cachedPath = [];
1333
+ this.parent = parent;
1334
+ this.data = value;
1335
+ this._path = path;
1336
+ this._key = key;
1337
+ }
1338
+ get path() {
1339
+ if (!this._cachedPath.length) {
1340
+ if (Array.isArray(this._key)) {
1341
+ this._cachedPath.push(...this._path, ...this._key);
1342
+ } else {
1343
+ this._cachedPath.push(...this._path, this._key);
1344
+ }
1345
+ }
1346
+ return this._cachedPath;
1347
+ }
1348
+ }
1349
+ var handleResult = (ctx, result) => {
1350
+ if (isValid(result)) {
1351
+ return { success: true, data: result.value };
1352
+ } else {
1353
+ if (!ctx.common.issues.length) {
1354
+ throw new Error("Validation failed but no issues detected.");
1355
+ }
1356
+ return {
1357
+ success: false,
1358
+ get error() {
1359
+ if (this._error)
1360
+ return this._error;
1361
+ const error = new ZodError(ctx.common.issues);
1362
+ this._error = error;
1363
+ return this._error;
1364
+ }
1365
+ };
1366
+ }
1367
+ };
1368
+ function processCreateParams(params) {
1369
+ if (!params)
1370
+ return {};
1371
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
1372
+ if (errorMap2 && (invalid_type_error || required_error)) {
1373
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
1374
+ }
1375
+ if (errorMap2)
1376
+ return { errorMap: errorMap2, description };
1377
+ const customMap = (iss, ctx) => {
1378
+ const { message } = params;
1379
+ if (iss.code === "invalid_enum_value") {
1380
+ return { message: message ?? ctx.defaultError };
1381
+ }
1382
+ if (typeof ctx.data === "undefined") {
1383
+ return { message: message ?? required_error ?? ctx.defaultError };
1384
+ }
1385
+ if (iss.code !== "invalid_type")
1386
+ return { message: ctx.defaultError };
1387
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
1388
+ };
1389
+ return { errorMap: customMap, description };
1390
+ }
1391
+
1392
+ class ZodType {
1393
+ get description() {
1394
+ return this._def.description;
1395
+ }
1396
+ _getType(input) {
1397
+ return getParsedType(input.data);
1398
+ }
1399
+ _getOrReturnCtx(input, ctx) {
1400
+ return ctx || {
1401
+ common: input.parent.common,
1402
+ data: input.data,
1403
+ parsedType: getParsedType(input.data),
1404
+ schemaErrorMap: this._def.errorMap,
1405
+ path: input.path,
1406
+ parent: input.parent
1407
+ };
1408
+ }
1409
+ _processInputParams(input) {
1410
+ return {
1411
+ status: new ParseStatus,
1412
+ ctx: {
1413
+ common: input.parent.common,
1414
+ data: input.data,
1415
+ parsedType: getParsedType(input.data),
1416
+ schemaErrorMap: this._def.errorMap,
1417
+ path: input.path,
1418
+ parent: input.parent
1419
+ }
1420
+ };
1421
+ }
1422
+ _parseSync(input) {
1423
+ const result = this._parse(input);
1424
+ if (isAsync(result)) {
1425
+ throw new Error("Synchronous parse encountered promise.");
1426
+ }
1427
+ return result;
1428
+ }
1429
+ _parseAsync(input) {
1430
+ const result = this._parse(input);
1431
+ return Promise.resolve(result);
1432
+ }
1433
+ parse(data, params) {
1434
+ const result = this.safeParse(data, params);
1435
+ if (result.success)
1436
+ return result.data;
1437
+ throw result.error;
1438
+ }
1439
+ safeParse(data, params) {
1440
+ const ctx = {
1441
+ common: {
1442
+ issues: [],
1443
+ async: params?.async ?? false,
1444
+ contextualErrorMap: params?.errorMap
1445
+ },
1446
+ path: params?.path || [],
1447
+ schemaErrorMap: this._def.errorMap,
1448
+ parent: null,
1449
+ data,
1450
+ parsedType: getParsedType(data)
1451
+ };
1452
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1453
+ return handleResult(ctx, result);
1454
+ }
1455
+ "~validate"(data) {
1456
+ const ctx = {
1457
+ common: {
1458
+ issues: [],
1459
+ async: !!this["~standard"].async
1460
+ },
1461
+ path: [],
1462
+ schemaErrorMap: this._def.errorMap,
1463
+ parent: null,
1464
+ data,
1465
+ parsedType: getParsedType(data)
1466
+ };
1467
+ if (!this["~standard"].async) {
1468
+ try {
1469
+ const result = this._parseSync({ data, path: [], parent: ctx });
1470
+ return isValid(result) ? {
1471
+ value: result.value
1472
+ } : {
1473
+ issues: ctx.common.issues
1474
+ };
1475
+ } catch (err) {
1476
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
1477
+ this["~standard"].async = true;
1478
+ }
1479
+ ctx.common = {
1480
+ issues: [],
1481
+ async: true
1482
+ };
1483
+ }
1484
+ }
1485
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
1486
+ value: result.value
1487
+ } : {
1488
+ issues: ctx.common.issues
1489
+ });
1490
+ }
1491
+ async parseAsync(data, params) {
1492
+ const result = await this.safeParseAsync(data, params);
1493
+ if (result.success)
1494
+ return result.data;
1495
+ throw result.error;
1496
+ }
1497
+ async safeParseAsync(data, params) {
1498
+ const ctx = {
1499
+ common: {
1500
+ issues: [],
1501
+ contextualErrorMap: params?.errorMap,
1502
+ async: true
1503
+ },
1504
+ path: params?.path || [],
1505
+ schemaErrorMap: this._def.errorMap,
1506
+ parent: null,
1507
+ data,
1508
+ parsedType: getParsedType(data)
1509
+ };
1510
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1511
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1512
+ return handleResult(ctx, result);
1513
+ }
1514
+ refine(check, message) {
1515
+ const getIssueProperties = (val) => {
1516
+ if (typeof message === "string" || typeof message === "undefined") {
1517
+ return { message };
1518
+ } else if (typeof message === "function") {
1519
+ return message(val);
1520
+ } else {
1521
+ return message;
1522
+ }
1523
+ };
1524
+ return this._refinement((val, ctx) => {
1525
+ const result = check(val);
1526
+ const setError = () => ctx.addIssue({
1527
+ code: ZodIssueCode.custom,
1528
+ ...getIssueProperties(val)
1529
+ });
1530
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
1531
+ return result.then((data) => {
1532
+ if (!data) {
1533
+ setError();
1534
+ return false;
1535
+ } else {
1536
+ return true;
1537
+ }
1538
+ });
1539
+ }
1540
+ if (!result) {
1541
+ setError();
1542
+ return false;
1543
+ } else {
1544
+ return true;
1545
+ }
1546
+ });
1547
+ }
1548
+ refinement(check, refinementData) {
1549
+ return this._refinement((val, ctx) => {
1550
+ if (!check(val)) {
1551
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1552
+ return false;
1553
+ } else {
1554
+ return true;
1555
+ }
1556
+ });
1557
+ }
1558
+ _refinement(refinement) {
1559
+ return new ZodEffects({
1560
+ schema: this,
1561
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1562
+ effect: { type: "refinement", refinement }
1563
+ });
1564
+ }
1565
+ superRefine(refinement) {
1566
+ return this._refinement(refinement);
1567
+ }
1568
+ constructor(def) {
1569
+ this.spa = this.safeParseAsync;
1570
+ this._def = def;
1571
+ this.parse = this.parse.bind(this);
1572
+ this.safeParse = this.safeParse.bind(this);
1573
+ this.parseAsync = this.parseAsync.bind(this);
1574
+ this.safeParseAsync = this.safeParseAsync.bind(this);
1575
+ this.spa = this.spa.bind(this);
1576
+ this.refine = this.refine.bind(this);
1577
+ this.refinement = this.refinement.bind(this);
1578
+ this.superRefine = this.superRefine.bind(this);
1579
+ this.optional = this.optional.bind(this);
1580
+ this.nullable = this.nullable.bind(this);
1581
+ this.nullish = this.nullish.bind(this);
1582
+ this.array = this.array.bind(this);
1583
+ this.promise = this.promise.bind(this);
1584
+ this.or = this.or.bind(this);
1585
+ this.and = this.and.bind(this);
1586
+ this.transform = this.transform.bind(this);
1587
+ this.brand = this.brand.bind(this);
1588
+ this.default = this.default.bind(this);
1589
+ this.catch = this.catch.bind(this);
1590
+ this.describe = this.describe.bind(this);
1591
+ this.pipe = this.pipe.bind(this);
1592
+ this.readonly = this.readonly.bind(this);
1593
+ this.isNullable = this.isNullable.bind(this);
1594
+ this.isOptional = this.isOptional.bind(this);
1595
+ this["~standard"] = {
1596
+ version: 1,
1597
+ vendor: "zod",
1598
+ validate: (data) => this["~validate"](data)
1599
+ };
1600
+ }
1601
+ optional() {
1602
+ return ZodOptional.create(this, this._def);
1603
+ }
1604
+ nullable() {
1605
+ return ZodNullable.create(this, this._def);
1606
+ }
1607
+ nullish() {
1608
+ return this.nullable().optional();
1609
+ }
1610
+ array() {
1611
+ return ZodArray.create(this);
1612
+ }
1613
+ promise() {
1614
+ return ZodPromise.create(this, this._def);
1615
+ }
1616
+ or(option) {
1617
+ return ZodUnion.create([this, option], this._def);
1618
+ }
1619
+ and(incoming) {
1620
+ return ZodIntersection.create(this, incoming, this._def);
1621
+ }
1622
+ transform(transform) {
1623
+ return new ZodEffects({
1624
+ ...processCreateParams(this._def),
1625
+ schema: this,
1626
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1627
+ effect: { type: "transform", transform }
1628
+ });
1629
+ }
1630
+ default(def) {
1631
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1632
+ return new ZodDefault({
1633
+ ...processCreateParams(this._def),
1634
+ innerType: this,
1635
+ defaultValue: defaultValueFunc,
1636
+ typeName: ZodFirstPartyTypeKind.ZodDefault
1637
+ });
1638
+ }
1639
+ brand() {
1640
+ return new ZodBranded({
1641
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1642
+ type: this,
1643
+ ...processCreateParams(this._def)
1644
+ });
1645
+ }
1646
+ catch(def) {
1647
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1648
+ return new ZodCatch({
1649
+ ...processCreateParams(this._def),
1650
+ innerType: this,
1651
+ catchValue: catchValueFunc,
1652
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1653
+ });
1654
+ }
1655
+ describe(description) {
1656
+ const This = this.constructor;
1657
+ return new This({
1658
+ ...this._def,
1659
+ description
1660
+ });
1661
+ }
1662
+ pipe(target) {
1663
+ return ZodPipeline.create(this, target);
1664
+ }
1665
+ readonly() {
1666
+ return ZodReadonly.create(this);
1667
+ }
1668
+ isOptional() {
1669
+ return this.safeParse(undefined).success;
1670
+ }
1671
+ isNullable() {
1672
+ return this.safeParse(null).success;
1673
+ }
1674
+ }
1675
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1676
+ var cuid2Regex = /^[0-9a-z]+$/;
1677
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1678
+ 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;
1679
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1680
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1681
+ 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)?)??$/;
1682
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1683
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1684
+ var emojiRegex;
1685
+ 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])$/;
1686
+ 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])$/;
1687
+ 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]))$/;
1688
+ 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])$/;
1689
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1690
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1691
+ 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])))`;
1692
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
1693
+ function timeRegexSource(args) {
1694
+ let secondsRegexSource = `[0-5]\\d`;
1695
+ if (args.precision) {
1696
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1697
+ } else if (args.precision == null) {
1698
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1699
+ }
1700
+ const secondsQuantifier = args.precision ? "+" : "?";
1701
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1702
+ }
1703
+ function timeRegex(args) {
1704
+ return new RegExp(`^${timeRegexSource(args)}$`);
1705
+ }
1706
+ function datetimeRegex(args) {
1707
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1708
+ const opts = [];
1709
+ opts.push(args.local ? `Z?` : `Z`);
1710
+ if (args.offset)
1711
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1712
+ regex = `${regex}(${opts.join("|")})`;
1713
+ return new RegExp(`^${regex}$`);
1714
+ }
1715
+ function isValidIP(ip, version) {
1716
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1717
+ return true;
1718
+ }
1719
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1720
+ return true;
1721
+ }
1722
+ return false;
1723
+ }
1724
+ function isValidJWT(jwt, alg) {
1725
+ if (!jwtRegex.test(jwt))
1726
+ return false;
1727
+ try {
1728
+ const [header] = jwt.split(".");
1729
+ if (!header)
1730
+ return false;
1731
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1732
+ const decoded = JSON.parse(atob(base64));
1733
+ if (typeof decoded !== "object" || decoded === null)
1734
+ return false;
1735
+ if ("typ" in decoded && decoded?.typ !== "JWT")
1736
+ return false;
1737
+ if (!decoded.alg)
1738
+ return false;
1739
+ if (alg && decoded.alg !== alg)
1740
+ return false;
1741
+ return true;
1742
+ } catch {
1743
+ return false;
1744
+ }
1745
+ }
1746
+ function isValidCidr(ip, version) {
1747
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1748
+ return true;
1749
+ }
1750
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1751
+ return true;
1752
+ }
1753
+ return false;
1754
+ }
1755
+
1756
+ class ZodString extends ZodType {
1757
+ _parse(input) {
1758
+ if (this._def.coerce) {
1759
+ input.data = String(input.data);
1760
+ }
1761
+ const parsedType = this._getType(input);
1762
+ if (parsedType !== ZodParsedType.string) {
1763
+ const ctx2 = this._getOrReturnCtx(input);
1764
+ addIssueToContext(ctx2, {
1765
+ code: ZodIssueCode.invalid_type,
1766
+ expected: ZodParsedType.string,
1767
+ received: ctx2.parsedType
1768
+ });
1769
+ return INVALID;
1770
+ }
1771
+ const status = new ParseStatus;
1772
+ let ctx = undefined;
1773
+ for (const check of this._def.checks) {
1774
+ if (check.kind === "min") {
1775
+ if (input.data.length < check.value) {
1776
+ ctx = this._getOrReturnCtx(input, ctx);
1777
+ addIssueToContext(ctx, {
1778
+ code: ZodIssueCode.too_small,
1779
+ minimum: check.value,
1780
+ type: "string",
1781
+ inclusive: true,
1782
+ exact: false,
1783
+ message: check.message
1784
+ });
1785
+ status.dirty();
1786
+ }
1787
+ } else if (check.kind === "max") {
1788
+ if (input.data.length > check.value) {
1789
+ ctx = this._getOrReturnCtx(input, ctx);
1790
+ addIssueToContext(ctx, {
1791
+ code: ZodIssueCode.too_big,
1792
+ maximum: check.value,
1793
+ type: "string",
1794
+ inclusive: true,
1795
+ exact: false,
1796
+ message: check.message
1797
+ });
1798
+ status.dirty();
1799
+ }
1800
+ } else if (check.kind === "length") {
1801
+ const tooBig = input.data.length > check.value;
1802
+ const tooSmall = input.data.length < check.value;
1803
+ if (tooBig || tooSmall) {
1804
+ ctx = this._getOrReturnCtx(input, ctx);
1805
+ if (tooBig) {
1806
+ addIssueToContext(ctx, {
1807
+ code: ZodIssueCode.too_big,
1808
+ maximum: check.value,
1809
+ type: "string",
1810
+ inclusive: true,
1811
+ exact: true,
1812
+ message: check.message
1813
+ });
1814
+ } else if (tooSmall) {
1815
+ addIssueToContext(ctx, {
1816
+ code: ZodIssueCode.too_small,
1817
+ minimum: check.value,
1818
+ type: "string",
1819
+ inclusive: true,
1820
+ exact: true,
1821
+ message: check.message
1822
+ });
1823
+ }
1824
+ status.dirty();
1825
+ }
1826
+ } else if (check.kind === "email") {
1827
+ if (!emailRegex.test(input.data)) {
1828
+ ctx = this._getOrReturnCtx(input, ctx);
1829
+ addIssueToContext(ctx, {
1830
+ validation: "email",
1831
+ code: ZodIssueCode.invalid_string,
1832
+ message: check.message
1833
+ });
1834
+ status.dirty();
1835
+ }
1836
+ } else if (check.kind === "emoji") {
1837
+ if (!emojiRegex) {
1838
+ emojiRegex = new RegExp(_emojiRegex, "u");
1839
+ }
1840
+ if (!emojiRegex.test(input.data)) {
1841
+ ctx = this._getOrReturnCtx(input, ctx);
1842
+ addIssueToContext(ctx, {
1843
+ validation: "emoji",
1844
+ code: ZodIssueCode.invalid_string,
1845
+ message: check.message
1846
+ });
1847
+ status.dirty();
1848
+ }
1849
+ } else if (check.kind === "uuid") {
1850
+ if (!uuidRegex.test(input.data)) {
1851
+ ctx = this._getOrReturnCtx(input, ctx);
1852
+ addIssueToContext(ctx, {
1853
+ validation: "uuid",
1854
+ code: ZodIssueCode.invalid_string,
1855
+ message: check.message
1856
+ });
1857
+ status.dirty();
1858
+ }
1859
+ } else if (check.kind === "nanoid") {
1860
+ if (!nanoidRegex.test(input.data)) {
1861
+ ctx = this._getOrReturnCtx(input, ctx);
1862
+ addIssueToContext(ctx, {
1863
+ validation: "nanoid",
1864
+ code: ZodIssueCode.invalid_string,
1865
+ message: check.message
1866
+ });
1867
+ status.dirty();
1868
+ }
1869
+ } else if (check.kind === "cuid") {
1870
+ if (!cuidRegex.test(input.data)) {
1871
+ ctx = this._getOrReturnCtx(input, ctx);
1872
+ addIssueToContext(ctx, {
1873
+ validation: "cuid",
1874
+ code: ZodIssueCode.invalid_string,
1875
+ message: check.message
1876
+ });
1877
+ status.dirty();
1878
+ }
1879
+ } else if (check.kind === "cuid2") {
1880
+ if (!cuid2Regex.test(input.data)) {
1881
+ ctx = this._getOrReturnCtx(input, ctx);
1882
+ addIssueToContext(ctx, {
1883
+ validation: "cuid2",
1884
+ code: ZodIssueCode.invalid_string,
1885
+ message: check.message
1886
+ });
1887
+ status.dirty();
1888
+ }
1889
+ } else if (check.kind === "ulid") {
1890
+ if (!ulidRegex.test(input.data)) {
1891
+ ctx = this._getOrReturnCtx(input, ctx);
1892
+ addIssueToContext(ctx, {
1893
+ validation: "ulid",
1894
+ code: ZodIssueCode.invalid_string,
1895
+ message: check.message
1896
+ });
1897
+ status.dirty();
1898
+ }
1899
+ } else if (check.kind === "url") {
1900
+ try {
1901
+ new URL(input.data);
1902
+ } catch {
1903
+ ctx = this._getOrReturnCtx(input, ctx);
1904
+ addIssueToContext(ctx, {
1905
+ validation: "url",
1906
+ code: ZodIssueCode.invalid_string,
1907
+ message: check.message
1908
+ });
1909
+ status.dirty();
1910
+ }
1911
+ } else if (check.kind === "regex") {
1912
+ check.regex.lastIndex = 0;
1913
+ const testResult = check.regex.test(input.data);
1914
+ if (!testResult) {
1915
+ ctx = this._getOrReturnCtx(input, ctx);
1916
+ addIssueToContext(ctx, {
1917
+ validation: "regex",
1918
+ code: ZodIssueCode.invalid_string,
1919
+ message: check.message
1920
+ });
1921
+ status.dirty();
1922
+ }
1923
+ } else if (check.kind === "trim") {
1924
+ input.data = input.data.trim();
1925
+ } else if (check.kind === "includes") {
1926
+ if (!input.data.includes(check.value, check.position)) {
1927
+ ctx = this._getOrReturnCtx(input, ctx);
1928
+ addIssueToContext(ctx, {
1929
+ code: ZodIssueCode.invalid_string,
1930
+ validation: { includes: check.value, position: check.position },
1931
+ message: check.message
1932
+ });
1933
+ status.dirty();
1934
+ }
1935
+ } else if (check.kind === "toLowerCase") {
1936
+ input.data = input.data.toLowerCase();
1937
+ } else if (check.kind === "toUpperCase") {
1938
+ input.data = input.data.toUpperCase();
1939
+ } else if (check.kind === "startsWith") {
1940
+ if (!input.data.startsWith(check.value)) {
1941
+ ctx = this._getOrReturnCtx(input, ctx);
1942
+ addIssueToContext(ctx, {
1943
+ code: ZodIssueCode.invalid_string,
1944
+ validation: { startsWith: check.value },
1945
+ message: check.message
1946
+ });
1947
+ status.dirty();
1948
+ }
1949
+ } else if (check.kind === "endsWith") {
1950
+ if (!input.data.endsWith(check.value)) {
1951
+ ctx = this._getOrReturnCtx(input, ctx);
1952
+ addIssueToContext(ctx, {
1953
+ code: ZodIssueCode.invalid_string,
1954
+ validation: { endsWith: check.value },
1955
+ message: check.message
1956
+ });
1957
+ status.dirty();
1958
+ }
1959
+ } else if (check.kind === "datetime") {
1960
+ const regex = datetimeRegex(check);
1961
+ if (!regex.test(input.data)) {
1962
+ ctx = this._getOrReturnCtx(input, ctx);
1963
+ addIssueToContext(ctx, {
1964
+ code: ZodIssueCode.invalid_string,
1965
+ validation: "datetime",
1966
+ message: check.message
1967
+ });
1968
+ status.dirty();
1969
+ }
1970
+ } else if (check.kind === "date") {
1971
+ const regex = dateRegex;
1972
+ if (!regex.test(input.data)) {
1973
+ ctx = this._getOrReturnCtx(input, ctx);
1974
+ addIssueToContext(ctx, {
1975
+ code: ZodIssueCode.invalid_string,
1976
+ validation: "date",
1977
+ message: check.message
1978
+ });
1979
+ status.dirty();
1980
+ }
1981
+ } else if (check.kind === "time") {
1982
+ const regex = timeRegex(check);
1983
+ if (!regex.test(input.data)) {
1984
+ ctx = this._getOrReturnCtx(input, ctx);
1985
+ addIssueToContext(ctx, {
1986
+ code: ZodIssueCode.invalid_string,
1987
+ validation: "time",
1988
+ message: check.message
1989
+ });
1990
+ status.dirty();
1991
+ }
1992
+ } else if (check.kind === "duration") {
1993
+ if (!durationRegex.test(input.data)) {
1994
+ ctx = this._getOrReturnCtx(input, ctx);
1995
+ addIssueToContext(ctx, {
1996
+ validation: "duration",
1997
+ code: ZodIssueCode.invalid_string,
1998
+ message: check.message
1999
+ });
2000
+ status.dirty();
2001
+ }
2002
+ } else if (check.kind === "ip") {
2003
+ if (!isValidIP(input.data, check.version)) {
2004
+ ctx = this._getOrReturnCtx(input, ctx);
2005
+ addIssueToContext(ctx, {
2006
+ validation: "ip",
2007
+ code: ZodIssueCode.invalid_string,
2008
+ message: check.message
2009
+ });
2010
+ status.dirty();
2011
+ }
2012
+ } else if (check.kind === "jwt") {
2013
+ if (!isValidJWT(input.data, check.alg)) {
2014
+ ctx = this._getOrReturnCtx(input, ctx);
2015
+ addIssueToContext(ctx, {
2016
+ validation: "jwt",
2017
+ code: ZodIssueCode.invalid_string,
2018
+ message: check.message
2019
+ });
2020
+ status.dirty();
2021
+ }
2022
+ } else if (check.kind === "cidr") {
2023
+ if (!isValidCidr(input.data, check.version)) {
2024
+ ctx = this._getOrReturnCtx(input, ctx);
2025
+ addIssueToContext(ctx, {
2026
+ validation: "cidr",
2027
+ code: ZodIssueCode.invalid_string,
2028
+ message: check.message
2029
+ });
2030
+ status.dirty();
2031
+ }
2032
+ } else if (check.kind === "base64") {
2033
+ if (!base64Regex.test(input.data)) {
2034
+ ctx = this._getOrReturnCtx(input, ctx);
2035
+ addIssueToContext(ctx, {
2036
+ validation: "base64",
2037
+ code: ZodIssueCode.invalid_string,
2038
+ message: check.message
2039
+ });
2040
+ status.dirty();
2041
+ }
2042
+ } else if (check.kind === "base64url") {
2043
+ if (!base64urlRegex.test(input.data)) {
2044
+ ctx = this._getOrReturnCtx(input, ctx);
2045
+ addIssueToContext(ctx, {
2046
+ validation: "base64url",
2047
+ code: ZodIssueCode.invalid_string,
2048
+ message: check.message
2049
+ });
2050
+ status.dirty();
2051
+ }
2052
+ } else {
2053
+ util.assertNever(check);
2054
+ }
2055
+ }
2056
+ return { status: status.value, value: input.data };
2057
+ }
2058
+ _regex(regex, validation, message) {
2059
+ return this.refinement((data) => regex.test(data), {
2060
+ validation,
2061
+ code: ZodIssueCode.invalid_string,
2062
+ ...errorUtil.errToObj(message)
2063
+ });
2064
+ }
2065
+ _addCheck(check) {
2066
+ return new ZodString({
2067
+ ...this._def,
2068
+ checks: [...this._def.checks, check]
2069
+ });
2070
+ }
2071
+ email(message) {
2072
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
2073
+ }
2074
+ url(message) {
2075
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
2076
+ }
2077
+ emoji(message) {
2078
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
2079
+ }
2080
+ uuid(message) {
2081
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
2082
+ }
2083
+ nanoid(message) {
2084
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
2085
+ }
2086
+ cuid(message) {
2087
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
2088
+ }
2089
+ cuid2(message) {
2090
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
2091
+ }
2092
+ ulid(message) {
2093
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
2094
+ }
2095
+ base64(message) {
2096
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
2097
+ }
2098
+ base64url(message) {
2099
+ return this._addCheck({
2100
+ kind: "base64url",
2101
+ ...errorUtil.errToObj(message)
2102
+ });
2103
+ }
2104
+ jwt(options) {
2105
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
2106
+ }
2107
+ ip(options) {
2108
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
2109
+ }
2110
+ cidr(options) {
2111
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
2112
+ }
2113
+ datetime(options) {
2114
+ if (typeof options === "string") {
2115
+ return this._addCheck({
2116
+ kind: "datetime",
2117
+ precision: null,
2118
+ offset: false,
2119
+ local: false,
2120
+ message: options
2121
+ });
2122
+ }
2123
+ return this._addCheck({
2124
+ kind: "datetime",
2125
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
2126
+ offset: options?.offset ?? false,
2127
+ local: options?.local ?? false,
2128
+ ...errorUtil.errToObj(options?.message)
2129
+ });
2130
+ }
2131
+ date(message) {
2132
+ return this._addCheck({ kind: "date", message });
2133
+ }
2134
+ time(options) {
2135
+ if (typeof options === "string") {
2136
+ return this._addCheck({
2137
+ kind: "time",
2138
+ precision: null,
2139
+ message: options
2140
+ });
2141
+ }
2142
+ return this._addCheck({
2143
+ kind: "time",
2144
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
2145
+ ...errorUtil.errToObj(options?.message)
2146
+ });
2147
+ }
2148
+ duration(message) {
2149
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
2150
+ }
2151
+ regex(regex, message) {
2152
+ return this._addCheck({
2153
+ kind: "regex",
2154
+ regex,
2155
+ ...errorUtil.errToObj(message)
2156
+ });
2157
+ }
2158
+ includes(value, options) {
2159
+ return this._addCheck({
2160
+ kind: "includes",
2161
+ value,
2162
+ position: options?.position,
2163
+ ...errorUtil.errToObj(options?.message)
2164
+ });
2165
+ }
2166
+ startsWith(value, message) {
2167
+ return this._addCheck({
2168
+ kind: "startsWith",
2169
+ value,
2170
+ ...errorUtil.errToObj(message)
2171
+ });
2172
+ }
2173
+ endsWith(value, message) {
2174
+ return this._addCheck({
2175
+ kind: "endsWith",
2176
+ value,
2177
+ ...errorUtil.errToObj(message)
2178
+ });
2179
+ }
2180
+ min(minLength, message) {
2181
+ return this._addCheck({
2182
+ kind: "min",
2183
+ value: minLength,
2184
+ ...errorUtil.errToObj(message)
2185
+ });
2186
+ }
2187
+ max(maxLength, message) {
2188
+ return this._addCheck({
2189
+ kind: "max",
2190
+ value: maxLength,
2191
+ ...errorUtil.errToObj(message)
2192
+ });
2193
+ }
2194
+ length(len, message) {
2195
+ return this._addCheck({
2196
+ kind: "length",
2197
+ value: len,
2198
+ ...errorUtil.errToObj(message)
2199
+ });
2200
+ }
2201
+ nonempty(message) {
2202
+ return this.min(1, errorUtil.errToObj(message));
2203
+ }
2204
+ trim() {
2205
+ return new ZodString({
2206
+ ...this._def,
2207
+ checks: [...this._def.checks, { kind: "trim" }]
2208
+ });
2209
+ }
2210
+ toLowerCase() {
2211
+ return new ZodString({
2212
+ ...this._def,
2213
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
2214
+ });
2215
+ }
2216
+ toUpperCase() {
2217
+ return new ZodString({
2218
+ ...this._def,
2219
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
2220
+ });
2221
+ }
2222
+ get isDatetime() {
2223
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
2224
+ }
2225
+ get isDate() {
2226
+ return !!this._def.checks.find((ch) => ch.kind === "date");
2227
+ }
2228
+ get isTime() {
2229
+ return !!this._def.checks.find((ch) => ch.kind === "time");
2230
+ }
2231
+ get isDuration() {
2232
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
2233
+ }
2234
+ get isEmail() {
2235
+ return !!this._def.checks.find((ch) => ch.kind === "email");
2236
+ }
2237
+ get isURL() {
2238
+ return !!this._def.checks.find((ch) => ch.kind === "url");
2239
+ }
2240
+ get isEmoji() {
2241
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
2242
+ }
2243
+ get isUUID() {
2244
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
2245
+ }
2246
+ get isNANOID() {
2247
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
2248
+ }
2249
+ get isCUID() {
2250
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
2251
+ }
2252
+ get isCUID2() {
2253
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
2254
+ }
2255
+ get isULID() {
2256
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
2257
+ }
2258
+ get isIP() {
2259
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
2260
+ }
2261
+ get isCIDR() {
2262
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
2263
+ }
2264
+ get isBase64() {
2265
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
2266
+ }
2267
+ get isBase64url() {
2268
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
2269
+ }
2270
+ get minLength() {
2271
+ let min = null;
2272
+ for (const ch of this._def.checks) {
2273
+ if (ch.kind === "min") {
2274
+ if (min === null || ch.value > min)
2275
+ min = ch.value;
2276
+ }
2277
+ }
2278
+ return min;
2279
+ }
2280
+ get maxLength() {
2281
+ let max = null;
2282
+ for (const ch of this._def.checks) {
2283
+ if (ch.kind === "max") {
2284
+ if (max === null || ch.value < max)
2285
+ max = ch.value;
2286
+ }
2287
+ }
2288
+ return max;
2289
+ }
2290
+ }
2291
+ ZodString.create = (params) => {
2292
+ return new ZodString({
2293
+ checks: [],
2294
+ typeName: ZodFirstPartyTypeKind.ZodString,
2295
+ coerce: params?.coerce ?? false,
2296
+ ...processCreateParams(params)
2297
+ });
2298
+ };
2299
+ function floatSafeRemainder(val, step) {
2300
+ const valDecCount = (val.toString().split(".")[1] || "").length;
2301
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
2302
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
2303
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
2304
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
2305
+ return valInt % stepInt / 10 ** decCount;
2306
+ }
2307
+
2308
+ class ZodNumber extends ZodType {
2309
+ constructor() {
2310
+ super(...arguments);
2311
+ this.min = this.gte;
2312
+ this.max = this.lte;
2313
+ this.step = this.multipleOf;
2314
+ }
2315
+ _parse(input) {
2316
+ if (this._def.coerce) {
2317
+ input.data = Number(input.data);
2318
+ }
2319
+ const parsedType = this._getType(input);
2320
+ if (parsedType !== ZodParsedType.number) {
2321
+ const ctx2 = this._getOrReturnCtx(input);
2322
+ addIssueToContext(ctx2, {
2323
+ code: ZodIssueCode.invalid_type,
2324
+ expected: ZodParsedType.number,
2325
+ received: ctx2.parsedType
2326
+ });
2327
+ return INVALID;
2328
+ }
2329
+ let ctx = undefined;
2330
+ const status = new ParseStatus;
2331
+ for (const check of this._def.checks) {
2332
+ if (check.kind === "int") {
2333
+ if (!util.isInteger(input.data)) {
2334
+ ctx = this._getOrReturnCtx(input, ctx);
2335
+ addIssueToContext(ctx, {
2336
+ code: ZodIssueCode.invalid_type,
2337
+ expected: "integer",
2338
+ received: "float",
2339
+ message: check.message
2340
+ });
2341
+ status.dirty();
2342
+ }
2343
+ } else if (check.kind === "min") {
2344
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2345
+ if (tooSmall) {
2346
+ ctx = this._getOrReturnCtx(input, ctx);
2347
+ addIssueToContext(ctx, {
2348
+ code: ZodIssueCode.too_small,
2349
+ minimum: check.value,
2350
+ type: "number",
2351
+ inclusive: check.inclusive,
2352
+ exact: false,
2353
+ message: check.message
2354
+ });
2355
+ status.dirty();
2356
+ }
2357
+ } else if (check.kind === "max") {
2358
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2359
+ if (tooBig) {
2360
+ ctx = this._getOrReturnCtx(input, ctx);
2361
+ addIssueToContext(ctx, {
2362
+ code: ZodIssueCode.too_big,
2363
+ maximum: check.value,
2364
+ type: "number",
2365
+ inclusive: check.inclusive,
2366
+ exact: false,
2367
+ message: check.message
2368
+ });
2369
+ status.dirty();
2370
+ }
2371
+ } else if (check.kind === "multipleOf") {
2372
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
2373
+ ctx = this._getOrReturnCtx(input, ctx);
2374
+ addIssueToContext(ctx, {
2375
+ code: ZodIssueCode.not_multiple_of,
2376
+ multipleOf: check.value,
2377
+ message: check.message
2378
+ });
2379
+ status.dirty();
2380
+ }
2381
+ } else if (check.kind === "finite") {
2382
+ if (!Number.isFinite(input.data)) {
2383
+ ctx = this._getOrReturnCtx(input, ctx);
2384
+ addIssueToContext(ctx, {
2385
+ code: ZodIssueCode.not_finite,
2386
+ message: check.message
2387
+ });
2388
+ status.dirty();
2389
+ }
2390
+ } else {
2391
+ util.assertNever(check);
2392
+ }
2393
+ }
2394
+ return { status: status.value, value: input.data };
2395
+ }
2396
+ gte(value, message) {
2397
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2398
+ }
2399
+ gt(value, message) {
2400
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2401
+ }
2402
+ lte(value, message) {
2403
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2404
+ }
2405
+ lt(value, message) {
2406
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2407
+ }
2408
+ setLimit(kind, value, inclusive, message) {
2409
+ return new ZodNumber({
2410
+ ...this._def,
2411
+ checks: [
2412
+ ...this._def.checks,
2413
+ {
2414
+ kind,
2415
+ value,
2416
+ inclusive,
2417
+ message: errorUtil.toString(message)
2418
+ }
2419
+ ]
2420
+ });
2421
+ }
2422
+ _addCheck(check) {
2423
+ return new ZodNumber({
2424
+ ...this._def,
2425
+ checks: [...this._def.checks, check]
2426
+ });
2427
+ }
2428
+ int(message) {
2429
+ return this._addCheck({
2430
+ kind: "int",
2431
+ message: errorUtil.toString(message)
2432
+ });
2433
+ }
2434
+ positive(message) {
2435
+ return this._addCheck({
2436
+ kind: "min",
2437
+ value: 0,
2438
+ inclusive: false,
2439
+ message: errorUtil.toString(message)
2440
+ });
2441
+ }
2442
+ negative(message) {
2443
+ return this._addCheck({
2444
+ kind: "max",
2445
+ value: 0,
2446
+ inclusive: false,
2447
+ message: errorUtil.toString(message)
2448
+ });
2449
+ }
2450
+ nonpositive(message) {
2451
+ return this._addCheck({
2452
+ kind: "max",
2453
+ value: 0,
2454
+ inclusive: true,
2455
+ message: errorUtil.toString(message)
2456
+ });
2457
+ }
2458
+ nonnegative(message) {
2459
+ return this._addCheck({
2460
+ kind: "min",
2461
+ value: 0,
2462
+ inclusive: true,
2463
+ message: errorUtil.toString(message)
2464
+ });
2465
+ }
2466
+ multipleOf(value, message) {
2467
+ return this._addCheck({
2468
+ kind: "multipleOf",
2469
+ value,
2470
+ message: errorUtil.toString(message)
2471
+ });
2472
+ }
2473
+ finite(message) {
2474
+ return this._addCheck({
2475
+ kind: "finite",
2476
+ message: errorUtil.toString(message)
2477
+ });
2478
+ }
2479
+ safe(message) {
2480
+ return this._addCheck({
2481
+ kind: "min",
2482
+ inclusive: true,
2483
+ value: Number.MIN_SAFE_INTEGER,
2484
+ message: errorUtil.toString(message)
2485
+ })._addCheck({
2486
+ kind: "max",
2487
+ inclusive: true,
2488
+ value: Number.MAX_SAFE_INTEGER,
2489
+ message: errorUtil.toString(message)
2490
+ });
2491
+ }
2492
+ get minValue() {
2493
+ let min = null;
2494
+ for (const ch of this._def.checks) {
2495
+ if (ch.kind === "min") {
2496
+ if (min === null || ch.value > min)
2497
+ min = ch.value;
2498
+ }
2499
+ }
2500
+ return min;
2501
+ }
2502
+ get maxValue() {
2503
+ let max = null;
2504
+ for (const ch of this._def.checks) {
2505
+ if (ch.kind === "max") {
2506
+ if (max === null || ch.value < max)
2507
+ max = ch.value;
2508
+ }
2509
+ }
2510
+ return max;
2511
+ }
2512
+ get isInt() {
2513
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
2514
+ }
2515
+ get isFinite() {
2516
+ let max = null;
2517
+ let min = null;
2518
+ for (const ch of this._def.checks) {
2519
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
2520
+ return true;
2521
+ } else if (ch.kind === "min") {
2522
+ if (min === null || ch.value > min)
2523
+ min = ch.value;
2524
+ } else if (ch.kind === "max") {
2525
+ if (max === null || ch.value < max)
2526
+ max = ch.value;
2527
+ }
2528
+ }
2529
+ return Number.isFinite(min) && Number.isFinite(max);
2530
+ }
2531
+ }
2532
+ ZodNumber.create = (params) => {
2533
+ return new ZodNumber({
2534
+ checks: [],
2535
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
2536
+ coerce: params?.coerce || false,
2537
+ ...processCreateParams(params)
2538
+ });
2539
+ };
2540
+
2541
+ class ZodBigInt extends ZodType {
2542
+ constructor() {
2543
+ super(...arguments);
2544
+ this.min = this.gte;
2545
+ this.max = this.lte;
2546
+ }
2547
+ _parse(input) {
2548
+ if (this._def.coerce) {
2549
+ try {
2550
+ input.data = BigInt(input.data);
2551
+ } catch {
2552
+ return this._getInvalidInput(input);
2553
+ }
2554
+ }
2555
+ const parsedType = this._getType(input);
2556
+ if (parsedType !== ZodParsedType.bigint) {
2557
+ return this._getInvalidInput(input);
2558
+ }
2559
+ let ctx = undefined;
2560
+ const status = new ParseStatus;
2561
+ for (const check of this._def.checks) {
2562
+ if (check.kind === "min") {
2563
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2564
+ if (tooSmall) {
2565
+ ctx = this._getOrReturnCtx(input, ctx);
2566
+ addIssueToContext(ctx, {
2567
+ code: ZodIssueCode.too_small,
2568
+ type: "bigint",
2569
+ minimum: check.value,
2570
+ inclusive: check.inclusive,
2571
+ message: check.message
2572
+ });
2573
+ status.dirty();
2574
+ }
2575
+ } else if (check.kind === "max") {
2576
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2577
+ if (tooBig) {
2578
+ ctx = this._getOrReturnCtx(input, ctx);
2579
+ addIssueToContext(ctx, {
2580
+ code: ZodIssueCode.too_big,
2581
+ type: "bigint",
2582
+ maximum: check.value,
2583
+ inclusive: check.inclusive,
2584
+ message: check.message
2585
+ });
2586
+ status.dirty();
2587
+ }
2588
+ } else if (check.kind === "multipleOf") {
2589
+ if (input.data % check.value !== BigInt(0)) {
2590
+ ctx = this._getOrReturnCtx(input, ctx);
2591
+ addIssueToContext(ctx, {
2592
+ code: ZodIssueCode.not_multiple_of,
2593
+ multipleOf: check.value,
2594
+ message: check.message
2595
+ });
2596
+ status.dirty();
2597
+ }
2598
+ } else {
2599
+ util.assertNever(check);
2600
+ }
2601
+ }
2602
+ return { status: status.value, value: input.data };
2603
+ }
2604
+ _getInvalidInput(input) {
2605
+ const ctx = this._getOrReturnCtx(input);
2606
+ addIssueToContext(ctx, {
2607
+ code: ZodIssueCode.invalid_type,
2608
+ expected: ZodParsedType.bigint,
2609
+ received: ctx.parsedType
2610
+ });
2611
+ return INVALID;
2612
+ }
2613
+ gte(value, message) {
2614
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2615
+ }
2616
+ gt(value, message) {
2617
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2618
+ }
2619
+ lte(value, message) {
2620
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2621
+ }
2622
+ lt(value, message) {
2623
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2624
+ }
2625
+ setLimit(kind, value, inclusive, message) {
2626
+ return new ZodBigInt({
2627
+ ...this._def,
2628
+ checks: [
2629
+ ...this._def.checks,
2630
+ {
2631
+ kind,
2632
+ value,
2633
+ inclusive,
2634
+ message: errorUtil.toString(message)
2635
+ }
2636
+ ]
2637
+ });
2638
+ }
2639
+ _addCheck(check) {
2640
+ return new ZodBigInt({
2641
+ ...this._def,
2642
+ checks: [...this._def.checks, check]
2643
+ });
2644
+ }
2645
+ positive(message) {
2646
+ return this._addCheck({
2647
+ kind: "min",
2648
+ value: BigInt(0),
2649
+ inclusive: false,
2650
+ message: errorUtil.toString(message)
2651
+ });
2652
+ }
2653
+ negative(message) {
2654
+ return this._addCheck({
2655
+ kind: "max",
2656
+ value: BigInt(0),
2657
+ inclusive: false,
2658
+ message: errorUtil.toString(message)
2659
+ });
2660
+ }
2661
+ nonpositive(message) {
2662
+ return this._addCheck({
2663
+ kind: "max",
2664
+ value: BigInt(0),
2665
+ inclusive: true,
2666
+ message: errorUtil.toString(message)
2667
+ });
2668
+ }
2669
+ nonnegative(message) {
2670
+ return this._addCheck({
2671
+ kind: "min",
2672
+ value: BigInt(0),
2673
+ inclusive: true,
2674
+ message: errorUtil.toString(message)
2675
+ });
2676
+ }
2677
+ multipleOf(value, message) {
2678
+ return this._addCheck({
2679
+ kind: "multipleOf",
2680
+ value,
2681
+ message: errorUtil.toString(message)
2682
+ });
2683
+ }
2684
+ get minValue() {
2685
+ let min = null;
2686
+ for (const ch of this._def.checks) {
2687
+ if (ch.kind === "min") {
2688
+ if (min === null || ch.value > min)
2689
+ min = ch.value;
2690
+ }
2691
+ }
2692
+ return min;
2693
+ }
2694
+ get maxValue() {
2695
+ let max = null;
2696
+ for (const ch of this._def.checks) {
2697
+ if (ch.kind === "max") {
2698
+ if (max === null || ch.value < max)
2699
+ max = ch.value;
2700
+ }
2701
+ }
2702
+ return max;
2703
+ }
2704
+ }
2705
+ ZodBigInt.create = (params) => {
2706
+ return new ZodBigInt({
2707
+ checks: [],
2708
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
2709
+ coerce: params?.coerce ?? false,
2710
+ ...processCreateParams(params)
2711
+ });
2712
+ };
2713
+
2714
+ class ZodBoolean extends ZodType {
2715
+ _parse(input) {
2716
+ if (this._def.coerce) {
2717
+ input.data = Boolean(input.data);
2718
+ }
2719
+ const parsedType = this._getType(input);
2720
+ if (parsedType !== ZodParsedType.boolean) {
2721
+ const ctx = this._getOrReturnCtx(input);
2722
+ addIssueToContext(ctx, {
2723
+ code: ZodIssueCode.invalid_type,
2724
+ expected: ZodParsedType.boolean,
2725
+ received: ctx.parsedType
2726
+ });
2727
+ return INVALID;
2728
+ }
2729
+ return OK(input.data);
2730
+ }
2731
+ }
2732
+ ZodBoolean.create = (params) => {
2733
+ return new ZodBoolean({
2734
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2735
+ coerce: params?.coerce || false,
2736
+ ...processCreateParams(params)
2737
+ });
2738
+ };
2739
+
2740
+ class ZodDate extends ZodType {
2741
+ _parse(input) {
2742
+ if (this._def.coerce) {
2743
+ input.data = new Date(input.data);
2744
+ }
2745
+ const parsedType = this._getType(input);
2746
+ if (parsedType !== ZodParsedType.date) {
2747
+ const ctx2 = this._getOrReturnCtx(input);
2748
+ addIssueToContext(ctx2, {
2749
+ code: ZodIssueCode.invalid_type,
2750
+ expected: ZodParsedType.date,
2751
+ received: ctx2.parsedType
2752
+ });
2753
+ return INVALID;
2754
+ }
2755
+ if (Number.isNaN(input.data.getTime())) {
2756
+ const ctx2 = this._getOrReturnCtx(input);
2757
+ addIssueToContext(ctx2, {
2758
+ code: ZodIssueCode.invalid_date
2759
+ });
2760
+ return INVALID;
2761
+ }
2762
+ const status = new ParseStatus;
2763
+ let ctx = undefined;
2764
+ for (const check of this._def.checks) {
2765
+ if (check.kind === "min") {
2766
+ if (input.data.getTime() < check.value) {
2767
+ ctx = this._getOrReturnCtx(input, ctx);
2768
+ addIssueToContext(ctx, {
2769
+ code: ZodIssueCode.too_small,
2770
+ message: check.message,
2771
+ inclusive: true,
2772
+ exact: false,
2773
+ minimum: check.value,
2774
+ type: "date"
2775
+ });
2776
+ status.dirty();
2777
+ }
2778
+ } else if (check.kind === "max") {
2779
+ if (input.data.getTime() > check.value) {
2780
+ ctx = this._getOrReturnCtx(input, ctx);
2781
+ addIssueToContext(ctx, {
2782
+ code: ZodIssueCode.too_big,
2783
+ message: check.message,
2784
+ inclusive: true,
2785
+ exact: false,
2786
+ maximum: check.value,
2787
+ type: "date"
2788
+ });
2789
+ status.dirty();
2790
+ }
2791
+ } else {
2792
+ util.assertNever(check);
2793
+ }
2794
+ }
2795
+ return {
2796
+ status: status.value,
2797
+ value: new Date(input.data.getTime())
2798
+ };
2799
+ }
2800
+ _addCheck(check) {
2801
+ return new ZodDate({
2802
+ ...this._def,
2803
+ checks: [...this._def.checks, check]
2804
+ });
2805
+ }
2806
+ min(minDate, message) {
2807
+ return this._addCheck({
2808
+ kind: "min",
2809
+ value: minDate.getTime(),
2810
+ message: errorUtil.toString(message)
2811
+ });
2812
+ }
2813
+ max(maxDate, message) {
2814
+ return this._addCheck({
2815
+ kind: "max",
2816
+ value: maxDate.getTime(),
2817
+ message: errorUtil.toString(message)
2818
+ });
2819
+ }
2820
+ get minDate() {
2821
+ let min = null;
2822
+ for (const ch of this._def.checks) {
2823
+ if (ch.kind === "min") {
2824
+ if (min === null || ch.value > min)
2825
+ min = ch.value;
2826
+ }
2827
+ }
2828
+ return min != null ? new Date(min) : null;
2829
+ }
2830
+ get maxDate() {
2831
+ let max = null;
2832
+ for (const ch of this._def.checks) {
2833
+ if (ch.kind === "max") {
2834
+ if (max === null || ch.value < max)
2835
+ max = ch.value;
2836
+ }
2837
+ }
2838
+ return max != null ? new Date(max) : null;
2839
+ }
2840
+ }
2841
+ ZodDate.create = (params) => {
2842
+ return new ZodDate({
2843
+ checks: [],
2844
+ coerce: params?.coerce || false,
2845
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2846
+ ...processCreateParams(params)
2847
+ });
2848
+ };
2849
+
2850
+ class ZodSymbol extends ZodType {
2851
+ _parse(input) {
2852
+ const parsedType = this._getType(input);
2853
+ if (parsedType !== ZodParsedType.symbol) {
2854
+ const ctx = this._getOrReturnCtx(input);
2855
+ addIssueToContext(ctx, {
2856
+ code: ZodIssueCode.invalid_type,
2857
+ expected: ZodParsedType.symbol,
2858
+ received: ctx.parsedType
2859
+ });
2860
+ return INVALID;
2861
+ }
2862
+ return OK(input.data);
2863
+ }
2864
+ }
2865
+ ZodSymbol.create = (params) => {
2866
+ return new ZodSymbol({
2867
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2868
+ ...processCreateParams(params)
2869
+ });
2870
+ };
2871
+
2872
+ class ZodUndefined extends ZodType {
2873
+ _parse(input) {
2874
+ const parsedType = this._getType(input);
2875
+ if (parsedType !== ZodParsedType.undefined) {
2876
+ const ctx = this._getOrReturnCtx(input);
2877
+ addIssueToContext(ctx, {
2878
+ code: ZodIssueCode.invalid_type,
2879
+ expected: ZodParsedType.undefined,
2880
+ received: ctx.parsedType
2881
+ });
2882
+ return INVALID;
2883
+ }
2884
+ return OK(input.data);
2885
+ }
2886
+ }
2887
+ ZodUndefined.create = (params) => {
2888
+ return new ZodUndefined({
2889
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2890
+ ...processCreateParams(params)
2891
+ });
2892
+ };
2893
+
2894
+ class ZodNull extends ZodType {
2895
+ _parse(input) {
2896
+ const parsedType = this._getType(input);
2897
+ if (parsedType !== ZodParsedType.null) {
2898
+ const ctx = this._getOrReturnCtx(input);
2899
+ addIssueToContext(ctx, {
2900
+ code: ZodIssueCode.invalid_type,
2901
+ expected: ZodParsedType.null,
2902
+ received: ctx.parsedType
2903
+ });
2904
+ return INVALID;
2905
+ }
2906
+ return OK(input.data);
2907
+ }
2908
+ }
2909
+ ZodNull.create = (params) => {
2910
+ return new ZodNull({
2911
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2912
+ ...processCreateParams(params)
2913
+ });
2914
+ };
2915
+
2916
+ class ZodAny extends ZodType {
2917
+ constructor() {
2918
+ super(...arguments);
2919
+ this._any = true;
2920
+ }
2921
+ _parse(input) {
2922
+ return OK(input.data);
2923
+ }
2924
+ }
2925
+ ZodAny.create = (params) => {
2926
+ return new ZodAny({
2927
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2928
+ ...processCreateParams(params)
2929
+ });
2930
+ };
2931
+
2932
+ class ZodUnknown extends ZodType {
2933
+ constructor() {
2934
+ super(...arguments);
2935
+ this._unknown = true;
2936
+ }
2937
+ _parse(input) {
2938
+ return OK(input.data);
2939
+ }
2940
+ }
2941
+ ZodUnknown.create = (params) => {
2942
+ return new ZodUnknown({
2943
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2944
+ ...processCreateParams(params)
2945
+ });
2946
+ };
2947
+
2948
+ class ZodNever extends ZodType {
2949
+ _parse(input) {
2950
+ const ctx = this._getOrReturnCtx(input);
2951
+ addIssueToContext(ctx, {
2952
+ code: ZodIssueCode.invalid_type,
2953
+ expected: ZodParsedType.never,
2954
+ received: ctx.parsedType
2955
+ });
2956
+ return INVALID;
2957
+ }
2958
+ }
2959
+ ZodNever.create = (params) => {
2960
+ return new ZodNever({
2961
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2962
+ ...processCreateParams(params)
2963
+ });
2964
+ };
2965
+
2966
+ class ZodVoid extends ZodType {
2967
+ _parse(input) {
2968
+ const parsedType = this._getType(input);
2969
+ if (parsedType !== ZodParsedType.undefined) {
2970
+ const ctx = this._getOrReturnCtx(input);
2971
+ addIssueToContext(ctx, {
2972
+ code: ZodIssueCode.invalid_type,
2973
+ expected: ZodParsedType.void,
2974
+ received: ctx.parsedType
2975
+ });
2976
+ return INVALID;
2977
+ }
2978
+ return OK(input.data);
2979
+ }
2980
+ }
2981
+ ZodVoid.create = (params) => {
2982
+ return new ZodVoid({
2983
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2984
+ ...processCreateParams(params)
2985
+ });
2986
+ };
2987
+
2988
+ class ZodArray extends ZodType {
2989
+ _parse(input) {
2990
+ const { ctx, status } = this._processInputParams(input);
2991
+ const def = this._def;
2992
+ if (ctx.parsedType !== ZodParsedType.array) {
2993
+ addIssueToContext(ctx, {
2994
+ code: ZodIssueCode.invalid_type,
2995
+ expected: ZodParsedType.array,
2996
+ received: ctx.parsedType
2997
+ });
2998
+ return INVALID;
2999
+ }
3000
+ if (def.exactLength !== null) {
3001
+ const tooBig = ctx.data.length > def.exactLength.value;
3002
+ const tooSmall = ctx.data.length < def.exactLength.value;
3003
+ if (tooBig || tooSmall) {
3004
+ addIssueToContext(ctx, {
3005
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
3006
+ minimum: tooSmall ? def.exactLength.value : undefined,
3007
+ maximum: tooBig ? def.exactLength.value : undefined,
3008
+ type: "array",
3009
+ inclusive: true,
3010
+ exact: true,
3011
+ message: def.exactLength.message
3012
+ });
3013
+ status.dirty();
3014
+ }
3015
+ }
3016
+ if (def.minLength !== null) {
3017
+ if (ctx.data.length < def.minLength.value) {
3018
+ addIssueToContext(ctx, {
3019
+ code: ZodIssueCode.too_small,
3020
+ minimum: def.minLength.value,
3021
+ type: "array",
3022
+ inclusive: true,
3023
+ exact: false,
3024
+ message: def.minLength.message
3025
+ });
3026
+ status.dirty();
3027
+ }
3028
+ }
3029
+ if (def.maxLength !== null) {
3030
+ if (ctx.data.length > def.maxLength.value) {
3031
+ addIssueToContext(ctx, {
3032
+ code: ZodIssueCode.too_big,
3033
+ maximum: def.maxLength.value,
3034
+ type: "array",
3035
+ inclusive: true,
3036
+ exact: false,
3037
+ message: def.maxLength.message
3038
+ });
3039
+ status.dirty();
3040
+ }
3041
+ }
3042
+ if (ctx.common.async) {
3043
+ return Promise.all([...ctx.data].map((item, i) => {
3044
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
3045
+ })).then((result2) => {
3046
+ return ParseStatus.mergeArray(status, result2);
3047
+ });
3048
+ }
3049
+ const result = [...ctx.data].map((item, i) => {
3050
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
3051
+ });
3052
+ return ParseStatus.mergeArray(status, result);
3053
+ }
3054
+ get element() {
3055
+ return this._def.type;
3056
+ }
3057
+ min(minLength, message) {
3058
+ return new ZodArray({
3059
+ ...this._def,
3060
+ minLength: { value: minLength, message: errorUtil.toString(message) }
3061
+ });
3062
+ }
3063
+ max(maxLength, message) {
3064
+ return new ZodArray({
3065
+ ...this._def,
3066
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
3067
+ });
3068
+ }
3069
+ length(len, message) {
3070
+ return new ZodArray({
3071
+ ...this._def,
3072
+ exactLength: { value: len, message: errorUtil.toString(message) }
3073
+ });
3074
+ }
3075
+ nonempty(message) {
3076
+ return this.min(1, message);
3077
+ }
3078
+ }
3079
+ ZodArray.create = (schema, params) => {
3080
+ return new ZodArray({
3081
+ type: schema,
3082
+ minLength: null,
3083
+ maxLength: null,
3084
+ exactLength: null,
3085
+ typeName: ZodFirstPartyTypeKind.ZodArray,
3086
+ ...processCreateParams(params)
3087
+ });
3088
+ };
3089
+ function deepPartialify(schema) {
3090
+ if (schema instanceof ZodObject) {
3091
+ const newShape = {};
3092
+ for (const key in schema.shape) {
3093
+ const fieldSchema = schema.shape[key];
3094
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
3095
+ }
3096
+ return new ZodObject({
3097
+ ...schema._def,
3098
+ shape: () => newShape
3099
+ });
3100
+ } else if (schema instanceof ZodArray) {
3101
+ return new ZodArray({
3102
+ ...schema._def,
3103
+ type: deepPartialify(schema.element)
3104
+ });
3105
+ } else if (schema instanceof ZodOptional) {
3106
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
3107
+ } else if (schema instanceof ZodNullable) {
3108
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
3109
+ } else if (schema instanceof ZodTuple) {
3110
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
3111
+ } else {
3112
+ return schema;
3113
+ }
3114
+ }
3115
+
3116
+ class ZodObject extends ZodType {
3117
+ constructor() {
3118
+ super(...arguments);
3119
+ this._cached = null;
3120
+ this.nonstrict = this.passthrough;
3121
+ this.augment = this.extend;
3122
+ }
3123
+ _getCached() {
3124
+ if (this._cached !== null)
3125
+ return this._cached;
3126
+ const shape = this._def.shape();
3127
+ const keys = util.objectKeys(shape);
3128
+ this._cached = { shape, keys };
3129
+ return this._cached;
3130
+ }
3131
+ _parse(input) {
3132
+ const parsedType = this._getType(input);
3133
+ if (parsedType !== ZodParsedType.object) {
3134
+ const ctx2 = this._getOrReturnCtx(input);
3135
+ addIssueToContext(ctx2, {
3136
+ code: ZodIssueCode.invalid_type,
3137
+ expected: ZodParsedType.object,
3138
+ received: ctx2.parsedType
3139
+ });
3140
+ return INVALID;
3141
+ }
3142
+ const { status, ctx } = this._processInputParams(input);
3143
+ const { shape, keys: shapeKeys } = this._getCached();
3144
+ const extraKeys = [];
3145
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
3146
+ for (const key in ctx.data) {
3147
+ if (!shapeKeys.includes(key)) {
3148
+ extraKeys.push(key);
3149
+ }
3150
+ }
3151
+ }
3152
+ const pairs = [];
3153
+ for (const key of shapeKeys) {
3154
+ const keyValidator = shape[key];
3155
+ const value = ctx.data[key];
3156
+ pairs.push({
3157
+ key: { status: "valid", value: key },
3158
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
3159
+ alwaysSet: key in ctx.data
3160
+ });
3161
+ }
3162
+ if (this._def.catchall instanceof ZodNever) {
3163
+ const unknownKeys = this._def.unknownKeys;
3164
+ if (unknownKeys === "passthrough") {
3165
+ for (const key of extraKeys) {
3166
+ pairs.push({
3167
+ key: { status: "valid", value: key },
3168
+ value: { status: "valid", value: ctx.data[key] }
3169
+ });
3170
+ }
3171
+ } else if (unknownKeys === "strict") {
3172
+ if (extraKeys.length > 0) {
3173
+ addIssueToContext(ctx, {
3174
+ code: ZodIssueCode.unrecognized_keys,
3175
+ keys: extraKeys
3176
+ });
3177
+ status.dirty();
3178
+ }
3179
+ } else if (unknownKeys === "strip") {} else {
3180
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
3181
+ }
3182
+ } else {
3183
+ const catchall = this._def.catchall;
3184
+ for (const key of extraKeys) {
3185
+ const value = ctx.data[key];
3186
+ pairs.push({
3187
+ key: { status: "valid", value: key },
3188
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
3189
+ alwaysSet: key in ctx.data
3190
+ });
3191
+ }
3192
+ }
3193
+ if (ctx.common.async) {
3194
+ return Promise.resolve().then(async () => {
3195
+ const syncPairs = [];
3196
+ for (const pair of pairs) {
3197
+ const key = await pair.key;
3198
+ const value = await pair.value;
3199
+ syncPairs.push({
3200
+ key,
3201
+ value,
3202
+ alwaysSet: pair.alwaysSet
3203
+ });
3204
+ }
3205
+ return syncPairs;
3206
+ }).then((syncPairs) => {
3207
+ return ParseStatus.mergeObjectSync(status, syncPairs);
3208
+ });
3209
+ } else {
3210
+ return ParseStatus.mergeObjectSync(status, pairs);
3211
+ }
3212
+ }
3213
+ get shape() {
3214
+ return this._def.shape();
3215
+ }
3216
+ strict(message) {
3217
+ errorUtil.errToObj;
3218
+ return new ZodObject({
3219
+ ...this._def,
3220
+ unknownKeys: "strict",
3221
+ ...message !== undefined ? {
3222
+ errorMap: (issue, ctx) => {
3223
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
3224
+ if (issue.code === "unrecognized_keys")
3225
+ return {
3226
+ message: errorUtil.errToObj(message).message ?? defaultError
3227
+ };
3228
+ return {
3229
+ message: defaultError
3230
+ };
3231
+ }
3232
+ } : {}
3233
+ });
3234
+ }
3235
+ strip() {
3236
+ return new ZodObject({
3237
+ ...this._def,
3238
+ unknownKeys: "strip"
3239
+ });
3240
+ }
3241
+ passthrough() {
3242
+ return new ZodObject({
3243
+ ...this._def,
3244
+ unknownKeys: "passthrough"
3245
+ });
3246
+ }
3247
+ extend(augmentation) {
3248
+ return new ZodObject({
3249
+ ...this._def,
3250
+ shape: () => ({
3251
+ ...this._def.shape(),
3252
+ ...augmentation
3253
+ })
3254
+ });
3255
+ }
3256
+ merge(merging) {
3257
+ const merged = new ZodObject({
3258
+ unknownKeys: merging._def.unknownKeys,
3259
+ catchall: merging._def.catchall,
3260
+ shape: () => ({
3261
+ ...this._def.shape(),
3262
+ ...merging._def.shape()
3263
+ }),
3264
+ typeName: ZodFirstPartyTypeKind.ZodObject
3265
+ });
3266
+ return merged;
3267
+ }
3268
+ setKey(key, schema) {
3269
+ return this.augment({ [key]: schema });
3270
+ }
3271
+ catchall(index) {
3272
+ return new ZodObject({
3273
+ ...this._def,
3274
+ catchall: index
3275
+ });
3276
+ }
3277
+ pick(mask) {
3278
+ const shape = {};
3279
+ for (const key of util.objectKeys(mask)) {
3280
+ if (mask[key] && this.shape[key]) {
3281
+ shape[key] = this.shape[key];
3282
+ }
3283
+ }
3284
+ return new ZodObject({
3285
+ ...this._def,
3286
+ shape: () => shape
3287
+ });
3288
+ }
3289
+ omit(mask) {
3290
+ const shape = {};
3291
+ for (const key of util.objectKeys(this.shape)) {
3292
+ if (!mask[key]) {
3293
+ shape[key] = this.shape[key];
3294
+ }
3295
+ }
3296
+ return new ZodObject({
3297
+ ...this._def,
3298
+ shape: () => shape
3299
+ });
3300
+ }
3301
+ deepPartial() {
3302
+ return deepPartialify(this);
3303
+ }
3304
+ partial(mask) {
3305
+ const newShape = {};
3306
+ for (const key of util.objectKeys(this.shape)) {
3307
+ const fieldSchema = this.shape[key];
3308
+ if (mask && !mask[key]) {
3309
+ newShape[key] = fieldSchema;
3310
+ } else {
3311
+ newShape[key] = fieldSchema.optional();
3312
+ }
3313
+ }
3314
+ return new ZodObject({
3315
+ ...this._def,
3316
+ shape: () => newShape
3317
+ });
3318
+ }
3319
+ required(mask) {
3320
+ const newShape = {};
3321
+ for (const key of util.objectKeys(this.shape)) {
3322
+ if (mask && !mask[key]) {
3323
+ newShape[key] = this.shape[key];
3324
+ } else {
3325
+ const fieldSchema = this.shape[key];
3326
+ let newField = fieldSchema;
3327
+ while (newField instanceof ZodOptional) {
3328
+ newField = newField._def.innerType;
3329
+ }
3330
+ newShape[key] = newField;
3331
+ }
3332
+ }
3333
+ return new ZodObject({
3334
+ ...this._def,
3335
+ shape: () => newShape
3336
+ });
3337
+ }
3338
+ keyof() {
3339
+ return createZodEnum(util.objectKeys(this.shape));
3340
+ }
3341
+ }
3342
+ ZodObject.create = (shape, params) => {
3343
+ return new ZodObject({
3344
+ shape: () => shape,
3345
+ unknownKeys: "strip",
3346
+ catchall: ZodNever.create(),
3347
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3348
+ ...processCreateParams(params)
3349
+ });
3350
+ };
3351
+ ZodObject.strictCreate = (shape, params) => {
3352
+ return new ZodObject({
3353
+ shape: () => shape,
3354
+ unknownKeys: "strict",
3355
+ catchall: ZodNever.create(),
3356
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3357
+ ...processCreateParams(params)
3358
+ });
3359
+ };
3360
+ ZodObject.lazycreate = (shape, params) => {
3361
+ return new ZodObject({
3362
+ shape,
3363
+ unknownKeys: "strip",
3364
+ catchall: ZodNever.create(),
3365
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3366
+ ...processCreateParams(params)
3367
+ });
3368
+ };
3369
+
3370
+ class ZodUnion extends ZodType {
3371
+ _parse(input) {
3372
+ const { ctx } = this._processInputParams(input);
3373
+ const options = this._def.options;
3374
+ function handleResults(results) {
3375
+ for (const result of results) {
3376
+ if (result.result.status === "valid") {
3377
+ return result.result;
3378
+ }
3379
+ }
3380
+ for (const result of results) {
3381
+ if (result.result.status === "dirty") {
3382
+ ctx.common.issues.push(...result.ctx.common.issues);
3383
+ return result.result;
3384
+ }
3385
+ }
3386
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
3387
+ addIssueToContext(ctx, {
3388
+ code: ZodIssueCode.invalid_union,
3389
+ unionErrors
3390
+ });
3391
+ return INVALID;
3392
+ }
3393
+ if (ctx.common.async) {
3394
+ return Promise.all(options.map(async (option) => {
3395
+ const childCtx = {
3396
+ ...ctx,
3397
+ common: {
3398
+ ...ctx.common,
3399
+ issues: []
3400
+ },
3401
+ parent: null
3402
+ };
3403
+ return {
3404
+ result: await option._parseAsync({
3405
+ data: ctx.data,
3406
+ path: ctx.path,
3407
+ parent: childCtx
3408
+ }),
3409
+ ctx: childCtx
3410
+ };
3411
+ })).then(handleResults);
3412
+ } else {
3413
+ let dirty = undefined;
3414
+ const issues = [];
3415
+ for (const option of options) {
3416
+ const childCtx = {
3417
+ ...ctx,
3418
+ common: {
3419
+ ...ctx.common,
3420
+ issues: []
3421
+ },
3422
+ parent: null
3423
+ };
3424
+ const result = option._parseSync({
3425
+ data: ctx.data,
3426
+ path: ctx.path,
3427
+ parent: childCtx
3428
+ });
3429
+ if (result.status === "valid") {
3430
+ return result;
3431
+ } else if (result.status === "dirty" && !dirty) {
3432
+ dirty = { result, ctx: childCtx };
3433
+ }
3434
+ if (childCtx.common.issues.length) {
3435
+ issues.push(childCtx.common.issues);
3436
+ }
3437
+ }
3438
+ if (dirty) {
3439
+ ctx.common.issues.push(...dirty.ctx.common.issues);
3440
+ return dirty.result;
3441
+ }
3442
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
3443
+ addIssueToContext(ctx, {
3444
+ code: ZodIssueCode.invalid_union,
3445
+ unionErrors
3446
+ });
3447
+ return INVALID;
3448
+ }
3449
+ }
3450
+ get options() {
3451
+ return this._def.options;
3452
+ }
3453
+ }
3454
+ ZodUnion.create = (types, params) => {
3455
+ return new ZodUnion({
3456
+ options: types,
3457
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
3458
+ ...processCreateParams(params)
3459
+ });
3460
+ };
3461
+ var getDiscriminator = (type) => {
3462
+ if (type instanceof ZodLazy) {
3463
+ return getDiscriminator(type.schema);
3464
+ } else if (type instanceof ZodEffects) {
3465
+ return getDiscriminator(type.innerType());
3466
+ } else if (type instanceof ZodLiteral) {
3467
+ return [type.value];
3468
+ } else if (type instanceof ZodEnum) {
3469
+ return type.options;
3470
+ } else if (type instanceof ZodNativeEnum) {
3471
+ return util.objectValues(type.enum);
3472
+ } else if (type instanceof ZodDefault) {
3473
+ return getDiscriminator(type._def.innerType);
3474
+ } else if (type instanceof ZodUndefined) {
3475
+ return [undefined];
3476
+ } else if (type instanceof ZodNull) {
3477
+ return [null];
3478
+ } else if (type instanceof ZodOptional) {
3479
+ return [undefined, ...getDiscriminator(type.unwrap())];
3480
+ } else if (type instanceof ZodNullable) {
3481
+ return [null, ...getDiscriminator(type.unwrap())];
3482
+ } else if (type instanceof ZodBranded) {
3483
+ return getDiscriminator(type.unwrap());
3484
+ } else if (type instanceof ZodReadonly) {
3485
+ return getDiscriminator(type.unwrap());
3486
+ } else if (type instanceof ZodCatch) {
3487
+ return getDiscriminator(type._def.innerType);
3488
+ } else {
3489
+ return [];
3490
+ }
3491
+ };
3492
+
3493
+ 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
+ static create(discriminator, options, params) {
3539
+ const optionsMap = new Map;
3540
+ for (const type of options) {
3541
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3542
+ if (!discriminatorValues.length) {
3543
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3544
+ }
3545
+ for (const value of discriminatorValues) {
3546
+ if (optionsMap.has(value)) {
3547
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
3548
+ }
3549
+ optionsMap.set(value, type);
3550
+ }
3551
+ }
3552
+ return new ZodDiscriminatedUnion({
3553
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3554
+ discriminator,
3555
+ options,
3556
+ optionsMap,
3557
+ ...processCreateParams(params)
3558
+ });
3559
+ }
3560
+ }
3561
+ function mergeValues(a, b) {
3562
+ const aType = getParsedType(a);
3563
+ const bType = getParsedType(b);
3564
+ if (a === b) {
3565
+ return { valid: true, data: a };
3566
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3567
+ const bKeys = util.objectKeys(b);
3568
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
3569
+ const newObj = { ...a, ...b };
3570
+ for (const key of sharedKeys) {
3571
+ const sharedValue = mergeValues(a[key], b[key]);
3572
+ if (!sharedValue.valid) {
3573
+ return { valid: false };
3574
+ }
3575
+ newObj[key] = sharedValue.data;
3576
+ }
3577
+ return { valid: true, data: newObj };
3578
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3579
+ if (a.length !== b.length) {
3580
+ return { valid: false };
3581
+ }
3582
+ const newArray = [];
3583
+ for (let index = 0;index < a.length; index++) {
3584
+ const itemA = a[index];
3585
+ const itemB = b[index];
3586
+ const sharedValue = mergeValues(itemA, itemB);
3587
+ if (!sharedValue.valid) {
3588
+ return { valid: false };
3589
+ }
3590
+ newArray.push(sharedValue.data);
3591
+ }
3592
+ return { valid: true, data: newArray };
3593
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
3594
+ return { valid: true, data: a };
3595
+ } else {
3596
+ return { valid: false };
3597
+ }
3598
+ }
3599
+
3600
+ class ZodIntersection extends ZodType {
3601
+ _parse(input) {
3602
+ const { status, ctx } = this._processInputParams(input);
3603
+ const handleParsed = (parsedLeft, parsedRight) => {
3604
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3605
+ return INVALID;
3606
+ }
3607
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
3608
+ if (!merged.valid) {
3609
+ addIssueToContext(ctx, {
3610
+ code: ZodIssueCode.invalid_intersection_types
3611
+ });
3612
+ return INVALID;
3613
+ }
3614
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
3615
+ status.dirty();
3616
+ }
3617
+ return { status: status.value, value: merged.data };
3618
+ };
3619
+ if (ctx.common.async) {
3620
+ return Promise.all([
3621
+ this._def.left._parseAsync({
3622
+ data: ctx.data,
3623
+ path: ctx.path,
3624
+ parent: ctx
3625
+ }),
3626
+ this._def.right._parseAsync({
3627
+ data: ctx.data,
3628
+ path: ctx.path,
3629
+ parent: ctx
3630
+ })
3631
+ ]).then(([left, right]) => handleParsed(left, right));
3632
+ } else {
3633
+ return handleParsed(this._def.left._parseSync({
3634
+ data: ctx.data,
3635
+ path: ctx.path,
3636
+ parent: ctx
3637
+ }), this._def.right._parseSync({
3638
+ data: ctx.data,
3639
+ path: ctx.path,
3640
+ parent: ctx
3641
+ }));
3642
+ }
3643
+ }
3644
+ }
3645
+ ZodIntersection.create = (left, right, params) => {
3646
+ return new ZodIntersection({
3647
+ left,
3648
+ right,
3649
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
3650
+ ...processCreateParams(params)
3651
+ });
3652
+ };
3653
+
3654
+ class ZodTuple extends ZodType {
3655
+ _parse(input) {
3656
+ const { status, ctx } = this._processInputParams(input);
3657
+ if (ctx.parsedType !== ZodParsedType.array) {
3658
+ addIssueToContext(ctx, {
3659
+ code: ZodIssueCode.invalid_type,
3660
+ expected: ZodParsedType.array,
3661
+ received: ctx.parsedType
3662
+ });
3663
+ return INVALID;
3664
+ }
3665
+ if (ctx.data.length < this._def.items.length) {
3666
+ addIssueToContext(ctx, {
3667
+ code: ZodIssueCode.too_small,
3668
+ minimum: this._def.items.length,
3669
+ inclusive: true,
3670
+ exact: false,
3671
+ type: "array"
3672
+ });
3673
+ return INVALID;
3674
+ }
3675
+ const rest = this._def.rest;
3676
+ if (!rest && ctx.data.length > this._def.items.length) {
3677
+ addIssueToContext(ctx, {
3678
+ code: ZodIssueCode.too_big,
3679
+ maximum: this._def.items.length,
3680
+ inclusive: true,
3681
+ exact: false,
3682
+ type: "array"
3683
+ });
3684
+ status.dirty();
3685
+ }
3686
+ const items = [...ctx.data].map((item, itemIndex) => {
3687
+ const schema = this._def.items[itemIndex] || this._def.rest;
3688
+ if (!schema)
3689
+ return null;
3690
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3691
+ }).filter((x) => !!x);
3692
+ if (ctx.common.async) {
3693
+ return Promise.all(items).then((results) => {
3694
+ return ParseStatus.mergeArray(status, results);
3695
+ });
3696
+ } else {
3697
+ return ParseStatus.mergeArray(status, items);
3698
+ }
3699
+ }
3700
+ get items() {
3701
+ return this._def.items;
3702
+ }
3703
+ rest(rest) {
3704
+ return new ZodTuple({
3705
+ ...this._def,
3706
+ rest
3707
+ });
3708
+ }
3709
+ }
3710
+ ZodTuple.create = (schemas, params) => {
3711
+ if (!Array.isArray(schemas)) {
3712
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3713
+ }
3714
+ return new ZodTuple({
3715
+ items: schemas,
3716
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
3717
+ rest: null,
3718
+ ...processCreateParams(params)
3719
+ });
3720
+ };
3721
+
3722
+ class ZodRecord extends ZodType {
3723
+ get keySchema() {
3724
+ return this._def.keyType;
3725
+ }
3726
+ get valueSchema() {
3727
+ return this._def.valueType;
3728
+ }
3729
+ _parse(input) {
3730
+ const { status, ctx } = this._processInputParams(input);
3731
+ if (ctx.parsedType !== ZodParsedType.object) {
3732
+ addIssueToContext(ctx, {
3733
+ code: ZodIssueCode.invalid_type,
3734
+ expected: ZodParsedType.object,
3735
+ received: ctx.parsedType
3736
+ });
3737
+ return INVALID;
3738
+ }
3739
+ const pairs = [];
3740
+ const keyType = this._def.keyType;
3741
+ const valueType = this._def.valueType;
3742
+ for (const key in ctx.data) {
3743
+ pairs.push({
3744
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3745
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3746
+ alwaysSet: key in ctx.data
3747
+ });
3748
+ }
3749
+ if (ctx.common.async) {
3750
+ return ParseStatus.mergeObjectAsync(status, pairs);
3751
+ } else {
3752
+ return ParseStatus.mergeObjectSync(status, pairs);
3753
+ }
3754
+ }
3755
+ get element() {
3756
+ return this._def.valueType;
3757
+ }
3758
+ static create(first, second, third) {
3759
+ if (second instanceof ZodType) {
3760
+ return new ZodRecord({
3761
+ keyType: first,
3762
+ valueType: second,
3763
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3764
+ ...processCreateParams(third)
3765
+ });
3766
+ }
3767
+ return new ZodRecord({
3768
+ keyType: ZodString.create(),
3769
+ valueType: first,
3770
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3771
+ ...processCreateParams(second)
3772
+ });
3773
+ }
3774
+ }
3775
+
3776
+ class ZodMap extends ZodType {
3777
+ get keySchema() {
3778
+ return this._def.keyType;
3779
+ }
3780
+ get valueSchema() {
3781
+ return this._def.valueType;
3782
+ }
3783
+ _parse(input) {
3784
+ const { status, ctx } = this._processInputParams(input);
3785
+ if (ctx.parsedType !== ZodParsedType.map) {
3786
+ addIssueToContext(ctx, {
3787
+ code: ZodIssueCode.invalid_type,
3788
+ expected: ZodParsedType.map,
3789
+ received: ctx.parsedType
3790
+ });
3791
+ return INVALID;
3792
+ }
3793
+ const keyType = this._def.keyType;
3794
+ const valueType = this._def.valueType;
3795
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3796
+ return {
3797
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3798
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3799
+ };
3800
+ });
3801
+ if (ctx.common.async) {
3802
+ const finalMap = new Map;
3803
+ return Promise.resolve().then(async () => {
3804
+ for (const pair of pairs) {
3805
+ const key = await pair.key;
3806
+ const value = await pair.value;
3807
+ if (key.status === "aborted" || value.status === "aborted") {
3808
+ return INVALID;
3809
+ }
3810
+ if (key.status === "dirty" || value.status === "dirty") {
3811
+ status.dirty();
3812
+ }
3813
+ finalMap.set(key.value, value.value);
3814
+ }
3815
+ return { status: status.value, value: finalMap };
3816
+ });
3817
+ } else {
3818
+ const finalMap = new Map;
3819
+ for (const pair of pairs) {
3820
+ const key = pair.key;
3821
+ const value = pair.value;
3822
+ if (key.status === "aborted" || value.status === "aborted") {
3823
+ return INVALID;
3824
+ }
3825
+ if (key.status === "dirty" || value.status === "dirty") {
3826
+ status.dirty();
3827
+ }
3828
+ finalMap.set(key.value, value.value);
3829
+ }
3830
+ return { status: status.value, value: finalMap };
3831
+ }
3832
+ }
3833
+ }
3834
+ ZodMap.create = (keyType, valueType, params) => {
3835
+ return new ZodMap({
3836
+ valueType,
3837
+ keyType,
3838
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3839
+ ...processCreateParams(params)
3840
+ });
3841
+ };
3842
+
3843
+ class ZodSet extends ZodType {
3844
+ _parse(input) {
3845
+ const { status, ctx } = this._processInputParams(input);
3846
+ if (ctx.parsedType !== ZodParsedType.set) {
3847
+ addIssueToContext(ctx, {
3848
+ code: ZodIssueCode.invalid_type,
3849
+ expected: ZodParsedType.set,
3850
+ received: ctx.parsedType
3851
+ });
3852
+ return INVALID;
3853
+ }
3854
+ const def = this._def;
3855
+ if (def.minSize !== null) {
3856
+ if (ctx.data.size < def.minSize.value) {
3857
+ addIssueToContext(ctx, {
3858
+ code: ZodIssueCode.too_small,
3859
+ minimum: def.minSize.value,
3860
+ type: "set",
3861
+ inclusive: true,
3862
+ exact: false,
3863
+ message: def.minSize.message
3864
+ });
3865
+ status.dirty();
3866
+ }
3867
+ }
3868
+ if (def.maxSize !== null) {
3869
+ if (ctx.data.size > def.maxSize.value) {
3870
+ addIssueToContext(ctx, {
3871
+ code: ZodIssueCode.too_big,
3872
+ maximum: def.maxSize.value,
3873
+ type: "set",
3874
+ inclusive: true,
3875
+ exact: false,
3876
+ message: def.maxSize.message
3877
+ });
3878
+ status.dirty();
3879
+ }
3880
+ }
3881
+ const valueType = this._def.valueType;
3882
+ function finalizeSet(elements2) {
3883
+ const parsedSet = new Set;
3884
+ for (const element of elements2) {
3885
+ if (element.status === "aborted")
3886
+ return INVALID;
3887
+ if (element.status === "dirty")
3888
+ status.dirty();
3889
+ parsedSet.add(element.value);
3890
+ }
3891
+ return { status: status.value, value: parsedSet };
3892
+ }
3893
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3894
+ if (ctx.common.async) {
3895
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3896
+ } else {
3897
+ return finalizeSet(elements);
3898
+ }
3899
+ }
3900
+ min(minSize, message) {
3901
+ return new ZodSet({
3902
+ ...this._def,
3903
+ minSize: { value: minSize, message: errorUtil.toString(message) }
3904
+ });
3905
+ }
3906
+ max(maxSize, message) {
3907
+ return new ZodSet({
3908
+ ...this._def,
3909
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
3910
+ });
3911
+ }
3912
+ size(size, message) {
3913
+ return this.min(size, message).max(size, message);
3914
+ }
3915
+ nonempty(message) {
3916
+ return this.min(1, message);
3917
+ }
3918
+ }
3919
+ ZodSet.create = (valueType, params) => {
3920
+ return new ZodSet({
3921
+ valueType,
3922
+ minSize: null,
3923
+ maxSize: null,
3924
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3925
+ ...processCreateParams(params)
3926
+ });
3927
+ };
3928
+
3929
+ class ZodFunction extends ZodType {
3930
+ constructor() {
3931
+ super(...arguments);
3932
+ this.validate = this.implement;
3933
+ }
3934
+ _parse(input) {
3935
+ const { ctx } = this._processInputParams(input);
3936
+ if (ctx.parsedType !== ZodParsedType.function) {
3937
+ addIssueToContext(ctx, {
3938
+ code: ZodIssueCode.invalid_type,
3939
+ expected: ZodParsedType.function,
3940
+ received: ctx.parsedType
3941
+ });
3942
+ return INVALID;
3943
+ }
3944
+ function makeArgsIssue(args, error) {
3945
+ return makeIssue({
3946
+ data: args,
3947
+ path: ctx.path,
3948
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3949
+ issueData: {
3950
+ code: ZodIssueCode.invalid_arguments,
3951
+ argumentsError: error
3952
+ }
3953
+ });
3954
+ }
3955
+ function makeReturnsIssue(returns, error) {
3956
+ return makeIssue({
3957
+ data: returns,
3958
+ path: ctx.path,
3959
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3960
+ issueData: {
3961
+ code: ZodIssueCode.invalid_return_type,
3962
+ returnTypeError: error
3963
+ }
3964
+ });
3965
+ }
3966
+ const params = { errorMap: ctx.common.contextualErrorMap };
3967
+ const fn = ctx.data;
3968
+ if (this._def.returns instanceof ZodPromise) {
3969
+ const me = this;
3970
+ return OK(async function(...args) {
3971
+ const error = new ZodError([]);
3972
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3973
+ error.addIssue(makeArgsIssue(args, e));
3974
+ throw error;
3975
+ });
3976
+ const result = await Reflect.apply(fn, this, parsedArgs);
3977
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3978
+ error.addIssue(makeReturnsIssue(result, e));
3979
+ throw error;
3980
+ });
3981
+ return parsedReturns;
3982
+ });
3983
+ } else {
3984
+ const me = this;
3985
+ return OK(function(...args) {
3986
+ const parsedArgs = me._def.args.safeParse(args, params);
3987
+ if (!parsedArgs.success) {
3988
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3989
+ }
3990
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3991
+ const parsedReturns = me._def.returns.safeParse(result, params);
3992
+ if (!parsedReturns.success) {
3993
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3994
+ }
3995
+ return parsedReturns.data;
3996
+ });
3997
+ }
3998
+ }
3999
+ parameters() {
4000
+ return this._def.args;
4001
+ }
4002
+ returnType() {
4003
+ return this._def.returns;
4004
+ }
4005
+ args(...items) {
4006
+ return new ZodFunction({
4007
+ ...this._def,
4008
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
4009
+ });
4010
+ }
4011
+ returns(returnType) {
4012
+ return new ZodFunction({
4013
+ ...this._def,
4014
+ returns: returnType
4015
+ });
4016
+ }
4017
+ implement(func) {
4018
+ const validatedFunc = this.parse(func);
4019
+ return validatedFunc;
4020
+ }
4021
+ strictImplement(func) {
4022
+ const validatedFunc = this.parse(func);
4023
+ return validatedFunc;
4024
+ }
4025
+ static create(args, returns, params) {
4026
+ return new ZodFunction({
4027
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
4028
+ returns: returns || ZodUnknown.create(),
4029
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
4030
+ ...processCreateParams(params)
4031
+ });
4032
+ }
4033
+ }
4034
+
4035
+ class ZodLazy extends ZodType {
4036
+ get schema() {
4037
+ return this._def.getter();
4038
+ }
4039
+ _parse(input) {
4040
+ const { ctx } = this._processInputParams(input);
4041
+ const lazySchema = this._def.getter();
4042
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
4043
+ }
4044
+ }
4045
+ ZodLazy.create = (getter, params) => {
4046
+ return new ZodLazy({
4047
+ getter,
4048
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
4049
+ ...processCreateParams(params)
4050
+ });
4051
+ };
4052
+
4053
+ class ZodLiteral extends ZodType {
4054
+ _parse(input) {
4055
+ if (input.data !== this._def.value) {
4056
+ const ctx = this._getOrReturnCtx(input);
4057
+ addIssueToContext(ctx, {
4058
+ received: ctx.data,
4059
+ code: ZodIssueCode.invalid_literal,
4060
+ expected: this._def.value
4061
+ });
4062
+ return INVALID;
4063
+ }
4064
+ return { status: "valid", value: input.data };
4065
+ }
4066
+ get value() {
4067
+ return this._def.value;
4068
+ }
4069
+ }
4070
+ ZodLiteral.create = (value, params) => {
4071
+ return new ZodLiteral({
4072
+ value,
4073
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
4074
+ ...processCreateParams(params)
4075
+ });
4076
+ };
4077
+ function createZodEnum(values, params) {
4078
+ return new ZodEnum({
4079
+ values,
4080
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
4081
+ ...processCreateParams(params)
4082
+ });
4083
+ }
4084
+
4085
+ class ZodEnum extends ZodType {
4086
+ _parse(input) {
4087
+ if (typeof input.data !== "string") {
4088
+ const ctx = this._getOrReturnCtx(input);
4089
+ const expectedValues = this._def.values;
4090
+ addIssueToContext(ctx, {
4091
+ expected: util.joinValues(expectedValues),
4092
+ received: ctx.parsedType,
4093
+ code: ZodIssueCode.invalid_type
4094
+ });
4095
+ return INVALID;
4096
+ }
4097
+ if (!this._cache) {
4098
+ this._cache = new Set(this._def.values);
4099
+ }
4100
+ if (!this._cache.has(input.data)) {
4101
+ const ctx = this._getOrReturnCtx(input);
4102
+ const expectedValues = this._def.values;
4103
+ addIssueToContext(ctx, {
4104
+ received: ctx.data,
4105
+ code: ZodIssueCode.invalid_enum_value,
4106
+ options: expectedValues
4107
+ });
4108
+ return INVALID;
4109
+ }
4110
+ return OK(input.data);
4111
+ }
4112
+ get options() {
4113
+ return this._def.values;
4114
+ }
4115
+ get enum() {
4116
+ const enumValues = {};
4117
+ for (const val of this._def.values) {
4118
+ enumValues[val] = val;
4119
+ }
4120
+ return enumValues;
4121
+ }
4122
+ get Values() {
4123
+ const enumValues = {};
4124
+ for (const val of this._def.values) {
4125
+ enumValues[val] = val;
4126
+ }
4127
+ return enumValues;
4128
+ }
4129
+ get Enum() {
4130
+ const enumValues = {};
4131
+ for (const val of this._def.values) {
4132
+ enumValues[val] = val;
4133
+ }
4134
+ return enumValues;
4135
+ }
4136
+ extract(values, newDef = this._def) {
4137
+ return ZodEnum.create(values, {
4138
+ ...this._def,
4139
+ ...newDef
4140
+ });
4141
+ }
4142
+ exclude(values, newDef = this._def) {
4143
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
4144
+ ...this._def,
4145
+ ...newDef
4146
+ });
4147
+ }
4148
+ }
4149
+ ZodEnum.create = createZodEnum;
4150
+
4151
+ class ZodNativeEnum extends ZodType {
4152
+ _parse(input) {
4153
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
4154
+ const ctx = this._getOrReturnCtx(input);
4155
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
4156
+ const expectedValues = util.objectValues(nativeEnumValues);
4157
+ addIssueToContext(ctx, {
4158
+ expected: util.joinValues(expectedValues),
4159
+ received: ctx.parsedType,
4160
+ code: ZodIssueCode.invalid_type
4161
+ });
4162
+ return INVALID;
4163
+ }
4164
+ if (!this._cache) {
4165
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
4166
+ }
4167
+ if (!this._cache.has(input.data)) {
4168
+ const expectedValues = util.objectValues(nativeEnumValues);
4169
+ addIssueToContext(ctx, {
4170
+ received: ctx.data,
4171
+ code: ZodIssueCode.invalid_enum_value,
4172
+ options: expectedValues
4173
+ });
4174
+ return INVALID;
4175
+ }
4176
+ return OK(input.data);
4177
+ }
4178
+ get enum() {
4179
+ return this._def.values;
4180
+ }
4181
+ }
4182
+ ZodNativeEnum.create = (values, params) => {
4183
+ return new ZodNativeEnum({
4184
+ values,
4185
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
4186
+ ...processCreateParams(params)
4187
+ });
4188
+ };
4189
+
4190
+ class ZodPromise extends ZodType {
4191
+ unwrap() {
4192
+ return this._def.type;
4193
+ }
4194
+ _parse(input) {
4195
+ const { ctx } = this._processInputParams(input);
4196
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
4197
+ addIssueToContext(ctx, {
4198
+ code: ZodIssueCode.invalid_type,
4199
+ expected: ZodParsedType.promise,
4200
+ received: ctx.parsedType
4201
+ });
4202
+ return INVALID;
4203
+ }
4204
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
4205
+ return OK(promisified.then((data) => {
4206
+ return this._def.type.parseAsync(data, {
4207
+ path: ctx.path,
4208
+ errorMap: ctx.common.contextualErrorMap
4209
+ });
4210
+ }));
4211
+ }
4212
+ }
4213
+ ZodPromise.create = (schema, params) => {
4214
+ return new ZodPromise({
4215
+ type: schema,
4216
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
4217
+ ...processCreateParams(params)
4218
+ });
4219
+ };
4220
+
4221
+ class ZodEffects extends ZodType {
4222
+ innerType() {
4223
+ return this._def.schema;
4224
+ }
4225
+ sourceType() {
4226
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
4227
+ }
4228
+ _parse(input) {
4229
+ const { status, ctx } = this._processInputParams(input);
4230
+ const effect = this._def.effect || null;
4231
+ const checkCtx = {
4232
+ addIssue: (arg) => {
4233
+ addIssueToContext(ctx, arg);
4234
+ if (arg.fatal) {
4235
+ status.abort();
4236
+ } else {
4237
+ status.dirty();
4238
+ }
4239
+ },
4240
+ get path() {
4241
+ return ctx.path;
4242
+ }
4243
+ };
4244
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
4245
+ if (effect.type === "preprocess") {
4246
+ const processed = effect.transform(ctx.data, checkCtx);
4247
+ if (ctx.common.async) {
4248
+ return Promise.resolve(processed).then(async (processed2) => {
4249
+ if (status.value === "aborted")
4250
+ return INVALID;
4251
+ const result = await this._def.schema._parseAsync({
4252
+ data: processed2,
4253
+ path: ctx.path,
4254
+ parent: ctx
4255
+ });
4256
+ if (result.status === "aborted")
4257
+ return INVALID;
4258
+ if (result.status === "dirty")
4259
+ return DIRTY(result.value);
4260
+ if (status.value === "dirty")
4261
+ return DIRTY(result.value);
4262
+ return result;
4263
+ });
4264
+ } else {
4265
+ if (status.value === "aborted")
4266
+ return INVALID;
4267
+ const result = this._def.schema._parseSync({
4268
+ data: processed,
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
+ }
4281
+ if (effect.type === "refinement") {
4282
+ const executeRefinement = (acc) => {
4283
+ const result = effect.refinement(acc, checkCtx);
4284
+ if (ctx.common.async) {
4285
+ return Promise.resolve(result);
4286
+ }
4287
+ if (result instanceof Promise) {
4288
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
4289
+ }
4290
+ return acc;
4291
+ };
4292
+ if (ctx.common.async === false) {
4293
+ const inner = this._def.schema._parseSync({
4294
+ data: ctx.data,
4295
+ path: ctx.path,
4296
+ parent: ctx
4297
+ });
4298
+ if (inner.status === "aborted")
4299
+ return INVALID;
4300
+ if (inner.status === "dirty")
4301
+ status.dirty();
4302
+ executeRefinement(inner.value);
4303
+ return { status: status.value, value: inner.value };
4304
+ } else {
4305
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
4306
+ if (inner.status === "aborted")
4307
+ return INVALID;
4308
+ if (inner.status === "dirty")
4309
+ status.dirty();
4310
+ return executeRefinement(inner.value).then(() => {
4311
+ return { status: status.value, value: inner.value };
4312
+ });
4313
+ });
4314
+ }
4315
+ }
4316
+ if (effect.type === "transform") {
4317
+ if (ctx.common.async === false) {
4318
+ const base = this._def.schema._parseSync({
4319
+ data: ctx.data,
4320
+ path: ctx.path,
4321
+ parent: ctx
4322
+ });
4323
+ if (!isValid(base))
4324
+ return INVALID;
4325
+ const result = effect.transform(base.value, checkCtx);
4326
+ if (result instanceof Promise) {
4327
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
4328
+ }
4329
+ return { status: status.value, value: result };
4330
+ } else {
4331
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
4332
+ if (!isValid(base))
4333
+ return INVALID;
4334
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
4335
+ status: status.value,
4336
+ value: result
4337
+ }));
4338
+ });
4339
+ }
4340
+ }
4341
+ util.assertNever(effect);
4342
+ }
468
4343
  }
469
- function getDependents(scenarioId) {
470
- const db2 = getDatabase();
471
- const rows = db2.query("SELECT scenario_id FROM scenario_dependencies WHERE depends_on = ?").all(scenarioId);
472
- return rows.map((r) => r.scenario_id);
4344
+ ZodEffects.create = (schema, effect, params) => {
4345
+ return new ZodEffects({
4346
+ schema,
4347
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4348
+ effect,
4349
+ ...processCreateParams(params)
4350
+ });
4351
+ };
4352
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
4353
+ return new ZodEffects({
4354
+ schema,
4355
+ effect: { type: "preprocess", transform: preprocess },
4356
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4357
+ ...processCreateParams(params)
4358
+ });
4359
+ };
4360
+ class ZodOptional extends ZodType {
4361
+ _parse(input) {
4362
+ const parsedType = this._getType(input);
4363
+ if (parsedType === ZodParsedType.undefined) {
4364
+ return OK(undefined);
4365
+ }
4366
+ return this._def.innerType._parse(input);
4367
+ }
4368
+ unwrap() {
4369
+ return this._def.innerType;
4370
+ }
473
4371
  }
474
- function getTransitiveDependencies(scenarioId) {
475
- const db2 = getDatabase();
476
- const visited = new Set;
477
- const queue = [scenarioId];
478
- while (queue.length > 0) {
479
- const current = queue.shift();
480
- const deps = db2.query("SELECT depends_on FROM scenario_dependencies WHERE scenario_id = ?").all(current);
481
- for (const dep of deps) {
482
- if (!visited.has(dep.depends_on)) {
483
- visited.add(dep.depends_on);
484
- queue.push(dep.depends_on);
485
- }
4372
+ ZodOptional.create = (type, params) => {
4373
+ return new ZodOptional({
4374
+ innerType: type,
4375
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
4376
+ ...processCreateParams(params)
4377
+ });
4378
+ };
4379
+
4380
+ class ZodNullable extends ZodType {
4381
+ _parse(input) {
4382
+ const parsedType = this._getType(input);
4383
+ if (parsedType === ZodParsedType.null) {
4384
+ return OK(null);
486
4385
  }
4386
+ return this._def.innerType._parse(input);
4387
+ }
4388
+ unwrap() {
4389
+ return this._def.innerType;
487
4390
  }
488
- return Array.from(visited);
489
4391
  }
490
- function topologicalSort(scenarioIds) {
491
- const db2 = getDatabase();
492
- const idSet = new Set(scenarioIds);
493
- const inDegree = new Map;
494
- const dependents = new Map;
495
- for (const id of scenarioIds) {
496
- inDegree.set(id, 0);
497
- dependents.set(id, []);
4392
+ ZodNullable.create = (type, params) => {
4393
+ return new ZodNullable({
4394
+ innerType: type,
4395
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
4396
+ ...processCreateParams(params)
4397
+ });
4398
+ };
4399
+
4400
+ class ZodDefault extends ZodType {
4401
+ _parse(input) {
4402
+ const { ctx } = this._processInputParams(input);
4403
+ let data = ctx.data;
4404
+ if (ctx.parsedType === ZodParsedType.undefined) {
4405
+ data = this._def.defaultValue();
4406
+ }
4407
+ return this._def.innerType._parse({
4408
+ data,
4409
+ path: ctx.path,
4410
+ parent: ctx
4411
+ });
498
4412
  }
499
- for (const id of scenarioIds) {
500
- const deps = db2.query("SELECT depends_on FROM scenario_dependencies WHERE scenario_id = ?").all(id);
501
- for (const dep of deps) {
502
- if (idSet.has(dep.depends_on)) {
503
- inDegree.set(id, (inDegree.get(id) ?? 0) + 1);
504
- dependents.get(dep.depends_on).push(id);
4413
+ removeDefault() {
4414
+ return this._def.innerType;
4415
+ }
4416
+ }
4417
+ ZodDefault.create = (type, params) => {
4418
+ return new ZodDefault({
4419
+ innerType: type,
4420
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
4421
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
4422
+ ...processCreateParams(params)
4423
+ });
4424
+ };
4425
+
4426
+ class ZodCatch extends ZodType {
4427
+ _parse(input) {
4428
+ const { ctx } = this._processInputParams(input);
4429
+ const newCtx = {
4430
+ ...ctx,
4431
+ common: {
4432
+ ...ctx.common,
4433
+ issues: []
505
4434
  }
4435
+ };
4436
+ const result = this._def.innerType._parse({
4437
+ data: newCtx.data,
4438
+ path: newCtx.path,
4439
+ parent: {
4440
+ ...newCtx
4441
+ }
4442
+ });
4443
+ if (isAsync(result)) {
4444
+ return result.then((result2) => {
4445
+ return {
4446
+ status: "valid",
4447
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
4448
+ get error() {
4449
+ return new ZodError(newCtx.common.issues);
4450
+ },
4451
+ input: newCtx.data
4452
+ })
4453
+ };
4454
+ });
4455
+ } else {
4456
+ return {
4457
+ status: "valid",
4458
+ value: result.status === "valid" ? result.value : this._def.catchValue({
4459
+ get error() {
4460
+ return new ZodError(newCtx.common.issues);
4461
+ },
4462
+ input: newCtx.data
4463
+ })
4464
+ };
506
4465
  }
507
4466
  }
508
- const queue = [];
509
- for (const [id, deg] of inDegree) {
510
- if (deg === 0)
511
- queue.push(id);
4467
+ removeCatch() {
4468
+ return this._def.innerType;
512
4469
  }
513
- const sorted = [];
514
- while (queue.length > 0) {
515
- const current = queue.shift();
516
- sorted.push(current);
517
- for (const dep of dependents.get(current) ?? []) {
518
- const newDeg = (inDegree.get(dep) ?? 1) - 1;
519
- inDegree.set(dep, newDeg);
520
- if (newDeg === 0)
521
- queue.push(dep);
4470
+ }
4471
+ ZodCatch.create = (type, params) => {
4472
+ return new ZodCatch({
4473
+ innerType: type,
4474
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
4475
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
4476
+ ...processCreateParams(params)
4477
+ });
4478
+ };
4479
+
4480
+ class ZodNaN extends ZodType {
4481
+ _parse(input) {
4482
+ const parsedType = this._getType(input);
4483
+ if (parsedType !== ZodParsedType.nan) {
4484
+ const ctx = this._getOrReturnCtx(input);
4485
+ addIssueToContext(ctx, {
4486
+ code: ZodIssueCode.invalid_type,
4487
+ expected: ZodParsedType.nan,
4488
+ received: ctx.parsedType
4489
+ });
4490
+ return INVALID;
522
4491
  }
4492
+ return { status: "valid", value: input.data };
523
4493
  }
524
- if (sorted.length !== scenarioIds.length) {
525
- throw new DependencyCycleError("multiple", "multiple");
526
- }
527
- return sorted;
528
4494
  }
529
- function createFlow(input) {
530
- const db2 = getDatabase();
531
- const id = uuid();
532
- const timestamp = now();
533
- db2.query(`
534
- INSERT INTO flows (id, project_id, name, description, scenario_ids, created_at, updated_at)
535
- VALUES (?, ?, ?, ?, ?, ?, ?)
536
- `).run(id, input.projectId ?? null, input.name, input.description ?? null, JSON.stringify(input.scenarioIds), timestamp, timestamp);
537
- return getFlow(id);
4495
+ ZodNaN.create = (params) => {
4496
+ return new ZodNaN({
4497
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
4498
+ ...processCreateParams(params)
4499
+ });
4500
+ };
4501
+ var BRAND = Symbol("zod_brand");
4502
+
4503
+ class ZodBranded extends ZodType {
4504
+ _parse(input) {
4505
+ const { ctx } = this._processInputParams(input);
4506
+ const data = ctx.data;
4507
+ return this._def.type._parse({
4508
+ data,
4509
+ path: ctx.path,
4510
+ parent: ctx
4511
+ });
4512
+ }
4513
+ unwrap() {
4514
+ return this._def.type;
4515
+ }
538
4516
  }
539
- function getFlow(id) {
540
- const db2 = getDatabase();
541
- let row = db2.query("SELECT * FROM flows WHERE id = ?").get(id);
542
- if (row)
543
- return flowFromRow(row);
544
- const fullId = resolvePartialId("flows", id);
545
- if (fullId) {
546
- row = db2.query("SELECT * FROM flows WHERE id = ?").get(fullId);
547
- if (row)
548
- return flowFromRow(row);
4517
+
4518
+ class ZodPipeline extends ZodType {
4519
+ _parse(input) {
4520
+ const { status, ctx } = this._processInputParams(input);
4521
+ if (ctx.common.async) {
4522
+ const handleAsync = async () => {
4523
+ const inResult = await this._def.in._parseAsync({
4524
+ data: ctx.data,
4525
+ path: ctx.path,
4526
+ parent: ctx
4527
+ });
4528
+ if (inResult.status === "aborted")
4529
+ return INVALID;
4530
+ if (inResult.status === "dirty") {
4531
+ status.dirty();
4532
+ return DIRTY(inResult.value);
4533
+ } else {
4534
+ return this._def.out._parseAsync({
4535
+ data: inResult.value,
4536
+ path: ctx.path,
4537
+ parent: ctx
4538
+ });
4539
+ }
4540
+ };
4541
+ return handleAsync();
4542
+ } else {
4543
+ const inResult = this._def.in._parseSync({
4544
+ data: ctx.data,
4545
+ path: ctx.path,
4546
+ parent: ctx
4547
+ });
4548
+ if (inResult.status === "aborted")
4549
+ return INVALID;
4550
+ if (inResult.status === "dirty") {
4551
+ status.dirty();
4552
+ return {
4553
+ status: "dirty",
4554
+ value: inResult.value
4555
+ };
4556
+ } else {
4557
+ return this._def.out._parseSync({
4558
+ data: inResult.value,
4559
+ path: ctx.path,
4560
+ parent: ctx
4561
+ });
4562
+ }
4563
+ }
4564
+ }
4565
+ static create(a, b) {
4566
+ return new ZodPipeline({
4567
+ in: a,
4568
+ out: b,
4569
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
4570
+ });
549
4571
  }
550
- return null;
551
4572
  }
552
- function listFlows(projectId) {
553
- const db2 = getDatabase();
554
- if (projectId) {
555
- const rows2 = db2.query("SELECT * FROM flows WHERE project_id = ? ORDER BY created_at DESC").all(projectId);
556
- return rows2.map(flowFromRow);
4573
+
4574
+ class ZodReadonly extends ZodType {
4575
+ _parse(input) {
4576
+ const result = this._def.innerType._parse(input);
4577
+ const freeze = (data) => {
4578
+ if (isValid(data)) {
4579
+ data.value = Object.freeze(data.value);
4580
+ }
4581
+ return data;
4582
+ };
4583
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4584
+ }
4585
+ unwrap() {
4586
+ return this._def.innerType;
557
4587
  }
558
- const rows = db2.query("SELECT * FROM flows ORDER BY created_at DESC").all();
559
- return rows.map(flowFromRow);
560
4588
  }
561
- function deleteFlow(id) {
562
- const db2 = getDatabase();
563
- const flow = getFlow(id);
564
- if (!flow)
565
- return false;
566
- const result = db2.query("DELETE FROM flows WHERE id = ?").run(flow.id);
567
- return result.changes > 0;
4589
+ ZodReadonly.create = (type, params) => {
4590
+ return new ZodReadonly({
4591
+ innerType: type,
4592
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
4593
+ ...processCreateParams(params)
4594
+ });
4595
+ };
4596
+ function cleanParams(params, data) {
4597
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
4598
+ const p2 = typeof p === "string" ? { message: p } : p;
4599
+ return p2;
568
4600
  }
569
- var init_flows = __esm(() => {
570
- init_database();
571
- init_database();
572
- init_types();
573
- });
574
-
575
- // src/server/index.ts
576
- import { existsSync as existsSync4 } from "fs";
577
- import { join as join4 } from "path";
578
- import { homedir as homedir4 } from "os";
579
-
4601
+ function custom(check, _params = {}, fatal) {
4602
+ if (check)
4603
+ return ZodAny.create().superRefine((data, ctx) => {
4604
+ const r = check(data);
4605
+ if (r instanceof Promise) {
4606
+ return r.then((r2) => {
4607
+ if (!r2) {
4608
+ const params = cleanParams(_params, data);
4609
+ const _fatal = params.fatal ?? fatal ?? true;
4610
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4611
+ }
4612
+ });
4613
+ }
4614
+ if (!r) {
4615
+ const params = cleanParams(_params, data);
4616
+ const _fatal = params.fatal ?? fatal ?? true;
4617
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4618
+ }
4619
+ return;
4620
+ });
4621
+ return ZodAny.create();
4622
+ }
4623
+ var late = {
4624
+ object: ZodObject.lazycreate
4625
+ };
4626
+ var ZodFirstPartyTypeKind;
4627
+ (function(ZodFirstPartyTypeKind2) {
4628
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
4629
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
4630
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
4631
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
4632
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
4633
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
4634
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
4635
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
4636
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
4637
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
4638
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
4639
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
4640
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
4641
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
4642
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
4643
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
4644
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4645
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
4646
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
4647
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
4648
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
4649
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
4650
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
4651
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
4652
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
4653
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
4654
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
4655
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
4656
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
4657
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
4658
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
4659
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
4660
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4661
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4662
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4663
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4664
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4665
+ var instanceOfType = (cls, params = {
4666
+ message: `Input not instance of ${cls.name}`
4667
+ }) => custom((data) => data instanceof cls, params);
4668
+ var stringType = ZodString.create;
4669
+ var numberType = ZodNumber.create;
4670
+ var nanType = ZodNaN.create;
4671
+ var bigIntType = ZodBigInt.create;
4672
+ var booleanType = ZodBoolean.create;
4673
+ var dateType = ZodDate.create;
4674
+ var symbolType = ZodSymbol.create;
4675
+ var undefinedType = ZodUndefined.create;
4676
+ var nullType = ZodNull.create;
4677
+ var anyType = ZodAny.create;
4678
+ var unknownType = ZodUnknown.create;
4679
+ var neverType = ZodNever.create;
4680
+ var voidType = ZodVoid.create;
4681
+ var arrayType = ZodArray.create;
4682
+ var objectType = ZodObject.create;
4683
+ var strictObjectType = ZodObject.strictCreate;
4684
+ var unionType = ZodUnion.create;
4685
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
4686
+ var intersectionType = ZodIntersection.create;
4687
+ var tupleType = ZodTuple.create;
4688
+ var recordType = ZodRecord.create;
4689
+ var mapType = ZodMap.create;
4690
+ var setType = ZodSet.create;
4691
+ var functionType = ZodFunction.create;
4692
+ var lazyType = ZodLazy.create;
4693
+ var literalType = ZodLiteral.create;
4694
+ var enumType = ZodEnum.create;
4695
+ var nativeEnumType = ZodNativeEnum.create;
4696
+ var promiseType = ZodPromise.create;
4697
+ var effectsType = ZodEffects.create;
4698
+ var optionalType = ZodOptional.create;
4699
+ var nullableType = ZodNullable.create;
4700
+ var preprocessType = ZodEffects.createWithPreprocess;
4701
+ var pipelineType = ZodPipeline.create;
4702
+ var ostring = () => stringType().optional();
4703
+ var onumber = () => numberType().optional();
4704
+ var oboolean = () => booleanType().optional();
4705
+ var coerce = {
4706
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
4707
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
4708
+ boolean: (arg) => ZodBoolean.create({
4709
+ ...arg,
4710
+ coerce: true
4711
+ }),
4712
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
4713
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
4714
+ };
4715
+ var NEVER = INVALID;
580
4716
  // src/db/scenarios.ts
581
4717
  init_types();
582
4718
  init_database();
@@ -737,6 +4873,35 @@ function updateScenario(id, input, version) {
737
4873
  }
738
4874
  return getScenario(existing.id);
739
4875
  }
4876
+ function countScenarios(filter) {
4877
+ const db2 = getDatabase();
4878
+ const conditions = [];
4879
+ const params = [];
4880
+ if (filter?.projectId) {
4881
+ conditions.push("project_id = ?");
4882
+ params.push(filter.projectId);
4883
+ }
4884
+ if (filter?.tags && filter.tags.length > 0) {
4885
+ for (const tag of filter.tags) {
4886
+ conditions.push("tags LIKE ?");
4887
+ params.push(`%"${tag}"%`);
4888
+ }
4889
+ }
4890
+ if (filter?.priority) {
4891
+ conditions.push("priority = ?");
4892
+ params.push(filter.priority);
4893
+ }
4894
+ if (filter?.search) {
4895
+ conditions.push("(name LIKE ? OR description LIKE ?)");
4896
+ const term = `%${filter.search}%`;
4897
+ params.push(term, term);
4898
+ }
4899
+ let sql = "SELECT COUNT(*) as count FROM scenarios";
4900
+ if (conditions.length > 0)
4901
+ sql += " WHERE " + conditions.join(" AND ");
4902
+ const row = db2.query(sql).get(...params);
4903
+ return row.count;
4904
+ }
740
4905
  function deleteScenario(id) {
741
4906
  const db2 = getDatabase();
742
4907
  const scenario = getScenario(id);
@@ -800,6 +4965,24 @@ function listRuns(filter) {
800
4965
  const rows = db2.query(sql).all(...params);
801
4966
  return rows.map(runFromRow);
802
4967
  }
4968
+ function countRuns(filter) {
4969
+ const db2 = getDatabase();
4970
+ const conditions = [];
4971
+ const params = [];
4972
+ if (filter?.projectId) {
4973
+ conditions.push("project_id = ?");
4974
+ params.push(filter.projectId);
4975
+ }
4976
+ if (filter?.status) {
4977
+ conditions.push("status = ?");
4978
+ params.push(filter.status);
4979
+ }
4980
+ let sql = "SELECT COUNT(*) as count FROM runs";
4981
+ if (conditions.length > 0)
4982
+ sql += " WHERE " + conditions.join(" AND ");
4983
+ const row = db2.query(sql).get(...params);
4984
+ return row.count;
4985
+ }
803
4986
  function updateRun(id, updates) {
804
4987
  const db2 = getDatabase();
805
4988
  const existing = getRun(id);
@@ -941,6 +5124,11 @@ function updateResult(id, updates) {
941
5124
  function getResultsByRun(runId) {
942
5125
  return listResults(runId);
943
5126
  }
5127
+ function countResultsByRun(runId) {
5128
+ const db2 = getDatabase();
5129
+ const row = db2.query("SELECT COUNT(*) as count FROM results WHERE run_id = ?").get(runId);
5130
+ return row.count;
5131
+ }
944
5132
 
945
5133
  // src/db/screenshots.ts
946
5134
  init_types();
@@ -965,16 +5153,29 @@ function listScreenshots(resultId) {
965
5153
  const rows = db2.query("SELECT * FROM screenshots WHERE result_id = ? ORDER BY step_number ASC").all(resultId);
966
5154
  return rows.map(screenshotFromRow);
967
5155
  }
5156
+ function countScreenshots(resultId) {
5157
+ const db2 = getDatabase();
5158
+ const row = db2.query("SELECT COUNT(*) as count FROM screenshots WHERE result_id = ?").get(resultId);
5159
+ return row.count;
5160
+ }
968
5161
 
969
5162
  // src/lib/browser.ts
970
- import { chromium } from "playwright";
5163
+ import { chromium as chromium2 } from "playwright";
971
5164
  init_types();
972
5165
  var DEFAULT_VIEWPORT = { width: 1280, height: 720 };
973
5166
  async function launchBrowser(options) {
5167
+ const engine = options?.engine ?? process.env["TESTERS_BROWSER_ENGINE"] ?? "playwright";
5168
+ if (engine === "lightpanda") {
5169
+ const { launchLightpanda: launchLightpanda2, isLightpandaAvailable: isLightpandaAvailable2 } = await Promise.resolve().then(() => (init_browser_lightpanda(), exports_browser_lightpanda));
5170
+ if (!isLightpandaAvailable2()) {
5171
+ throw new BrowserError("Lightpanda not installed. Run: testers install-browser --engine lightpanda");
5172
+ }
5173
+ return launchLightpanda2({ viewport: options?.viewport });
5174
+ }
974
5175
  const headless = options?.headless ?? true;
975
5176
  const viewport = options?.viewport ?? DEFAULT_VIEWPORT;
976
5177
  try {
977
- const browser = await chromium.launch({
5178
+ const browser = await chromium2.launch({
978
5179
  headless,
979
5180
  args: [
980
5181
  `--window-size=${viewport.width},${viewport.height}`
@@ -987,6 +5188,11 @@ async function launchBrowser(options) {
987
5188
  }
988
5189
  }
989
5190
  async function getPage(browser, options) {
5191
+ const engine = options?.engine ?? "playwright";
5192
+ if (engine === "lightpanda") {
5193
+ const { getLightpandaPage: getLightpandaPage2 } = await Promise.resolve().then(() => (init_browser_lightpanda(), exports_browser_lightpanda));
5194
+ return getLightpandaPage2(browser, options);
5195
+ }
990
5196
  const viewport = options?.viewport ?? DEFAULT_VIEWPORT;
991
5197
  try {
992
5198
  const context = await browser.newContext({
@@ -1001,7 +5207,11 @@ async function getPage(browser, options) {
1001
5207
  throw new BrowserError(`Failed to create page: ${message}`);
1002
5208
  }
1003
5209
  }
1004
- async function closeBrowser(browser) {
5210
+ async function closeBrowser(browser, engine) {
5211
+ if (engine === "lightpanda") {
5212
+ const { closeLightpanda: closeLightpanda2 } = await Promise.resolve().then(() => (init_browser_lightpanda(), exports_browser_lightpanda));
5213
+ return closeLightpanda2(browser);
5214
+ }
1005
5215
  try {
1006
5216
  await browser.close();
1007
5217
  } catch (error) {
@@ -2033,6 +6243,38 @@ async function dispatchWebhooks(event, run, schedule) {
2033
6243
  }
2034
6244
  }
2035
6245
 
6246
+ // src/lib/logs-integration.ts
6247
+ async function pushFailedRunToLogs(run, failedResults, scenarios) {
6248
+ const logsUrl = process.env.LOGS_URL;
6249
+ if (!logsUrl)
6250
+ return;
6251
+ const scenarioMap = new Map(scenarios.map((s) => [s.id, s]));
6252
+ const entries = failedResults.map((result) => {
6253
+ const scenario = scenarioMap.get(result.scenarioId);
6254
+ return {
6255
+ level: "error",
6256
+ source: "sdk",
6257
+ service: "testers",
6258
+ message: `[testers] Scenario failed: ${scenario?.name ?? result.scenarioId}${result.error ? ` \u2014 ${result.error}` : ""}`,
6259
+ metadata: {
6260
+ run_id: run.id,
6261
+ scenario_id: result.scenarioId,
6262
+ scenario_name: scenario?.name,
6263
+ url: run.url,
6264
+ status: result.status,
6265
+ duration_ms: result.durationMs
6266
+ }
6267
+ };
6268
+ });
6269
+ try {
6270
+ await fetch(`${logsUrl.replace(/\/$/, "")}/api/logs`, {
6271
+ method: "POST",
6272
+ headers: { "Content-Type": "application/json" },
6273
+ body: JSON.stringify(entries)
6274
+ });
6275
+ } catch {}
6276
+ }
6277
+
2036
6278
  // src/lib/runner.ts
2037
6279
  var eventHandler = null;
2038
6280
  function emit(event) {
@@ -2042,7 +6284,7 @@ function emit(event) {
2042
6284
  function withTimeout(promise, ms, label) {
2043
6285
  return new Promise((resolve, reject) => {
2044
6286
  const timer = setTimeout(() => {
2045
- reject(new Error(`Scenario timeout after ${ms}ms: ${label}`));
6287
+ reject(new Error(`Scenario '${label}' timed out after ${ms}ms. Try: testers run --timeout ${ms * 2} or simplify the scenario steps.`));
2046
6288
  }, ms);
2047
6289
  promise.then((val) => {
2048
6290
  clearTimeout(timer);
@@ -2070,7 +6312,7 @@ async function runSingleScenario(scenario, runId, options) {
2070
6312
  let browser = null;
2071
6313
  let page = null;
2072
6314
  try {
2073
- browser = await launchBrowser({ headless: !(options.headed ?? false) });
6315
+ browser = await launchBrowser({ headless: !(options.headed ?? false), engine: options.engine });
2074
6316
  page = await getPage(browser, {
2075
6317
  viewport: config.browser.viewport
2076
6318
  });
@@ -2135,7 +6377,7 @@ async function runSingleScenario(scenario, runId, options) {
2135
6377
  return updatedResult;
2136
6378
  } finally {
2137
6379
  if (browser)
2138
- await closeBrowser(browser);
6380
+ await closeBrowser(browser, options.engine);
2139
6381
  }
2140
6382
  }
2141
6383
  async function runBatch(scenarios, options) {
@@ -2175,6 +6417,7 @@ async function runBatch(scenarios, options) {
2175
6417
  } catch {}
2176
6418
  return true;
2177
6419
  };
6420
+ const maxRetries = options.retry ?? 0;
2178
6421
  if (parallel <= 1) {
2179
6422
  for (const scenario of sortedScenarios) {
2180
6423
  if (!await canRun(scenario)) {
@@ -2185,7 +6428,13 @@ async function runBatch(scenarios, options) {
2185
6428
  emit({ type: "scenario:error", scenarioId: scenario.id, scenarioName: scenario.name, error: "Dependency failed \u2014 skipped", runId: run.id });
2186
6429
  continue;
2187
6430
  }
2188
- const result = await runSingleScenario(scenario, run.id, options);
6431
+ let result = await runSingleScenario(scenario, run.id, options);
6432
+ let attempt = 1;
6433
+ while ((result.status === "failed" || result.status === "error") && attempt <= maxRetries) {
6434
+ emit({ type: "scenario:start", scenarioId: scenario.id, scenarioName: scenario.name, runId: run.id, retryAttempt: attempt + 1, maxRetries: maxRetries + 1 });
6435
+ result = await runSingleScenario(scenario, run.id, options);
6436
+ attempt++;
6437
+ }
2189
6438
  results.push(result);
2190
6439
  if (result.status === "failed" || result.status === "error") {
2191
6440
  failedScenarioIds.add(scenario.id);
@@ -2232,6 +6481,10 @@ async function runBatch(scenarios, options) {
2232
6481
  emit({ type: "run:complete", runId: run.id });
2233
6482
  const eventType = finalRun.status === "failed" ? "failed" : "completed";
2234
6483
  dispatchWebhooks(eventType, finalRun).catch(() => {});
6484
+ if (finalRun.status === "failed") {
6485
+ const failedResults = results.filter((r) => r.status === "failed" || r.status === "error");
6486
+ pushFailedRunToLogs(finalRun, failedResults, scenarios).catch(() => {});
6487
+ }
2235
6488
  return { run: finalRun, results };
2236
6489
  }
2237
6490
  async function runByFilter(options) {
@@ -2617,14 +6870,15 @@ function parseUrl(req) {
2617
6870
  const url = new URL(req.url);
2618
6871
  return { pathname: url.pathname, searchParams: url.searchParams };
2619
6872
  }
2620
- function jsonResponse(data, status = 200) {
6873
+ function jsonResponse(data, status = 200, extra) {
2621
6874
  return new Response(JSON.stringify(data), {
2622
6875
  status,
2623
6876
  headers: {
2624
6877
  "Content-Type": "application/json",
2625
6878
  "Access-Control-Allow-Origin": "*",
2626
6879
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
2627
- "Access-Control-Allow-Headers": "Content-Type, Authorization"
6880
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
6881
+ ...extra
2628
6882
  }
2629
6883
  });
2630
6884
  }
@@ -2652,6 +6906,57 @@ function getContentType(filePath) {
2652
6906
  const ext = filePath.slice(filePath.lastIndexOf("."));
2653
6907
  return CONTENT_TYPES[ext] ?? "application/octet-stream";
2654
6908
  }
6909
+ var CreateScenarioSchema = exports_external.object({
6910
+ name: exports_external.string().min(1, "name is required"),
6911
+ description: exports_external.string().default(""),
6912
+ steps: exports_external.array(exports_external.string()).optional(),
6913
+ tags: exports_external.array(exports_external.string()).optional(),
6914
+ priority: exports_external.enum(["low", "medium", "high", "critical"]).optional(),
6915
+ model: exports_external.string().optional(),
6916
+ timeoutMs: exports_external.number().int().positive().optional(),
6917
+ targetPath: exports_external.string().optional(),
6918
+ requiresAuth: exports_external.boolean().optional(),
6919
+ authConfig: exports_external.record(exports_external.unknown()).optional(),
6920
+ metadata: exports_external.record(exports_external.unknown()).optional(),
6921
+ assertions: exports_external.array(exports_external.record(exports_external.unknown())).optional(),
6922
+ projectId: exports_external.string().optional()
6923
+ });
6924
+ var UpdateScenarioSchema = exports_external.object({
6925
+ version: exports_external.number().int().nonnegative("version is required"),
6926
+ name: exports_external.string().min(1).optional(),
6927
+ description: exports_external.string().optional(),
6928
+ steps: exports_external.array(exports_external.string()).optional(),
6929
+ tags: exports_external.array(exports_external.string()).optional(),
6930
+ priority: exports_external.enum(["low", "medium", "high", "critical"]).optional(),
6931
+ model: exports_external.string().optional(),
6932
+ timeoutMs: exports_external.number().int().positive().optional(),
6933
+ targetPath: exports_external.string().optional(),
6934
+ requiresAuth: exports_external.boolean().optional(),
6935
+ authConfig: exports_external.record(exports_external.unknown()).optional(),
6936
+ metadata: exports_external.record(exports_external.unknown()).optional(),
6937
+ assertions: exports_external.array(exports_external.record(exports_external.unknown())).optional()
6938
+ });
6939
+ var CreateRunSchema = exports_external.object({
6940
+ url: exports_external.string().url("url must be a valid URL"),
6941
+ scenarioIds: exports_external.array(exports_external.string()).optional(),
6942
+ tags: exports_external.array(exports_external.string()).optional(),
6943
+ model: exports_external.string().optional(),
6944
+ headed: exports_external.boolean().optional(),
6945
+ parallel: exports_external.number().int().positive().optional(),
6946
+ projectId: exports_external.string().optional()
6947
+ });
6948
+ function validationError(issues) {
6949
+ return new Response(JSON.stringify({
6950
+ error: "Validation failed",
6951
+ issues: issues.map((i) => ({ path: i.path.join("."), message: i.message }))
6952
+ }), {
6953
+ status: 400,
6954
+ headers: {
6955
+ "Content-Type": "application/json",
6956
+ "Access-Control-Allow-Origin": "*"
6957
+ }
6958
+ });
6959
+ }
2655
6960
  async function handleRequest(req) {
2656
6961
  const { pathname, searchParams } = parseUrl(req);
2657
6962
  const method = req.method;
@@ -2684,18 +6989,23 @@ async function handleRequest(req) {
2684
6989
  const priority = searchParams.get("priority");
2685
6990
  const limit = searchParams.get("limit");
2686
6991
  const offset = searchParams.get("offset");
2687
- const scenarios = listScenarios({
6992
+ const filter = {
2688
6993
  tags: tag ? [tag] : undefined,
2689
6994
  priority,
2690
6995
  limit: limit ? parseInt(limit, 10) : undefined,
2691
6996
  offset: offset ? parseInt(offset, 10) : undefined
2692
- });
2693
- return jsonResponse(scenarios);
6997
+ };
6998
+ const scenarios = listScenarios(filter);
6999
+ const total = countScenarios(filter);
7000
+ return jsonResponse(scenarios, 200, { "X-Total-Count": String(total) });
2694
7001
  }
2695
7002
  if (pathname === "/api/scenarios" && method === "POST") {
2696
7003
  try {
2697
7004
  const body = await req.json();
2698
- const scenario = createScenario(body);
7005
+ const parsed = CreateScenarioSchema.safeParse(body);
7006
+ if (!parsed.success)
7007
+ return validationError(parsed.error.issues);
7008
+ const scenario = createScenario(parsed.data);
2699
7009
  return jsonResponse(scenario, 201);
2700
7010
  } catch (err) {
2701
7011
  const msg = err instanceof Error ? err.message : String(err);
@@ -2715,7 +7025,10 @@ async function handleRequest(req) {
2715
7025
  const id = scenarioUpdateMatch[1];
2716
7026
  try {
2717
7027
  const body = await req.json();
2718
- const { version, ...updates } = body;
7028
+ const parsed = UpdateScenarioSchema.safeParse(body);
7029
+ if (!parsed.success)
7030
+ return validationError(parsed.error.issues);
7031
+ const { version, ...updates } = parsed.data;
2719
7032
  const scenario = updateScenario(id, updates, version);
2720
7033
  return jsonResponse(scenario);
2721
7034
  } catch (err) {
@@ -2736,7 +7049,11 @@ async function handleRequest(req) {
2736
7049
  }
2737
7050
  if (pathname === "/api/runs" && method === "POST") {
2738
7051
  try {
2739
- const body = await req.json();
7052
+ const raw = await req.json();
7053
+ const parsed = CreateRunSchema.safeParse(raw);
7054
+ if (!parsed.success)
7055
+ return validationError(parsed.error.issues);
7056
+ const body = parsed.data;
2740
7057
  const runPromise = runByFilter(body);
2741
7058
  runPromise.then(() => {}).catch((err) => {
2742
7059
  console.error("Run failed:", err);
@@ -2750,11 +7067,15 @@ async function handleRequest(req) {
2750
7067
  if (pathname === "/api/runs" && method === "GET") {
2751
7068
  const status = searchParams.get("status");
2752
7069
  const limit = searchParams.get("limit");
2753
- const runs = listRuns({
7070
+ const offset = searchParams.get("offset");
7071
+ const runFilter = {
2754
7072
  status,
2755
- limit: limit ? parseInt(limit, 10) : undefined
2756
- });
2757
- return jsonResponse(runs);
7073
+ limit: limit ? parseInt(limit, 10) : undefined,
7074
+ offset: offset ? parseInt(offset, 10) : undefined
7075
+ };
7076
+ const runs = listRuns(runFilter);
7077
+ const total = countRuns(runFilter);
7078
+ return jsonResponse(runs, 200, { "X-Total-Count": String(total) });
2758
7079
  }
2759
7080
  const runGetMatch = pathname.match(/^\/api\/runs\/([^/]+)$/);
2760
7081
  if (runGetMatch && method === "GET") {
@@ -2763,7 +7084,21 @@ async function handleRequest(req) {
2763
7084
  if (!run)
2764
7085
  return errorResponse("Run not found", 404);
2765
7086
  const results = getResultsByRun(id);
2766
- return jsonResponse({ ...run, results });
7087
+ const total = countResultsByRun(id);
7088
+ return jsonResponse({ ...run, results }, 200, { "X-Total-Count": String(total) });
7089
+ }
7090
+ const scenarioHistoryMatch = pathname.match(/^\/api\/scenarios\/([^/]+)\/history$/);
7091
+ if (scenarioHistoryMatch && method === "GET") {
7092
+ const id = scenarioHistoryMatch[1];
7093
+ const limit = parseInt(searchParams.get("limit") ?? "10", 10);
7094
+ const db2 = getDatabase();
7095
+ const rows = db2.query(`SELECT r.status, r.created_at FROM results r
7096
+ JOIN runs run ON r.run_id = run.id
7097
+ WHERE r.scenario_id = ? OR r.scenario_id IN (
7098
+ SELECT id FROM scenarios WHERE short_id = ?
7099
+ )
7100
+ ORDER BY r.created_at DESC LIMIT ?`).all(id, id, limit);
7101
+ return jsonResponse(rows.reverse());
2767
7102
  }
2768
7103
  const resultGetMatch = pathname.match(/^\/api\/results\/([^/]+)$/);
2769
7104
  if (resultGetMatch && method === "GET") {
@@ -2772,7 +7107,8 @@ async function handleRequest(req) {
2772
7107
  if (!result)
2773
7108
  return errorResponse("Result not found", 404);
2774
7109
  const screenshots = listScreenshots(id);
2775
- return jsonResponse({ ...result, screenshots });
7110
+ const total = countScreenshots(id);
7111
+ return jsonResponse({ ...result, screenshots }, 200, { "X-Total-Count": String(total) });
2776
7112
  }
2777
7113
  const screenshotFileMatch = pathname.match(/^\/api\/screenshots\/([^/]+)\/file$/);
2778
7114
  if (screenshotFileMatch && method === "GET") {