@debugkit/cli 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -4
- package/dist/cli.js +174 -20
- package/dist/lambda/index.mjs +3 -2
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -16,11 +16,12 @@ Run it from your app's folder. It walks you through these steps:
|
|
|
16
16
|
- **AWS:** a Lambda with a public URL and DynamoDB.
|
|
17
17
|
- **Just this machine:** no cloud, for a first look.
|
|
18
18
|
3. **Signs you in and sets everything up in your own account.**
|
|
19
|
-
- **Firebase:** you sign in with Google in your browser, then pick or create a project. The CLI creates the Firestore database, deploys the indexes and the
|
|
19
|
+
- **Firebase:** you sign in with Google in your browser, then pick or create a project. The CLI creates the Firestore database, deploys the indexes and the expiry on raw events, and deploys the ingest function. Cloud Functions need the Blaze plan, so it opens the billing page if you need to upgrade.
|
|
20
20
|
- **AWS:** you use an existing profile or sign in with AWS SSO in your browser, so you don't paste any access keys. The CLI creates the DynamoDB table, a Lambda with a public URL, an IAM role that can only write to the table, and a read-only policy for hosting the dashboard later.
|
|
21
|
-
4. **
|
|
22
|
-
5. **
|
|
23
|
-
6. **
|
|
21
|
+
4. **Asks how long to keep raw events:** 30, 60 (default), 90, 180 or 365 days, or any number, with a rough storage cost. Counts, issues and release health are kept forever. You can change it later on the dashboard's Settings page.
|
|
22
|
+
5. **Wires up your app.** It writes the endpoint and ingest key to `.env` (or into the code for bare React Native), creates `debug.ts`, and tells you the one or two lines left to add.
|
|
23
|
+
6. **Opens your dashboard,** connected to your data and still empty, behind a login you choose.
|
|
24
|
+
7. **Walks you through it:**
|
|
24
25
|
- what each part of the dashboard will show;
|
|
25
26
|
- a test event, sent through the real ingest so you watch it arrive;
|
|
26
27
|
- what the SDK records on its own;
|
|
@@ -70,6 +71,7 @@ Options: `--provider firebase|aws|local` skips the provider question, `--cwd <di
|
|
|
70
71
|
| Just this machine | Run end to end: the empty dashboard, then test events arriving |
|
|
71
72
|
| Firebase | Run end to end against a real project: function deployed, indexes added without touching existing ones, test events read back on the dashboard |
|
|
72
73
|
| AWS | Unit-tested (profile parsing, the "not found" handling, key merging) and the bundled Lambda run locally. Not yet run against a real account |
|
|
74
|
+
| Environments (`--env`) | Run end to end with "just this machine" in an Expo-style app: separate config and login, `.env` untouched, `debug.ts` with the on/off switch. `eas env:set` is checked against EAS's help but not yet run against a real EAS project |
|
|
73
75
|
| Platforms | Vite and React run for real. The Expo, React Native, Next.js, TanStack Start and Node templates are unit-tested |
|
|
74
76
|
|
|
75
77
|
## What it needs
|
package/dist/cli.js
CHANGED
|
@@ -113,7 +113,7 @@ function writeConfig(cwd, cfg) {
|
|
|
113
113
|
const f = readFile(cwd) ?? {};
|
|
114
114
|
const out = current ? { ...f, environments: { ...f.environments, [current]: { ...cfg, environment: current } } } : { ...cfg, ...f.environments ? { environments: f.environments } : {} };
|
|
115
115
|
writeFileSync(config, JSON.stringify(out, null, 2) + "\n");
|
|
116
|
-
writeFileSync(join(dir, ".gitignore"), "dashboard*.env\nfirebase*/functions/node_modules/\nfirebase*/.firebase/\n*.log\n");
|
|
116
|
+
writeFileSync(join(dir, ".gitignore"), "dashboard*.env\nfirebase*/functions/node_modules/\nfirebase*/functions/.env.*\nfirebase*/.firebase/\n*.log\n");
|
|
117
117
|
}
|
|
118
118
|
function upsertEnv(file, values) {
|
|
119
119
|
const lines = existsSync(file) ? readFileSync(file, "utf8").split(/\r?\n/) : [];
|
|
@@ -191,7 +191,7 @@ var dim = (s) => pc.dim(s);
|
|
|
191
191
|
var bold = (s) => pc.bold(s);
|
|
192
192
|
|
|
193
193
|
// src/dashboard.ts
|
|
194
|
-
var VERSION = true ? "0.
|
|
194
|
+
var VERSION = true ? "0.5.0" : "0.0.0-dev";
|
|
195
195
|
var DASHBOARD_VERSION = VERSION;
|
|
196
196
|
function hashPassword(password2) {
|
|
197
197
|
const salt = randomBytes(16);
|
|
@@ -366,6 +366,11 @@ function installCommand(pm, pkgs) {
|
|
|
366
366
|
}
|
|
367
367
|
|
|
368
368
|
// ../schema/src/core.ts
|
|
369
|
+
var LATENCY_BUCKETS_MS = [50, 100, 200, 300, 500, 750, 1e3, 1500, 2e3, 3e3, 5e3, 1e4];
|
|
370
|
+
function latencyBucket(ms) {
|
|
371
|
+
const i = LATENCY_BUCKETS_MS.findIndex((edge) => ms <= edge);
|
|
372
|
+
return i === -1 ? LATENCY_BUCKETS_MS.length : i;
|
|
373
|
+
}
|
|
369
374
|
var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
|
|
370
375
|
var GECKO = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
|
|
371
376
|
var NOT_IN_APP = [/node_modules/, /\bnative\b/, /\[native code\]/, /InternalBytecode/];
|
|
@@ -607,8 +612,19 @@ function instrumentWebLifecycle(sink) {
|
|
|
607
612
|
|
|
608
613
|
// ../sdk/src/client.ts
|
|
609
614
|
var SDK_NAME = "@debugkit/sdk";
|
|
610
|
-
var SDK_VERSION = "0.
|
|
615
|
+
var SDK_VERSION = "0.5.0";
|
|
611
616
|
var QUEUE_KEY = "@debugkit/queue";
|
|
617
|
+
var ANON_KEY = "@debugkit/anonymousId";
|
|
618
|
+
function webStorage() {
|
|
619
|
+
try {
|
|
620
|
+
const ls = globalThis.localStorage;
|
|
621
|
+
if (!ls) return void 0;
|
|
622
|
+
ls.getItem(ANON_KEY);
|
|
623
|
+
return ls;
|
|
624
|
+
} catch {
|
|
625
|
+
return void 0;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
612
628
|
var MAX_QUEUE = 500;
|
|
613
629
|
var uid = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`).replace(/-/g, "");
|
|
614
630
|
var now = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -645,6 +661,7 @@ var DebugClient = class {
|
|
|
645
661
|
this.auto = resolveAuto(options);
|
|
646
662
|
this.rawFetch = typeof globalThis.fetch === "function" ? globalThis.fetch.__raw ?? globalThis.fetch : void 0;
|
|
647
663
|
this.ready = true;
|
|
664
|
+
this.loadAnonymousId();
|
|
648
665
|
void this.restore();
|
|
649
666
|
if (this.auto.errors && !this.handlersInstalled) this.installGlobalHandlers();
|
|
650
667
|
this.instrument();
|
|
@@ -730,7 +747,31 @@ var DebugClient = class {
|
|
|
730
747
|
throw err;
|
|
731
748
|
}
|
|
732
749
|
}
|
|
750
|
+
/** Response times per endpoint, sent as one metric event each about once a minute. */
|
|
751
|
+
timings = /* @__PURE__ */ new Map();
|
|
752
|
+
timingsSince = Date.now();
|
|
753
|
+
/** Set when the ingest rejects metric events (older than 0.7): stop sending them, keep the rest. */
|
|
754
|
+
noMetrics = false;
|
|
755
|
+
timeRequest(key, ms, failed) {
|
|
756
|
+
if (this.noMetrics) return;
|
|
757
|
+
let t = this.timings.get(key);
|
|
758
|
+
if (!t) {
|
|
759
|
+
if (this.timings.size >= 50) return;
|
|
760
|
+
this.timings.set(key, t = { count: 0, errors: 0, buckets: new Array(LATENCY_BUCKETS_MS.length + 1).fill(0) });
|
|
761
|
+
}
|
|
762
|
+
t.count++;
|
|
763
|
+
if (failed) t.errors++;
|
|
764
|
+
t.buckets[latencyBucket(ms)]++;
|
|
765
|
+
}
|
|
766
|
+
/** Turn the collected timings into metric events (every minute, or now when `force`). */
|
|
767
|
+
queueTimings(force = false) {
|
|
768
|
+
if (!this.timings.size || this.noMetrics || !force && Date.now() - this.timingsSince < 6e4) return;
|
|
769
|
+
for (const [key, t] of this.timings) this.push({ type: "metric", id: uid(), ts: now(), name: "http", key: key.slice(0, 300), count: t.count, errors: t.errors, buckets: t.buckets });
|
|
770
|
+
this.timings.clear();
|
|
771
|
+
this.timingsSince = Date.now();
|
|
772
|
+
}
|
|
733
773
|
async flush() {
|
|
774
|
+
this.queueTimings(this.closing);
|
|
734
775
|
if (this.flushing) await this.flushing.catch(() => {
|
|
735
776
|
});
|
|
736
777
|
if (this.flushing) return this.flushing;
|
|
@@ -750,10 +791,12 @@ var DebugClient = class {
|
|
|
750
791
|
return this.flushing;
|
|
751
792
|
}
|
|
752
793
|
/** Stop the flush timer, undo automatic instrumentation and send what is queued. */
|
|
794
|
+
closing = false;
|
|
753
795
|
close() {
|
|
754
796
|
if (this.timer) clearInterval(this.timer);
|
|
755
797
|
this.uninstrument();
|
|
756
|
-
|
|
798
|
+
this.closing = true;
|
|
799
|
+
return this.flush().finally(() => this.closing = false);
|
|
757
800
|
}
|
|
758
801
|
/* ---------------- internals ---------------- */
|
|
759
802
|
/** @internal Used by the platform entry points for errors that have no thrown value. */
|
|
@@ -831,6 +874,7 @@ var DebugClient = class {
|
|
|
831
874
|
/** Set when the ingest rejects 0.2 fields: it predates them, so send what it understands. */
|
|
832
875
|
legacyIngest = false;
|
|
833
876
|
async send(events) {
|
|
877
|
+
if (this.noMetrics) events = events.filter((e) => e.type !== "metric");
|
|
834
878
|
if (this.legacyIngest) events = toLegacy(events);
|
|
835
879
|
if (!events.length) return;
|
|
836
880
|
const body = {
|
|
@@ -851,6 +895,11 @@ var DebugClient = class {
|
|
|
851
895
|
});
|
|
852
896
|
if (res.status >= 400 && res.status < 500 && res.status !== 429) {
|
|
853
897
|
this.log(`ingest rejected batch (${res.status})`, await res.text().catch(() => ""));
|
|
898
|
+
if (res.status === 400 && !this.noMetrics && events.some((e) => e.type === "metric")) {
|
|
899
|
+
this.noMetrics = true;
|
|
900
|
+
this.timings.clear();
|
|
901
|
+
return this.send(events);
|
|
902
|
+
}
|
|
854
903
|
if (res.status === 400 && !this.legacyIngest && hasNewFields(events)) {
|
|
855
904
|
this.legacyIngest = true;
|
|
856
905
|
return this.send(events);
|
|
@@ -865,6 +914,33 @@ var DebugClient = class {
|
|
|
865
914
|
} catch {
|
|
866
915
|
}
|
|
867
916
|
}
|
|
917
|
+
/**
|
|
918
|
+
* Reuse the install's anonymous id: from localStorage in browsers straight away, or from the
|
|
919
|
+
* `storage` option (AsyncStorage in React Native) once it loads. Events queued before then
|
|
920
|
+
* carry the new id, which only matters for the very first launch.
|
|
921
|
+
*/
|
|
922
|
+
loadAnonymousId() {
|
|
923
|
+
const ws = webStorage();
|
|
924
|
+
if (ws) {
|
|
925
|
+
try {
|
|
926
|
+
const saved = ws.getItem(ANON_KEY);
|
|
927
|
+
if (saved) this.user = { ...this.user, anonymousId: saved };
|
|
928
|
+
else ws.setItem(ANON_KEY, this.user.anonymousId);
|
|
929
|
+
} catch {
|
|
930
|
+
}
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
const storage = this.opts.storage;
|
|
934
|
+
if (!storage) return;
|
|
935
|
+
void (async () => {
|
|
936
|
+
try {
|
|
937
|
+
const saved = await storage.getItem(ANON_KEY);
|
|
938
|
+
if (saved) this.user = { ...this.user, anonymousId: saved };
|
|
939
|
+
else await storage.setItem(ANON_KEY, this.user.anonymousId);
|
|
940
|
+
} catch {
|
|
941
|
+
}
|
|
942
|
+
})();
|
|
943
|
+
}
|
|
868
944
|
async restore() {
|
|
869
945
|
try {
|
|
870
946
|
const raw = await this.opts.storage?.getItem(QUEUE_KEY);
|
|
@@ -914,7 +990,10 @@ var DebugClient = class {
|
|
|
914
990
|
navigated: (to) => this.navigated(to),
|
|
915
991
|
lifecycle: (state) => {
|
|
916
992
|
this.breadcrumb("ui", state === "background" ? "App went to the background" : "App came to the foreground");
|
|
917
|
-
if (state === "background")
|
|
993
|
+
if (state === "background") {
|
|
994
|
+
this.queueTimings(true);
|
|
995
|
+
void this.flush();
|
|
996
|
+
}
|
|
918
997
|
},
|
|
919
998
|
ignored: (url) => this.isIgnored(url)
|
|
920
999
|
};
|
|
@@ -934,6 +1013,7 @@ var DebugClient = class {
|
|
|
934
1013
|
const slow = ms >= (net.slowMs ?? 3e3);
|
|
935
1014
|
const outcome = r.aborted ? "aborted" : r.timedOut ? "timed out" : r.status !== void 0 ? String(r.status) : "failed";
|
|
936
1015
|
this.breadcrumb("network", `${r.method} ${url} \u2192 ${outcome} (${ms}ms)`, { status: r.status ?? null, durationMs: ms }, failed ? "error" : slow ? "warning" : "info");
|
|
1016
|
+
if (!r.aborted) this.timeRequest(`${r.method} ${url}`, ms, failed);
|
|
937
1017
|
if (!failed) return;
|
|
938
1018
|
const flow = net.flows?.find(([p2]) => typeof p2 === "string" ? url.includes(p2) : p2.test(url))?.[1];
|
|
939
1019
|
const cause = r.error ? normaliseError(r.error) : void 0;
|
|
@@ -976,7 +1056,7 @@ var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type
|
|
|
976
1056
|
function toLegacy(events) {
|
|
977
1057
|
const out = [];
|
|
978
1058
|
for (const e of events) {
|
|
979
|
-
if (e.type === "session") continue;
|
|
1059
|
+
if (e.type === "session" || e.type === "metric") continue;
|
|
980
1060
|
if (e.type === "error" && e.request) {
|
|
981
1061
|
const { request: _r, ...rest } = e;
|
|
982
1062
|
out.push(rest);
|
|
@@ -1138,7 +1218,7 @@ async function walkthrough(opts) {
|
|
|
1138
1218
|
[
|
|
1139
1219
|
...(d.narrative ?? []).map((l) => `\u201C${l}\u201D`),
|
|
1140
1220
|
"",
|
|
1141
|
-
`${bold(String(d.issues.length))} issues \xB7 ${bold(String(d.health?.
|
|
1221
|
+
`${bold(String(d.issues.length))} issues \xB7 ${bold(String(d.health?.sessionsRange ?? 0))} session \xB7 failing endpoint ${code(d.health?.endpoints?.[0]?.endpoint ?? "\u2014")}`,
|
|
1142
1222
|
"",
|
|
1143
1223
|
`Refresh the dashboard. You'll see a ${pc.red("HttpError")} from a failed request (captured the way the SDK does it automatically),`,
|
|
1144
1224
|
`a ${pc.red("SyntaxError")} reported from a try/catch, and the ${code("onboarding.test")} flow with a 50% failure rate from track().`,
|
|
@@ -1196,6 +1276,13 @@ function mergeKeys(existing, key, appId) {
|
|
|
1196
1276
|
return pairs.join(",");
|
|
1197
1277
|
}
|
|
1198
1278
|
|
|
1279
|
+
// src/providers/types.ts
|
|
1280
|
+
var adminEnv = (endpoint, ctx) => ({
|
|
1281
|
+
DEBUG_ADMIN_URL: `${endpoint.replace(/\/+$/, "")}/admin`,
|
|
1282
|
+
DEBUG_ADMIN_TOKEN: ctx.adminToken,
|
|
1283
|
+
DEBUG_RETENTION_DAYS: String(ctx.retentionDays)
|
|
1284
|
+
});
|
|
1285
|
+
|
|
1199
1286
|
// src/providers/aws.ts
|
|
1200
1287
|
var REGIONS = [
|
|
1201
1288
|
{ value: "af-south-1", label: "Cape Town (af-south-1)" },
|
|
@@ -1398,11 +1485,13 @@ async function setupAws(ctx) {
|
|
|
1398
1485
|
new lambdaMod.UpdateFunctionConfigurationCommand({
|
|
1399
1486
|
FunctionName: functionName,
|
|
1400
1487
|
Role: roleArn,
|
|
1401
|
-
Environment: {
|
|
1488
|
+
Environment: {
|
|
1489
|
+
Variables: { ...fn.Configuration?.Environment?.Variables, DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keys, DEBUG_RETENTION_DAYS: String(ctx.retentionDays), DEBUG_ADMIN_TOKEN: ctx.adminToken }
|
|
1490
|
+
}
|
|
1402
1491
|
})
|
|
1403
1492
|
);
|
|
1404
1493
|
} else {
|
|
1405
|
-
const env = { Variables: { DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keyEntry(ctx.ingestKey, ctx.app.appId) } };
|
|
1494
|
+
const env = { Variables: { DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keyEntry(ctx.ingestKey, ctx.app.appId), DEBUG_RETENTION_DAYS: String(ctx.retentionDays), DEBUG_ADMIN_TOKEN: ctx.adminToken } };
|
|
1406
1495
|
for (let attempt = 0; ; attempt++) {
|
|
1407
1496
|
try {
|
|
1408
1497
|
await lambda.send(
|
|
@@ -1464,7 +1553,7 @@ async function setupAws(ctx) {
|
|
|
1464
1553
|
}
|
|
1465
1554
|
return {
|
|
1466
1555
|
config: { provider: "aws", endpoint: url.replace(/\/$/, ""), ingestKey: ctx.ingestKey, aws: { region, profile, table, functionName, roleName, readOnlyPolicyArn } },
|
|
1467
|
-
dashboardEnv: { DEBUG_STORE: "dynamodb", AWS_REGION: region, DEBUG_DYNAMO_TABLE: table, ...profile ? { AWS_PROFILE: profile } : {} },
|
|
1556
|
+
dashboardEnv: { DEBUG_STORE: "dynamodb", AWS_REGION: region, DEBUG_DYNAMO_TABLE: table, ...profile ? { AWS_PROFILE: profile } : {}, ...adminEnv(url, ctx) },
|
|
1468
1557
|
created: [
|
|
1469
1558
|
`DynamoDB table ${code(table)} in ${region}${ownTable ? " (on-demand)" : " (your existing table)"}`,
|
|
1470
1559
|
`Lambda ${code(functionName)} with a public URL: ${code(url)}`,
|
|
@@ -1503,16 +1592,42 @@ var firestore_indexes_default = {
|
|
|
1503
1592
|
collectionGroup: "rollups",
|
|
1504
1593
|
queryScope: "COLLECTION",
|
|
1505
1594
|
fields: [
|
|
1506
|
-
{
|
|
1507
|
-
|
|
1595
|
+
{
|
|
1596
|
+
fieldPath: "dimension",
|
|
1597
|
+
order: "ASCENDING"
|
|
1598
|
+
},
|
|
1599
|
+
{
|
|
1600
|
+
fieldPath: "day",
|
|
1601
|
+
order: "ASCENDING"
|
|
1602
|
+
}
|
|
1508
1603
|
]
|
|
1509
1604
|
},
|
|
1510
1605
|
{
|
|
1511
1606
|
collectionGroup: "events",
|
|
1512
1607
|
queryScope: "COLLECTION",
|
|
1513
1608
|
fields: [
|
|
1514
|
-
{
|
|
1515
|
-
|
|
1609
|
+
{
|
|
1610
|
+
fieldPath: "fingerprint",
|
|
1611
|
+
order: "ASCENDING"
|
|
1612
|
+
},
|
|
1613
|
+
{
|
|
1614
|
+
fieldPath: "ts",
|
|
1615
|
+
order: "DESCENDING"
|
|
1616
|
+
}
|
|
1617
|
+
]
|
|
1618
|
+
},
|
|
1619
|
+
{
|
|
1620
|
+
collectionGroup: "users",
|
|
1621
|
+
queryScope: "COLLECTION",
|
|
1622
|
+
fields: [
|
|
1623
|
+
{
|
|
1624
|
+
fieldPath: "scope",
|
|
1625
|
+
order: "ASCENDING"
|
|
1626
|
+
},
|
|
1627
|
+
{
|
|
1628
|
+
fieldPath: "lastDay",
|
|
1629
|
+
order: "ASCENDING"
|
|
1630
|
+
}
|
|
1516
1631
|
]
|
|
1517
1632
|
}
|
|
1518
1633
|
],
|
|
@@ -1522,6 +1637,12 @@ var firestore_indexes_default = {
|
|
|
1522
1637
|
fieldPath: "expireAt",
|
|
1523
1638
|
ttl: true,
|
|
1524
1639
|
indexes: []
|
|
1640
|
+
},
|
|
1641
|
+
{
|
|
1642
|
+
collectionGroup: "rollups",
|
|
1643
|
+
fieldPath: "expireAt",
|
|
1644
|
+
ttl: true,
|
|
1645
|
+
indexes: []
|
|
1525
1646
|
}
|
|
1526
1647
|
]
|
|
1527
1648
|
};
|
|
@@ -1637,7 +1758,7 @@ async function setupFirebase(ctx) {
|
|
|
1637
1758
|
s.stop(`Created the Firestore database (${location2})`);
|
|
1638
1759
|
}
|
|
1639
1760
|
const region = functionRegion(location2);
|
|
1640
|
-
const dir = writeFunctionSource(ctx, region);
|
|
1761
|
+
const dir = writeFunctionSource(ctx, region, projectId);
|
|
1641
1762
|
s.start("Installing the ingest function's dependencies");
|
|
1642
1763
|
const inst = await capture("npm", ["install", "--no-audit", "--no-fund"], { cwd: join5(dir, "functions") });
|
|
1643
1764
|
if (inst.code !== 0) {
|
|
@@ -1685,7 +1806,7 @@ async function setupFirebase(ctx) {
|
|
|
1685
1806
|
await ensureDashboardAccess(projectId);
|
|
1686
1807
|
return {
|
|
1687
1808
|
config: { provider: "firebase", endpoint, ingestKey: ctx.ingestKey, firebase: { projectId, region, account, location: location2 } },
|
|
1688
|
-
dashboardEnv: { DEBUG_STORE: "firestore", GOOGLE_CLOUD_PROJECT: projectId, GCLOUD_PROJECT: projectId },
|
|
1809
|
+
dashboardEnv: { DEBUG_STORE: "firestore", GOOGLE_CLOUD_PROJECT: projectId, GCLOUD_PROJECT: projectId, ...adminEnv(endpoint, ctx) },
|
|
1689
1810
|
created: [
|
|
1690
1811
|
`Firestore database in ${code(projectId)} (${location2}), with indexes and 30-day expiry on raw events`,
|
|
1691
1812
|
`Cloud Function ${code(FUNCTION_NAME)} in ${region}: ${code(endpoint)}`,
|
|
@@ -1733,7 +1854,7 @@ function functionRegion(location2) {
|
|
|
1733
1854
|
if (location2.startsWith("nam")) return "us-central1";
|
|
1734
1855
|
return /^[a-z]+-[a-z]+\d+$/.test(location2) ? location2 : "us-central1";
|
|
1735
1856
|
}
|
|
1736
|
-
function writeFunctionSource(ctx, region) {
|
|
1857
|
+
function writeFunctionSource(ctx, region, projectId = "default") {
|
|
1737
1858
|
const dir = paths(ctx.app.cwd).firebase;
|
|
1738
1859
|
mkdirSync2(join5(dir, "functions"), { recursive: true });
|
|
1739
1860
|
writeFileSync2(
|
|
@@ -1783,14 +1904,22 @@ initializeApp();
|
|
|
1783
1904
|
|
|
1784
1905
|
export const ${FUNCTION_NAME} = onRequest(
|
|
1785
1906
|
{ region: ${JSON.stringify(region)}, invoker: "public", memory: "256MiB", maxInstances: 10 },
|
|
1786
|
-
firebaseHandler({
|
|
1907
|
+
firebaseHandler({
|
|
1908
|
+
store: new FirestoreStore(getFirestore()),
|
|
1909
|
+
keys: parseIngestKeys(process.env.DEBUG_INGEST_KEYS),
|
|
1910
|
+
retentionDays: Number(process.env.DEBUG_RETENTION_DAYS) || undefined,
|
|
1911
|
+
adminToken: process.env.DEBUG_ADMIN_TOKEN,
|
|
1912
|
+
}),
|
|
1787
1913
|
);
|
|
1788
1914
|
`
|
|
1789
1915
|
);
|
|
1790
1916
|
const envFile = join5(dir, "functions", ".env");
|
|
1791
1917
|
const current2 = existsSync5(envFile) ? /^DEBUG_INGEST_KEYS=(.*)$/m.exec(readFileSync4(envFile, "utf8"))?.[1] : void 0;
|
|
1792
1918
|
writeFileSync2(envFile, `DEBUG_INGEST_KEYS=${mergeKeys(current2, ctx.ingestKey, ctx.app.appId)}
|
|
1919
|
+
DEBUG_RETENTION_DAYS=${ctx.retentionDays}
|
|
1793
1920
|
`);
|
|
1921
|
+
writeFileSync2(join5(dir, "functions", `.env.${projectId}`), `DEBUG_ADMIN_TOKEN=${ctx.adminToken}
|
|
1922
|
+
`, { mode: 384 });
|
|
1794
1923
|
return dir;
|
|
1795
1924
|
}
|
|
1796
1925
|
|
|
@@ -2041,6 +2170,29 @@ function parseArgs(argv) {
|
|
|
2041
2170
|
return out;
|
|
2042
2171
|
}
|
|
2043
2172
|
var envLabel = () => environment.get() ? ` (${environment.get()})` : "";
|
|
2173
|
+
async function askRetention(current2, provider) {
|
|
2174
|
+
const perGb = provider === "aws" ? 0.25 : 0.18;
|
|
2175
|
+
const cost = (d) => {
|
|
2176
|
+
const gb = 1e4 * d * 2 / 1e6;
|
|
2177
|
+
return `${gb < 1 ? gb.toFixed(1) : Math.round(gb)} GB \u2248 $${(gb * perGb).toFixed(2)}/month at 10k events a day`;
|
|
2178
|
+
};
|
|
2179
|
+
p.note(
|
|
2180
|
+
[
|
|
2181
|
+
"Raw events carry the stack trace, breadcrumbs and device details. They expire after the period you pick.",
|
|
2182
|
+
`${bold("Counts, issues and release health are kept forever")}, so charts cover any date range.`,
|
|
2183
|
+
"You can change this later on the dashboard's Settings page."
|
|
2184
|
+
].join("\n"),
|
|
2185
|
+
"Data retention"
|
|
2186
|
+
);
|
|
2187
|
+
const options = [30, 60, 90, 180, 365].map((d) => ({ value: String(d), label: `${d} days`, hint: cost(d) }));
|
|
2188
|
+
const picked = await choose("Keep raw events for how long?", [...options, { value: "custom", label: "Another number of days" }], String(current2 ?? 60));
|
|
2189
|
+
if (picked !== "custom") return Number(picked);
|
|
2190
|
+
const days = await ask("Days (1 to 3650)", {
|
|
2191
|
+
initial: String(current2 ?? 60),
|
|
2192
|
+
validate: (v) => /^\d+$/.test(v) && Number(v) >= 1 && Number(v) <= 3650 ? void 0 : "A whole number from 1 to 3650"
|
|
2193
|
+
});
|
|
2194
|
+
return Number(days);
|
|
2195
|
+
}
|
|
2044
2196
|
function requireConfig(cwd) {
|
|
2045
2197
|
let cfg = readConfig(cwd);
|
|
2046
2198
|
if (!cfg && !environment.get()) {
|
|
@@ -2087,7 +2239,9 @@ async function init(cwd, preset) {
|
|
|
2087
2239
|
);
|
|
2088
2240
|
const dashboardPort = await freePort(4400);
|
|
2089
2241
|
const ingestKey = existing?.provider === provider && existing.ingestKey ? existing.ingestKey : `pk_${provider === "local" ? "local" : "live"}_${randomBytes2(12).toString("hex")}`;
|
|
2090
|
-
const
|
|
2242
|
+
const retentionDays = provider === "local" ? 30 : await askRetention(existing?.retentionDays, provider);
|
|
2243
|
+
const adminToken = readEnv(paths(cwd).dashboardEnv).DEBUG_ADMIN_TOKEN ?? `adm_${randomBytes2(24).toString("hex")}`;
|
|
2244
|
+
const ctx = { app, ingestKey, dashboardPort, retentionDays, adminToken };
|
|
2091
2245
|
let result;
|
|
2092
2246
|
try {
|
|
2093
2247
|
result = provider === "firebase" ? await setupFirebase(ctx) : provider === "aws" ? await setupAws(ctx) : await setupLocal(ctx);
|
|
@@ -2095,7 +2249,7 @@ async function init(cwd, preset) {
|
|
|
2095
2249
|
p.log.error(err.message);
|
|
2096
2250
|
bail("Setup stopped. Nothing else was changed in your app. Fix the error above and run npx debugkit init again.");
|
|
2097
2251
|
}
|
|
2098
|
-
const cfg = { ...result.config, appId: app.appId, dashboardPort, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
2252
|
+
const cfg = { ...result.config, appId: app.appId, dashboardPort, retentionDays, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
2099
2253
|
writeConfig(cwd, cfg);
|
|
2100
2254
|
p.note(result.created.map((l) => `\u2022 ${l}`).join("\n"), "Created");
|
|
2101
2255
|
const remaining = await wireApp(app, cfg);
|
package/dist/lambda/index.mjs
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
var ct=Object.defineProperty;var dt=(r,e)=>{for(var t in e)ct(r,t,{get:e[t],enumerable:!0})};import{DynamoDBClient as Yr}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as Kr}from"@aws-sdk/lib-dynamodb";import{BatchWriteCommand as lt,GetCommand as pt,PutCommand as ft,QueryCommand as Ve,UpdateCommand as ke}from"@aws-sdk/lib-dynamodb";function Ze(r){let e=new Map;for(let t of r){let s=ut(t),n=e.get(s)??{app:t.app,day:t.day,dimension:t.dimension,key:t.key,errors:0,events:0};t.kind==="error"?n.errors+=t.by:n.events+=t.by,e.set(s,n)}return[...e.values()]}var ut=r=>`${r.day}__${r.dimension}__${encodeURIComponent(r.key)}`;var we=class{constructor(e,t){this.doc=e;this.opts=t}doc;opts;get table(){return this.opts.table}async registerApp(e){await this.doc.send(new ft({TableName:this.table,Item:{pk:"APPS",sk:e}}))}async writeEvents(e){let t=n=>Math.floor(Date.parse(n.receivedAt)/1e3)+(this.opts.retentionDays??30)*86400,s=e.flatMap(n=>{let a=`${n.event.ts}#${n.event.id}`,i={...n,ttl:t(n)},o=[{pk:`APP#${n.app}#EV#${n.day}`,sk:a,...i}];return n.fingerprint&&o.push({pk:`APP#${n.app}#ISSUEEV#${n.fingerprint}`,sk:a,...i}),o});for(let n=0;n<s.length;n+=25){let a={[this.table]:s.slice(n,n+25).map(i=>({PutRequest:{Item:i}}))};for(let i=0;a&&Object.keys(a).length&&i<5;i++)a=(await this.doc.send(new lt({RequestItems:a}))).UnprocessedItems,a&&Object.keys(a).length&&await new Promise(u=>setTimeout(u,50*2**i))}}async upsertIssues(e){await Promise.all(e.map(async t=>{await this.doc.send(new ke({TableName:this.table,Key:{pk:`APP#${t.app}#ISSUE`,sk:t.fingerprint},UpdateExpression:"ADD #count :by SET app = :app, fingerprint = :fp, title = :title, flow = :flow, culprit = :culprit, firstSeen = if_not_exists(firstSeen, :first)",ExpressionAttributeNames:{"#count":"count"},ExpressionAttributeValues:{":by":t.by,":app":t.app,":fp":t.fingerprint,":title":t.title,":flow":t.flow??null,":culprit":t.culprit??null,":first":t.firstTs}})),await this.doc.send(new ke({TableName:this.table,Key:{pk:`APP#${t.app}#ISSUE`,sk:t.fingerprint},UpdateExpression:"SET lastSeen = :ts, lastEvent = :ev",ConditionExpression:"attribute_not_exists(lastSeen) OR lastSeen < :ts",ExpressionAttributeValues:{":ts":t.ts,":ev":t.lastEvent}})).catch(s=>{if(s.name!=="ConditionalCheckFailedException")throw s}),await this.doc.send(new ke({TableName:this.table,Key:{pk:`APP#${t.app}#ISSUE`,sk:t.fingerprint},UpdateExpression:"SET firstSeen = :first",ConditionExpression:"firstSeen > :first",ExpressionAttributeValues:{":first":t.firstTs}})).catch(s=>{if(s.name!=="ConditionalCheckFailedException")throw s})}))}async incrementRollups(e){await Promise.all(Ze(e).map(t=>this.doc.send(new ke({TableName:this.table,Key:{pk:`APP#${t.app}#ROLLUP#${t.dimension}`,sk:`${t.day}#${t.key}`},UpdateExpression:"ADD errors :e, events :v SET app = :app, #day = :day, dimension = :dim, #key = :key",ExpressionAttributeNames:{"#day":"day","#key":"key"},ExpressionAttributeValues:{":e":t.errors,":v":t.events,":app":t.app,":day":t.day,":dim":t.dimension,":key":t.key}}))))}async listApps(){return(await this.queryAll({pk:"APPS"})).map(e=>e.sk).sort()}async listIssues(e,{limit:t=200}={}){return(await this.queryAll({pk:`APP#${e}#ISSUE`})).sort((n,a)=>a.lastSeen.localeCompare(n.lastSeen)).slice(0,t).map(be)}async getIssue(e,t){let s=await this.doc.send(new pt({TableName:this.table,Key:{pk:`APP#${e}#ISSUE`,sk:t}}));return s.Item?be(s.Item):null}async getRollups(e,t,s,n){return(await this.queryAll({pk:`APP#${e}#ROLLUP#${t}`,between:[`${s}#`,`${n}#\uFFFF`]})).map(i=>be(i))}async listIssueEvents(e,t,{limit:s=50}={}){return((await this.doc.send(new Ve({TableName:this.table,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":`APP#${e}#ISSUEEV#${t}`},ScanIndexForward:!1,Limit:s}))).Items??[]).map(a=>be(a))}async queryAll({pk:e,between:t}){let s=[],n;do{let a=await this.doc.send(new Ve({TableName:this.table,KeyConditionExpression:t?"pk = :pk AND sk BETWEEN :a AND :b":"pk = :pk",ExpressionAttributeValues:t?{":pk":e,":a":t[0],":b":t[1]}:{":pk":e},ExclusiveStartKey:n}));s.push(...a.Items??[]),n=a.LastEvaluatedKey}while(n);return s}};function be(r){let{pk:e,sk:t,ttl:s,...n}=r;return n}var d={};dt(d,{BRAND:()=>Vt,DIRTY:()=>q,EMPTY_PATH:()=>gt,INVALID:()=>h,NEVER:()=>wr,OK:()=>E,ParseStatus:()=>w,Schema:()=>_,ZodAny:()=>B,ZodArray:()=>Z,ZodBigInt:()=>H,ZodBoolean:()=>J,ZodBranded:()=>ve,ZodCatch:()=>ae,ZodDate:()=>Y,ZodDefault:()=>ne,ZodDiscriminatedUnion:()=>Te,ZodEffects:()=>O,ZodEnum:()=>re,ZodError:()=>S,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>Ie,ZodIntersection:()=>X,ZodIssueCode:()=>c,ZodLazy:()=>ee,ZodLiteral:()=>te,ZodMap:()=>me,ZodNaN:()=>ye,ZodNativeEnum:()=>se,ZodNever:()=>A,ZodNull:()=>G,ZodNullable:()=>$,ZodNumber:()=>W,ZodObject:()=>T,ZodOptional:()=>I,ZodParsedType:()=>f,ZodPipeline:()=>_e,ZodPromise:()=>F,ZodReadonly:()=>ie,ZodRecord:()=>Ce,ZodSchema:()=>_,ZodSet:()=>he,ZodString:()=>U,ZodSymbol:()=>pe,ZodTransformer:()=>O,ZodTuple:()=>j,ZodType:()=>_,ZodUndefined:()=>K,ZodUnion:()=>Q,ZodUnknown:()=>M,ZodVoid:()=>fe,addIssueToContext:()=>l,any:()=>Jt,array:()=>Qt,bigint:()=>Bt,boolean:()=>Ke,coerce:()=>br,custom:()=>He,date:()=>Ft,datetimeRegex:()=>qe,defaultErrorMap:()=>P,discriminatedUnion:()=>rr,effect:()=>mr,enum:()=>lr,function:()=>cr,getErrorMap:()=>de,getParsedType:()=>N,instanceof:()=>Lt,intersection:()=>sr,isAborted:()=>Ee,isAsync:()=>ue,isDirty:()=>Se,isValid:()=>L,late:()=>zt,lazy:()=>dr,literal:()=>ur,makeIssue:()=>ge,map:()=>ir,nan:()=>Ut,nativeEnum:()=>pr,never:()=>Kt,null:()=>Ht,nullable:()=>yr,number:()=>Ye,object:()=>Xt,objectUtil:()=>Oe,oboolean:()=>kr,onumber:()=>xr,optional:()=>hr,ostring:()=>_r,pipeline:()=>vr,preprocess:()=>gr,promise:()=>fr,quotelessJson:()=>mt,record:()=>ar,set:()=>or,setErrorMap:()=>yt,strictObject:()=>er,string:()=>Je,symbol:()=>qt,transformer:()=>mr,tuple:()=>nr,undefined:()=>Wt,union:()=>tr,unknown:()=>Yt,util:()=>x,void:()=>Gt});var x;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{let a={};for(let i of n)a[i]=i;return a},r.getValidEnumValues=n=>{let a=r.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(let o of a)i[o]=n[o];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let a=[];for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(let i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(x||(x={}));var Oe;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Oe||(Oe={}));var f=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),N=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}};var c=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),mt=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),S=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let o=s,u=0;for(;u<i.path.length;){let p=i.path[u];u===i.path.length-1?(o[p]=o[p]||{_errors:[]},o[p]._errors.push(t(i))):o[p]=o[p]||{_errors:[]},o=o[p],u++}}};return n(this),s}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},s=[];for(let n of this.issues)if(n.path.length>0){let a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};S.create=r=>new S(r);var ht=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}},P=ht;var ze=P;function yt(r){ze=r}function de(){return ze}var ge=r=>{let{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="",u=s.filter(p=>!!p).slice().reverse();for(let p of u)o=p(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},gt=[];function l(r,e){let t=de(),s=ge({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===P?void 0:P].filter(n=>!!n)});r.common.issues.push(s)}var w=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let s=[];for(let n of t){if(n.status==="aborted")return h;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){let s=[];for(let n of t){let a=await n.key,i=await n.value;s.push({key:a,value:i})}return r.mergeObjectSync(e,s)}static mergeObjectSync(e,t){let s={};for(let n of t){let{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return h;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value)}return{status:e.value,value:s}}},h=Object.freeze({status:"aborted"}),q=r=>({status:"dirty",value:r}),E=r=>({status:"valid",value:r}),Ee=r=>r.status==="aborted",Se=r=>r.status==="dirty",L=r=>r.status==="valid",ue=r=>typeof Promise<"u"&&r instanceof Promise;var m;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));var R=class{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Le=(r,e)=>{if(L(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new S(r.common.issues);return this._error=t,this._error}}};function g(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{let{message:u}=r;return i.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??s??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:u??t??o.defaultError}},description:n}}var _=class{get description(){return this._def.description}_getType(e){return N(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ue(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){let s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},n=this._parseSync({data:e,path:s.path,parent:s});return Le(s,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)};if(!this["~standard"].async)try{let s=this._parseSync({data:e,path:[],parent:t});return L(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>L(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){let s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){let s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(ue(n)?n:Promise.resolve(n));return Le(s,a)}refine(e,t){let s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{let i=e(n),o=()=>a.addIssue({code:c.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new O({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return I.create(this,this._def)}nullable(){return $.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Z.create(this)}promise(){return F.create(this,this._def)}or(e){return Q.create([this,e],this._def)}and(e){return X.create(this,e,this._def)}transform(e){return new O({...g(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ne({...g(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new ve({typeName:y.ZodBranded,type:this,...g(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ae({...g(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _e.create(this,e)}readonly(){return ie.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},vt=/^c[^\s-]{8,}$/i,_t=/^[0-9a-z]+$/,xt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kt=/^[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,bt=/^[a-z0-9_-]{21}$/i,wt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Et=/^[-+]?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)?)??$/,St=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Tt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ae,Ct=/^(?:(?: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])$/,It=/^(?:(?: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])$/,Rt=/^(([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]))$/,Ot=/^(([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])$/,At=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Nt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Be="((\\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])))",jt=new RegExp(`^${Be}$`);function Fe(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function $t(r){return new RegExp(`^${Fe(r)}$`)}function qe(r){let e=`${Be}T${Fe(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Pt(r,e){return!!((e==="v4"||!e)&&Ct.test(r)||(e==="v6"||!e)&&Rt.test(r))}function Dt(r,e){if(!wt.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Mt(r,e){return!!((e==="v4"||!e)&&It.test(r)||(e==="v6"||!e)&&Ot.test(r))}var U=class r extends _{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_type,expected:f.string,received:a.parsedType}),h}let s=new w,n;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?l(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&l(n,{code:c.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if(a.kind==="email")St.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"email",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")Ae||(Ae=new RegExp(Tt,"u")),Ae.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"emoji",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")kt.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"uuid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")bt.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"nanoid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")vt.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"cuid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")_t.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"cuid2",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")xt.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"ulid",code:c.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),l(n,{validation:"url",code:c.invalid_string,message:a.message}),s.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"regex",code:c.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?qe(a).test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?jt.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?$t(a).test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?Et.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"duration",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?Pt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"ip",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?Dt(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"jwt",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?Mt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"cidr",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?At.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"base64",code:c.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?Nt.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"base64url",code:c.invalid_string,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:c.invalid_string,...m.errToObj(s)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};U.create=r=>new U({checks:[],typeName:y.ZodString,coerce:r?.coerce??!1,...g(r)});function Zt(r,e){let t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=Number.parseInt(r.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}var W=class r extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_type,expected:f.number,received:a.parsedType}),h}let s,n=new w;for(let a of this._def.checks)a.kind==="int"?x.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?Zt(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.not_finite,message:a.message}),n.dirty()):x.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}};W.create=r=>new W({checks:[],typeName:y.ZodNumber,coerce:r?.coerce||!1,...g(r)});var H=class r extends _{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let s,n=new w;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):x.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return l(t,{code:c.invalid_type,expected:f.bigint,received:t.parsedType}),h}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,s,n){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};H.create=r=>new H({checks:[],typeName:y.ZodBigInt,coerce:r?.coerce??!1,...g(r)});var J=class extends _{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let s=this._getOrReturnCtx(e);return l(s,{code:c.invalid_type,expected:f.boolean,received:s.parsedType}),h}return E(e.data)}};J.create=r=>new J({typeName:y.ZodBoolean,coerce:r?.coerce||!1,...g(r)});var Y=class r extends _{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_type,expected:f.date,received:a.parsedType}),h}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_date}),h}let s=new w,n;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):x.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Y.create=r=>new Y({checks:[],coerce:r?.coerce||!1,typeName:y.ZodDate,...g(r)});var pe=class extends _{_parse(e){if(this._getType(e)!==f.symbol){let s=this._getOrReturnCtx(e);return l(s,{code:c.invalid_type,expected:f.symbol,received:s.parsedType}),h}return E(e.data)}};pe.create=r=>new pe({typeName:y.ZodSymbol,...g(r)});var K=class extends _{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return l(s,{code:c.invalid_type,expected:f.undefined,received:s.parsedType}),h}return E(e.data)}};K.create=r=>new K({typeName:y.ZodUndefined,...g(r)});var G=class extends _{_parse(e){if(this._getType(e)!==f.null){let s=this._getOrReturnCtx(e);return l(s,{code:c.invalid_type,expected:f.null,received:s.parsedType}),h}return E(e.data)}};G.create=r=>new G({typeName:y.ZodNull,...g(r)});var B=class extends _{constructor(){super(...arguments),this._any=!0}_parse(e){return E(e.data)}};B.create=r=>new B({typeName:y.ZodAny,...g(r)});var M=class extends _{constructor(){super(...arguments),this._unknown=!0}_parse(e){return E(e.data)}};M.create=r=>new M({typeName:y.ZodUnknown,...g(r)});var A=class extends _{_parse(e){let t=this._getOrReturnCtx(e);return l(t,{code:c.invalid_type,expected:f.never,received:t.parsedType}),h}};A.create=r=>new A({typeName:y.ZodNever,...g(r)});var fe=class extends _{_parse(e){if(this._getType(e)!==f.undefined){let s=this._getOrReturnCtx(e);return l(s,{code:c.invalid_type,expected:f.void,received:s.parsedType}),h}return E(e.data)}};fe.create=r=>new fe({typeName:y.ZodVoid,...g(r)});var Z=class r extends _{_parse(e){let{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.array)return l(t,{code:c.invalid_type,expected:f.array,received:t.parsedType}),h;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(l(t,{code:i?c.too_big:c.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(l(t,{code:c.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(l(t,{code:c.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new R(t,i,t.path,o)))).then(i=>w.mergeArray(s,i));let a=[...t.data].map((i,o)=>n.type._parseSync(new R(t,i,t.path,o)));return w.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}};Z.create=(r,e)=>new Z({type:r,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,...g(e)});function le(r){if(r instanceof T){let e={};for(let t in r.shape){let s=r.shape[t];e[t]=I.create(le(s))}return new T({...r._def,shape:()=>e})}else return r instanceof Z?new Z({...r._def,type:le(r.element)}):r instanceof I?I.create(le(r.unwrap())):r instanceof $?$.create(le(r.unwrap())):r instanceof j?j.create(r.items.map(e=>le(e))):r}var T=class r extends _{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let p=this._getOrReturnCtx(e);return l(p,{code:c.invalid_type,expected:f.object,received:p.parsedType}),h}let{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof A&&this._def.unknownKeys==="strip"))for(let p in n.data)i.includes(p)||o.push(p);let u=[];for(let p of i){let v=a[p],b=n.data[p];u.push({key:{status:"valid",value:p},value:v._parse(new R(n,b,n.path,p)),alwaysSet:p in n.data})}if(this._def.catchall instanceof A){let p=this._def.unknownKeys;if(p==="passthrough")for(let v of o)u.push({key:{status:"valid",value:v},value:{status:"valid",value:n.data[v]}});else if(p==="strict")o.length>0&&(l(n,{code:c.unrecognized_keys,keys:o}),s.dirty());else if(p!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let p=this._def.catchall;for(let v of o){let b=n.data[v];u.push({key:{status:"valid",value:v},value:p._parse(new R(n,b,n.path,v)),alwaysSet:v in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let p=[];for(let v of u){let b=await v.key,oe=await v.value;p.push({key:b,value:oe,alwaysSet:v.alwaysSet})}return p}).then(p=>w.mergeObjectSync(s,p)):w.mergeObjectSync(s,u)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{let n=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let s of x.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let s of x.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new r({...this._def,shape:()=>t})}deepPartial(){return le(this)}partial(e){let t={};for(let s of x.objectKeys(this.shape)){let n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let s of x.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof I;)a=a._def.innerType;t[s]=a}return new r({...this._def,shape:()=>t})}keyof(){return We(x.objectKeys(this.shape))}};T.create=(r,e)=>new T({shape:()=>r,unknownKeys:"strip",catchall:A.create(),typeName:y.ZodObject,...g(e)});T.strictCreate=(r,e)=>new T({shape:()=>r,unknownKeys:"strict",catchall:A.create(),typeName:y.ZodObject,...g(e)});T.lazycreate=(r,e)=>new T({shape:r,unknownKeys:"strip",catchall:A.create(),typeName:y.ZodObject,...g(e)});var Q=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new S(o.ctx.common.issues));return l(t,{code:c.invalid_union,unionErrors:i}),h}if(t.common.async)return Promise.all(s.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a,i=[];for(let u of s){let p={...t,common:{...t.common,issues:[]},parent:null},v=u._parseSync({data:t.data,path:t.path,parent:p});if(v.status==="valid")return v;v.status==="dirty"&&!a&&(a={result:v,ctx:p}),p.common.issues.length&&i.push(p.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(u=>new S(u));return l(t,{code:c.invalid_union,unionErrors:o}),h}}get options(){return this._def.options}};Q.create=(r,e)=>new Q({options:r,typeName:y.ZodUnion,...g(e)});var D=r=>r instanceof ee?D(r.schema):r instanceof O?D(r.innerType()):r instanceof te?[r.value]:r instanceof re?r.options:r instanceof se?x.objectValues(r.enum):r instanceof ne?D(r._def.innerType):r instanceof K?[void 0]:r instanceof G?[null]:r instanceof I?[void 0,...D(r.unwrap())]:r instanceof $?[null,...D(r.unwrap())]:r instanceof ve||r instanceof ie?D(r.unwrap()):r instanceof ae?D(r._def.innerType):[],Te=class r extends _{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return l(t,{code:c.invalid_type,expected:f.object,received:t.parsedType}),h;let s=this.discriminator,n=t.data[s],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(l(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),h)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){let n=new Map;for(let a of t){let i=D(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a)}}return new r({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...g(s)})}};function Ne(r,e){let t=N(r),s=N(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&s===f.object){let n=x.objectKeys(e),a=x.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(let o of a){let u=Ne(r[o],e[o]);if(!u.valid)return{valid:!1};i[o]=u.data}return{valid:!0,data:i}}else if(t===f.array&&s===f.array){if(r.length!==e.length)return{valid:!1};let n=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],u=Ne(i,o);if(!u.valid)return{valid:!1};n.push(u.data)}return{valid:!0,data:n}}else return t===f.date&&s===f.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var X=class extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(Ee(a)||Ee(i))return h;let o=Ne(a.value,i.value);return o.valid?((Se(a)||Se(i))&&t.dirty(),{status:t.value,value:o.data}):(l(s,{code:c.invalid_intersection_types}),h)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};X.create=(r,e,t)=>new X({left:r,right:e,typeName:y.ZodIntersection,...g(t)});var j=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return l(s,{code:c.invalid_type,expected:f.array,received:s.parsedType}),h;if(s.data.length<this._def.items.length)return l(s,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),h;!this._def.rest&&s.data.length>this._def.items.length&&(l(s,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...s.data].map((i,o)=>{let u=this._def.items[o]||this._def.rest;return u?u._parse(new R(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>w.mergeArray(t,i)):w.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};j.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new j({items:r,typeName:y.ZodTuple,rest:null,...g(e)})};var Ce=class r extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return l(s,{code:c.invalid_type,expected:f.object,received:s.parsedType}),h;let n=[],a=this._def.keyType,i=this._def.valueType;for(let o in s.data)n.push({key:a._parse(new R(s,o,s.path,o)),value:i._parse(new R(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?w.mergeObjectAsync(t,n):w.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof _?new r({keyType:e,valueType:t,typeName:y.ZodRecord,...g(s)}):new r({keyType:U.create(),valueType:e,typeName:y.ZodRecord,...g(t)})}},me=class extends _{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return l(s,{code:c.invalid_type,expected:f.map,received:s.parsedType}),h;let n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([o,u],p)=>({key:n._parse(new R(s,o,s.path,[p,"key"])),value:a._parse(new R(s,u,s.path,[p,"value"]))}));if(s.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let u of i){let p=await u.key,v=await u.value;if(p.status==="aborted"||v.status==="aborted")return h;(p.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(p.value,v.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let u of i){let p=u.key,v=u.value;if(p.status==="aborted"||v.status==="aborted")return h;(p.status==="dirty"||v.status==="dirty")&&t.dirty(),o.set(p.value,v.value)}return{status:t.value,value:o}}}};me.create=(r,e,t)=>new me({valueType:e,keyType:r,typeName:y.ZodMap,...g(t)});var he=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return l(s,{code:c.invalid_type,expected:f.set,received:s.parsedType}),h;let n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(l(s,{code:c.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(l(s,{code:c.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let a=this._def.valueType;function i(u){let p=new Set;for(let v of u){if(v.status==="aborted")return h;v.status==="dirty"&&t.dirty(),p.add(v.value)}return{status:t.value,value:p}}let o=[...s.data.values()].map((u,p)=>a._parse(new R(s,u,s.path,p)));return s.common.async?Promise.all(o).then(u=>i(u)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};he.create=(r,e)=>new he({valueType:r,minSize:null,maxSize:null,typeName:y.ZodSet,...g(e)});var Ie=class r extends _{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return l(t,{code:c.invalid_type,expected:f.function,received:t.parsedType}),h;function s(o,u){return ge({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,de(),P].filter(p=>!!p),issueData:{code:c.invalid_arguments,argumentsError:u}})}function n(o,u){return ge({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,de(),P].filter(p=>!!p),issueData:{code:c.invalid_return_type,returnTypeError:u}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof F){let o=this;return E(async function(...u){let p=new S([]),v=await o._def.args.parseAsync(u,a).catch(ce=>{throw p.addIssue(s(u,ce)),p}),b=await Reflect.apply(i,this,v);return await o._def.returns._def.type.parseAsync(b,a).catch(ce=>{throw p.addIssue(n(b,ce)),p})})}else{let o=this;return E(function(...u){let p=o._def.args.safeParse(u,a);if(!p.success)throw new S([s(u,p.error)]);let v=Reflect.apply(i,this,p.data),b=o._def.returns.safeParse(v,a);if(!b.success)throw new S([n(v,b.error)]);return b.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:j.create(e).rest(M.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new r({args:e||j.create([]).rest(M.create()),returns:t||M.create(),typeName:y.ZodFunction,...g(s)})}},ee=class extends _{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ee.create=(r,e)=>new ee({getter:r,typeName:y.ZodLazy,...g(e)});var te=class extends _{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return l(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),h}return{status:"valid",value:e.data}}get value(){return this._def.value}};te.create=(r,e)=>new te({value:r,typeName:y.ZodLiteral,...g(e)});function We(r,e){return new re({values:r,typeName:y.ZodEnum,...g(e)})}var re=class r extends _{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),s=this._def.values;return l(t,{expected:x.joinValues(s),received:t.parsedType,code:c.invalid_type}),h}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),s=this._def.values;return l(t,{received:t.data,code:c.invalid_enum_value,options:s}),h}return E(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}};re.create=We;var se=class extends _{_parse(e){let t=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){let n=x.objectValues(t);return l(s,{expected:x.joinValues(n),received:s.parsedType,code:c.invalid_type}),h}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=x.objectValues(t);return l(s,{received:s.data,code:c.invalid_enum_value,options:n}),h}return E(e.data)}get enum(){return this._def.values}};se.create=(r,e)=>new se({values:r,typeName:y.ZodNativeEnum,...g(e)});var F=class extends _{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return l(t,{code:c.invalid_type,expected:f.promise,received:t.parsedType}),h;let s=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return E(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};F.create=(r,e)=>new F({type:r,typeName:y.ZodPromise,...g(e)});var O=class extends _{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{l(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){let i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return h;let u=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return u.status==="aborted"?h:u.status==="dirty"?q(u.value):t.value==="dirty"?q(u.value):u});{if(t.value==="aborted")return h;let o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?h:o.status==="dirty"?q(o.value):t.value==="dirty"?q(o.value):o}}if(n.type==="refinement"){let i=o=>{let u=n.refinement(o,a);if(s.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){let o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?h:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?h:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(s.common.async===!1){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!L(i))return h;let o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>L(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):h);x.assertNever(n)}};O.create=(r,e,t)=>new O({schema:r,typeName:y.ZodEffects,effect:e,...g(t)});O.createWithPreprocess=(r,e,t)=>new O({schema:e,effect:{type:"preprocess",transform:r},typeName:y.ZodEffects,...g(t)});var I=class extends _{_parse(e){return this._getType(e)===f.undefined?E(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};I.create=(r,e)=>new I({innerType:r,typeName:y.ZodOptional,...g(e)});var $=class extends _{_parse(e){return this._getType(e)===f.null?E(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$.create=(r,e)=>new $({innerType:r,typeName:y.ZodNullable,...g(e)});var ne=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return t.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ne.create=(r,e)=>new ne({innerType:r,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...g(e)});var ae=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return ue(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new S(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new S(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};ae.create=(r,e)=>new ae({innerType:r,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...g(e)});var ye=class extends _{_parse(e){if(this._getType(e)!==f.nan){let s=this._getOrReturnCtx(e);return l(s,{code:c.invalid_type,expected:f.nan,received:s.parsedType}),h}return{status:"valid",value:e.data}}};ye.create=r=>new ye({typeName:y.ZodNaN,...g(r)});var Vt=Symbol("zod_brand"),ve=class extends _{_parse(e){let{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},_e=class r extends _{_parse(e){let{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?h:a.status==="dirty"?(t.dirty(),q(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{let n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?h:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new r({in:e,out:t,typeName:y.ZodPipeline})}},ie=class extends _{_parse(e){let t=this._def.innerType._parse(e),s=n=>(L(n)&&(n.value=Object.freeze(n.value)),n);return ue(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}};ie.create=(r,e)=>new ie({innerType:r,typeName:y.ZodReadonly,...g(e)});function Ue(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function He(r,e={},t){return r?B.create().superRefine((s,n)=>{let a=r(s);if(a instanceof Promise)return a.then(i=>{if(!i){let o=Ue(e,s),u=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:u})}});if(!a){let i=Ue(e,s),o=i.fatal??t??!0;n.addIssue({code:"custom",...i,fatal:o})}}):B.create()}var zt={object:T.lazycreate},y;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(y||(y={}));var Lt=(r,e={message:`Input not instance of ${r.name}`})=>He(t=>t instanceof r,e),Je=U.create,Ye=W.create,Ut=ye.create,Bt=H.create,Ke=J.create,Ft=Y.create,qt=pe.create,Wt=K.create,Ht=G.create,Jt=B.create,Yt=M.create,Kt=A.create,Gt=fe.create,Qt=Z.create,Xt=T.create,er=T.strictCreate,tr=Q.create,rr=Te.create,sr=X.create,nr=j.create,ar=Ce.create,ir=me.create,or=he.create,cr=Ie.create,dr=ee.create,ur=te.create,lr=re.create,pr=se.create,fr=F.create,mr=O.create,hr=I.create,yr=$.create,gr=O.createWithPreprocess,vr=_e.create,_r=()=>Je().optional(),xr=()=>Ye().optional(),kr=()=>Ke().optional(),br={string:(r=>U.create({...r,coerce:!0})),number:(r=>W.create({...r,coerce:!0})),boolean:(r=>J.create({...r,coerce:!0})),bigint:(r=>H.create({...r,coerce:!0})),date:(r=>Y.create({...r,coerce:!0}))};var wr=h;var Er=/^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/,Sr=/^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/,Tr=[/node_modules/,/\bnative\b/,/\[native code\]/,/InternalBytecode/],Cr=/\.(?:js)?bundle\b/;function Ir(r){return r.replace(/^address at /,"")}function Ge(r){if(!r)return[];let e=[];for(let t of r.split(`
|
|
2
|
-
`)){let s=Er.exec(t)??Sr.exec(t);if(!s)continue;let[,n,a,i,o]=s,u=Ir(a??"");if(e.push({fn:n||void 0,file:u,line:Number(i),col:Number(o),inApp:Cr.test(u)?!/^(?:anonymous|eval|global code)$/.test(n??""):!Tr.some(p=>p.test(u))}),e.length>=100)break}return e}var Rr=d.string().min(1).max(64).regex(/^[a-z0-9_]+(\.[a-z0-9_]+)*$/,"flow must be dotted lowercase, e.g. auth.login"),Or=d.record(d.string().max(200)).optional(),je=d.string().datetime({offset:!0}),Ar=d.object({model:d.string().optional(),manufacturer:d.string().optional(),brand:d.string().optional(),type:d.enum(["phone","tablet","desktop","tv","unknown"]).default("unknown"),isEmulator:d.boolean().optional(),memoryMb:d.number().optional(),screen:d.object({width:d.number(),height:d.number(),scale:d.number().optional()}).optional()}),Nr=d.object({name:d.string(),version:d.string().optional()}),jr=d.object({id:d.string().min(1),version:d.string().optional(),build:d.string().optional(),environment:d.string().default("production")}),$r=d.object({name:d.string(),version:d.string().optional(),engine:d.string().optional()}),Pr=d.object({type:d.enum(["wifi","cellular","ethernet","none","unknown"]).default("unknown"),effectiveType:d.string().optional(),isConnected:d.boolean().optional()}),Dr=d.object({app:jr,device:Ar.default({}),os:Nr,runtime:$r,network:Pr.optional(),locale:d.string().optional(),timezone:d.string().optional()}),Mr=d.object({ts:je,category:d.enum(["navigation","network","ui","log","event","custom"]),message:d.string().max(500),level:d.enum(["debug","info","warning","error"]).default("info"),data:d.record(d.union([d.string(),d.number(),d.boolean(),d.null()])).optional()}),Zr=d.object({fn:d.string().optional(),file:d.string().optional(),line:d.number().optional(),col:d.number().optional(),inApp:d.boolean().optional()}),Vr=d.enum(["low","medium","high","critical"]),$e=d.object({id:d.string().min(8).max(64),ts:je,flow:Rr.optional(),step:d.string().max(64).optional(),tags:Or}),zr=$e.extend({type:d.literal("error"),handled:d.boolean().default(!0),severity:Vr.optional(),error:d.object({name:d.string().max(200).default("Error"),message:d.string().max(2e3),stack:d.string().max(2e4).optional(),frames:d.array(Zr).max(100).optional()}),breadcrumbs:d.array(Mr).max(50).optional(),request:d.object({method:d.string().max(10),url:d.string().max(500),status:d.number().int().optional(),durationMs:d.number().optional()}).optional()}),Lr=$e.extend({type:d.literal("event"),name:d.string().min(1).max(100),outcome:d.enum(["success","failure","abandoned"]).optional(),props:d.record(d.union([d.string(),d.number(),d.boolean(),d.null()])).optional()}),Ur=$e.extend({type:d.literal("session"),status:d.enum(["started","errored","crashed"])}),Br=d.discriminatedUnion("type",[zr,Lr,Ur]),Xe=d.object({schema:d.literal(1).default(1),sdk:d.object({name:d.string(),version:d.string()}),context:Dr,user:d.object({id:d.string().optional(),anonymousId:d.string()}).optional(),session:d.object({id:d.string(),startedAt:je}),events:d.array(Br).min(1).max(100)});import{createHash as Fr}from"crypto";function qr(r){return r.replace(/https?:\/\/\S+/g,"<url>").replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,"<uuid>").replace(/\b[0-9a-f]{16,}\b/gi,"<hex>").replace(/[\w.+-]+@[\w-]+\.[\w.]+/g,"<email>").replace(/\d+(\.\d+)?/g,"<n>").replace(/(["'`]).*?\1/g,"<str>").trim().slice(0,300)}function et(r){if(!r)return"";let e=r.replace(/\/\/&.*$/,"").replace(/[?#].*$/,"").replace(/^[a-z]+:\/\/[^/]+/i,"");if(/\.(?:js)?bundle$/.test(e))return e.replace(/^.*\//,"");for(let t of["/src/","/lib/","/app/"]){let s=e.lastIndexOf(t);if(s>=0){e=e.slice(s+1);break}}return e.replace(/\.[0-9a-f]{6,}\./g,".")}function tt(r){return r?.find(e=>e.inApp!==!1&&e.file)??r?.[0]}function rt(r){let e=tt(r.error.frames);if(!e)return;let t=et(e.file)+(e.line?`:${e.line}`:"");return e.fn?`${e.fn} (${t})`:t}function st(r){let e=tt(r.error.frames),t=r.request,s=t?`${t.method.toUpperCase()} ${t.url} ${t.status?`${Math.floor(t.status/100)}xx`:"failed"}`:e?`${e.fn??"?"}@${et(e.file)}`:qr(r.error.message);return Fr("sha256").update([r.error.name,s,r.flow??""].join("|")).digest("hex").slice(0,24)}function nt(r){return`${r.error.name}: ${r.error.message}`.slice(0,200)}function at(r){let e={};for(let t of(r??"").split(",").map(s=>s.trim()).filter(Boolean)){let[s,n]=t.split(":");s&&n&&(e[s]=n)}return e}var Wr=r=>r.slice(0,10);function Hr(r,e){let t=Date.parse(r),s=e.getTime();return Number.isNaN(t)||t>s+5*6e4||t<s-7*864e5?e.toISOString():new Date(t).toISOString()}function Jr(r){return{...r,os:{...r.os,name:r.os.name.toLowerCase()},runtime:{...r.runtime,name:r.runtime.name.toLowerCase()}}}async function it(r,e,t){let s=t.now?.()??new Date;if(!e||!t.keys[e])return{status:401,body:{ok:!1,error:"invalid ingest key"}};if(Buffer.byteLength(r)>(t.maxBytes??512*1024))return{status:413,body:{ok:!1,error:"payload too large"}};let n;try{n=JSON.parse(r)}catch{return{status:400,body:{ok:!1,error:"invalid json"}}}let a=Xe.safeParse(n);if(!a.success)return{status:400,body:{ok:!1,error:"invalid envelope",issues:a.error.flatten()}};let i=a.data,o=i.context.app.id;if(t.keys[e]!==o&&t.keys[e]!=="*")return{status:403,body:{ok:!1,error:`key not allowed for app ${o}`}};let u=Jr(i.context),p=s.toISOString(),v=[],b=[],oe=new Map;for(let ce of i.events){let k={...ce,ts:Hr(ce.ts,s)};k.type==="error"&&!k.error.frames?.length&&k.error.stack&&(k.error.frames=Ge(k.error.stack));let xe=Wr(k.ts);if(k.type==="session"){b.push({app:o,day:xe,dimension:"session",key:`${u.app.version||"unknown"}|${k.status}`,kind:"event",by:1});continue}let Me=k.type==="error"?"error":"event",V=(C,Re)=>b.push({app:o,day:xe,dimension:C,key:Re||"unknown",kind:Me,by:1}),z;if(k.type==="error"){z=st(k);let C=oe.get(z),Re={app:o,day:xe,fingerprint:z,event:k,context:u,user:i.user,sessionId:i.session.id,receivedAt:p};oe.set(z,{app:o,fingerprint:z,title:nt(k),culprit:rt(k),flow:k.flow,by:(C?.by??0)+1,ts:C&&C.ts>k.ts?C.ts:k.ts,firstTs:C&&C.firstTs<k.ts?C.firstTs:k.ts,lastEvent:C&&C.ts>k.ts?C.lastEvent:Re}),V("issue",z),k.request&&V("endpoint",`${k.request.method.toUpperCase()} ${k.request.url}`),b.push({app:o,day:k.ts.slice(0,13),dimension:"issueHour",key:z,kind:Me,by:1})}V("total","all"),V("flow",k.flow??"untagged"),V("os",`${u.os.name} ${u.os.version??""}`.trim()),V("appVersion",u.app.version),V("deviceModel",u.device.model),k.type==="event"&&k.outcome&&k.flow&&V("flowOutcome",`${k.flow}|${k.outcome}`),v.push({app:o,day:xe,fingerprint:z,event:k,context:u,user:i.user,sessionId:i.session.id,receivedAt:p})}return await t.store.registerApp(o),await Promise.all([v.length?t.store.writeEvents(v):void 0,t.store.upsertIssues([...oe.values()]),t.store.incrementRollups(b)]),{status:202,body:{ok:!0,accepted:i.events.length}}}var Pe={"access-control-allow-origin":"*","access-control-allow-methods":"POST, OPTIONS","access-control-allow-headers":"content-type, x-debug-key","access-control-max-age":"86400"};function ot(r){return async e=>{let t=e.requestContext?.http?.method??e.httpMethod??"POST";if(t==="OPTIONS")return{statusCode:204,headers:Pe,body:""};if(t!=="POST")return De(405,{ok:!1,error:"method not allowed"});let s=Object.fromEntries(Object.entries(e.headers??{}).map(([a,i])=>[a.toLowerCase(),i])),n=e.isBase64Encoded?Buffer.from(e.body??"","base64").toString("utf8"):e.body??"";try{let a=await it(n,s["x-debug-key"],r);return De(a.status,a.body)}catch(a){return console.error("[deBug] ingest failed",a),De(500,{ok:!1,error:"internal"})}}}var De=(r,e)=>({statusCode:r,headers:{...Pe,"content-type":"application/json"},body:JSON.stringify(e)});var Gr=Kr.from(new Yr({}),{marshallOptions:{removeUndefinedValues:!0}}),Hs=ot({store:new we(Gr,{table:process.env.DEBUG_TABLE??"debugkit"}),keys:at(process.env.DEBUG_INGEST_KEYS)});export{Hs as handler};
|
|
1
|
+
var Ot=Object.defineProperty;var Ct=(s,e)=>{for(var t in e)Ot(s,t,{get:e[t],enumerable:!0})};import{DynamoDBClient as Tr}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as Ir}from"@aws-sdk/lib-dynamodb";import{BatchWriteCommand as lr,GetCommand as He,PutCommand as dr,QueryCommand as qe,UpdateCommand as B}from"@aws-sdk/lib-dynamodb";var u={};Ct(u,{BRAND:()=>rs,DIRTY:()=>G,EMPTY_PATH:()=>Dt,INVALID:()=>h,NEVER:()=>Ls,OK:()=>S,ParseStatus:()=>w,Schema:()=>x,ZodAny:()=>H,ZodArray:()=>z,ZodBigInt:()=>J,ZodBoolean:()=>Q,ZodBranded:()=>we,ZodCatch:()=>ue,ZodDate:()=>X,ZodDefault:()=>ce,ZodDiscriminatedUnion:()=>Ie,ZodEffects:()=>$,ZodEnum:()=>ie,ZodError:()=>I,ZodFirstPartyTypeKind:()=>y,ZodFunction:()=>Oe,ZodIntersection:()=>re,ZodIssueCode:()=>d,ZodLazy:()=>ne,ZodLiteral:()=>ae,ZodMap:()=>ve,ZodNaN:()=>xe,ZodNativeEnum:()=>oe,ZodNever:()=>P,ZodNull:()=>te,ZodNullable:()=>j,ZodNumber:()=>Y,ZodObject:()=>R,ZodOptional:()=>O,ZodParsedType:()=>f,ZodPipeline:()=>Se,ZodPromise:()=>q,ZodReadonly:()=>le,ZodRecord:()=>Re,ZodSchema:()=>x,ZodSet:()=>_e,ZodString:()=>K,ZodSymbol:()=>ge,ZodTransformer:()=>$,ZodTuple:()=>U,ZodType:()=>x,ZodUndefined:()=>ee,ZodUnion:()=>se,ZodUnknown:()=>L,ZodVoid:()=>ye,addIssueToContext:()=>p,any:()=>ps,array:()=>gs,bigint:()=>os,boolean:()=>mt,coerce:()=>Zs,custom:()=>dt,date:()=>cs,datetimeRegex:()=>ut,defaultErrorMap:()=>V,discriminatedUnion:()=>xs,effect:()=>$s,enum:()=>Rs,function:()=>Es,getErrorMap:()=>fe,getParsedType:()=>D,instanceof:()=>as,intersection:()=>ks,isAborted:()=>Ee,isAsync:()=>me,isDirty:()=>Te,isValid:()=>W,late:()=>ns,lazy:()=>Ts,literal:()=>Is,makeIssue:()=>be,map:()=>Ss,nan:()=>is,nativeEnum:()=>Os,never:()=>ms,null:()=>ds,nullable:()=>Ps,number:()=>ft,object:()=>ys,objectUtil:()=>Ve,oboolean:()=>Vs,onumber:()=>Ms,optional:()=>Ns,ostring:()=>js,pipeline:()=>Us,preprocess:()=>Ds,promise:()=>Cs,quotelessJson:()=>$t,record:()=>ws,set:()=>As,setErrorMap:()=>Pt,strictObject:()=>vs,string:()=>pt,symbol:()=>us,transformer:()=>$s,tuple:()=>bs,undefined:()=>ls,union:()=>_s,unknown:()=>fs,util:()=>b,void:()=>hs});var b;(function(s){s.assertEqual=n=>{};function e(n){}s.assertIs=e;function t(n){throw new Error}s.assertNever=t,s.arrayToEnum=n=>{let a={};for(let i of n)a[i]=i;return a},s.getValidEnumValues=n=>{let a=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(let o of a)i[o]=n[o];return s.objectValues(i)},s.objectValues=n=>s.objectKeys(n).map(function(a){return n[a]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let a=[];for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},s.find=(n,a)=>{for(let i of n)if(a(i))return i},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}s.joinValues=r,s.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(b||(b={}));var Ve;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Ve||(Ve={}));var f=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),D=s=>{switch(typeof s){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(s)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(s)?f.array:s===null?f.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?f.promise:typeof Map<"u"&&s instanceof Map?f.map:typeof Set<"u"&&s instanceof Set?f.set:typeof Date<"u"&&s instanceof Date?f.date:f.object;default:return f.unknown}};var d=b.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$t=s=>JSON.stringify(s,null,2).replace(/"([^"]+)":/g,"$1:"),I=class s extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},r={_errors:[]},n=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let o=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(t(i))):o[l]=o[l]||{_errors:[]},o=o[l],c++}}};return n(this),r}static assert(e){if(!(e instanceof s))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let n of this.issues)if(n.path.length>0){let a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};I.create=s=>new I(s);var Nt=(s,e)=>{let t;switch(s.code){case d.invalid_type:s.received===f.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,b.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${b.joinValues(s.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${b.joinValues(s.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${b.joinValues(s.options)}, received '${s.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:b.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case d.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case d.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,b.assertNever(s)}return{message:t}},V=Nt;var nt=V;function Pt(s){nt=s}function fe(){return nt}var be=s=>{let{data:e,path:t,errorMaps:r,issueData:n}=s,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)o=l(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},Dt=[];function p(s,e){let t=fe(),r=be({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===V?void 0:V].filter(n=>!!n)});s.common.issues.push(r)}var w=class s{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return h;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let a=await n.key,i=await n.value;r.push({key:a,value:i})}return s.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return h;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(r[a.value]=i.value)}return{status:e.value,value:r}}},h=Object.freeze({status:"aborted"}),G=s=>({status:"dirty",value:s}),S=s=>({status:"valid",value:s}),Ee=s=>s.status==="aborted",Te=s=>s.status==="dirty",W=s=>s.status==="valid",me=s=>typeof Promise<"u"&&s instanceof Promise;var m;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));var C=class{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},at=(s,e)=>{if(W(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new I(s.common.issues);return this._error=t,this._error}}};function _(s){if(!s)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:n}=s;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{let{message:c}=s;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??r??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:n}}var x=class{get description(){return this._def.description}_getType(e){return D(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(me(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},n=this._parseSync({data:e,path:r.path,parent:r});return at(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return W(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>W(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(me(n)?n:Promise.resolve(n));return at(r,a)}refine(e,t){let r=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{let i=e(n),o=()=>a.addIssue({code:d.custom,...r(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof t=="function"?t(r,n):t),!1))}_refinement(e){return new $({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return O.create(this,this._def)}nullable(){return j.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return z.create(this)}promise(){return q.create(this,this._def)}or(e){return se.create([this,e],this._def)}and(e){return re.create(this,e,this._def)}transform(e){return new $({..._(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ce({..._(this._def),innerType:this,defaultValue:t,typeName:y.ZodDefault})}brand(){return new we({typeName:y.ZodBranded,type:this,..._(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new ue({..._(this._def),innerType:this,catchValue:t,typeName:y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Se.create(this,e)}readonly(){return le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ut=/^c[^\s-]{8,}$/i,jt=/^[0-9a-z]+$/,Mt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Vt=/^[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,Zt=/^[a-z0-9_-]{21}$/i,Lt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zt=/^[-+]?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)?)??$/,Bt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ft="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ze,Wt=/^(?:(?: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])$/,Kt=/^(?:(?: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])$/,Ht=/^(([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]))$/,qt=/^(([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])$/,Gt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ot="((\\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])))",Jt=new RegExp(`^${ot}$`);function ct(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);let t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Qt(s){return new RegExp(`^${ct(s)}$`)}function ut(s){let e=`${ot}T${ct(s)}`,t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Xt(s,e){return!!((e==="v4"||!e)&&Wt.test(s)||(e==="v6"||!e)&&Ht.test(s))}function es(s,e){if(!Lt.test(s))return!1;try{let[t]=s.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function ts(s,e){return!!((e==="v4"||!e)&&Kt.test(s)||(e==="v6"||!e)&&qt.test(s))}var K=class s extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.string,received:a.parsedType}),h}let r=new w,n;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?p(n,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&p(n,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")Bt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"email",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")Ze||(Ze=new RegExp(Ft,"u")),Ze.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"emoji",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")Vt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"uuid",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")Zt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"nanoid",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")Ut.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")jt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cuid2",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")Mt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ulid",code:d.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),p(n,{validation:"url",code:d.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"regex",code:d.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?ut(a).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?Jt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?Qt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?zt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"duration",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?Xt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"ip",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?es(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"jwt",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?ts(e.data,a.version)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"cidr",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?Gt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64",code:d.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?Yt.test(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{validation:"base64url",code:d.invalid_string,message:a.message}),r.dirty()):b.assertNever(a);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(n=>e.test(n),{validation:t,code:d.invalid_string,...m.errToObj(r)})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new s({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};K.create=s=>new K({checks:[],typeName:y.ZodString,coerce:s?.coerce??!1,..._(s)});function ss(s,e){let t=(s.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=t>r?t:r,a=Number.parseInt(s.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}var Y=class s extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.number,received:a.parsedType}),h}let r,n=new w;for(let a of this._def.checks)a.kind==="int"?b.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:d.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?ss(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),p(r,{code:d.not_finite,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Y.create=s=>new Y({checks:[],typeName:y.ZodNumber,coerce:s?.coerce||!1,..._(s)});var J=class s extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let r,n=new w;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),p(r,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.bigint,received:t.parsedType}),h}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};J.create=s=>new J({checks:[],typeName:y.ZodBigInt,coerce:s?.coerce??!1,..._(s)});var Q=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.boolean,received:r.parsedType}),h}return S(e.data)}};Q.create=s=>new Q({typeName:y.ZodBoolean,coerce:s?.coerce||!1,..._(s)});var X=class s extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:f.date,received:a.parsedType}),h}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_date}),h}let r=new w,n;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):b.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};X.create=s=>new X({checks:[],coerce:s?.coerce||!1,typeName:y.ZodDate,..._(s)});var ge=class extends x{_parse(e){if(this._getType(e)!==f.symbol){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.symbol,received:r.parsedType}),h}return S(e.data)}};ge.create=s=>new ge({typeName:y.ZodSymbol,..._(s)});var ee=class extends x{_parse(e){if(this._getType(e)!==f.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.undefined,received:r.parsedType}),h}return S(e.data)}};ee.create=s=>new ee({typeName:y.ZodUndefined,..._(s)});var te=class extends x{_parse(e){if(this._getType(e)!==f.null){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.null,received:r.parsedType}),h}return S(e.data)}};te.create=s=>new te({typeName:y.ZodNull,..._(s)});var H=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return S(e.data)}};H.create=s=>new H({typeName:y.ZodAny,..._(s)});var L=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return S(e.data)}};L.create=s=>new L({typeName:y.ZodUnknown,..._(s)});var P=class extends x{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:f.never,received:t.parsedType}),h}};P.create=s=>new P({typeName:y.ZodNever,..._(s)});var ye=class extends x{_parse(e){if(this._getType(e)!==f.undefined){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.void,received:r.parsedType}),h}return S(e.data)}};ye.create=s=>new ye({typeName:y.ZodVoid,..._(s)});var z=class s extends x{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.array)return p(t,{code:d.invalid_type,expected:f.array,received:t.parsedType}),h;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(p(t,{code:i?d.too_big:d.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(p(t,{code:d.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(p(t,{code:d.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new C(t,i,t.path,o)))).then(i=>w.mergeArray(r,i));let a=[...t.data].map((i,o)=>n.type._parseSync(new C(t,i,t.path,o)));return w.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new s({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new s({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new s({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}};z.create=(s,e)=>new z({type:s,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,..._(e)});function he(s){if(s instanceof R){let e={};for(let t in s.shape){let r=s.shape[t];e[t]=O.create(he(r))}return new R({...s._def,shape:()=>e})}else return s instanceof z?new z({...s._def,type:he(s.element)}):s instanceof O?O.create(he(s.unwrap())):s instanceof j?j.create(he(s.unwrap())):s instanceof U?U.create(s.items.map(e=>he(e))):s}var R=class s extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let l=this._getOrReturnCtx(e);return p(l,{code:d.invalid_type,expected:f.object,received:l.parsedType}),h}let{status:r,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof P&&this._def.unknownKeys==="strip"))for(let l in n.data)i.includes(l)||o.push(l);let c=[];for(let l of i){let g=a[l],k=n.data[l];c.push({key:{status:"valid",value:l},value:g._parse(new C(n,k,n.path,l)),alwaysSet:l in n.data})}if(this._def.catchall instanceof P){let l=this._def.unknownKeys;if(l==="passthrough")for(let g of o)c.push({key:{status:"valid",value:g},value:{status:"valid",value:n.data[g]}});else if(l==="strict")o.length>0&&(p(n,{code:d.unrecognized_keys,keys:o}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let g of o){let k=n.data[g];c.push({key:{status:"valid",value:g},value:l._parse(new C(n,k,n.path,g)),alwaysSet:g in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let l=[];for(let g of c){let k=await g.key,A=await g.value;l.push({key:k,value:A,alwaysSet:g.alwaysSet})}return l}).then(l=>w.mergeObjectSync(r,l)):w.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new s({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new s({...this._def,unknownKeys:"strip"})}passthrough(){return new s({...this._def,unknownKeys:"passthrough"})}extend(e){return new s({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new s({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new s({...this._def,catchall:e})}pick(e){let t={};for(let r of b.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new s({...this._def,shape:()=>t})}omit(e){let t={};for(let r of b.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new s({...this._def,shape:()=>t})}deepPartial(){return he(this)}partial(e){let t={};for(let r of b.objectKeys(this.shape)){let n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new s({...this._def,shape:()=>t})}required(e){let t={};for(let r of b.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof O;)a=a._def.innerType;t[r]=a}return new s({...this._def,shape:()=>t})}keyof(){return lt(b.objectKeys(this.shape))}};R.create=(s,e)=>new R({shape:()=>s,unknownKeys:"strip",catchall:P.create(),typeName:y.ZodObject,..._(e)});R.strictCreate=(s,e)=>new R({shape:()=>s,unknownKeys:"strict",catchall:P.create(),typeName:y.ZodObject,..._(e)});R.lazycreate=(s,e)=>new R({shape:s,unknownKeys:"strip",catchall:P.create(),typeName:y.ZodObject,..._(e)});var se=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new I(o.ctx.common.issues));return p(t,{code:d.invalid_union,unionErrors:i}),h}if(t.common.async)return Promise.all(r.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a,i=[];for(let c of r){let l={...t,common:{...t.common,issues:[]},parent:null},g=c._parseSync({data:t.data,path:t.path,parent:l});if(g.status==="valid")return g;g.status==="dirty"&&!a&&(a={result:g,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new I(c));return p(t,{code:d.invalid_union,unionErrors:o}),h}}get options(){return this._def.options}};se.create=(s,e)=>new se({options:s,typeName:y.ZodUnion,..._(e)});var Z=s=>s instanceof ne?Z(s.schema):s instanceof $?Z(s.innerType()):s instanceof ae?[s.value]:s instanceof ie?s.options:s instanceof oe?b.objectValues(s.enum):s instanceof ce?Z(s._def.innerType):s instanceof ee?[void 0]:s instanceof te?[null]:s instanceof O?[void 0,...Z(s.unwrap())]:s instanceof j?[null,...Z(s.unwrap())]:s instanceof we||s instanceof le?Z(s.unwrap()):s instanceof ue?Z(s._def.innerType):[],Ie=class s extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:d.invalid_type,expected:f.object,received:t.parsedType}),h;let r=this.discriminator,n=t.data[r],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),h)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let a of t){let i=Z(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a)}}return new s({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,..._(r)})}};function Le(s,e){let t=D(s),r=D(e);if(s===e)return{valid:!0,data:s};if(t===f.object&&r===f.object){let n=b.objectKeys(e),a=b.objectKeys(s).filter(o=>n.indexOf(o)!==-1),i={...s,...e};for(let o of a){let c=Le(s[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(t===f.array&&r===f.array){if(s.length!==e.length)return{valid:!1};let n=[];for(let a=0;a<s.length;a++){let i=s[a],o=e[a],c=Le(i,o);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return t===f.date&&r===f.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}var re=class extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(a,i)=>{if(Ee(a)||Ee(i))return h;let o=Le(a.value,i.value);return o.valid?((Te(a)||Te(i))&&t.dirty(),{status:t.value,value:o.data}):(p(r,{code:d.invalid_intersection_types}),h)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};re.create=(s,e,t)=>new re({left:s,right:e,typeName:y.ZodIntersection,..._(t)});var U=class s extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.array)return p(r,{code:d.invalid_type,expected:f.array,received:r.parsedType}),h;if(r.data.length<this._def.items.length)return p(r,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),h;!this._def.rest&&r.data.length>this._def.items.length&&(p(r,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new C(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>w.mergeArray(t,i)):w.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new s({...this._def,rest:e})}};U.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new U({items:s,typeName:y.ZodTuple,rest:null,..._(e)})};var Re=class s extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.object)return p(r,{code:d.invalid_type,expected:f.object,received:r.parsedType}),h;let n=[],a=this._def.keyType,i=this._def.valueType;for(let o in r.data)n.push({key:a._parse(new C(r,o,r.path,o)),value:i._parse(new C(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?w.mergeObjectAsync(t,n):w.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof x?new s({keyType:e,valueType:t,typeName:y.ZodRecord,..._(r)}):new s({keyType:K.create(),valueType:e,typeName:y.ZodRecord,..._(t)})}},ve=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.map)return p(r,{code:d.invalid_type,expected:f.map,received:r.parsedType}),h;let n=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,c],l)=>({key:n._parse(new C(r,o,r.path,[l,"key"])),value:a._parse(new C(r,c,r.path,[l,"value"]))}));if(r.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,g=await c.value;if(l.status==="aborted"||g.status==="aborted")return h;(l.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(l.value,g.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let l=c.key,g=c.value;if(l.status==="aborted"||g.status==="aborted")return h;(l.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(l.value,g.value)}return{status:t.value,value:o}}}};ve.create=(s,e,t)=>new ve({valueType:e,keyType:s,typeName:y.ZodMap,..._(t)});var _e=class s extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==f.set)return p(r,{code:d.invalid_type,expected:f.set,received:r.parsedType}),h;let n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(p(r,{code:d.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(p(r,{code:d.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let l=new Set;for(let g of c){if(g.status==="aborted")return h;g.status==="dirty"&&t.dirty(),l.add(g.value)}return{status:t.value,value:l}}let o=[...r.data.values()].map((c,l)=>a._parse(new C(r,c,r.path,l)));return r.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new s({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new s({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};_e.create=(s,e)=>new _e({valueType:s,minSize:null,maxSize:null,typeName:y.ZodSet,..._(e)});var Oe=class s extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:d.invalid_type,expected:f.function,received:t.parsedType}),h;function r(o,c){return be({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,fe(),V].filter(l=>!!l),issueData:{code:d.invalid_arguments,argumentsError:c}})}function n(o,c){return be({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,fe(),V].filter(l=>!!l),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof q){let o=this;return S(async function(...c){let l=new I([]),g=await o._def.args.parseAsync(c,a).catch(E=>{throw l.addIssue(r(c,E)),l}),k=await Reflect.apply(i,this,g);return await o._def.returns._def.type.parseAsync(k,a).catch(E=>{throw l.addIssue(n(k,E)),l})})}else{let o=this;return S(function(...c){let l=o._def.args.safeParse(c,a);if(!l.success)throw new I([r(c,l.error)]);let g=Reflect.apply(i,this,l.data),k=o._def.returns.safeParse(g,a);if(!k.success)throw new I([n(g,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new s({...this._def,args:U.create(e).rest(L.create())})}returns(e){return new s({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new s({args:e||U.create([]).rest(L.create()),returns:t||L.create(),typeName:y.ZodFunction,..._(r)})}},ne=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ne.create=(s,e)=>new ne({getter:s,typeName:y.ZodLazy,..._(e)});var ae=class extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),h}return{status:"valid",value:e.data}}get value(){return this._def.value}};ae.create=(s,e)=>new ae({value:s,typeName:y.ZodLiteral,..._(e)});function lt(s,e){return new ie({values:s,typeName:y.ZodEnum,..._(e)})}var ie=class s extends x{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{expected:b.joinValues(r),received:t.parsedType,code:d.invalid_type}),h}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return p(t,{received:t.data,code:d.invalid_enum_value,options:r}),h}return S(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return s.create(e,{...this._def,...t})}exclude(e,t=this._def){return s.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};ie.create=lt;var oe=class extends x{_parse(e){let t=b.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==f.string&&r.parsedType!==f.number){let n=b.objectValues(t);return p(r,{expected:b.joinValues(n),received:r.parsedType,code:d.invalid_type}),h}if(this._cache||(this._cache=new Set(b.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=b.objectValues(t);return p(r,{received:r.data,code:d.invalid_enum_value,options:n}),h}return S(e.data)}get enum(){return this._def.values}};oe.create=(s,e)=>new oe({values:s,typeName:y.ZodNativeEnum,..._(e)});var q=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:d.invalid_type,expected:f.promise,received:t.parsedType}),h;let r=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return S(r.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};q.create=(s,e)=>new q({type:s,typeName:y.ZodPromise,..._(e)});var $=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{p(r,i),i.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){let i=n.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return h;let c=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return c.status==="aborted"?h:c.status==="dirty"?G(c.value):t.value==="dirty"?G(c.value):c});{if(t.value==="aborted")return h;let o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?h:o.status==="dirty"?G(o.value):t.value==="dirty"?G(o.value):o}}if(n.type==="refinement"){let i=o=>{let c=n.refinement(o,a);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?h:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?h:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!W(i))return h;let o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>W(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):h);b.assertNever(n)}};$.create=(s,e,t)=>new $({schema:s,typeName:y.ZodEffects,effect:e,..._(t)});$.createWithPreprocess=(s,e,t)=>new $({schema:e,effect:{type:"preprocess",transform:s},typeName:y.ZodEffects,..._(t)});var O=class extends x{_parse(e){return this._getType(e)===f.undefined?S(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};O.create=(s,e)=>new O({innerType:s,typeName:y.ZodOptional,..._(e)});var j=class extends x{_parse(e){return this._getType(e)===f.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j.create=(s,e)=>new j({innerType:s,typeName:y.ZodNullable,..._(e)});var ce=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===f.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ce.create=(s,e)=>new ce({innerType:s,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var ue=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return me(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new I(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new I(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};ue.create=(s,e)=>new ue({innerType:s,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var xe=class extends x{_parse(e){if(this._getType(e)!==f.nan){let r=this._getOrReturnCtx(e);return p(r,{code:d.invalid_type,expected:f.nan,received:r.parsedType}),h}return{status:"valid",value:e.data}}};xe.create=s=>new xe({typeName:y.ZodNaN,..._(s)});var rs=Symbol("zod_brand"),we=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},Se=class s extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?h:a.status==="dirty"?(t.dirty(),G(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?h:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new s({in:e,out:t,typeName:y.ZodPipeline})}},le=class extends x{_parse(e){let t=this._def.innerType._parse(e),r=n=>(W(n)&&(n.value=Object.freeze(n.value)),n);return me(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}};le.create=(s,e)=>new le({innerType:s,typeName:y.ZodReadonly,..._(e)});function it(s,e){let t=typeof s=="function"?s(e):typeof s=="string"?{message:s}:s;return typeof t=="string"?{message:t}:t}function dt(s,e={},t){return s?H.create().superRefine((r,n)=>{let a=s(r);if(a instanceof Promise)return a.then(i=>{if(!i){let o=it(e,r),c=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=it(e,r),o=i.fatal??t??!0;n.addIssue({code:"custom",...i,fatal:o})}}):H.create()}var ns={object:R.lazycreate},y;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(y||(y={}));var as=(s,e={message:`Input not instance of ${s.name}`})=>dt(t=>t instanceof s,e),pt=K.create,ft=Y.create,is=xe.create,os=J.create,mt=Q.create,cs=X.create,us=ge.create,ls=ee.create,ds=te.create,ps=H.create,fs=L.create,ms=P.create,hs=ye.create,gs=z.create,ys=R.create,vs=R.strictCreate,_s=se.create,xs=Ie.create,ks=re.create,bs=U.create,ws=Re.create,Ss=ve.create,As=_e.create,Es=Oe.create,Ts=ne.create,Is=ae.create,Rs=ie.create,Os=oe.create,Cs=q.create,$s=$.create,Ns=O.create,Ps=j.create,Ds=$.createWithPreprocess,Us=Se.create,js=()=>pt().optional(),Ms=()=>ft().optional(),Vs=()=>mt().optional(),Zs={string:(s=>K.create({...s,coerce:!0})),number:(s=>Y.create({...s,coerce:!0})),boolean:(s=>Q.create({...s,coerce:!0})),bigint:(s=>J.create({...s,coerce:!0})),date:(s=>X.create({...s,coerce:!0}))};var Ls=h;function zs(s,e){let t=s.split(/[.+-]/),r=e.split(/[.+-]/);for(let n=0;n<Math.max(t.length,r.length);n++){let a=t[n]??"",i=r[n]??"",o=/^\d+$/.test(a)&&/^\d+$/.test(i)?Number(a)-Number(i):a.localeCompare(i);if(o)return o}return 0}function ht(s){let e=s.version||"unknown";return s.update?`${e}+${s.update.slice(0,12)}`:e}function ze(s,e,t,r){return s&&e?zs(e,s)>=0:!!t&&r>t}var Bs=/^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/,Fs=/^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/,Ws=[/node_modules/,/\bnative\b/,/\[native code\]/,/InternalBytecode/],Ks=/\.(?:js)?bundle\b/;function Hs(s){return s.replace(/^address at /,"")}function gt(s){if(!s)return[];let e=[];for(let t of s.split(`
|
|
2
|
+
`)){let r=Bs.exec(t)??Fs.exec(t);if(!r)continue;let[,n,a,i,o]=r,c=Hs(a??"");if(e.push({fn:n||void 0,file:c,line:Number(i),col:Number(o),inApp:Ks.test(c)?!/^(?:anonymous|eval|global code)$/.test(n??""):!Ws.some(l=>l.test(c))}),e.length>=100)break}return e}var qs=u.string().min(1).max(64).regex(/^[a-z0-9_]+(\.[a-z0-9_]+)*$/,"flow must be dotted lowercase, e.g. auth.login"),Gs=u.record(u.string().max(200)).optional(),Be=u.string().datetime({offset:!0}),Ys=u.object({model:u.string().optional(),manufacturer:u.string().optional(),brand:u.string().optional(),type:u.enum(["phone","tablet","desktop","tv","unknown"]).default("unknown"),isEmulator:u.boolean().optional(),memoryMb:u.number().optional(),screen:u.object({width:u.number(),height:u.number(),scale:u.number().optional()}).optional()}),Js=u.object({name:u.string(),version:u.string().optional()}),Qs=u.object({id:u.string().min(1),version:u.string().optional(),build:u.string().optional(),update:u.string().max(100).optional(),environment:u.string().default("production")}),Xs=u.object({name:u.string(),version:u.string().optional(),engine:u.string().optional()}),er=u.object({type:u.enum(["wifi","cellular","ethernet","none","unknown"]).default("unknown"),effectiveType:u.string().optional(),isConnected:u.boolean().optional()}),tr=u.object({app:Qs,device:Ys.default({}),os:Js,runtime:Xs,network:er.optional(),locale:u.string().optional(),timezone:u.string().optional()}),sr=u.object({ts:Be,category:u.enum(["navigation","network","ui","log","event","custom"]),message:u.string().max(500),level:u.enum(["debug","info","warning","error"]).default("info"),data:u.record(u.union([u.string(),u.number(),u.boolean(),u.null()])).optional()}),rr=u.object({fn:u.string().optional(),file:u.string().optional(),line:u.number().optional(),col:u.number().optional(),inApp:u.boolean().optional()}),nr=u.enum(["low","medium","high","critical"]),Ce=u.object({id:u.string().min(8).max(64),ts:Be,flow:qs.optional(),step:u.string().max(64).optional(),tags:Gs}),ar=Ce.extend({type:u.literal("error"),handled:u.boolean().default(!0),severity:nr.optional(),error:u.object({name:u.string().max(200).default("Error"),message:u.string().max(2e3),stack:u.string().max(2e4).optional(),frames:u.array(rr).max(100).optional()}),breadcrumbs:u.array(sr).max(50).optional(),request:u.object({method:u.string().max(10),url:u.string().max(500),status:u.number().int().optional(),durationMs:u.number().optional()}).optional()}),ir=Ce.extend({type:u.literal("event"),name:u.string().min(1).max(100),outcome:u.enum(["success","failure","abandoned"]).optional(),props:u.record(u.union([u.string(),u.number(),u.boolean(),u.null()])).optional()}),or=Ce.extend({type:u.literal("session"),status:u.enum(["started","errored","crashed"])}),cr=Ce.extend({type:u.literal("metric"),name:u.literal("http"),key:u.string().min(1).max(300),count:u.number().int().min(1).max(1e6),errors:u.number().int().min(0).max(1e6),buckets:u.array(u.number().int().min(0)).length(13)}),ur=u.discriminatedUnion("type",[ar,ir,or,cr]),vt=u.object({schema:u.literal(1).default(1),sdk:u.object({name:u.string(),version:u.string()}),context:tr,user:u.object({id:u.string().optional(),anonymousId:u.string()}).optional(),session:u.object({id:u.string(),startedAt:Be}),events:u.array(ur).min(1).max(100)});function $e(s){let e=new Map;for(let t of s){let r=Fe(t),n=e.get(r)??{app:t.app,day:t.day,dimension:t.dimension,key:t.key,errors:0,events:0};t.kind==="error"?n.errors+=t.by:n.events+=t.by,e.set(r,n)}return[...e.values()]}var Fe=s=>`${s.day}__${s.dimension}__${encodeURIComponent(s.key)}`;var We=1,Ke=3650,_t=7;var Ne=class{constructor(e,t){this.doc=e;this.opts=t}doc;opts;get table(){return this.opts.table}async registerApp(e){await this.doc.send(new dr({TableName:this.table,Item:{pk:"APPS",sk:e}}))}async writeEvents(e,t={}){let r=t.retentionDays??this.opts.retentionDays??30,n=i=>Math.floor(Date.parse(i.receivedAt)/1e3)+r*86400,a=e.flatMap(i=>{let o=`${i.event.ts}#${i.event.id}`,c={...i,ttl:n(i)},l=[{pk:`APP#${i.app}#EV#${i.day}`,sk:o,...c}];return i.fingerprint&&l.push({pk:`APP#${i.app}#ISSUEEV#${i.fingerprint}`,sk:o,...c}),l});for(let i=0;i<a.length;i+=25){let o={[this.table]:a.slice(i,i+25).map(c=>({PutRequest:{Item:c}}))};for(let c=0;o&&Object.keys(o).length&&c<5;c++)o=(await this.doc.send(new lr({RequestItems:o}))).UnprocessedItems,o&&Object.keys(o).length&&await new Promise(g=>setTimeout(g,50*2**c))}}async upsertIssues(e){let t={created:[],regressed:[]};return await Promise.all(e.map(async r=>{(await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"ADD #count :by SET app = :app, fingerprint = :fp, title = :title, flow = :flow, culprit = :culprit, firstSeen = if_not_exists(firstSeen, :first)",ExpressionAttributeNames:{"#count":"count"},ExpressionAttributeValues:{":by":r.by,":app":r.app,":fp":r.fingerprint,":title":r.title,":flow":r.flow??null,":culprit":r.culprit??null,":first":r.firstTs},ReturnValues:"UPDATED_OLD"}))).Attributes?.count===void 0&&t.created.push(r.fingerprint),await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"SET lastSeen = :ts, lastEvent = :ev, lastVersion = :v, firstVersion = if_not_exists(firstVersion, :v)",ConditionExpression:"attribute_not_exists(lastSeen) OR lastSeen < :ts",ExpressionAttributeValues:{":ts":r.ts,":ev":r.lastEvent,":v":r.version??null}})).catch(i=>{if(i.name!=="ConditionalCheckFailedException")throw i});let a=(await this.doc.send(new He({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},ProjectionExpression:"#s, resolvedIn, resolvedAt",ExpressionAttributeNames:{"#s":"status"}}))).Item;a?.status==="resolved"&&ze(a.resolvedIn,r.version,a.resolvedAt,r.ts)&&await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"SET #s = :r, regressedAt = :ts",ConditionExpression:"#s = :resolved",ExpressionAttributeNames:{"#s":"status"},ExpressionAttributeValues:{":r":"regressed",":ts":r.ts,":resolved":"resolved"}})).then(()=>t.regressed.push(r.fingerprint)).catch(i=>{if(i.name!=="ConditionalCheckFailedException")throw i}),await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${r.app}#ISSUE`,sk:r.fingerprint},UpdateExpression:"SET firstSeen = :first",ConditionExpression:"firstSeen > :first",ExpressionAttributeValues:{":first":r.firstTs}})).catch(i=>{if(i.name!=="ConditionalCheckFailedException")throw i})})),t}async incrementRollups(e){await Promise.all($e(e).map(t=>this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${t.app}#ROLLUP#${t.dimension}`,sk:`${t.day}#${t.key}`},UpdateExpression:`ADD errors :e, events :v SET app = :app, #day = :day, dimension = :dim, #key = :key${t.dimension==="issueHour"?", #ttl = :ttl":""}`,ExpressionAttributeNames:{"#day":"day","#key":"key",...t.dimension==="issueHour"?{"#ttl":"ttl"}:{}},ExpressionAttributeValues:{":e":t.errors,":v":t.events,":app":t.app,":day":t.day,":dim":t.dimension,":key":t.key,...t.dimension==="issueHour"?{":ttl":Math.floor(Date.parse(`${t.day}:00:00Z`)/1e3)+_t*86400}:{}}}))))}async markUsers(e,t){await Promise.all(t.map(r=>this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${e}#USERS#${r.scope}`,sk:r.member},UpdateExpression:"SET lastDay = :d",ConditionExpression:"attribute_not_exists(lastDay) OR lastDay < :d",ExpressionAttributeValues:{":d":r.day}})).catch(n=>{if(n.name!=="ConditionalCheckFailedException")throw n})))}async countUsers(e,t,r){let n=0,a;do{let i=await this.doc.send(new qe({TableName:this.table,KeyConditionExpression:"pk = :pk",FilterExpression:"lastDay >= :d",ExpressionAttributeValues:{":pk":`APP#${e}#USERS#${t}`,":d":r},Select:"COUNT",ExclusiveStartKey:a}));n+=i.Count??0,a=i.LastEvaluatedKey}while(a);return n}async setIssueStatus(e,t,r){let n=r.status==="resolved",a=await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${e}#ISSUE`,sk:t},UpdateExpression:n?"SET #s = :s, resolvedAt = :at, resolvedIn = :in REMOVE regressedAt":"SET #s = :s REMOVE resolvedIn, resolvedAt, regressedAt",ConditionExpression:"attribute_exists(pk)",ExpressionAttributeNames:{"#s":"status"},ExpressionAttributeValues:n?{":s":r.status,":at":new Date().toISOString(),":in":r.resolvedIn??null}:{":s":r.status},ReturnValues:"ALL_NEW"})).catch(i=>{if(i.name==="ConditionalCheckFailedException")return null;throw i});return a?.Attributes?de(a.Attributes):null}async getSettings(e){let t=await this.doc.send(new He({TableName:this.table,Key:{pk:`APP#${e}#SETTINGS`,sk:"app"}}));return t.Item?de(t.Item):null}async putSettings(e,t){let r=Object.fromEntries(Object.entries({...t,updatedAt:new Date().toISOString()}).filter(([,i])=>i!==void 0)),n=Object.keys(r),a=await this.doc.send(new B({TableName:this.table,Key:{pk:`APP#${e}#SETTINGS`,sk:"app"},UpdateExpression:`SET ${n.map((i,o)=>`#n${o} = :v${o}`).join(", ")}`,ExpressionAttributeNames:Object.fromEntries(n.map((i,o)=>[`#n${o}`,i])),ExpressionAttributeValues:Object.fromEntries(n.map((i,o)=>[`:v${o}`,r[i]])),ReturnValues:"ALL_NEW"}));return de(a.Attributes??r)}async restampExpiry(e,t,{cursor:r}={}){let n=r?Number(r):0,a=0;for(let i=0;i<30&&n<=3650;i++,n++){let o=new Date(Date.now()-n*864e5).toISOString().slice(0,10),c=await this.queryAll({pk:`APP#${e}#EV#${o}`});for(let l of c){let g=Math.floor(Date.parse(l.receivedAt)/1e3)+t*86400,k=[{pk:l.pk,sk:l.sk},...l.fingerprint?[{pk:`APP#${e}#ISSUEEV#${l.fingerprint}`,sk:l.sk}]:[]];await Promise.all(k.map(A=>this.doc.send(new B({TableName:this.table,Key:A,UpdateExpression:"SET #t = :t",ConditionExpression:"attribute_exists(pk)",ExpressionAttributeNames:{"#t":"ttl"},ExpressionAttributeValues:{":t":g}})).catch(E=>{if(E.name!=="ConditionalCheckFailedException")throw E}))),a++}if(c.length){n++;break}}return{updated:a,cursor:n<=3650?String(n):void 0}}async listApps(){return(await this.queryAll({pk:"APPS"})).map(e=>e.sk).sort()}async listIssues(e,{limit:t=200}={}){return(await this.queryAll({pk:`APP#${e}#ISSUE`})).sort((n,a)=>a.lastSeen.localeCompare(n.lastSeen)).slice(0,t).map(de)}async getIssue(e,t){let r=await this.doc.send(new He({TableName:this.table,Key:{pk:`APP#${e}#ISSUE`,sk:t}}));return r.Item?de(r.Item):null}async getRollups(e,t,r,n){return(await this.queryAll({pk:`APP#${e}#ROLLUP#${t}`,between:[`${r}#`,`${n}#\uFFFF`]})).map(i=>de(i))}async listIssueEvents(e,t,{limit:r=50}={}){return((await this.doc.send(new qe({TableName:this.table,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":`APP#${e}#ISSUEEV#${t}`},ScanIndexForward:!1,Limit:r}))).Items??[]).map(a=>de(a))}async queryAll({pk:e,between:t}){let r=[],n;do{let a=await this.doc.send(new qe({TableName:this.table,KeyConditionExpression:t?"pk = :pk AND sk BETWEEN :a AND :b":"pk = :pk",ExpressionAttributeValues:t?{":pk":e,":a":t[0],":b":t[1]}:{":pk":e},ExclusiveStartKey:n}));r.push(...a.Items??[]),n=a.LastEvaluatedKey}while(n);return r}};function de(s){let{pk:e,sk:t,ttl:r,...n}=s;return n}import{createHash as wr}from"crypto";import{timingSafeEqual as mr}from"crypto";var Ae=/^https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/_-]{10,200}$/,Pe=new Map,pr=36e5,fr=(s,e)=>fetch(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(3e3)});async function Ge(s,e,t,r,n=fr){let a=r?.alerts;if(!e||!a?.slackWebhookUrl||!Ae.test(a.slackWebhookUrl))return 0;let i=new Set(r?.criticalFlows??[]),o=[...a.newIssues!==!1?e.created.map(l=>({fp:l,kind:"new"})):[],...a.regressions!==!1?e.regressed.map(l=>({fp:l,kind:"regressed"})):[]].filter(({fp:l})=>!a.onlyCriticalFlows||i.has(t.get(l)?.flow??"")).filter(({fp:l,kind:g})=>{let k=`${s}|${l}|${g}`,A=Pe.get(k);return A&&Date.now()-A<pr?!1:(Pe.set(k,Date.now()),!0)}).slice(0,10);Pe.size>5e3&&Pe.clear();let c=0;for(let{fp:l,kind:g}of o){let k=t.get(l);if(!k)continue;let A=a.dashboardUrl?`${a.dashboardUrl.replace(/\/+$/,"")}/issues/${l}?app=${encodeURIComponent(s)}`:void 0,E=[k.culprit&&`\`${k.culprit}\``,k.flow&&`flow \`${k.flow}\`${i.has(k.flow)?" (critical)":""}`,k.version&&`version ${k.version}`].filter(Boolean).join(" \xB7 "),Me=`${g==="new"?":new: New issue":":rotating_light: Regressed"} in *${s}*: ${A?`<${A}|${k.title}>`:k.title}${E?`
|
|
3
|
+
${E}`:""}`;try{await n(a.slackWebhookUrl,{text:Me}),c++}catch(pe){console.error("[deBug] Slack alert failed",pe)}}return c}var Ye=30,hr=6e4,Je=new Map;async function De(s,e){let t=Je.get(e);if(t&&Date.now()-t.at<hr)return t.settings;let r;try{r=await s.getSettings(e)}catch{r=null}return Je.set(e,{at:Date.now(),settings:r}),r}async function Ue(s,e,t){return(await De(s,e))?.retentionDays??t??Ye}function xt(s){return s?.alerts?.slackWebhookUrl?{...s,alerts:{...s.alerts,slackWebhookUrl:`https://hooks.slack.com/\u2026${s.alerts.slackWebhookUrl.slice(-4)}`}}:s}var gr=/^[a-z0-9_]+(\.[a-z0-9_]+)*$/;function yr(s,e){let t={};if(s.retentionDays!==void 0){let r=Number(s.retentionDays);if(!Number.isInteger(r)||r<We||r>Ke)return`retentionDays must be a whole number from ${We} to ${Ke}`;t.retentionDays=r}if(s.criticalFlows!==void 0){if(!Array.isArray(s.criticalFlows)||s.criticalFlows.length>30||!s.criticalFlows.every(r=>typeof r=="string"&&r.length<=64&&gr.test(r)))return"criticalFlows must be up to 30 dotted lowercase flow names, like checkout.payment";t.criticalFlows=[...new Set(s.criticalFlows)]}if(s.alerts!==void 0){let r=s.alerts;if(!r||typeof r!="object")return"alerts must be an object";let n={},a=r.slackWebhookUrl;if(typeof a=="string"&&a.includes("\u2026"))n.slackWebhookUrl=e?.alerts?.slackWebhookUrl;else if(a===""||a===null||a===void 0)n.slackWebhookUrl=void 0;else if(typeof a=="string"&&Ae.test(a))n.slackWebhookUrl=a;else return"slackWebhookUrl must be a Slack incoming-webhook URL (https://hooks.slack.com/services/\u2026)";for(let i of["newIssues","regressions","onlyCriticalFlows"])typeof r[i]=="boolean"&&(n[i]=r[i]);if(typeof r.dashboardUrl=="string"&&r.dashboardUrl){if(!/^https?:\/\/[^\s]{3,300}$/.test(r.dashboardUrl))return"dashboardUrl must be an http(s) URL";n.dashboardUrl=r.dashboardUrl}t.alerts=n}return Object.keys(t).length?t:"nothing to change"}function vr(s,e){let t=Buffer.from((s??"").replace(/^Bearer\s+/i,"")),r=Buffer.from(e);return t.length===r.length&&mr(t,r)}var _r=/^[a-z0-9][a-z0-9._-]{0,63}$/i;async function Qe(s,e){if(!e.adminToken||e.adminToken.length<16)return{status:404,body:{ok:!1,error:"admin routes are off (set DEBUG_ADMIN_TOKEN)"}};if(!vr(s.authorization,e.adminToken))return{status:401,body:{ok:!1,error:"unauthorized"}};let t={};if(s.method!=="GET"&&s.body)try{t=JSON.parse(s.body)}catch{return{status:400,body:{ok:!1,error:"invalid json"}}}let r=String((s.method==="GET"?s.query?.app:t.app)??"");if(!_r.test(r))return{status:400,body:{ok:!1,error:"app is required"}};let n=s.path.replace(/\/+$/,"").replace(/^.*\/admin/,"");if(n==="/settings"&&s.method==="GET"){let a=await e.store.getSettings(r);return{status:200,body:{ok:!0,settings:xt(a),retentionDays:a?.retentionDays??e.retentionDays??Ye}}}if(n==="/settings"&&(s.method==="PUT"||s.method==="POST")){let a=await e.store.getSettings(r),i=yr(t,a);if(typeof i=="string")return{status:400,body:{ok:!1,error:i}};let o=await e.store.putSettings(r,i);return Je.delete(r),{status:200,body:{ok:!0,settings:xt(o),retentionDays:o.retentionDays??e.retentionDays??Ye}}}if(n==="/alert-test"&&s.method==="POST"){let a=(await e.store.getSettings(r))?.alerts?.slackWebhookUrl;if(!a||!Ae.test(a))return{status:400,body:{ok:!1,error:"No Slack webhook is set for this app"}};let i=await fetch(a,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:`:white_check_mark: deBug alerts for *${r}* are working.`}),signal:AbortSignal.timeout(5e3)}).catch(o=>o);return i instanceof Error||!i.ok?{status:502,body:{ok:!1,error:`Slack didn't accept it: ${i instanceof Error?i.message:i.status}`}}:{status:200,body:{ok:!0}}}if(n==="/restamp"&&s.method==="POST"){let a=await Ue(e.store,r,e.retentionDays),i=await e.store.restampExpiry(r,a,{cursor:typeof t.cursor=="string"?t.cursor:void 0});return{status:200,body:{ok:!0,retentionDays:a,...i}}}if(n==="/issue"&&(s.method==="PUT"||s.method==="POST")){let a=String(t.fingerprint??""),i=String(t.status??"");if(!/^[a-f0-9]{8,64}$/.test(a))return{status:400,body:{ok:!1,error:"fingerprint is required"}};if(i!=="open"&&i!=="resolved"&&i!=="ignored")return{status:400,body:{ok:!1,error:"status must be open, resolved or ignored"}};let o=typeof t.resolvedIn=="string"&&t.resolvedIn.trim()?t.resolvedIn.trim().slice(0,100):void 0,c=await e.store.setIssueStatus(r,a,{status:i,resolvedIn:i==="resolved"?o:void 0});return c?{status:200,body:{ok:!0,status:c.status,resolvedIn:c.resolvedIn??null}}:{status:404,body:{ok:!1,error:"no such issue"}}}return{status:404,body:{ok:!1,error:"not found"}}}var xr={"Africa/Johannesburg":"ZA","Africa/Lagos":"NG","Africa/Nairobi":"KE","Africa/Cairo":"EG","Africa/Casablanca":"MA","Africa/Accra":"GH","Africa/Harare":"ZW","Africa/Lusaka":"ZM","Africa/Maputo":"MZ","Africa/Windhoek":"NA","Africa/Gaborone":"BW","Africa/Kampala":"UG","Africa/Dar_es_Salaam":"TZ","Africa/Addis_Ababa":"ET","Africa/Kigali":"RW","Africa/Algiers":"DZ","Africa/Tunis":"TN","Africa/Abidjan":"CI","Africa/Dakar":"SN","Africa/Luanda":"AO","Europe/London":"GB","Europe/Dublin":"IE","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Europe/Amsterdam":"NL","Europe/Brussels":"BE","Europe/Lisbon":"PT","Europe/Stockholm":"SE","Europe/Oslo":"NO","Europe/Copenhagen":"DK","Europe/Helsinki":"FI","Europe/Warsaw":"PL","Europe/Zurich":"CH","Europe/Vienna":"AT","Europe/Athens":"GR","Europe/Istanbul":"TR","Europe/Moscow":"RU","Europe/Kyiv":"UA","Europe/Kiev":"UA","Europe/Prague":"CZ","Europe/Budapest":"HU","Europe/Bucharest":"RO","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Phoenix":"US","America/Anchorage":"US","Pacific/Honolulu":"US","America/Detroit":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Edmonton":"CA","America/Halifax":"CA","America/Mexico_City":"MX","America/Sao_Paulo":"BR","America/Argentina/Buenos_Aires":"AR","America/Bogota":"CO","America/Lima":"PE","America/Santiago":"CL","Asia/Dubai":"AE","Asia/Riyadh":"SA","Asia/Qatar":"QA","Asia/Jerusalem":"IL","Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Karachi":"PK","Asia/Dhaka":"BD","Asia/Bangkok":"TH","Asia/Jakarta":"ID","Asia/Singapore":"SG","Asia/Kuala_Lumpur":"MY","Asia/Manila":"PH","Asia/Ho_Chi_Minh":"VN","Asia/Hong_Kong":"HK","Asia/Shanghai":"CN","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Taipei":"TW","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Pacific/Auckland":"NZ","Indian/Mauritius":"MU"};function Xe(s){let e=s.timezone?xr[s.timezone]:void 0;return e||(/[-_]([A-Z]{2})(?:\b|$)/.exec(s.locale??"")?.[1]??"unknown")}import{createHash as kr}from"crypto";function br(s){return s.replace(/https?:\/\/\S+/g,"<url>").replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,"<uuid>").replace(/\b[0-9a-f]{16,}\b/gi,"<hex>").replace(/[\w.+-]+@[\w-]+\.[\w.]+/g,"<email>").replace(/\d+(\.\d+)?/g,"<n>").replace(/(["'`]).*?\1/g,"<str>").trim().slice(0,300)}function kt(s){if(!s)return"";let e=s.replace(/\/\/&.*$/,"").replace(/[?#].*$/,"").replace(/^[a-z]+:\/\/[^/]+/i,"");if(/\.(?:js)?bundle$/.test(e))return e.replace(/^.*\//,"");for(let t of["/src/","/lib/","/app/"]){let r=e.lastIndexOf(t);if(r>=0){e=e.slice(r+1);break}}return e.replace(/\.[0-9a-f]{6,}\./g,".")}function bt(s){return s?.find(e=>e.inApp!==!1&&e.file)??s?.[0]}function wt(s){let e=bt(s.error.frames);if(!e)return;let t=kt(e.file)+(e.line?`:${e.line}`:"");return e.fn?`${e.fn} (${t})`:t}function St(s){let e=bt(s.error.frames),t=s.request,r=t?`${t.method.toUpperCase()} ${t.url} ${t.status?`${Math.floor(t.status/100)}xx`:"failed"}`:e?`${e.fn??"?"}@${kt(e.file)}`:br(s.error.message);return kr("sha256").update([s.error.name,r,s.flow??""].join("|")).digest("hex").slice(0,24)}function At(s){return`${s.error.name}: ${s.error.message}`.slice(0,200)}function Tt(s){let e={};for(let t of(s??"").split(",").map(r=>r.trim()).filter(Boolean)){let[r,n]=t.split(":");r&&n&&(e[r]=n)}return e}var Et=s=>s.slice(0,10);function Sr(s,e){let t=Date.parse(s),r=e.getTime();return Number.isNaN(t)||t>r+5*6e4||t<r-7*864e5?e.toISOString():new Date(t).toISOString()}function Ar(s){return{...s,os:{...s.os,name:s.os.name.toLowerCase()},runtime:{...s.runtime,name:s.runtime.name.toLowerCase()}}}async function It(s,e,t){let r=t.now?.()??new Date;if(!e||!t.keys[e])return{status:401,body:{ok:!1,error:"invalid ingest key"}};if(Buffer.byteLength(s)>(t.maxBytes??512*1024))return{status:413,body:{ok:!1,error:"payload too large"}};let n;try{n=JSON.parse(s)}catch{return{status:400,body:{ok:!1,error:"invalid json"}}}let a=vt.safeParse(n);if(!a.success)return{status:400,body:{ok:!1,error:"invalid envelope",issues:a.error.flatten()}};let i=a.data,o=i.context.app.id;if(t.keys[e]!==o&&t.keys[e]!=="*")return{status:403,body:{ok:!1,error:`key not allowed for app ${o}`}};let c=Ar(i.context),l=r.toISOString(),g=[],k=[],A=new Map,E=new Set;for(let st of i.events){let v={...st,ts:Sr(st.ts,r)};v.type==="error"&&!v.error.frames?.length&&v.error.stack&&(v.error.frames=gt(v.error.stack));let F=Et(v.ts);if(v.type==="session"){k.push({app:o,day:F,dimension:"session",key:`${c.app.version||"unknown"}|${v.status}`,kind:"event",by:1}),E.add("app"),v.status==="started"&&k.push({app:o,day:F,dimension:"release",key:ht(c.app),kind:"event",by:1}),v.status==="crashed"&&E.add("crash");continue}if(E.add("app"),v.type==="metric"){k.push({app:o,day:F,dimension:"requests",key:v.key,kind:"event",by:v.count}),v.errors&&k.push({app:o,day:F,dimension:"requests",key:v.key,kind:"error",by:v.errors}),v.buckets.forEach((T,ke)=>T&&k.push({app:o,day:F,dimension:"latency",key:`${v.key}|${ke}`,kind:"event",by:T}));continue}let rt=v.type==="error"?"error":"event",N=(T,ke)=>k.push({app:o,day:F,dimension:T,key:ke||"unknown",kind:rt,by:1}),M;if(v.type==="error"){M=St(v);let T=A.get(M),ke={app:o,day:F,fingerprint:M,event:v,context:c,user:i.user,sessionId:i.session.id,receivedAt:l};A.set(M,{app:o,fingerprint:M,title:At(v),culprit:wt(v),flow:v.flow,by:(T?.by??0)+1,ts:T&&T.ts>v.ts?T.ts:v.ts,firstTs:T&&T.firstTs<v.ts?T.firstTs:v.ts,lastEvent:T&&T.ts>v.ts?T.lastEvent:ke,version:c.app.version}),E.add(`issue:${M}`),N("issue",M),v.request&&N("endpoint",`${v.request.method.toUpperCase()} ${v.request.url}`),k.push({app:o,day:v.ts.slice(0,13),dimension:"issueHour",key:M,kind:rt,by:1})}N("total","all"),N("flow",v.flow??"untagged"),N("os",`${c.os.name} ${c.os.version??""}`.trim()),N("appVersion",c.app.version),N("deviceModel",c.device.model),v.type==="event"&&v.outcome&&v.flow&&(N("flowOutcome",`${v.flow}|${v.outcome}`),v.step&&N("flowStep",`${v.flow}|${v.step}|${v.outcome}`)),v.type==="error"&&(N("network",c.network?.type),N("country",Xe(c))),g.push({app:o,day:F,fingerprint:M,event:v,context:c,user:i.user,sessionId:i.session.id,receivedAt:l})}await t.store.registerApp(o);let Me=g.length?await Ue(t.store,o,t.retentionDays):void 0,[,pe]=await Promise.all([g.length?t.store.writeEvents(g,{retentionDays:Me}):void 0,t.store.upsertIssues([...A.values()]),t.store.incrementRollups(k),Er(t.store,o,i.user?.id??i.user?.anonymousId??i.session.id,E,Et(l))]);return pe&&(pe.created.length||pe.regressed.length)&&await Ge(o,pe,A,await De(t.store,o)),{status:202,body:{ok:!0,accepted:i.events.length}}}var je=new Set;async function Er(s,e,t,r,n){if(!r.size)return;let a=wr("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24),i=[];for(let o of r){let c=`${e}|${o}|${a}|${n}`;je.has(c)||(je.add(c),i.push({scope:o,member:a,day:n}))}je.size>5e4&&je.clear(),i.length&&await s.markUsers(e,i)}var et={"access-control-allow-origin":"*","access-control-allow-methods":"POST, OPTIONS","access-control-allow-headers":"content-type, x-debug-key","access-control-max-age":"86400"};function Rt(s){return async e=>{let t=e.requestContext?.http?.method??e.httpMethod??"POST",r=e.rawPath??e.requestContext?.http?.path??e.path??"/";if(r.startsWith("/admin")){let i=Object.fromEntries(Object.entries(e.headers??{}).map(([c,l])=>[c.toLowerCase(),l])),o=e.isBase64Encoded?Buffer.from(e.body??"","base64").toString("utf8"):e.body??"";try{let c=await Qe({method:t,path:r,query:e.queryStringParameters??{},body:o,authorization:i.authorization},{store:s.store,adminToken:s.adminToken,retentionDays:s.retentionDays});return{statusCode:c.status,headers:{"content-type":"application/json"},body:JSON.stringify(c.body)}}catch(c){return console.error("[deBug] admin request failed",c),{statusCode:500,headers:{"content-type":"application/json"},body:JSON.stringify({ok:!1,error:"internal"})}}}if(t==="OPTIONS")return{statusCode:204,headers:et,body:""};if(t!=="POST")return tt(405,{ok:!1,error:"method not allowed"});let n=Object.fromEntries(Object.entries(e.headers??{}).map(([i,o])=>[i.toLowerCase(),o])),a=e.isBase64Encoded?Buffer.from(e.body??"","base64").toString("utf8"):e.body??"";try{let i=await It(a,n["x-debug-key"],s);return tt(i.status,i.body)}catch(i){return console.error("[deBug] ingest failed",i),tt(500,{ok:!1,error:"internal"})}}}var tt=(s,e)=>({statusCode:s,headers:{...et,"content-type":"application/json"},body:JSON.stringify(e)});var Rr=Ir.from(new Tr({}),{marshallOptions:{removeUndefinedValues:!0}}),Gn=Rt({store:new Ne(Rr,{table:process.env.DEBUG_TABLE??"debugkit"}),keys:Tt(process.env.DEBUG_INGEST_KEYS),retentionDays:Number(process.env.DEBUG_RETENTION_DAYS)||void 0,adminToken:process.env.DEBUG_ADMIN_TOKEN});export{Gn as handler};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@debugkit/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Set up deBug in your app: npx @debugkit/cli init (or npx debugkit init once @debugkit/sdk is installed). Deploys ingest to your own cloud, wires the SDK and walks you through the dashboard.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
22
22
|
"@aws-sdk/lib-dynamodb": "^3.700.0",
|
|
23
|
-
"@debugkit/adapters": "^0.
|
|
24
|
-
"@debugkit/ingest": "^0.
|
|
25
|
-
"@debugkit/sdk": "^0.
|
|
23
|
+
"@debugkit/adapters": "^0.5.0",
|
|
24
|
+
"@debugkit/ingest": "^0.5.0",
|
|
25
|
+
"@debugkit/sdk": "^0.5.0"
|
|
26
26
|
},
|
|
27
27
|
"engines": {
|
|
28
28
|
"node": ">=20.12"
|